hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
fb760e413c49369bd5118f7f8fc2da76187cd6b5
2,645
/** * * Copyright 2014 The Darks Learning Project (Liu lihua) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package darks.learning.common.minispantree; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Build minimum span tree by Prim algorithm * * @author lihua.llh * */ public class PrimMiniSpanTree<T, E> extends MiniSpanTree<T, E> { List<Integer> selectNodes; Set<Integer> remainNodes; List<GraphEdge<E>> targetEdges; /** * {@inheritDoc} */ @Override public void initialize(GraphBuilder<T, E> builder) { super.initialize(builder); selectNodes = new ArrayList<Integer>(); remainNodes = new HashSet<Integer>(); targetEdges = new LinkedList<GraphEdge<E>>(); for (int i = 0 ; i < nodes.size(); i++) { remainNodes.add(i); } } /** * {@inheritDoc} */ @Override public void buildTree(int startIndex) { selectNodes.add(startIndex); remainNodes.remove(startIndex); for (int i = 0; i < nodes.size() - 1; i++) { GraphEdge<E> minEdge = null; Integer newIndex = null; for (Integer remainIndex : remainNodes) { for (Integer selectIndex : selectNodes) { GraphEdge<E> edge = edges.get(selectIndex, remainIndex); if (edge != null) { if (minEdge == null || edge.getWeight() < minEdge.getWeight()) { newIndex = remainIndex; minEdge = edge; } } } } if (newIndex != null && minEdge != null) { remainNodes.remove(newIndex); selectNodes.add(newIndex); targetEdges.add(minEdge); } } } /** * {@inheritDoc} */ @Override public List<Integer> getResultNodesIndex() { return selectNodes; } /** * {@inheritDoc} */ @Override public List<? extends GraphNode<T>> getResultNodes() { List<GraphNode<T>> result = new ArrayList<GraphNode<T>>(selectNodes.size()); for (Integer index : selectNodes) { result.add(nodes.get(index)); } return result; } /** * {@inheritDoc} */ @Override public List<? extends GraphEdge<E>> getResultEdges() { return targetEdges; } }
20.992063
78
0.658601
8d629b939a4bb7ab00d7cd4eb402877adea8edce
41,224
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk; import static com.google.android.apps.forscience.whistlepunk.PitchSensorAnimationBehavior.calculateDifference; import static com.google.android.apps.forscience.whistlepunk.PitchSensorAnimationBehavior.fillNoteLists; import static com.google.android.apps.forscience.whistlepunk.PitchSensorAnimationBehavior.makeContentDescription; import static com.google.android.apps.forscience.whistlepunk.PitchSensorAnimationBehavior.noteFrequencies; import static com.google.android.apps.forscience.whistlepunk.PitchSensorAnimationBehavior.pitchToLevel; import static org.junit.Assert.assertEquals; import android.content.Context; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; @RunWith(RobolectricTestRunner.class) public class PitchSensorAnimationBehaviorTest { private String getContentDescriptionForPitch(double detectedPitch) { int level = pitchToLevel(detectedPitch); double difference = calculateDifference(detectedPitch, level); Context context = RuntimeEnvironment.application.getApplicationContext(); return makeContentDescription(context, level, difference); } @Test public void makeContentDescriptionNotes() throws Exception { if (noteFrequencies.isEmpty()) { fillNoteLists(); } assertEquals("low pitch", getContentDescriptionForPitch(noteFrequencies.get(0))); assertEquals("A, octave 0", getContentDescriptionForPitch(noteFrequencies.get(1))); assertEquals("B flat, octave 0", getContentDescriptionForPitch(noteFrequencies.get(2))); assertEquals("B, octave 0", getContentDescriptionForPitch(noteFrequencies.get(3))); assertEquals("C, octave 1", getContentDescriptionForPitch(noteFrequencies.get(4))); assertEquals("C sharp, octave 1", getContentDescriptionForPitch(noteFrequencies.get(5))); assertEquals("D, octave 1", getContentDescriptionForPitch(noteFrequencies.get(6))); assertEquals("E flat, octave 1", getContentDescriptionForPitch(noteFrequencies.get(7))); assertEquals("E, octave 1", getContentDescriptionForPitch(noteFrequencies.get(8))); assertEquals("F, octave 1", getContentDescriptionForPitch(noteFrequencies.get(9))); assertEquals("F sharp, octave 1", getContentDescriptionForPitch(noteFrequencies.get(10))); assertEquals("G, octave 1", getContentDescriptionForPitch(noteFrequencies.get(11))); assertEquals("A flat, octave 1", getContentDescriptionForPitch(noteFrequencies.get(12))); assertEquals("A, octave 1", getContentDescriptionForPitch(noteFrequencies.get(13))); assertEquals("B flat, octave 1", getContentDescriptionForPitch(noteFrequencies.get(14))); assertEquals("B, octave 1", getContentDescriptionForPitch(noteFrequencies.get(15))); assertEquals("C, octave 2", getContentDescriptionForPitch(noteFrequencies.get(16))); assertEquals("C sharp, octave 2", getContentDescriptionForPitch(noteFrequencies.get(17))); assertEquals("D, octave 2", getContentDescriptionForPitch(noteFrequencies.get(18))); assertEquals("E flat, octave 2", getContentDescriptionForPitch(noteFrequencies.get(19))); assertEquals("E, octave 2", getContentDescriptionForPitch(noteFrequencies.get(20))); assertEquals("F, octave 2", getContentDescriptionForPitch(noteFrequencies.get(21))); assertEquals("F sharp, octave 2", getContentDescriptionForPitch(noteFrequencies.get(22))); assertEquals("G, octave 2", getContentDescriptionForPitch(noteFrequencies.get(23))); assertEquals("A flat, octave 2", getContentDescriptionForPitch(noteFrequencies.get(24))); assertEquals("A, octave 2", getContentDescriptionForPitch(noteFrequencies.get(25))); assertEquals("B flat, octave 2", getContentDescriptionForPitch(noteFrequencies.get(26))); assertEquals("B, octave 2", getContentDescriptionForPitch(noteFrequencies.get(27))); assertEquals("C, octave 3", getContentDescriptionForPitch(noteFrequencies.get(28))); assertEquals("C sharp, octave 3", getContentDescriptionForPitch(noteFrequencies.get(29))); assertEquals("D, octave 3", getContentDescriptionForPitch(noteFrequencies.get(30))); assertEquals("E flat, octave 3", getContentDescriptionForPitch(noteFrequencies.get(31))); assertEquals("E, octave 3", getContentDescriptionForPitch(noteFrequencies.get(32))); assertEquals("F, octave 3", getContentDescriptionForPitch(noteFrequencies.get(33))); assertEquals("F sharp, octave 3", getContentDescriptionForPitch(noteFrequencies.get(34))); assertEquals("G, octave 3", getContentDescriptionForPitch(noteFrequencies.get(35))); assertEquals("A flat, octave 3", getContentDescriptionForPitch(noteFrequencies.get(36))); assertEquals("A, octave 3", getContentDescriptionForPitch(noteFrequencies.get(37))); assertEquals("B flat, octave 3", getContentDescriptionForPitch(noteFrequencies.get(38))); assertEquals("B, octave 3", getContentDescriptionForPitch(noteFrequencies.get(39))); assertEquals("C, octave 4", getContentDescriptionForPitch(noteFrequencies.get(40))); assertEquals("C sharp, octave 4", getContentDescriptionForPitch(noteFrequencies.get(41))); assertEquals("D, octave 4", getContentDescriptionForPitch(noteFrequencies.get(42))); assertEquals("E flat, octave 4", getContentDescriptionForPitch(noteFrequencies.get(43))); assertEquals("E, octave 4", getContentDescriptionForPitch(noteFrequencies.get(44))); assertEquals("F, octave 4", getContentDescriptionForPitch(noteFrequencies.get(45))); assertEquals("F sharp, octave 4", getContentDescriptionForPitch(noteFrequencies.get(46))); assertEquals("G, octave 4", getContentDescriptionForPitch(noteFrequencies.get(47))); assertEquals("A flat, octave 4", getContentDescriptionForPitch(noteFrequencies.get(48))); assertEquals("A, octave 4", getContentDescriptionForPitch(noteFrequencies.get(49))); assertEquals("B flat, octave 4", getContentDescriptionForPitch(noteFrequencies.get(50))); assertEquals("B, octave 4", getContentDescriptionForPitch(noteFrequencies.get(51))); assertEquals("C, octave 5", getContentDescriptionForPitch(noteFrequencies.get(52))); assertEquals("C sharp, octave 5", getContentDescriptionForPitch(noteFrequencies.get(53))); assertEquals("D, octave 5", getContentDescriptionForPitch(noteFrequencies.get(54))); assertEquals("E flat, octave 5", getContentDescriptionForPitch(noteFrequencies.get(55))); assertEquals("E, octave 5", getContentDescriptionForPitch(noteFrequencies.get(56))); assertEquals("F, octave 5", getContentDescriptionForPitch(noteFrequencies.get(57))); assertEquals("F sharp, octave 5", getContentDescriptionForPitch(noteFrequencies.get(58))); assertEquals("G, octave 5", getContentDescriptionForPitch(noteFrequencies.get(59))); assertEquals("A flat, octave 5", getContentDescriptionForPitch(noteFrequencies.get(60))); assertEquals("A, octave 5", getContentDescriptionForPitch(noteFrequencies.get(61))); assertEquals("B flat, octave 5", getContentDescriptionForPitch(noteFrequencies.get(62))); assertEquals("B, octave 5", getContentDescriptionForPitch(noteFrequencies.get(63))); assertEquals("C, octave 6", getContentDescriptionForPitch(noteFrequencies.get(64))); assertEquals("C sharp, octave 6", getContentDescriptionForPitch(noteFrequencies.get(65))); assertEquals("D, octave 6", getContentDescriptionForPitch(noteFrequencies.get(66))); assertEquals("E flat, octave 6", getContentDescriptionForPitch(noteFrequencies.get(67))); assertEquals("E, octave 6", getContentDescriptionForPitch(noteFrequencies.get(68))); assertEquals("F, octave 6", getContentDescriptionForPitch(noteFrequencies.get(69))); assertEquals("F sharp, octave 6", getContentDescriptionForPitch(noteFrequencies.get(70))); assertEquals("G, octave 6", getContentDescriptionForPitch(noteFrequencies.get(71))); assertEquals("A flat, octave 6", getContentDescriptionForPitch(noteFrequencies.get(72))); assertEquals("A, octave 6", getContentDescriptionForPitch(noteFrequencies.get(73))); assertEquals("B flat, octave 6", getContentDescriptionForPitch(noteFrequencies.get(74))); assertEquals("B, octave 6", getContentDescriptionForPitch(noteFrequencies.get(75))); assertEquals("C, octave 7", getContentDescriptionForPitch(noteFrequencies.get(76))); assertEquals("C sharp, octave 7", getContentDescriptionForPitch(noteFrequencies.get(77))); assertEquals("D, octave 7", getContentDescriptionForPitch(noteFrequencies.get(78))); assertEquals("E flat, octave 7", getContentDescriptionForPitch(noteFrequencies.get(79))); assertEquals("E, octave 7", getContentDescriptionForPitch(noteFrequencies.get(80))); assertEquals("F, octave 7", getContentDescriptionForPitch(noteFrequencies.get(81))); assertEquals("F sharp, octave 7", getContentDescriptionForPitch(noteFrequencies.get(82))); assertEquals("G, octave 7", getContentDescriptionForPitch(noteFrequencies.get(83))); assertEquals("A flat, octave 7", getContentDescriptionForPitch(noteFrequencies.get(84))); assertEquals("A, octave 7", getContentDescriptionForPitch(noteFrequencies.get(85))); assertEquals("B flat, octave 7", getContentDescriptionForPitch(noteFrequencies.get(86))); assertEquals("B, octave 7", getContentDescriptionForPitch(noteFrequencies.get(87))); assertEquals("C, octave 8", getContentDescriptionForPitch(noteFrequencies.get(88))); assertEquals("high pitch", getContentDescriptionForPitch(noteFrequencies.get(89))); } @Test public void makeContentDescriptionFlatter() throws Exception { if (noteFrequencies.isEmpty()) { fillNoteLists(); } assertEquals("low pitch", getContentDescriptionForPitch(noteFrequencies.get(0) - 1)); assertEquals( "0.25 half steps flatter than A, octave 0", getContentDescriptionForPitch((3 * noteFrequencies.get(1) + noteFrequencies.get(0)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 0", getContentDescriptionForPitch((3 * noteFrequencies.get(2) + noteFrequencies.get(1)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 0", getContentDescriptionForPitch((3 * noteFrequencies.get(3) + noteFrequencies.get(2)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(4) + noteFrequencies.get(3)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(5) + noteFrequencies.get(4)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(6) + noteFrequencies.get(5)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(7) + noteFrequencies.get(6)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(8) + noteFrequencies.get(7)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(9) + noteFrequencies.get(8)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(10) + noteFrequencies.get(9)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(11) + noteFrequencies.get(10)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(12) + noteFrequencies.get(11)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(13) + noteFrequencies.get(12)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(14) + noteFrequencies.get(13)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(15) + noteFrequencies.get(14)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(16) + noteFrequencies.get(15)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(17) + noteFrequencies.get(16)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(18) + noteFrequencies.get(17)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(19) + noteFrequencies.get(18)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(20) + noteFrequencies.get(19)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(21) + noteFrequencies.get(20)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(22) + noteFrequencies.get(21)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(23) + noteFrequencies.get(22)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(24) + noteFrequencies.get(23)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(25) + noteFrequencies.get(24)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(26) + noteFrequencies.get(25)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(27) + noteFrequencies.get(26)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(28) + noteFrequencies.get(27)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(29) + noteFrequencies.get(28)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(30) + noteFrequencies.get(29)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(31) + noteFrequencies.get(30)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(32) + noteFrequencies.get(31)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(33) + noteFrequencies.get(32)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(34) + noteFrequencies.get(33)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(35) + noteFrequencies.get(34)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(36) + noteFrequencies.get(35)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(37) + noteFrequencies.get(36)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(38) + noteFrequencies.get(37)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(39) + noteFrequencies.get(38)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(40) + noteFrequencies.get(39)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(41) + noteFrequencies.get(40)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(42) + noteFrequencies.get(41)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(43) + noteFrequencies.get(42)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(44) + noteFrequencies.get(43)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(45) + noteFrequencies.get(44)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(46) + noteFrequencies.get(45)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(47) + noteFrequencies.get(46)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(48) + noteFrequencies.get(47)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(49) + noteFrequencies.get(48)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(50) + noteFrequencies.get(49)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(51) + noteFrequencies.get(50)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(52) + noteFrequencies.get(51)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(53) + noteFrequencies.get(52)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(54) + noteFrequencies.get(53)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(55) + noteFrequencies.get(54)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(56) + noteFrequencies.get(55)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(57) + noteFrequencies.get(56)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(58) + noteFrequencies.get(57)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(59) + noteFrequencies.get(58)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(60) + noteFrequencies.get(59)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(61) + noteFrequencies.get(60)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(62) + noteFrequencies.get(61)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(63) + noteFrequencies.get(62)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(64) + noteFrequencies.get(63)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(65) + noteFrequencies.get(64)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(66) + noteFrequencies.get(65)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(67) + noteFrequencies.get(66)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(68) + noteFrequencies.get(67)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(69) + noteFrequencies.get(68)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(70) + noteFrequencies.get(69)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(71) + noteFrequencies.get(70)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(72) + noteFrequencies.get(71)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(73) + noteFrequencies.get(72)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(74) + noteFrequencies.get(73)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(75) + noteFrequencies.get(74)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(76) + noteFrequencies.get(75)) / 4)); assertEquals( "0.25 half steps flatter than C sharp, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(77) + noteFrequencies.get(76)) / 4)); assertEquals( "0.25 half steps flatter than D, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(78) + noteFrequencies.get(77)) / 4)); assertEquals( "0.25 half steps flatter than E flat, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(79) + noteFrequencies.get(78)) / 4)); assertEquals( "0.25 half steps flatter than E, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(80) + noteFrequencies.get(79)) / 4)); assertEquals( "0.25 half steps flatter than F, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(81) + noteFrequencies.get(80)) / 4)); assertEquals( "0.25 half steps flatter than F sharp, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(82) + noteFrequencies.get(81)) / 4)); assertEquals( "0.25 half steps flatter than G, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(83) + noteFrequencies.get(82)) / 4)); assertEquals( "0.25 half steps flatter than A flat, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(84) + noteFrequencies.get(83)) / 4)); assertEquals( "0.25 half steps flatter than A, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(85) + noteFrequencies.get(84)) / 4)); assertEquals( "0.25 half steps flatter than B flat, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(86) + noteFrequencies.get(85)) / 4)); assertEquals( "0.25 half steps flatter than B, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(87) + noteFrequencies.get(86)) / 4)); assertEquals( "0.25 half steps flatter than C, octave 8", getContentDescriptionForPitch((3 * noteFrequencies.get(88) + noteFrequencies.get(87)) / 4)); assertEquals( "high pitch", getContentDescriptionForPitch((3 * noteFrequencies.get(89) + noteFrequencies.get(88)) / 4)); } @Test public void makeContentDescriptionSharper() throws Exception { if (noteFrequencies.isEmpty()) { fillNoteLists(); } assertEquals( "low pitch", getContentDescriptionForPitch((3 * noteFrequencies.get(0) + noteFrequencies.get(1)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 0", getContentDescriptionForPitch((3 * noteFrequencies.get(1) + noteFrequencies.get(2)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 0", getContentDescriptionForPitch((3 * noteFrequencies.get(2) + noteFrequencies.get(3)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 0", getContentDescriptionForPitch((3 * noteFrequencies.get(3) + noteFrequencies.get(4)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(4) + noteFrequencies.get(5)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(5) + noteFrequencies.get(6)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(6) + noteFrequencies.get(7)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(7) + noteFrequencies.get(8)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(8) + noteFrequencies.get(9)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(9) + noteFrequencies.get(10)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(10) + noteFrequencies.get(11)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(11) + noteFrequencies.get(12)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(12) + noteFrequencies.get(13)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(13) + noteFrequencies.get(14)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(14) + noteFrequencies.get(15)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 1", getContentDescriptionForPitch((3 * noteFrequencies.get(15) + noteFrequencies.get(16)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(16) + noteFrequencies.get(17)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(17) + noteFrequencies.get(18)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(18) + noteFrequencies.get(19)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(19) + noteFrequencies.get(20)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(20) + noteFrequencies.get(21)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(21) + noteFrequencies.get(22)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(22) + noteFrequencies.get(23)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(23) + noteFrequencies.get(24)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(24) + noteFrequencies.get(25)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(25) + noteFrequencies.get(26)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(26) + noteFrequencies.get(27)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 2", getContentDescriptionForPitch((3 * noteFrequencies.get(27) + noteFrequencies.get(28)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(28) + noteFrequencies.get(29)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(29) + noteFrequencies.get(30)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(30) + noteFrequencies.get(31)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(31) + noteFrequencies.get(32)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(32) + noteFrequencies.get(33)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(33) + noteFrequencies.get(34)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(34) + noteFrequencies.get(35)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(35) + noteFrequencies.get(36)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(36) + noteFrequencies.get(37)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(37) + noteFrequencies.get(38)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(38) + noteFrequencies.get(39)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 3", getContentDescriptionForPitch((3 * noteFrequencies.get(39) + noteFrequencies.get(40)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(40) + noteFrequencies.get(41)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(41) + noteFrequencies.get(42)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(42) + noteFrequencies.get(43)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(43) + noteFrequencies.get(44)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(44) + noteFrequencies.get(45)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(45) + noteFrequencies.get(46)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(46) + noteFrequencies.get(47)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(47) + noteFrequencies.get(48)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(48) + noteFrequencies.get(49)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(49) + noteFrequencies.get(50)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(50) + noteFrequencies.get(51)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 4", getContentDescriptionForPitch((3 * noteFrequencies.get(51) + noteFrequencies.get(52)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(52) + noteFrequencies.get(53)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(53) + noteFrequencies.get(54)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(54) + noteFrequencies.get(55)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(55) + noteFrequencies.get(56)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(56) + noteFrequencies.get(57)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(57) + noteFrequencies.get(58)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(58) + noteFrequencies.get(59)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(59) + noteFrequencies.get(60)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(60) + noteFrequencies.get(61)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(61) + noteFrequencies.get(62)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(62) + noteFrequencies.get(63)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 5", getContentDescriptionForPitch((3 * noteFrequencies.get(63) + noteFrequencies.get(64)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(64) + noteFrequencies.get(65)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(65) + noteFrequencies.get(66)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(66) + noteFrequencies.get(67)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(67) + noteFrequencies.get(68)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(68) + noteFrequencies.get(69)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(69) + noteFrequencies.get(70)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(70) + noteFrequencies.get(71)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(71) + noteFrequencies.get(72)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(72) + noteFrequencies.get(73)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(73) + noteFrequencies.get(74)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(74) + noteFrequencies.get(75)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 6", getContentDescriptionForPitch((3 * noteFrequencies.get(75) + noteFrequencies.get(76)) / 4)); assertEquals( "0.25 half steps sharper than C, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(76) + noteFrequencies.get(77)) / 4)); assertEquals( "0.25 half steps sharper than C sharp, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(77) + noteFrequencies.get(78)) / 4)); assertEquals( "0.25 half steps sharper than D, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(78) + noteFrequencies.get(79)) / 4)); assertEquals( "0.25 half steps sharper than E flat, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(79) + noteFrequencies.get(80)) / 4)); assertEquals( "0.25 half steps sharper than E, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(80) + noteFrequencies.get(81)) / 4)); assertEquals( "0.25 half steps sharper than F, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(81) + noteFrequencies.get(82)) / 4)); assertEquals( "0.25 half steps sharper than F sharp, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(82) + noteFrequencies.get(83)) / 4)); assertEquals( "0.25 half steps sharper than G, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(83) + noteFrequencies.get(84)) / 4)); assertEquals( "0.25 half steps sharper than A flat, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(84) + noteFrequencies.get(85)) / 4)); assertEquals( "0.25 half steps sharper than A, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(85) + noteFrequencies.get(86)) / 4)); assertEquals( "0.25 half steps sharper than B flat, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(86) + noteFrequencies.get(87)) / 4)); assertEquals( "0.25 half steps sharper than B, octave 7", getContentDescriptionForPitch((3 * noteFrequencies.get(87) + noteFrequencies.get(88)) / 4)); assertEquals("high pitch", getContentDescriptionForPitch(noteFrequencies.get(89) + 1)); } }
60.181022
113
0.69639
7393e90ff3bf09dfaa5c4f33093c0a4f4a941e85
1,860
package cn.stylefeng.guns.config; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HttpsConfig { @Value("${server.port}") private int httpsPort; @Value("${http.port}") private int httpPort; @Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(initiateHttpConnector()); return tomcat; } private Connector initiateHttpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(httpPort); connector.setSecure(false); connector.setRedirectPort(httpsPort); return connector; } }
40.434783
91
0.705914
02599728b8f04d62e68748c5d2cee6e860f0bc98
4,727
package com.github.k24.rrrpagination.usecase; import com.github.k24.rrrpagination.entity.GithubRepository; import com.github.k24.rrrpagination.entity.PaginationResult; import com.github.k24.rrrpagination.gateway.GithubSearchGateway; import com.github.k24.rrrpagination.presentation.DummyContent; import com.github.k24.rrrpagination.presentation.GithubRepositoryPresentation; import java.util.List; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.subjects.BehaviorSubject; /** * Created by k24 on 2016/12/06. */ public class GithubRepositoryUseCase { private final GithubSearchGateway githubSearchGateway = new GithubSearchGateway(); private BehaviorSubject<Observable<PaginationResult<List<GithubRepository>>>> searchSubject; private GithubRepositoryPresentation presentation; private Observable<PaginationResult<List<GithubRepository>>> nextPagination; public GithubRepositoryUseCase bind(GithubRepositoryPresentation presentation) { this.presentation = presentation; return this; } private GithubRepositoryPresentation presentation() { return presentation != null && presentation.isViewAvailable() ? presentation : GithubRepositoryPresentation.NULL; } public Subscription loadRepositories() { searchSubject = BehaviorSubject.create(githubSearchGateway.repositories("android", "language:java")); return searchSubject .flatMap(new Func1<Observable<PaginationResult<List<GithubRepository>>>, Observable<PaginationResult<List<GithubRepository>>>>() { @Override public Observable<PaginationResult<List<GithubRepository>>> call(Observable<PaginationResult<List<GithubRepository>>> paginationResultObservable) { return paginationResultObservable; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<PaginationResult<List<GithubRepository>>>() { @Override public void call(PaginationResult<List<GithubRepository>> listPaginationResult) { List<GithubRepository> result = listPaginationResult.getResult(); nextPagination = listPaginationResult.getNext(); if (DummyContent.ITEMS.isEmpty()) { if (result.isEmpty()) { showEmptyView(); } else { refreshViews(result); } } else { addRepositories(result); } } }); } public boolean nextPage() { Observable<PaginationResult<List<GithubRepository>>> nextPagination = this.nextPagination; this.nextPagination = null; if (searchSubject == null || nextPagination == null) return false; searchSubject.onNext(nextPagination); return true; } private void showEmptyView() { presentation().showEmptyView(); } private void refreshViews(List<GithubRepository> repositories) { GithubRepositoryPresentation presentation = presentation(); if (!presentation.isViewAvailable()) return; presentation.refreshViews(convertToItems(repositories)); } private void addRepositories(List<GithubRepository> repositories) { GithubRepositoryPresentation presentation = presentation(); if (!presentation.isViewAvailable()) return; presentation.addItems(convertToItems(repositories)); } // Transform private static List<DummyContent.DummyItem> convertToItems(List<GithubRepository> repositories) { return Observable.just(repositories) .flatMapIterable(new Func1<List<GithubRepository>, Iterable<GithubRepository>>() { @Override public Iterable<GithubRepository> call(List<GithubRepository> repositories) { return repositories; } }) .map(new Func1<GithubRepository, DummyContent.DummyItem>() { @Override public DummyContent.DummyItem call(GithubRepository githubRepository) { return new DummyContent.DummyItem(String.valueOf(githubRepository.id), githubRepository.full_name, githubRepository.description); } }) .toList() .toBlocking() .single(); } }
42.972727
167
0.642479
df265272b2ca053d332a5db74eb25af9b12e53db
752
package es.com.blogspot.elblogdepicodev.activiti.misc; import org.activiti.engine.impl.pvm.PvmTransition; import org.activiti.engine.impl.pvm.delegate.ActivityBehavior; import org.activiti.engine.impl.pvm.delegate.ActivityExecution; public class ComprobarExistenciasServiceTask implements ActivityBehavior { @Override public void execute(ActivityExecution execution) throws Exception { PvmTransition transition = null; Producto producto = (Producto) execution.getVariable("producto"); if (producto.hayExistencias()) { transition = execution.getActivity().findOutgoingTransition("flowHayExistencias"); } else { transition = execution.getActivity().findOutgoingTransition("flowNoHayExistencias"); } execution.take(transition); } }
37.6
87
0.804521
db0c34b4934bebd9c867dc478f4d953149918ecc
1,086
package org.myrobotlab.speech; import java.io.IOException; import edu.cmu.sphinx.jsgf.JSGFGrammarException; import edu.cmu.sphinx.jsgf.JSGFGrammarParseException; /** * A Dialog node behavior that loads a completely new grammar upon entry into * the node */ public class NewGrammarDialogNodeBehavior extends DialogNodeBehavior { /** * creates a NewGrammarDialogNodeBehavior * * @param grammarName * the grammar name */ public NewGrammarDialogNodeBehavior() { } /** * Called with the dialog manager enters this entry */ public void onEntry() throws IOException { super.onEntry(); try { getGrammar().loadJSGF(getGrammarName()); } catch (JSGFGrammarParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSGFGrammarException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Returns the name of the grammar. The name of the grammar is the same as * the name of the node * * @return the grammar name */ public String getGrammarName() { return getName(); } }
22.163265
77
0.706262
4ab4dbc3cc74b03c97a387a5c209e09925c2511e
4,107
package toolkit.eventbus; import io.vertx.core.eventbus.EventBus; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.gaussian.amplifix.toolkit.datagrid.DropRegistry; import org.gaussian.amplifix.toolkit.eventbus.AmplifixEventBus; import org.gaussian.amplifix.toolkit.eventbus.AmplifixSender; import org.gaussian.amplifix.toolkit.eventbus.EventConsumer; import org.gaussian.amplifix.toolkit.model.TagSerializable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import toolkit.factory.domain.AuthorizeResponse; import toolkit.factory.domain.OrderResponse; import toolkit.factory.domain.SessionResponse; import static java.time.Instant.now; import static java.util.Arrays.asList; import static java.util.UUID.randomUUID; import static org.mockito.Mockito.clearInvocations; import static org.mockito.MockitoAnnotations.initMocks; import static toolkit.eventbus.MessageValidationHelper.assertValidConversionMessage; import static toolkit.eventbus.MessageValidationHelper.assertValidDropMessage; import static toolkit.eventbus.MessageValidationHelper.assertValidOrderResponseMessage; import static toolkit.eventbus.MessageValidationHelper.assertValidSessionResponseMessage; import static toolkit.eventbus.MessageValidationHelper.assertValidTraceSessionResponseMessage; import static toolkit.factory.domain.Status.APPROVED; @RunWith(VertxUnitRunner.class) public class AmplifixSenderTest { @Rule public final RunTestOnContext context = new RunTestOnContext(); @Mock private EventConsumer consumer; @Before public void setup() { clearInvocations(); initMocks(this); } public AmplifixSender createSender(EventBus eventBus, EventConsumer consumer) { AmplifixEventBus amplifixEventBus = new AmplifixEventBus(eventBus); amplifixEventBus.setConsumer(consumer); return new AmplifixSender(amplifixEventBus); } @Test public void createSession(TestContext testContext) { EventBus eventBus = context.vertx().eventBus(); eventBus.localConsumer("amplifix.events", assertValidSessionResponseMessage(testContext)); SessionResponse sessionResponse = new SessionResponse("test session response", "SE", now()); createSender(eventBus, consumer).send(sessionResponse); } @Test public void conversion(TestContext testContext) { EventBus eventBus = context.vertx().eventBus(); eventBus.localConsumer("amplifix.events", assertValidConversionMessage(testContext)); AuthorizeResponse authorizeResponse = new AuthorizeResponse("invoice", APPROVED); createSender(eventBus, consumer).send(authorizeResponse, "mock.session.id"); } @Test public void drop(TestContext testContext) { EventBus eventBus = context.vertx().eventBus(); eventBus.localConsumer("amplifix.events", assertValidDropMessage(testContext)); TagSerializable tags = new TagSerializable("country", "BR"); DropRegistry dropRegistry = new DropRegistry("session_drop", "session_id", randomUUID().toString(), asList(tags), "AuthorizeResponse", now()); createSender(eventBus, consumer).send(dropRegistry); } @Test public void createOrder(TestContext testContext) { EventBus eventBus = context.vertx().eventBus(); eventBus.localConsumer("amplifix.events", assertValidOrderResponseMessage(testContext)); OrderResponse orderResponse = new OrderResponse("invoice", APPROVED); createSender(eventBus, consumer).send(orderResponse); } @Test public void traceCreateSession(TestContext testContext) { EventBus eventBus = context.vertx().eventBus(); eventBus.localConsumer("amplifix.events", assertValidTraceSessionResponseMessage(testContext)); SessionResponse sessionResponse = new SessionResponse("test session response", "SE", now()); createSender(eventBus, consumer).trace(sessionResponse); } }
43.231579
150
0.770392
61901783f54e551a346b2504a06e4f778becfccb
3,931
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dfp.axis.v201702.activitygroupservice; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.dfp.axis.factory.DfpServices; import com.google.api.ads.dfp.axis.utils.v201702.StatementBuilder; import com.google.api.ads.dfp.axis.v201702.ActivityGroup; import com.google.api.ads.dfp.axis.v201702.ActivityGroupPage; import com.google.api.ads.dfp.axis.v201702.ActivityGroupServiceInterface; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; import com.google.common.collect.Iterables; import com.google.common.primitives.Longs; import java.util.Arrays; /** * This example updates activity groups by adding a company. To determine which * activity groups exist, run GetAllActivityGroups.java. * * Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class UpdateActivityGroups { // Set the ID of the activity group to update. private static final String ACTIVITY_GROUP_ID = "INSERT_ACTIVITY_GROUP_ID_HERE"; //Set the ID of the company to associate with the activity group. private static final String ADVERTISER_COMPANY_ID = "INSERT_ADVERTISER_COMPANY_ID_HERE"; public static void runExample(DfpServices dfpServices, DfpSession session, int activityGroupId, long advertiserCompanyId) throws Exception { // Get the ActivityGroupService. ActivityGroupServiceInterface activityGroupService = dfpServices.get(session, ActivityGroupServiceInterface.class); // Create a statement to only select a single activity group by ID. StatementBuilder statementBuilder = new StatementBuilder() .where("id = :id") .orderBy("id ASC") .limit(1) .withBindVariableValue("id", activityGroupId); // Get the activity group. ActivityGroupPage page = activityGroupService.getActivityGroupsByStatement(statementBuilder.toStatement()); ActivityGroup activityGroup = Iterables.getOnlyElement(Arrays.asList(page.getResults())); // Update the companies. activityGroup.setCompanyIds( Longs.concat(activityGroup.getCompanyIds(), new long[] {advertiserCompanyId})); // Update the activity group on the server. ActivityGroup[] activityGroups = activityGroupService.updateActivityGroups(new ActivityGroup[] {activityGroup}); for (ActivityGroup updatedActivityGroup : activityGroups) { System.out.printf( "Activity group with ID %d and name '%s' was updated.%n", updatedActivityGroup.getId(), updatedActivityGroup.getName()); } } public static void main(String[] args) throws Exception { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.DFP) .fromFile() .build() .generateCredential(); // Construct a DfpSession. DfpSession session = new DfpSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build(); DfpServices dfpServices = new DfpServices(); runExample(dfpServices, session, Integer.parseInt(ACTIVITY_GROUP_ID), Long.parseLong(ADVERTISER_COMPANY_ID)); } }
39.707071
93
0.745103
b1a6ff7cf78513b889cafffcb63764f53b135538
468
package br.com.zupacademy.sergio.ecommerce.model.dto; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.Stream; public class UploadedImagesDto { private final Collection<ImageDto> uploadedImages; public UploadedImagesDto(Stream<ImageDto> uploadedImages) { this.uploadedImages = uploadedImages.collect(Collectors.toList()); } public Collection<ImageDto> getUploadedImages() { return this.uploadedImages; } }
26
70
0.786325
0160f4da215c0dbf2a741077f1e50122dd4852d5
4,376
/** * Copyright 2016 Pinterest, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pinterest.teletraan.resource; import com.pinterest.deployservice.bean.EnvironBean; import com.pinterest.deployservice.bean.Resource; import com.pinterest.deployservice.bean.Role; import com.pinterest.deployservice.common.Constants; import com.pinterest.deployservice.dao.EnvironDAO; import com.pinterest.deployservice.handler.ConfigHistoryHandler; import com.pinterest.deployservice.handler.EnvironHandler; import com.pinterest.teletraan.TeletraanServiceContext; import com.pinterest.teletraan.security.Authorizer; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.Valid; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import java.util.Map; @Path("/v1/envs/{envName : [a-zA-Z0-9\\-_]+}/{stageName : [a-zA-Z0-9\\-_]+}/agent_configs") @Api(value = "/Environments", description = "Environment info APIs") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class EnvAgentConfigs { private static final Logger LOG = LoggerFactory.getLogger(EnvAgentConfigs.class); private EnvironDAO environDAO; private EnvironHandler environHandler; private ConfigHistoryHandler configHistoryHandler; private Authorizer authorizer; @Context UriInfo uriInfo; public EnvAgentConfigs(TeletraanServiceContext context) { environDAO = context.getEnvironDAO(); environHandler = new EnvironHandler(context); configHistoryHandler = new ConfigHistoryHandler(context); authorizer = context.getAuthorizer(); } @GET @ApiOperation( value = "Get agent configs", notes = "Returns a name,value map of environment agent configs given an environment name and stage name", response = String.class, responseContainer = "Map") public Map<String, String> get( @ApiParam(value = "Environment name", required = true)@PathParam("envName") String envName, @ApiParam(value = "Stage name", required = true)@PathParam("stageName") String stageName) throws Exception { EnvironBean envBean = Utils.getEnvStage(environDAO, envName, stageName); return environHandler.getAdvancedConfigs(envBean); } @PUT @ApiOperation( value = "Update agent configs", notes = "Updates environment agent configs given an environment name and stage name with a map of " + "name,value agent configs") public void update( @ApiParam(value = "Environment name", required = true)@PathParam("envName") String envName, @ApiParam(value = "Stage name", required = true)@PathParam("stageName") String stageName, @ApiParam(value = "Map of configs to update with", required = true)@Valid Map<String, String> configs, @Context SecurityContext sc) throws Exception { EnvironBean envBean = Utils.getEnvStage(environDAO, envName, stageName); authorizer.authorize(sc, new Resource(envBean.getEnv_name(), Resource.Type.ENV), Role.OPERATOR); String userName = sc.getUserPrincipal().getName(); environHandler.updateAdvancedConfigs(envBean, configs, userName); configHistoryHandler.updateConfigHistory(envBean.getEnv_id(), Constants.TYPE_ENV_ADVANCED, configs, userName); configHistoryHandler.updateChangeFeed(Constants.CONFIG_TYPE_ENV, envBean.getEnv_id(), Constants.TYPE_ENV_ADVANCED, userName); LOG.info("Successfully updated agent config {} for env {}/{} by {}.", configs, envName, stageName, userName); } }
46.553191
133
0.730804
00547bf156ebb97b236c80ff182d6c32b2887cd0
1,335
class Solution { public int numMagicSquaresInside(int[][] grid) { int res = 0; for(int i=0; i <= grid.length-3; i++) for(int j=0; j <= grid[0].length-3; j++) if(helper(i, j, grid)) res++; return res; } private boolean helper(int x, int y, int[][] grid) { if(grid[x+1][y+1] != 5) return false; // middle one has to be 5 // check distinct element from 1-9 int[] valid = new int[16]; // possible element 0 - 15 for(int i=x; i<=x+2; i++) for(int j=y; j<=y+2; j++) valid[grid[i][j]]++; for (int v = 1; v <= 9; v++) if (valid[v] != 1) return false; // check two rows, the total is fixed due to 1-9, no need to check the third if(grid[x][y] + grid[x][y+1] + grid[x][y+2] != 15) return false; if(grid[x+1][y] + grid[x+1][y+1] + grid[x+1][y+2] != 15) return false; // check two cols if(grid[x][y] + grid[x+1][y] + grid[x+2][y] != 15) return false; if(grid[x][y+1] + grid[x+1][y+1] + grid[x+2][y+1] != 15) return false; // check diagonal if(grid[x][y] + grid[x+1][y+1] + grid[x+2][y+2] != 15) return false; if(grid[x][y+2] + grid[x+1][y+1] + grid[x+2][y] != 15) return false; return true; } }
41.71875
84
0.476404
4a5d50f726558f8c4b3b33af9c44848445c4b28b
3,448
/* * Copyright 2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ws.salient.knowledge; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Locale; import static junit.framework.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.marshalling.Marshaller; import org.kie.api.marshalling.ObjectMarshallingStrategy; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.process.WorkItemHandler; import org.kie.internal.marshalling.MarshallerFactory; import static org.mockito.Mockito.mock; import ws.salient.examples.chat.Chat; import ws.salient.examples.chat.Message; import ws.salient.examples.chat.Message.Intent; import ws.salient.knowledge.SerializableStrategy.Format; import static ws.salient.knowledge.SerializableStrategy.Format.FST; import static ws.salient.knowledge.SerializableStrategy.Format.JAVA; public class SerializableStrategyTest { KieContainer kcontainer; KieBase kbase; KieSession ksession; WorkItemHandler functionHandler; @Before public void before() { kcontainer = KieServices.Factory.get().getKieClasspathContainer(); kbase = kcontainer.getKieBase("ws.salient.examples.chat"); ksession = kbase.newKieSession(); ksession.setGlobal("chat", new Chat(ksession, Locale.US, kcontainer.getClassLoader())); functionHandler = mock(WorkItemHandler.class); ksession.getWorkItemManager().registerWorkItemHandler("ws.salient.examples.chat.FunctionHandler", functionHandler); } @Test public void javaSerialize() throws Exception { serialize(JAVA, 876); } @Test public void fstSerialize() throws Exception { serialize(FST, 665); } public void serialize(Format format, int expectedSize) throws Exception { Marshaller marshaller = MarshallerFactory.newMarshaller(kbase, new ObjectMarshallingStrategy[] { new SerializableStrategy(kcontainer.getClassLoader(), format) }); ksession.insert(new Message("hi", Intent.HELLO)); ksession.fireAllRules(); ByteArrayOutputStream sessionOut = new ByteArrayOutputStream(); marshaller.marshall(sessionOut, ksession); byte[] sessionBytes = sessionOut.toByteArray(); assertEquals(expectedSize, sessionBytes.length); ksession = kbase.newKieSession(); marshaller.unmarshall(new ByteArrayInputStream(sessionBytes), ksession); assertEquals(1, ksession.getFactCount()); assertEquals(1, ksession.getProcessInstances().size()); } }
35.183673
124
0.703016
1ad7bd04146f649c139797776a087813e72e6a7f
7,347
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.epam.datalab.backendapi.service.impl; import com.epam.datalab.backendapi.dao.ProjectDAO; import com.epam.datalab.backendapi.dao.UserGroupDAO; import com.epam.datalab.backendapi.dao.UserRoleDAO; import com.epam.datalab.backendapi.domain.ProjectDTO; import com.epam.datalab.backendapi.resources.TestBase; import com.epam.datalab.backendapi.resources.dto.UserGroupDto; import com.epam.datalab.dto.UserInstanceStatus; import com.epam.datalab.exceptions.DatalabException; import com.epam.datalab.exceptions.ResourceNotFoundException; import io.dropwizard.auth.AuthenticationException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; import java.util.HashSet; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.anySet; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UserGroupServiceImplTest extends TestBase { private static final String ROLE_ID = "Role id"; private static final String USER = "test"; private static final String GROUP = "admin"; @Mock private UserRoleDAO userRoleDao; @Mock private UserGroupDAO userGroupDao; @Mock private ProjectDAO projectDAO; @InjectMocks private UserGroupServiceImpl userGroupService; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setup() throws AuthenticationException { authSetup(); } @Test public void createGroup() { when(userRoleDao.addGroupToRole(anySet(), anySet())).thenReturn(true); userGroupService.createGroup(getUserInfo(), GROUP, Collections.singleton(ROLE_ID), Collections.singleton(USER)); verify(userRoleDao).addGroupToRole(Collections.singleton(GROUP), Collections.singleton(ROLE_ID)); verify(userGroupDao).addUsers(GROUP, Collections.singleton(USER)); } @Test public void createGroupWithNoUsers() { when(userRoleDao.addGroupToRole(anySet(), anySet())).thenReturn(true); userGroupService.createGroup(getUserInfo(), GROUP, Collections.singleton(ROLE_ID), Collections.emptySet()); verify(userRoleDao).addGroupToRole(Collections.singleton(GROUP), Collections.singleton(ROLE_ID)); verify(userGroupDao).addUsers(anyString(), anySet()); } @Test public void createGroupWhenRoleNotFound() { when(userRoleDao.addGroupToRole(anySet(), anySet())).thenReturn(false); expectedException.expect(ResourceNotFoundException.class); userGroupService.createGroup(getUserInfo(), GROUP, Collections.singleton(ROLE_ID), Collections.singleton(USER)); } @Test public void removeGroup() { when(userRoleDao.removeGroup(anyString())).thenReturn(true); final ProjectDTO projectDTO = new ProjectDTO( "name", Collections.emptySet(), "", "", null, Collections.emptyList(), true); when(projectDAO.getProjectsWithEndpointStatusNotIn(UserInstanceStatus.TERMINATED, UserInstanceStatus.TERMINATING)).thenReturn(Collections.singletonList(projectDTO)); doNothing().when(userGroupDao).removeGroup(anyString()); userGroupService.removeGroup(getUserInfo(), GROUP); verify(userRoleDao).removeGroup(GROUP); verify(userGroupDao).removeGroup(GROUP); verifyNoMoreInteractions(userGroupDao, userRoleDao); } @Test public void removeGroupWhenItIsUsedInProject() { when(userRoleDao.removeGroup(anyString())).thenReturn(true); when(projectDAO.getProjectsWithEndpointStatusNotIn(UserInstanceStatus.TERMINATED, UserInstanceStatus.TERMINATING)).thenReturn(Collections.singletonList(new ProjectDTO( "name", Collections.singleton(GROUP), "", "", null, Collections.emptyList(), true))); doNothing().when(userGroupDao).removeGroup(anyString()); try { userGroupService.removeGroup(getUserInfo(), GROUP); } catch (Exception e) { assertEquals("Group can not be removed because it is used in some project", e.getMessage()); } verify(userRoleDao, never()).removeGroup(GROUP); verify(userGroupDao, never()).removeGroup(GROUP); verifyNoMoreInteractions(userGroupDao, userRoleDao); } @Test public void removeGroupWhenGroupNotExist() { final ProjectDTO projectDTO = new ProjectDTO( "name", Collections.emptySet(), "", "", null, Collections.emptyList(), true); when(projectDAO.getProjectsWithEndpointStatusNotIn(UserInstanceStatus.TERMINATED, UserInstanceStatus.TERMINATING)).thenReturn(Collections.singletonList(projectDTO)); when(userRoleDao.removeGroup(anyString())).thenReturn(false); doNothing().when(userGroupDao).removeGroup(anyString()); userGroupService.removeGroup(getUserInfo(), GROUP); verify(userRoleDao).removeGroup(GROUP); verify(userGroupDao).removeGroup(GROUP); verifyNoMoreInteractions(userGroupDao, userRoleDao); } @Test public void removeGroupWithException() { final ProjectDTO projectDTO = new ProjectDTO( "name", Collections.emptySet(), "", "", null, Collections.emptyList(), true); when(projectDAO.getProjectsWithEndpointStatusNotIn(UserInstanceStatus.TERMINATED, UserInstanceStatus.TERMINATING)).thenReturn(Collections.singletonList(projectDTO)); when(userRoleDao.removeGroup(anyString())).thenThrow(new DatalabException("Exception")); expectedException.expectMessage("Exception"); expectedException.expect(DatalabException.class); userGroupService.removeGroup(getUserInfo(), GROUP); } private UserGroupDto getUserGroup() { return new UserGroupDto(GROUP, Collections.emptyList(), Collections.emptySet()); } private List<ProjectDTO> getProjects() { return Collections.singletonList(ProjectDTO.builder() .groups(new HashSet<>(Collections.singletonList(GROUP))) .build()); } }
40.368132
120
0.729549
a16a7d5d8284fb6953748a10090934bd130a7793
3,782
package com.ipd.jmq.common.network.v3.command; import com.ipd.jmq.common.message.Message; import com.ipd.jmq.common.network.v3.session.ProducerId; import com.ipd.jmq.common.network.v3.session.TransactionId; import com.ipd.jmq.toolkit.lang.Preconditions; import java.util.Arrays; /** * 生产消息 */ public class PutMessage extends JMQPayload { // 生产者ID private ProducerId producerId; // 事务ID private TransactionId transactionId; // 消息数组 private Message[] messages; // 队列ID private short queueId; public ProducerId getProducerId() { return this.producerId; } public void setProducerId(ProducerId producerId) { this.producerId = producerId; } public PutMessage queueId(final short queueId) { setQueueId(queueId); return this; } public PutMessage transactionId(final TransactionId transactionId) { setTransactionId(transactionId); return this; } public PutMessage producerId(final ProducerId producerId) { setProducerId(producerId); return this; } public PutMessage messages(final Message... messages) { setMessages(messages); return this; } public TransactionId getTransactionId() { return this.transactionId; } public void setTransactionId(TransactionId transactionId) { this.transactionId = transactionId; } public Message[] getMessages() { return this.messages; } public void setMessages(Message[] messages) { this.messages = messages; } public short getQueueId() { return queueId; } public void setQueueId(short queueId) { this.queueId = queueId; } @Override public int predictionSize() { int size = Serializer.getPredictionSize(producerId.getProducerId()); if (transactionId != null) { size += Serializer.getPredictionSize(transactionId.getTransactionId()); } else { size += 1; } size += Serializer.getPredictionSize(messages); return size + 1; } @Override public void validate() { super.validate(); Preconditions.checkArgument(producerId != null, "productId must note be null"); } @Override public String toString() { final StringBuilder sb = new StringBuilder("PutMessage{"); sb.append("producerId=").append(producerId); sb.append(", transactionId=").append(transactionId); sb.append(", messages=").append(Arrays.toString(messages)); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } PutMessage that = (PutMessage) o; if (!Arrays.equals(messages, that.messages)) { return false; } if (producerId != null ? !producerId.equals(that.producerId) : that.producerId != null) { return false; } if (transactionId != null ? !transactionId.equals(that.transactionId) : that.transactionId != null) { return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (producerId != null ? producerId.hashCode() : 0); result = 31 * result + (transactionId != null ? transactionId.hashCode() : 0); result = 31 * result + (messages != null ? Arrays.hashCode(messages) : 0); return result; } @Override public int type() { return CmdTypes.PUT_MESSAGE; } }
26.263889
109
0.608408
290bca7abf87e447a711f27e4ce7e1eae5c6cd2a
1,965
package com.paypal.kyc.service.impl; import com.hyperwallet.clientsdk.model.HyperwalletWebhookNotification; import com.paypal.infrastructure.converter.Converter; import com.paypal.kyc.model.KYCBusinessStakeholderStatusNotificationBodyModel; import com.paypal.kyc.strategies.status.impl.KYCBusinessStakeholderStatusFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class KYCBusinessStakeholderNotificationServiceImplTest { @InjectMocks private KYCBusinessStakeholderNotificationServiceImpl testObj; @Mock private Converter<Object, KYCBusinessStakeholderStatusNotificationBodyModel> hyperWalletObjectToKYCBusinessStakeholderStatusNotificationBodyModelConverterMock; @Mock private KYCBusinessStakeholderStatusFactory kycBusinessStakeholderStatusFactoryMock; @Mock private HyperwalletWebhookNotification hyperwalletWebhookNotificationMock; @Mock private Object notificationObjectMock; @Mock private KYCBusinessStakeholderStatusNotificationBodyModel kycBusinessStakeholderNotificationMock; @Test void updateBusinessStakeholderKYCStatus_shouldConvertAndTreatThenIncomingNotification() { when(hyperwalletWebhookNotificationMock.getObject()).thenReturn(notificationObjectMock); when(hyperWalletObjectToKYCBusinessStakeholderStatusNotificationBodyModelConverterMock .convert(notificationObjectMock)).thenReturn(kycBusinessStakeholderNotificationMock); testObj.updateBusinessStakeholderKYCStatus(hyperwalletWebhookNotificationMock); verify(hyperWalletObjectToKYCBusinessStakeholderStatusNotificationBodyModelConverterMock) .convert(notificationObjectMock); verify(kycBusinessStakeholderStatusFactoryMock).execute(kycBusinessStakeholderNotificationMock); } }
38.529412
160
0.882443
d76a02b9e0d1e7e9f3ba16fa1a52838c9f13e705
9,454
/* * Copyright 2018 Soojeong Shin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.bakingapp.ui.detail; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.android.bakingapp.AppExecutors; import com.example.android.bakingapp.R; import com.example.android.bakingapp.data.RecipeDatabase; import com.example.android.bakingapp.data.ShoppingListEntry; import com.example.android.bakingapp.databinding.FragmentMasterListIngredientsBinding; import com.example.android.bakingapp.model.Ingredient; import com.example.android.bakingapp.model.Recipe; import com.example.android.bakingapp.utilities.InjectorUtils; import java.util.ArrayList; import java.util.List; import static com.example.android.bakingapp.utilities.Constant.EXTRA_RECIPE; /** * The MasterListIngredientsFragment displays ingredients of the recipe. */ public class MasterListIngredientsFragment extends Fragment implements IngredientsAdapter.IngredientsAdapterOnClickHandler { /** Member variable for the Recipe */ private Recipe mRecipe; /** Member variable for IngredientsAdapter */ private IngredientsAdapter mIngredientsAdapter; /** This field is used for data binding */ private FragmentMasterListIngredientsBinding mIngredientBinding; /** ViewModel for MasterListIngredientsFragment */ private IndicesViewModel mIndicesViewModel; /** Member variable for the RecipeDatabase */ private RecipeDatabase mDb; /** The list of checked ingredient indices */ private List<Integer> mIndices; /** * Mandatory empty constructor */ public MasterListIngredientsFragment() { } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Instantiate FragmentMasterListIngredientsBinding using DataBindingUtil mIngredientBinding = DataBindingUtil.inflate( inflater, R.layout.fragment_master_list_ingredients, container, false); View rootView = mIngredientBinding.getRoot(); // Get the recipe data from the MainActivity mRecipe = getRecipeData(); // Initialize a IngredientAdapter initAdapter(); // Display the number of servings in the two-pane tablet case setNumServingsTwoPane(mRecipe); // Display the number of ingredients in the two-pane tablet case setNumIngredientsTwoPane(mRecipe); // Get the RecipeDatabase instance mDb = RecipeDatabase.getInstance(this.getContext()); return rootView; } /** * Display the number of servings in the two-pane tablet case */ private void setNumServingsTwoPane(Recipe recipe) { // This tvServings will only initially exist in the two-pane tablet case if (mIngredientBinding.tvServings != null) { String numServings = getString(R.string.servings_label) + getString(R.string.space) + String.valueOf(recipe.getServings()); mIngredientBinding.tvServings.setText(numServings); } } /** * Display the number of ingredients in the two-pane tablet case */ private void setNumIngredientsTwoPane(Recipe recipe) { // The TextView tvIngredientsLabel will only initially exist in the two-pane tablet case if (mIngredientBinding.tvIngredientsLabel != null) { String numIngredients = getString(R.string.ingredients_label) + getString(R.string.space) + getString(R.string.open_parenthesis) + recipe.getIngredients().size() + getString(R.string.close_parenthesis); mIngredientBinding.tvIngredientsLabel.setText(numIngredients); } } /** * Create a IngredientsAdapter and set it to the RecyclerView */ private void initAdapter() { // Create a new list of the ingredient and indices List<Ingredient> ingredients = new ArrayList<>(); mIndices = new ArrayList<>(); // The IngredientsAdapter is responsible for displaying each ingredient in the list mIngredientsAdapter = new IngredientsAdapter(ingredients, this, mRecipe.getName(), mIndices); // A LinearLayoutManager is responsible for measuring and positioning item views within a // RecyclerView into a linear list. LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); // Set the layout manager to the RecyclerView mIngredientBinding.rvIngredients.setLayoutManager(layoutManager); // Use this setting to improve performance if you know that changes in content do not // change the child layout size in the RecyclerView mIngredientBinding.rvIngredients.setHasFixedSize(true); // Set the IngredientsAdapter to the RecyclerView mIngredientBinding.rvIngredients.setAdapter(mIngredientsAdapter); // Add a list of ingredients to the IngredientsAdapter mIngredientsAdapter.addAll(mRecipe.getIngredients()); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Get the recipe data from the MainActivity mRecipe = getRecipeData(); // Setup indices view model setupIndicesViewModel(getActivity()); } /** * Gets recipe data from the MainActivity * * @return The Recipe data */ private Recipe getRecipeData() { Intent intent = getActivity().getIntent(); if (intent != null) { if (intent.hasExtra(EXTRA_RECIPE)) { // Receive the Recipe object which contains ID, name, ingredients, steps, servings, // and image of the recipe Bundle b = intent.getBundleExtra(EXTRA_RECIPE); mRecipe = b.getParcelable(EXTRA_RECIPE); } } return mRecipe; } /** * Every time the user data is updated, update the check state of the UI */ private void setupIndicesViewModel(Context context) { // Get the ViewModel from the factory IndicesViewModelFactory factory = InjectorUtils.provideIndicesViewModelFactory( context, mRecipe.getName()); mIndicesViewModel = ViewModelProviders.of(this, factory).get(IndicesViewModel.class); // Update the list of ingredient indices mIndicesViewModel.getIndices().observe(this, new Observer<List<Integer>>() { @Override public void onChanged(@Nullable List<Integer> integers) { mIndices = integers; mIngredientsAdapter.setIndices(mIndices); } }); } /** * This method is overridden by MasterListIngredientsFragment class in order to handle * RecyclerView item clicks. * * @param ingredientIndex Position of the ingredient in the list */ @Override public void onIngredientClick(final int ingredientIndex) { // Get ShoppingListEntry based on current recipe name and ingredient final ShoppingListEntry currentShoppingListEntry = getCurrentShoppingListEntry(ingredientIndex); if (!mIndices.contains(ingredientIndex)) { // If the current ingredient index does not exist in the list of indices, insert it into the database. AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { mDb.recipeDao().insertIngredient(currentShoppingListEntry); } }); // Show a snack bar message when a user adds an ingredient to a shopping list Snackbar.make(mIngredientBinding.getRoot(), R.string.snackbar_added, Snackbar.LENGTH_SHORT).show(); } else { } } /** * Returns ShoppingListEntry based on recipe name and ingredient * * @param ingredientIndex Position of the ingredient in the list */ private ShoppingListEntry getCurrentShoppingListEntry(int ingredientIndex) { // Get the ingredient Ingredient ingredient = mRecipe.getIngredients().get(ingredientIndex); return new ShoppingListEntry(mRecipe.getName(), ingredient.getQuantity(), ingredient.getMeasure(), ingredient.getIngredient(), ingredientIndex); } }
38.430894
114
0.694732
28e5fa4da4b534b967d672c6e94365fb8d4a72d9
4,735
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.common.xml; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * Factory class for creating an XMLReader. This factory tries to use the system property 'org.xml.sax.driver', if that * fails it falls back on javax.xml.sax.parsers.SAXParserFactory. If the SAXParserFactory class can not be found (this * can happen when using a Java 1.3 or older), or the initialization using SAXParserFactory fails otherwise, the factory * falls back on the Xerces 2 SAX Parser. */ public class XMLReaderFactory { public static final String XERCES_SAXPARSER = "org.apache.xerces.parsers.SAXParser"; /** * creates an org.xml.sax.XMLReader object. The method first tries to create the XMLReader object specified in the * 'org.xml.sax.driver' system property. If that fails, it tries to use java.xml.parsers.SAXParserFactory. If that * also fails, it tries to initialize the Xerces 2 SAX parser. If that also fails, a SAXException is thrown. * * @return an XMLReader * @throws SAXException when no default XMLReader class can be found or instantiated. */ public static XMLReader createXMLReader() throws SAXException { final Logger logger = LoggerFactory.getLogger(XMLReader.class); XMLReader reader = null; // first, try and initialize based on the system property. String xmlReaderName = System.getProperty("org.xml.sax.driver"); if (xmlReaderName != null) { try { reader = _createXMLReader(xmlReaderName); } catch (ClassNotFoundException e) { logger.warn("Class " + xmlReaderName + " not found"); } catch (ClassCastException e) { logger.warn(xmlReaderName + " is not a valid XMLReader."); } catch (Exception e) { logger.warn("could not create instance of " + xmlReaderName); } logger.debug("XMLReader initialized using system property: " + xmlReaderName); } // next, try using javax.xml.parsers.SAXParserFactory if (reader == null) { try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); reader = factory.newSAXParser().getXMLReader(); } catch (NoClassDefFoundError e) { logger.warn("javax.xml.parsers.SAXParserFactory not available"); } catch (Exception e) { logger.warn("Failed to initialize XMLReader through JAXP"); } logger.debug("XMLReader initialized using JAXP: " + reader); } // Last resort: try using the Xerces 2 SAX Parser if (reader == null) { try { reader = _createXMLReader(XERCES_SAXPARSER); } catch (ClassNotFoundException e) { String message = "Class " + XERCES_SAXPARSER + " not found"; logger.error(message); throw new SAXException(message); } catch (ClassCastException e) { String message = XERCES_SAXPARSER + " is not a valid XMLReader."; logger.error(message); throw new SAXException(message); } catch (Exception e) { String message = "Could not create instance of " + XERCES_SAXPARSER; logger.error(message); throw new SAXException(message); } logger.debug("XMLReader initialized using default Xerces SAX parser " + XERCES_SAXPARSER); } return reader; } /** * Creates an org.xml.sax.XMLReader object using the supplied name. * * @return an XMLReader * @throws SAXException when the supplied XMLReader class name can not be found or instantiated. */ public static XMLReader createXMLReader(String name) throws SAXException { final Logger logger = LoggerFactory.getLogger(XMLReader.class); XMLReader reader = null; try { reader = _createXMLReader(name); } catch (ClassNotFoundException e) { logger.error("Class " + name + " not found"); throw new SAXException(e); } catch (ClassCastException e) { logger.error(name + " is not a valid XMLReader."); throw new SAXException(e); } catch (Exception e) { logger.error("Could not create instance of " + name); throw new SAXException(e); } return reader; } protected static XMLReader _createXMLReader(String name) throws ClassNotFoundException, ClassCastException, InstantiationException, IllegalAccessException { return (XMLReader) Class.forName(name).newInstance(); } }
39.132231
120
0.703696
8c0d7c22cb873e7d3ec081daebc96b35740049a8
133
package mypack1.inner; public class Demo3 { public void display() { System.out.println("Hi! I am demo3 in sub package!!!"); } }
14.777778
57
0.676692
41af8549e82c8726825b831e5489427099a4ffea
680
package com.example.greenhouse.constants; public class Constants { // CONFIGURATIONS public static final String ES_HOST = "127.0.0.1"; public static final String MYSQL_DB_HOST = "jdbc:mysql://localhost:3306/freedb_teamgreen?useSSL=false"; public static final String MYSQL_DB_USER = "root"; public static final String MYSQL_DB_PASSWORD = "password"; public static final String INTERNAL_SERVER_ERROR_MSG = "internal server error"; public static final String NOT_FOUND_MSG = "not found"; public static final String ERR_CLOSE_RESULT_SET = "error occurred while closing the result set"; public static final String EXPORTS_DIR = "export-dir"; }
37.777778
107
0.754412
1e9aa6eca7e00a7de55f6a6d7081d4b4b7dbca84
6,771
package com.share.wechatShare; import java.io.IOException; import java.net.URL; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.hotshare.everywhere.R; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Toast; import com.tencent.mm.sdk.modelmsg.SendMessageToWX; import com.tencent.mm.sdk.modelmsg.WXMediaMessage; import com.tencent.mm.sdk.modelmsg.WXWebpageObject; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; public class WechatShare extends CordovaPlugin { public CallbackContext callbackContext; private String title; private String summary; private String target_url; private String image_url; private static int scene = 0; public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { try { this.callbackContext = callbackContext; show(); JSONObject jsonObject = args.getJSONObject(0); title = jsonObject.getString("title"); summary = jsonObject.getString("summary"); target_url = jsonObject.getString("target_url"); image_url = jsonObject.getString("image_url"); final JSONObject result = new JSONObject(); result.put("result", true); final Context context = this.cordova.getActivity().getApplicationContext(); Runnable runable = new Runnable() { @Override public void run() { IWXAPI api; String APP_ID = "wxcfcf19c225a36351"; api = WXAPIFactory.createWXAPI(context, APP_ID, false); if (!api.isWXAppInstalled()) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { Toast.makeText(context, "您还未安装微信客户端", Toast.LENGTH_SHORT).show(); } }); return; } api.registerApp(APP_ID); WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = target_url; WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = title; msg.description = summary; Bitmap thumb = null; if (image_url == null || image_url.equals("")) { thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); } else { try { URL url = new URL(image_url); thumb = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException e) { e.printStackTrace(); } } thumb = centerSquareScaleBitmap(thumb, 200); msg.setThumbImage(thumb); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg; req.scene = scene; api.sendReq(req); hidden(); } }; if (action.equals("moment")) { scene = SendMessageToWX.Req.WXSceneTimeline; cordova.getThreadPool().execute(runable); return true; } else if (action.equals("session")) { scene = SendMessageToWX.Req.WXSceneSession; cordova.getThreadPool().execute(runable); return true; } else if (action.equals("favorite")) { scene = SendMessageToWX.Req.WXSceneFavorite; cordova.getThreadPool().execute(runable); return true; } else { return true; } } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); } return true; } private void hidden() { final Activity activity = this.cordova.getActivity(); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { ViewGroup root = (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content); root.removeViewAt(1); } }); } private void show() { final Activity activity = this.cordova.getActivity(); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { ViewGroup root = (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content); RelativeLayout rl = new RelativeLayout(activity); rl.setBackgroundColor(0x90000000); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); params.addRule(RelativeLayout.CENTER_IN_PARENT); rl.setLayoutParams(params); root.addView(rl); ProgressBar dlg = new ProgressBar(activity); RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); p.addRule(RelativeLayout.CENTER_IN_PARENT); dlg.setLayoutParams(p); rl.addView(dlg); } }); } /** * * @param bitmap * 原图 * @param edgeLength * 希望得到的正方形部分的边长 * @return 缩放截取正中部分后的位图。 */ public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) { if (null == bitmap || edgeLength <= 0) { return null; } Bitmap result = bitmap; int widthOrg = bitmap.getWidth(); int heightOrg = bitmap.getHeight(); if (widthOrg > edgeLength && heightOrg > edgeLength) { // 压缩到一个最小长度是edgeLength的bitmap int longerEdge = (int) (edgeLength * Math.max(widthOrg, heightOrg) / Math.min(widthOrg, heightOrg)); int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength; int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge; Bitmap scaledBitmap; try { scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true); } catch (Exception e) { return null; } // 从图中截取正中间的正方形部分。 int xTopLeft = (scaledWidth - edgeLength) / 2; int yTopLeft = (scaledHeight - edgeLength) / 2; try { result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength); scaledBitmap.recycle(); } catch (Exception e) { return null; } } return result; } private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); } }
32.552885
131
0.655885
fc940013757d10bbeefc78882dd9d4c4105570f4
1,326
package pro.taskana.common.rest.models; import java.util.ArrayList; import java.util.List; import org.springframework.hateoas.RepresentationModel; import org.springframework.lang.NonNull; import pro.taskana.common.api.TaskanaRole; /** EntityModel class for user information. */ public class TaskanaUserInfoRepresentationModel extends RepresentationModel<TaskanaUserInfoRepresentationModel> { /** The user Id of the current user. */ private String userId; /** All groups the current user is a member of. */ private List<String> groupIds = new ArrayList<>(); /** All taskana roles the current user fulfills. */ private List<TaskanaRole> roles = new ArrayList<>(); public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public List<String> getGroupIds() { return groupIds; } public void setGroupIds(List<String> groupIds) { this.groupIds = groupIds; } public List<TaskanaRole> getRoles() { return roles; } public void setRoles(List<TaskanaRole> roles) { this.roles = roles; } @Override public @NonNull String toString() { return "TaskanaUserInfoRepresentationModel [userId=" + userId + ", groupIds=" + groupIds + ", roles=" + roles + "]"; } }
23.678571
69
0.686275
59bce13c741056e3bff539221153382aa16a7f3e
1,763
package vijay.springframework.spring5recipeapp.services; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import vijay.springframework.spring5recipeapp.domain.Recipe; import vijay.springframework.spring5recipeapp.repositories.RecipeRepository; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ImageServiceImplTest { @Mock RecipeRepository recipeRepository; ImageService imageService; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); imageService = new ImageServiceImpl(recipeRepository); } @Test public void testsaveImageFile() throws Exception{ Recipe recipe = new Recipe(); recipe.setId(1L); MultipartFile file = new MockMultipartFile("imagefile", "testing.txt", "text/plain", "Spring Framework Guru".getBytes()); Optional<Recipe> recipeOptional = Optional.of(recipe); when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional); ArgumentCaptor<Recipe> argumentCaptor = ArgumentCaptor.forClass(Recipe.class); imageService.saveImageFile(1L, file); verify(recipeRepository,times(1)).save(argumentCaptor.capture()); Recipe savedRecipe = argumentCaptor.getValue(); assertEquals(file.getBytes().length,savedRecipe.getImage().length); } }
30.929825
92
0.752127
25186762a30911f96d6be437574239a5c68ee05c
432
package com.mmnaseri.utils.spring.data.utils; import java.util.ArrayList; import java.util.List; /** * @author Milad Naseri ([email protected]) * @since 1.0 (4/12/16, 6:51 PM) */ public class TestUtils { public static <E> List<E> iterableToList(Iterable<E> iterable) { final List<E> list = new ArrayList<>(); for (E item : iterable) { list.add(item); } return list; } }
20.571429
68
0.604167
201cd2ef3339b53d890e3f217f4a7b0ca0e470a2
7,511
package rbasamoyai.industrialwarfare.common.tileentities; import java.util.List; import java.util.Optional; import javax.annotation.Nonnull; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.LivingEntity; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.Direction; import net.minecraft.util.math.AxisAlignedBB; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; import rbasamoyai.industrialwarfare.common.capabilities.entities.npc.INPCDataHandler; import rbasamoyai.industrialwarfare.common.capabilities.tileentities.workstation.IWorkstationDataHandler; import rbasamoyai.industrialwarfare.common.containers.workstations.RecipeItemHandler; import rbasamoyai.industrialwarfare.common.entities.NPCEntity; import rbasamoyai.industrialwarfare.common.recipes.NormalWorkstationRecipe; import rbasamoyai.industrialwarfare.common.recipes.NormalWorkstationRecipeGetter; import rbasamoyai.industrialwarfare.common.recipes.NormalWorkstationRecipeWrapper; import rbasamoyai.industrialwarfare.core.init.BlockInit; import rbasamoyai.industrialwarfare.core.init.TileEntityTypeInit; import rbasamoyai.industrialwarfare.utils.IWUUIDUtils; /** * Workstations that have five input slots, one output slot, and only require that a worker be present. */ public class NormalWorkstationTileEntity extends WorkstationTileEntity { public static final String TAG_RECIPE = "recipe"; private static final int INPUT_SLOTS = 5; protected final RecipeItemHandler recipeItemHandler = new RecipeItemHandler(this, 1); protected NormalWorkstationRecipe workingRecipe; public NormalWorkstationTileEntity(TileEntityType<?> tileEntityTypeIn, Block workstation, int baseWorkTicks) { super(tileEntityTypeIn, workstation, baseWorkTicks); this.inputItemHandler.setSize(INPUT_SLOTS); this.workingRecipe = null; } public static NormalWorkstationTileEntity assemblerTE() { return new NormalWorkstationTileEntity(TileEntityTypeInit.ASSEMBLER_WORKSTATION.get(), BlockInit.ASSEMBLER_WORKSTATION.get(), 100); } public ItemStackHandler getRecipeItemHandler() { return this.recipeItemHandler; } public NormalWorkstationRecipe getRecipe() { return this.workingRecipe; } @Override public CompoundNBT save(CompoundNBT tag) { tag.put(TAG_RECIPE, this.recipeItemHandler.serializeNBT()); return super.save(tag); } @Override public void load(BlockState state, CompoundNBT tag) { this.recipeItemHandler.deserializeNBT(tag.getCompound(TAG_RECIPE)); super.load(state, tag); } @Nonnull @Override public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) { if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return side == Direction.DOWN ? this.outputOptional.cast() : this.inputOptional.cast(); } return super.getCapability(cap, side); } @Override public void setRecipe(ItemStack stack, boolean dropItem) { ItemStack previousRecipe = this.recipeItemHandler.getStackInSlot(0); if (!previousRecipe.isEmpty() && dropItem) { ItemStack previousRecipeDrop = this.recipeItemHandler.extractItem(0, this.recipeItemHandler.getSlotLimit(0), false); InventoryHelper.dropItemStack(this.level, (double) this.worldPosition.getX(), this.worldPosition.above().getY(), this.worldPosition.getZ(), previousRecipeDrop); } this.recipeItemHandler.setStackInSlot(0, stack); } @Override public void nullRecipe() { this.workingRecipe = null; this.getDataHandler().ifPresent(h -> { h.setWorkingTicks(0); }); this.setChangedAndForceUpdate(); } @Override public void tick() { this.innerTick(); super.tick(); } private void innerTick() { if (this.clockTicks > 0) return; if (this.level.isClientSide) return; LazyOptional<IWorkstationDataHandler> teOptional = this.getDataHandler(); LivingEntity workerEntity = this.checkForWorkerEntity(); teOptional.ifPresent(h -> { h.setWorker(workerEntity); h.setIsWorking(workerEntity != null); }); if (workerEntity == null) return; boolean isNPC = workerEntity instanceof NPCEntity; ItemStack recipeItem; if (this.workingRecipe == null) { if (isNPC) this.attemptCraft(workerEntity); return; } if (isNPC) { LazyOptional<INPCDataHandler> npcOptional = ((NPCEntity) workerEntity).getDataHandler(); recipeItem = npcOptional.map(INPCDataHandler::getRecipeItem).orElse(ItemStack.EMPTY); } else { recipeItem = this.recipeItemHandler.getStackInSlot(0); } NormalWorkstationRecipeWrapper wrapper = new NormalWorkstationRecipeWrapper(this.inputItemHandler, recipeItem, this.workstation, Optional.of(workerEntity)); if (!this.workingRecipe.matches(wrapper, this.level)) { this.haltCrafting(); return; } if (teOptional.map(IWorkstationDataHandler::getWorkingTicks).orElse(0) < this.baseWorkTicks) return; ItemStack result = this.workingRecipe.assemble(wrapper); this.outputItemHandler.insertResult(0, result, false); this.nullRecipe(); // Reset recipe } @Override public void attemptCraft(LivingEntity entity) { if (this.level.isClientSide) return; if (!ItemStack.matches(this.outputItemHandler.getStackInSlot(0), ItemStack.EMPTY)) return; LazyOptional<IWorkstationDataHandler> optional = this.getDataHandler(); LivingEntity workerEntity = this.checkForEntity(entity); if (workerEntity == null) { optional.ifPresent(h -> h.setWorker(null)); return; } boolean isNPC = workerEntity instanceof NPCEntity; ItemStack recipeItem = isNPC ? ((NPCEntity) workerEntity).getDataHandler().map(INPCDataHandler::getRecipeItem).orElse(ItemStack.EMPTY) : this.recipeItemHandler.getStackInSlot(0); NormalWorkstationRecipeWrapper wrapper = new NormalWorkstationRecipeWrapper(this.inputItemHandler, recipeItem, this.workstation, Optional.empty()); List<NormalWorkstationRecipe> recipesForBlock = NormalWorkstationRecipeGetter.INSTANCE.getRecipes(this.level.getRecipeManager(), this.workstation); for (NormalWorkstationRecipe recipe : recipesForBlock) { if (!recipe.matches(wrapper, this.level)) continue; this.workingRecipe = recipe; this.setRecipe(recipeItem, !isNPC); optional.ifPresent(h -> { h.setWorker(entity); h.setIsWorking(true); }); return; } } public LivingEntity checkForWorkerEntity() { double x1 = (double) this.worldPosition.getX() - 1; double y1 = (double) this.worldPosition.getY(); double z1 = (double) this.worldPosition.getZ() - 1; double x2 = (double) this.worldPosition.getX() + 2; double y2 = (double) this.worldPosition.getY() + 1; double z2 = (double) this.worldPosition.getZ() + 2; AxisAlignedBB box = new AxisAlignedBB(x1, y1, z1, x2, y2, z2); for (LivingEntity entity : this.level.getEntitiesOfClass(LivingEntity.class, box)) { if (IWUUIDUtils.equalsFromWorkstationOptional(this.getDataHandler(), entity.getUUID())) return entity; } return null; } private LivingEntity checkForEntity(LivingEntity entity) { this.getDataHandler().ifPresent(h -> h.setWorkerUUIDOnly(entity.getUUID())); LivingEntity result = this.checkForWorkerEntity(); this.getDataHandler().ifPresent(h -> h.setWorkerUUIDOnly(null)); return result; } }
35.597156
163
0.774198
7f9d7aaaa0d73338168278e22826661ee0531294
1,492
package org.keycloak.examples.domainextension.rest; import org.jboss.resteasy.annotations.cache.NoCache; import org.keycloak.examples.domainextension.CompanyRepresentation; import org.keycloak.examples.domainextension.spi.ExampleService; import org.keycloak.models.KeycloakSession; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; public class CompanyResource { private final KeycloakSession session; public CompanyResource(KeycloakSession session) { this.session = session; } @GET @Path("") @NoCache @Produces(MediaType.APPLICATION_JSON) public List<CompanyRepresentation> getCompanies() { return session.getProvider(ExampleService.class).listCompanies(); } @POST @Path("") @NoCache @Consumes(MediaType.APPLICATION_JSON) public Response createCompany(CompanyRepresentation rep) { session.getProvider(ExampleService.class).addCompany(rep); return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(rep.getId()).build()).build(); } @GET @NoCache @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public CompanyRepresentation getCompany(@PathParam("id") final String id) { return session.getProvider(ExampleService.class).findCompany(id); } }
29.254902
122
0.747319
f840eb7b5e9a3f7bd73588e8a3cbf9df871a1470
4,750
/* * The MIT License (MIT) * * Copyright 2021 Vladimir Mikhailov <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ru.beykerykt.minecraft.lightapi.bukkit.internal.chunks.observer.sched.impl; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.configuration.file.FileConfiguration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import ru.beykerykt.minecraft.lightapi.bukkit.internal.BukkitPlatformImpl; import ru.beykerykt.minecraft.lightapi.bukkit.internal.handler.IHandler; import ru.beykerykt.minecraft.lightapi.common.api.ResultCode; import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IChunkData; import ru.beykerykt.minecraft.lightapi.common.internal.chunks.observer.sched.impl.ScheduledChunkObserver; import ru.beykerykt.minecraft.lightapi.common.internal.service.IBackgroundService; public class BukkitScheduledChunkObserver extends ScheduledChunkObserver { /** * CONFIG */ private final String CONFIG_TITLE = getClass().getSimpleName(); private final String CONFIG_TICK_PERIOD = CONFIG_TITLE + ".tick-period"; private final IHandler mHandler; private ScheduledFuture mScheduledFuture; public BukkitScheduledChunkObserver(BukkitPlatformImpl platform, IBackgroundService service, IHandler handler) { super(platform, service); this.mHandler = handler; } private IHandler getHandler() { return mHandler; } @Override protected BukkitPlatformImpl getPlatformImpl() { return (BukkitPlatformImpl) super.getPlatformImpl(); } private void checkAndSetDefaults() { boolean needSave = false; FileConfiguration fc = getPlatformImpl().getPlugin().getConfig(); if (!fc.isSet(CONFIG_TICK_PERIOD)) { fc.set(CONFIG_TICK_PERIOD, 2); needSave = true; } if (needSave) { getPlatformImpl().getPlugin().saveConfig(); } } private void configure() { checkAndSetDefaults(); FileConfiguration fc = getPlatformImpl().getPlugin().getConfig(); int period = fc.getInt(CONFIG_TICK_PERIOD); mScheduledFuture = getBackgroundService().scheduleWithFixedDelay(this, 0, 50 * period, TimeUnit.MILLISECONDS); } @Override public void onStart() { configure(); super.onStart(); } @Override public void onShutdown() { if (mScheduledFuture != null) { mScheduledFuture.cancel(true); } super.onShutdown(); } @Override public IChunkData createChunkData(String worldName, int chunkX, int chunkZ) { if (!getPlatformImpl().isWorldAvailable(worldName)) { return null; } return getHandler().createChunkData(worldName, chunkX, chunkZ); } @Override public boolean isValidChunkSection(int sectionY) { return getHandler().isValidChunkSection(sectionY); } @Override public List<IChunkData> collectChunkSections(String worldName, int blockX, int blockY, int blockZ, int lightLevel, int lightFlags) { if (!getPlatformImpl().isWorldAvailable(worldName)) { return new ArrayList<>(); } World world = Bukkit.getWorld(worldName); return getHandler().collectChunkSections(world, blockX, blockY, blockZ, lightLevel, lightFlags); } @Override public int sendChunk(IChunkData data) { if (!getPlatformImpl().isWorldAvailable(data.getWorldName())) { return ResultCode.WORLD_NOT_AVAILABLE; } return getHandler().sendChunk(data); } }
35.447761
118
0.710316
15996e31afce85c5664750b139b4b25be70cb161
1,021
package ca.ubc.cs411.abe.expression; import ca.ubc.cs411.abe.type.Type; import ca.ubc.cs411.abe.value.Value; public class If extends ABE { private ABE pred, conseq, altern; public If(ABE pred, ABE conseq, ABE altern) { this.pred = pred; this.conseq = conseq; this.altern = altern; } @Override public Value interp() { if (pred.interp().toBool()) { return conseq.interp(); } return altern.interp(); } @Override public Type typeOf() { if (pred.typeOf() != Type.BOOL) { throw new Error("If constructor passed a non-Bool predicate: " + pred); } else if (conseq.typeOf() != altern.typeOf()) { throw new Error("If constructor passed consequence and alternative expressions with different types: " + conseq + ", " + altern); } return conseq.typeOf(); } @Override public String toString() { return "If(" + pred + "," + conseq + "," + altern + ")"; } }
26.868421
141
0.573947
f396bd7e94ea348a13335378e21813f8517a7bac
1,618
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.databinding.tool.reflection; public abstract class TypeUtil { public static final String BYTE = "B"; public static final String CHAR = "C"; public static final String DOUBLE = "D"; public static final String FLOAT = "F"; public static final String INT = "I"; public static final String LONG = "J"; public static final String SHORT = "S"; public static final String VOID = "V"; public static final String BOOLEAN = "Z"; public static final String ARRAY = "["; public static final String CLASS_PREFIX = "L"; public static final String CLASS_SUFFIX = ";"; private static TypeUtil sInstance; abstract public String getDescription(ModelClass modelClass); abstract public String getDescription(ModelMethod modelMethod); public static TypeUtil getInstance() { if (sInstance == null) { sInstance = ModelAnalyzer.getInstance().createTypeUtil(); } return sInstance; } }
27.896552
75
0.697157
5886e019f44357ba2a4541b2c1cb2084d6582851
2,603
/*- * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== * */ package org.onap.clamp.clds.transform; import java.io.StringReader; import java.io.StringWriter; import javax.xml.XMLConstants; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.onap.clamp.clds.util.ResourceFileUtil; /** * XSL Transformer. */ public class XslTransformer { private Templates templates; public void setXslResourceName(String xslResourceName) throws TransformerConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); templates = tfactory.newTemplates(new StreamSource(ResourceFileUtil.getResourceAsStream(xslResourceName))); } /** * Given xml input, return the transformed result. * * @param xml * @throws TransformerException */ public String doXslTransformToString(String xml) throws TransformerException { StringWriter output = new StringWriter(4096); Transformer transformer = templates.newTransformer(); transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(output)); return output.toString(); } }
37.724638
115
0.640799
059a667e5ec97101b32fc5e7d8f46970bdac06e4
1,072
package concurrent.future.forkjoin; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import org.assertj.core.api.Assertions; import org.junit.Test; /** * ForkJoinTest.java * * @author: zhaoxiaoping * @date: 2019/11/11 **/ public class ForkJoinTest { @Test public void testCustomRecursiveAction() { CustomRecursiveAction action = new CustomRecursiveAction("aabbccddeeff"); ForkJoinPool.commonPool().invoke(action); System.out.println(action.isDone()); } @Test public void testCustomRecursiveTask() throws ExecutionException, InterruptedException { Random random = new Random(); int[] arr = new int[50]; for (int i = 0; i < arr.length; i++) { arr[i] = random.nextInt(35); } CustomRecursiveTask task = new CustomRecursiveTask(arr); ForkJoinPool.commonPool().execute(task); Assertions.assertThat(task.get()).isEqualTo(task.join()); ForkJoinPool.commonPool().submit(task); Assertions.assertThat(task.get()).isEqualTo(task.join()); } }
27.487179
89
0.716418
8170aed792189128d8cb827bcc260af7a9ae012d
3,750
package com.github.adriens.imgflip.sdk.imgflip.sdk.domain.enums; import com.fasterxml.jackson.annotation.JsonFormat; @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum RankIcon { ICO0("ico0", "https://imgflip.com/icons/anon.svg"), ICO1("ico1", "https://imgflip.com/icons/anon-white.svg"), ICO2("ico2", "https://imgflip.com/icons/anon-yellow.svg"), ICO3("ico3", "https://imgflip.com/icons/anon-orange.svg"), ICO4("ico4", "https://imgflip.com/icons/anon-blue.svg"), ICO5("ico5", "https://imgflip.com/icons/star-black.svg"), ICO6("ico6", "https://imgflip.com/icons/star-black-white.svg"), ICO7("ico7", "https://imgflip.com/icons/star-black-yellow.svg"), ICO8("ico8", "https://imgflip.com/icons/star-black-orange.svg"), ICO9("ico9", "https://imgflip.com/icons/star-black-blue.svg"), ICO10("ico10", "https://imgflip.com/icons/star-black-rainbow.svg"), ICO11("ico11", "https://imgflip.com/icons/10k.svg"), ICO12("ico12", "https://imgflip.com/icons/lol.svg"), ICO13("ico13", "https://imgflip.com/icons/star-black-black-rainbow.svg"), ICO14("ico14", "https://imgflip.com/icons/star-black-white-rainbow.svg"), ICO15("ico15", "https://imgflip.com/icons/star-black-yellow-rainbow.svg"), ICO16("ico16", "https://imgflip.com/icons/star-black-orange-rainbow.svg"), ICO17("ico17", "https://imgflip.com/icons/star-black-blue-rainbow.svg"), ICO18("ico18", "https://imgflip.com/icons/hammer-white.svg"), ICO19("ico19", "https://imgflip.com/icons/hammer-yellow.svg"), ICO20("ico20", "https://imgflip.com/icons/hammer-orange.svg"), ICO21("ico21", "https://imgflip.com/icons/hammer-blue.svg"), ICO22("ico22", "https://imgflip.com/icons/crown-white.svg"), ICO23("ico23", "https://imgflip.com/icons/crown-yellow.svg"), ICO24("ico24", "https://imgflip.com/icons/crown-orange.svg"), ICO25("ico25", "https://imgflip.com/icons/crown-blue.svg"), ICO26("ico26", "https://imgflip.com/icons/advice.svg"), ICO27("ico27", "https://imgflip.com/icons/starnest-white.svg"), ICO28("ico28", "https://imgflip.com/icons/starnest-yellow.svg"), ICO29("ico29", "https://imgflip.com/icons/starnest-orange.svg"), ICO30("ico30", "https://imgflip.com/icons/starnest-blue.svg"), ICO31("ico31", "https://imgflip.com/icons/stars-white.svg"), ICO32("ico32", "https://imgflip.com/icons/stars-yellow.svg"), ICO33("ico33", "https://imgflip.com/icons/stars-orange.svg"), ICO34("ico34", "https://imgflip.com/icons/stars-blue.svg"), ICO35("ico35", "https://imgflip.com/icons/starburst.svg"), ICO36("ico36", "https://imgflip.com/icons/binary-white.svg"), ICO37("ico37", "https://imgflip.com/icons/binary-yellow.svg"), ICO38("ico38", "https://imgflip.com/icons/binary-orange.svg"), ICO39("ico39", "https://imgflip.com/icons/binary-blue.svg"), ICO40("ico40", "https://imgflip.com/icons/shooting-star-white.svg"), ICO41("ico41", "https://imgflip.com/icons/shooting-star-yellow.svg"), ICO42("ico42", "https://imgflip.com/icons/shooting-star-orange.svg"), ICO43("ico43", "https://imgflip.com/icons/shooting-star-blue.svg"), ICO46("ico46", "https://imgflip.com/icons/binary-green.svg"); public final String id; public final String url; RankIcon(String id, String url) { this.id = id; this.url = url; } public static RankIcon urlForId(String id) { for (RankIcon rankIcon : values()) { if (rankIcon.id.equals(id)) return rankIcon; } return null; } @Override public String toString() { return "RankIcon{" + "id='" + id + '\'' + ", url='" + url + '\'' + '}'; } }
46.875
78
0.6432
c873c26890b97506794354c79645daad1b638f74
2,840
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.datatypes.enums; import org.junit.Test; public class ResourceTypeEnumTest { private ResourceTypeEnum createTestSubject() { return ResourceTypeEnum.ABSTRACT; } @Test public void testGetValue() throws Exception { ResourceTypeEnum testSubject; String result; // default test testSubject = createTestSubject(); result = testSubject.getValue(); } @Test public void testIsAtomicType() throws Exception { ResourceTypeEnum testSubject; boolean result; // default test testSubject = createTestSubject(); result = testSubject.isAtomicType(); } @Test public void testGetType() throws Exception { String type = ""; ResourceTypeEnum result; // default test result = ResourceTypeEnum.getType(type); result = ResourceTypeEnum.getType(ResourceTypeEnum.ABSTRACT.name()); } @Test public void testGetTypeByName() throws Exception { String type = ""; ResourceTypeEnum result; // default test result = ResourceTypeEnum.getType(type); result = ResourceTypeEnum.getTypeByName(ResourceTypeEnum.ABSTRACT.name()); } @Test public void testGetTypeIgnoreCase() throws Exception { String type = ""; ResourceTypeEnum result; // default test result = ResourceTypeEnum.getTypeIgnoreCase(type); result = ResourceTypeEnum.getTypeIgnoreCase(ResourceTypeEnum.ABSTRACT.name()); } @Test public void testContainsName() throws Exception { String type = ""; boolean result; // default test result = ResourceTypeEnum.containsName(type); result = ResourceTypeEnum.containsName(ResourceTypeEnum.ABSTRACT.name()); } @Test public void testContainsIgnoreCase() throws Exception { String type = ""; boolean result; // default test result = ResourceTypeEnum.containsIgnoreCase(type); result = ResourceTypeEnum.containsIgnoreCase(ResourceTypeEnum.ABSTRACT.name()); } }
28.118812
83
0.664789
d4d511e4e74682652601dc394c432ce4d0bb063a
1,415
package cn.edu.buaa.crypto.signature.pks.bls01; import cn.edu.buaa.crypto.algebra.generators.PairingKeyPairGenerator; import cn.edu.buaa.crypto.algebra.serparams.PairingKeySerPair; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Pairing; import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory; import org.bouncycastle.crypto.KeyGenerationParameters; /** * Created by Weiran Liu on 2016/10/18. * * Boneh-Lynn-Shacham signature public key / secret key pair generator. */ public class BLS01SignKeyPairGenerator implements PairingKeyPairGenerator { private BLS01SignKeyPairGenerationParameter param; public void init(KeyGenerationParameters param) { this.param = (BLS01SignKeyPairGenerationParameter)param; } public PairingKeySerPair generateKeyPair() { Pairing pairing = PairingFactory.getPairing(this.param.getPairingParameters()); Element x = pairing.getZr().newRandomElement().getImmutable(); Element g = pairing.getG2().newRandomElement().getImmutable(); Element v = g.powZn(x).getImmutable(); BLS01SignPublicPairingKeySerParameter publicKeyParameters = new BLS01SignPublicPairingKeySerParameter(this.param.getPairingParameters(), g, v); return new PairingKeySerPair( publicKeyParameters, new BLS01SignSecretPairingKeySerParameter(this.param.getPairingParameters(), x)); } }
40.428571
151
0.758304
dd1ae5e7f38716cbe5e44f73a12e727954bb33b9
3,181
package com.lazaro.makario.flmaterialspinner; /* //// (O O) --------oOO----(_)------------------------------ Created by Làzaro, Makario Felipe on 18/09/2017. Email: [email protected] Complaint Received, 10 year later... ----------------------oOO-----------------------*/ import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class FLMaterialSpinnerAdapter extends ArrayAdapter<FLMaterialSpinnerItem> { private List<FLMaterialSpinnerItem> flMaterialSpinnerData = new ArrayList<>(); private List<String> flMaterialSpinnerListKeys = new ArrayList<String>(); private List<String> flMaterialSpinnerListValues = new ArrayList<String>(); private Context flMaterialSpinnerContext; private int flMaterialSpinnerLayoutResourceID; private int flMaterialSpinnerDisabledTextColor = 0; private int flMaterialSpinnerActiveTextColor = 0; public FLMaterialSpinnerAdapter(Context mContext, int layoutResourceId, List<FLMaterialSpinnerItem> data) { super(mContext, layoutResourceId, data); this.flMaterialSpinnerLayoutResourceID = layoutResourceId; this.flMaterialSpinnerContext = mContext; this.flMaterialSpinnerData = data; this.flMaterialSpinnerDisabledTextColor = this.flMaterialSpinnerContext.getResources().getColor(R.color.disabled_spinner_text); this.flMaterialSpinnerActiveTextColor = this.flMaterialSpinnerContext.getResources().getColor(R.color.enabled_spinner_text); this.flMaterialSpinnerListKeys = new ArrayList<String>(); this.flMaterialSpinnerListValues = new ArrayList<String>(); for(FLMaterialSpinnerItem flMaterialSpinnerItem : data){ this.flMaterialSpinnerListKeys.add(flMaterialSpinnerItem.getItemCode()); this.flMaterialSpinnerListValues.add(flMaterialSpinnerItem.getItemValue()); } } @Override public View getView(int position, View convertView, ViewGroup parent) { try{ if(convertView == null){ LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(this.flMaterialSpinnerLayoutResourceID, parent, false); } FLMaterialSpinnerItem objectItem = this.flMaterialSpinnerData.get(position); TextView textViewItem = (TextView) convertView.findViewById(R.id.textView); textViewItem.setText(objectItem.getItemValue()); textViewItem.setTextColor( (position==0) ? this.flMaterialSpinnerDisabledTextColor : this.flMaterialSpinnerActiveTextColor); } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return convertView; } public List<FLMaterialSpinnerItem> getAllData(){ return this.flMaterialSpinnerData; } public List<String> getFlMaterialSpinnerListKeys() { return this.flMaterialSpinnerListKeys; } public List<String> getFlMaterialSpinnerListValues() { return this.flMaterialSpinnerListValues; } }
35.344444
131
0.745677
4ec76c4fd6499454ff7d107c5975a612eb549ed8
332
package org.apache.cordova.api; // dummy class to ensure the org.apache.cordova.api package exists // this is required to support Cordova 2.9 and 3.0 with one code base // since I'm using wildcard imports to work around the renamed classes // import org.apache.cordova.*; // import org.apache.cordova.api.*; public class Dummy2 { }
36.888889
70
0.756024
3b9c455e83685b54abf5d9d842c19efc616b4405
4,340
package selenium.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; /** * * @author Jeroen Roovers <jroovers> */ public class ProfilePage extends PageObject { WebElement profileFollowingCount; WebElement profileFollowerCount; WebElement profileTweetCount; WebElement changeProfileButton; WebElement profileEditName; WebElement profileEditBio; WebElement profileEditLocation; WebElement profileEditWebsite; WebElement profileEditConfirm; WebElement profileFollowButton; WebElement profileUnFollowButton; public ProfilePage(WebDriver driver) { super(driver); wait = new WebDriverWait(this.driver, 5); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileFollowingCount"))); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileFollowerCount"))); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileTweetCount"))); } public void clickChangeProfileButton() { // wait for page to load wait.until(ExpectedConditions.elementToBeClickable(By.id("changeProfileButton"))); this.changeProfileButton = this.driver.findElement(By.id("changeProfileButton")); changeProfileButton.click(); // wait for dialog wait.until(ExpectedConditions.elementToBeClickable(By.id("profileEditConfirm"))); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileEditName"))); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileEditBio"))); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileEditLocation"))); wait.until(ExpectedConditions.elementToBeClickable(By.id("profileEditWebsite"))); this.profileEditName = this.driver.findElement(By.id("profileEditName")); this.profileEditBio = this.driver.findElement(By.id("profileEditBio")); this.profileEditLocation = this.driver.findElement(By.id("profileEditLocation")); this.profileEditWebsite = this.driver.findElement(By.id("profileEditWebsite")); this.profileEditConfirm = this.driver.findElement(By.id("profileEditConfirm")); } public void enterTextForName(String text) { this.profileEditName.clear(); this.profileEditName.sendKeys(text); } public void enterTextForBiography(String text) { this.profileEditBio.clear(); this.profileEditBio.sendKeys(text); } public void enterTextForLocation(String text) { this.profileEditLocation.clear(); this.profileEditLocation.sendKeys(text); } public void enterTextForWebsite(String text) { this.profileEditWebsite.clear(); this.profileEditWebsite.sendKeys(text); } public void clickProfileEditConfirmButton() { if (this.profileEditConfirm != null) { wait.until(ExpectedConditions.elementToBeClickable(By.id("profileEditConfirm"))); this.profileEditConfirm.click(); } } public void clickFollowButton() { wait.until(ExpectedConditions.elementToBeClickable(By.id("profileFollowButton"))); this.profileFollowButton = this.driver.findElement(By.id("profileFollowButton")); this.profileFollowButton.click(); } public void clickUnfollowButton() { wait.until(ExpectedConditions.elementToBeClickable(By.id("profileUnFollowButton"))); this.profileUnFollowButton = this.driver.findElement(By.id("profileUnFollowButton")); this.profileUnFollowButton.click(); } public String getProfileName(String text) { this.wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(text(),'" + text + "')]"))); WebElement profileName = driver.findElement(By.xpath("//*[contains(text(),'" + text + "')]")); return profileName.getText(); } public String getFollowerName(String text) { this.wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(), '" + text + "')]"))); WebElement followerName = driver.findElement(By.xpath("//div[contains(text(), '" + text + "')]")); return followerName.getText(); } }
40.560748
118
0.711521
8879ce0c5d19e45136ecc362b3df616996048336
1,730
package com.zero.spring.cloud.zuul.web.filter; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; /** * 使用zuul的过滤器功能 * @date 2017年11月8日 下午6:23:56 * @author zero */ @Component public class CustomNormalFilter extends ZuulFilter { private final Logger logger = LoggerFactory.getLogger(CustomNormalFilter.class); @Override public boolean shouldFilter() { return true; } /** * 过滤逻辑,可以使用复杂的过滤逻辑,譬如权限管理 */ @Override public Object run() { RequestContext crc = RequestContext.getCurrentContext(); HttpServletRequest request = crc.getRequest(); Object token = request.getParameter("token"); if(token == null) {// 假设未传token则不允许请求访问 logger.warn("Method[{}], URI[{}], request param without token, rejust it.", request.getMethod(), request.getRequestURI()); crc.setSendZuulResponse(false); crc.setResponseStatusCode(503); try { crc.getResponse().getWriter().write("token is empty!"); } catch(IOException e) { logger.error("Method[{}], URI[{}], request param without token, write back occurred IO exception.", request.getMethod(), request.getRequestURI(), e); } } logger.info("Method[{}], URI[{}], CustomNormalFilter allowed to access.", request.getMethod(), request.getRequestURI()); return null; } /** * 四种类型 * pre:路由之前 * routing:路由之时 * post: 路由之后 * error:发送错误调用 */ @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } }
25.441176
154
0.686705
36a589aade2b39f9618805f48b57910fb9d47cb3
5,636
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tajo.storage.trevni; import com.google.protobuf.Message; import org.apache.hadoop.conf.Configuration; import org.apache.tajo.catalog.Column; import org.apache.tajo.catalog.Schema; import org.apache.tajo.catalog.TableMeta; import org.apache.tajo.datum.BlobDatum; import org.apache.tajo.datum.DatumFactory; import org.apache.tajo.datum.NullDatum; import org.apache.tajo.datum.ProtobufDatumFactory; import org.apache.tajo.storage.FileScanner; import org.apache.tajo.storage.Tuple; import org.apache.tajo.storage.VTuple; import org.apache.tajo.storage.fragment.FileFragment; import org.apache.trevni.ColumnFileReader; import org.apache.trevni.ColumnValues; import org.apache.trevni.avro.HadoopInput; import java.io.IOException; import java.nio.ByteBuffer; import static org.apache.tajo.common.TajoDataTypes.DataType; public class TrevniScanner extends FileScanner { private ColumnFileReader reader; private int [] projectionMap; private ColumnValues [] columns; public TrevniScanner(Configuration conf, Schema schema, TableMeta meta, FileFragment fragment) throws IOException { super(conf, schema, meta, fragment); reader = new ColumnFileReader(new HadoopInput(fragment.getPath(), conf)); } @Override public void init() throws IOException { if (targets == null) { targets = schema.toArray(); } prepareProjection(targets); columns = new ColumnValues[projectionMap.length]; for (int i = 0; i < projectionMap.length; i++) { columns[i] = reader.getValues(projectionMap[i]); } super.init(); } private void prepareProjection(Column [] targets) { projectionMap = new int[targets.length]; int tid; for (int i = 0; i < targets.length; i++) { tid = schema.getColumnId(targets[i].getQualifiedName()); projectionMap[i] = tid; } } @Override public Tuple next() throws IOException { Tuple tuple = new VTuple(schema.size()); if (!columns[0].hasNext()) { return null; } int tid; // column id of the original input schema for (int i = 0; i < projectionMap.length; i++) { tid = projectionMap[i]; columns[i].startRow(); DataType dataType = schema.getColumn(tid).getDataType(); switch (dataType.getType()) { case BOOLEAN: tuple.put(tid, DatumFactory.createBool(((Integer)columns[i].nextValue()).byteValue())); break; case BIT: tuple.put(tid, DatumFactory.createBit(((Integer) columns[i].nextValue()).byteValue())); break; case CHAR: String str = (String) columns[i].nextValue(); tuple.put(tid, DatumFactory.createChar(str)); break; case INT2: tuple.put(tid, DatumFactory.createInt2(((Integer) columns[i].nextValue()).shortValue())); break; case INT4: tuple.put(tid, DatumFactory.createInt4((Integer) columns[i].nextValue())); break; case INT8: tuple.put(tid, DatumFactory.createInt8((Long) columns[i].nextValue())); break; case FLOAT4: tuple.put(tid, DatumFactory.createFloat4((Float) columns[i].nextValue())); break; case FLOAT8: tuple.put(tid, DatumFactory.createFloat8((Double) columns[i].nextValue())); break; case INET4: tuple.put(tid, DatumFactory.createInet4(((ByteBuffer) columns[i].nextValue()).array())); break; case TEXT: tuple.put(tid, DatumFactory.createText((String) columns[i].nextValue())); break; case PROTOBUF: { ProtobufDatumFactory factory = ProtobufDatumFactory.get(dataType.getCode()); Message.Builder builder = factory.newBuilder(); builder.mergeFrom(((ByteBuffer)columns[i].nextValue()).array()); tuple.put(tid, factory.createDatum(builder)); break; } case BLOB: tuple.put(tid, new BlobDatum(((ByteBuffer) columns[i].nextValue()))); break; case NULL_TYPE: tuple.put(tid, NullDatum.get()); break; default: throw new IOException("Unsupport data type"); } } return tuple; } @Override public void reset() throws IOException { for (int i = 0; i < projectionMap.length; i++) { columns[i] = reader.getValues(projectionMap[i]); } } @Override public void close() throws IOException { reader.close(); } @Override public boolean isProjectable() { return true; } @Override public boolean isSelectable() { return false; } @Override public boolean isSplittable(){ return false; } }
29.051546
117
0.646735
acc6eda945798ad7e3c6fb2fe087f3113dd73f1b
1,173
package com.capitalone.dashboard.exception; import com.capitalone.dashboard.model.score.settings.ScoreTypeValue; import com.capitalone.dashboard.model.ScoreWeight; public class PropagateScoreException extends Exception { private final ScoreTypeValue score; private final ScoreWeight.ProcessingState state; public PropagateScoreException(ScoreTypeValue score, ScoreWeight.ProcessingState state) { super(); this.score = score; this.state = state; } public PropagateScoreException(String message, ScoreTypeValue score, ScoreWeight.ProcessingState state) { super(message); this.score = score; this.state = state; } public PropagateScoreException(String message, Throwable cause, ScoreTypeValue score, ScoreWeight.ProcessingState state) { super(message, cause); this.score = score; this.state = state; } public PropagateScoreException(Throwable cause, ScoreTypeValue score, ScoreWeight.ProcessingState state) { super(cause); this.score = score; this.state = state; } public ScoreTypeValue getScore() { return score; } public ScoreWeight.ProcessingState getState() { return state; } }
26.659091
124
0.751918
2ac797febcb0ddc09b367eb36ccd1b6b1fc65ee8
3,632
// GT_EXTERNAL_LEGEND(2014) // Reviewed: DRCok 2016-03-09 package acsl.tests.helpers; import java.io.PrintWriter; import java.io.StringWriter; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import framac.helpers.Utils; /** The logging mechanism for the plugin - used for reporting progress or * errors within the plugin itself. All textual user output is sent to * the static methods of this class; specific kinds of reporters register as listeners. * Actually - in the current implementation there can be only one listener. * @author David R. Cok */ public class Log { /** The singleton Log object that does the actual logging */ /*@ non_null */ public static Log log = new Log(); /** Call this method for any non-error output - it sends the message on to the * current listener, or to System.out if there are no listeners * @param message the message to write; a line terminator will be added */ static public void log(@NonNull String message) { if (log.listener != null) log.listener.log(message); System.out.println(message); } static public void log(String filename, int linenumber, int start, int end, @NonNull String message) { String mssg = Utils.mapSystemFilenameToPosixFilename(filename) + ":" + linenumber + ":"+ start + "-" + end + ":" + message; log(mssg); } /** Call this method for any error output that happens because of an * exception - it sends the message to the * current listener, or to System.out if there are no listeners; * if the second argument is non-null, the stack trace is included * @param message the message to write; a line termination will be added */ static public void errorLog(@NonNull String message, @Nullable Throwable e) { String emsg = e == null ? null : e.getMessage(); if (emsg != null && emsg.length() != 0) message = message + " (" + emsg + ")"; //$NON-NLS-1$ //$NON-NLS-2$ if (e != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(); e.printStackTrace(pw); message = message + sw.toString(); } log(message); } static public void errorLog(String filename, int linenumber, int start, int end,@NonNull String message, @Nullable Throwable e) { String mssg = Utils.mapSystemFilenameToPosixFilename(filename) + ":" + linenumber + ":"+ start + "-" + end + ":" + message; errorLog(mssg,e); } /** The interface expected of listeners */ public static interface IListener { /** Records the argument, with an appended newline, as appropriate for the receiving listener */ public void log(@NonNull String msg); } /** An implementation of the IListener interface that includes a * delegate listener. */ public static abstract class DelegateListener implements IListener { protected @Nullable IListener delegate = null; public @Nullable IListener delegate() { return delegate; } } /** The one (if any) registered listener */ /*@ nullable */ protected @Nullable IListener listener = null; /** Returns the current listener */ public @Nullable IListener listener() { return listener; } /** Call this to set or remove the current listener */ public @Nullable IListener setListener(@Nullable IListener l) { IListener old = listener; listener = l; return old; } }
37.061224
133
0.645099
fd600614bc38050fdea6f0d7d02812717a85c038
829
package com.github.rich.message.service; import com.baomidou.mybatisplus.extension.service.IService; import com.github.rich.message.entity.SystemMessage; import com.github.rich.message.domain.vo.message.UserMessageVO; import java.util.List; /** * <p> * 系统消息 服务类 * </p> * * @author Petty * @since 2019-06-27 */ public interface ISystemMessageService extends IService<SystemMessage> { /** * List查找 * @param userId userId * @return List 返回结果 */ List<UserMessageVO> loadUnread(String userId); /** * 创建数据 * * @param systemMessage 要创建的对象 * @return Boolean */ String create(SystemMessage systemMessage); /** * 变更状态为已读 * * @param userId userId * @param id 消息ID * @return Boolean */ Boolean read(String userId, String id); }
18.840909
72
0.64415
c1c7370dbfb416103551349a34e20ac4ba44d7c7
17,409
/* * Copyright 2013 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.utils; import static voldemort.serialization.DefaultSerializerFactory.AVRO_GENERIC_TYPE_NAME; import static voldemort.serialization.DefaultSerializerFactory.AVRO_GENERIC_VERSIONED_TYPE_NAME; import static voldemort.serialization.DefaultSerializerFactory.AVRO_REFLECTIVE_TYPE_NAME; import static voldemort.serialization.DefaultSerializerFactory.AVRO_SPECIFIC_TYPE_NAME; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.routing.RoutingStrategyType; import voldemort.serialization.SerializerDefinition; import voldemort.serialization.avro.versioned.SchemaEvolutionValidator; import voldemort.store.StoreDefinition; import voldemort.store.StoreDefinitionBuilder; import voldemort.store.readonly.ReadOnlyStorageConfiguration; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class StoreDefinitionUtils { private static Logger logger = Logger.getLogger(StoreDefinitionUtils.class); /** * Given a list of store definitions, filters the list depending on the * boolean * * @param storeDefs Complete list of store definitions * @param isReadOnly Boolean indicating whether filter on read-only or not? * @return List of filtered store definition */ public static List<StoreDefinition> filterStores(List<StoreDefinition> storeDefs, final boolean isReadOnly) { List<StoreDefinition> filteredStores = Lists.newArrayList(); for(StoreDefinition storeDef: storeDefs) { if(storeDef.getType().equals(ReadOnlyStorageConfiguration.TYPE_NAME) == isReadOnly) { filteredStores.add(storeDef); } } return filteredStores; } /** * Given a list of store definitions return a list of store names * * @param storeDefList The list of store definitions * @return Returns a list of store names */ public static List<String> getStoreNames(List<StoreDefinition> storeDefList) { List<String> storeList = new ArrayList<String>(); for(StoreDefinition def: storeDefList) { storeList.add(def.getName()); } return storeList; } /** * Given a list of store definitions return a set of store names * * @param storeDefList The list of store definitions * @return Returns a set of store names */ public static Set<String> getStoreNamesSet(List<StoreDefinition> storeDefList) { HashSet<String> storeSet = new HashSet<String>(); for(StoreDefinition def: storeDefList) { storeSet.add(def.getName()); } return storeSet; } /** * Given a store name and a list of store definitions, returns the * appropriate store definition ( if it exists ) * * @param storeDefs List of store definitions * @param storeName The store name whose store definition is required * @return The store definition */ public static StoreDefinition getStoreDefinitionWithName(List<StoreDefinition> storeDefs, String storeName) { StoreDefinition def = null; for(StoreDefinition storeDef: storeDefs) { if(storeDef.getName().compareTo(storeName) == 0) { def = storeDef; break; } } if(def == null) { throw new VoldemortException("Could not find store " + storeName); } return def; } /** * Given a list of store definitions, find out and return a map of similar * store definitions + count of them * * @param storeDefs All store definitions * @return Map of a unique store definition + counts */ public static HashMap<StoreDefinition, Integer> getUniqueStoreDefinitionsWithCounts(List<StoreDefinition> storeDefs) { HashMap<StoreDefinition, Integer> uniqueStoreDefs = Maps.newHashMap(); for(StoreDefinition storeDef: storeDefs) { if(uniqueStoreDefs.isEmpty()) { uniqueStoreDefs.put(storeDef, 1); } else { StoreDefinition sameStore = null; // Go over all the other stores to find if this is unique for(StoreDefinition uniqueStoreDef: uniqueStoreDefs.keySet()) { if(uniqueStoreDef.getReplicationFactor() == storeDef.getReplicationFactor() && uniqueStoreDef.getRoutingStrategyType() .compareTo(storeDef.getRoutingStrategyType()) == 0) { // Further check for the zone routing case if(uniqueStoreDef.getRoutingStrategyType() .compareTo(RoutingStrategyType.ZONE_STRATEGY) == 0) { boolean zonesSame = true; for(int zoneId: uniqueStoreDef.getZoneReplicationFactor().keySet()) { if(storeDef.getZoneReplicationFactor().get(zoneId) == null || storeDef.getZoneReplicationFactor().get(zoneId) != uniqueStoreDef.getZoneReplicationFactor() .get(zoneId)) { zonesSame = false; break; } } if(zonesSame) { sameStore = uniqueStoreDef; } } else { sameStore = uniqueStoreDef; } if(sameStore != null) { // Bump up the count int currentCount = uniqueStoreDefs.get(sameStore); uniqueStoreDefs.put(sameStore, currentCount + 1); break; } } } if(sameStore == null) { // New store uniqueStoreDefs.put(storeDef, 1); } } } return uniqueStoreDefs; } /** * Determine whether or not a given serializedr is "AVRO" based * * @param serializerName * @return */ public static boolean isAvroSchema(String serializerName) { if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME) || serializerName.equals(AVRO_GENERIC_TYPE_NAME) || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME) || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) { return true; } else { return false; } } /** * If provided with an AVRO schema, validates it and checks if there are * backwards compatible. * * TODO should probably place some similar checks for other serializer types * as well? * * @param serializerDef */ private static void validateIfAvroSchema(SerializerDefinition serializerDef) { if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME) || serializerDef.getName().equals(AVRO_GENERIC_TYPE_NAME)) { SchemaEvolutionValidator.validateAllAvroSchemas(serializerDef); // check backwards compatibility if needed if(serializerDef.getName().equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)) { SchemaEvolutionValidator.checkSchemaCompatibility(serializerDef); } } } /** * Validate store schema -- backward compatibility if it is AVRO generic * versioned -- sanity checks for avro in general * * @param storeDefinition the store definition to check on */ public static void validateSchemaAsNeeded(StoreDefinition storeDefinition) { logger.info("Validating schema for store: " + storeDefinition.getName()); SerializerDefinition keySerDef = storeDefinition.getKeySerializer(); // validate the key schemas try { validateIfAvroSchema(keySerDef); } catch(Exception e) { logger.error("Validating key schema failed for store: " + storeDefinition.getName()); throw new VoldemortException("Error validating key schema for store: " + storeDefinition.getName() + " " + e.getMessage(), e); } // validate the value schemas SerializerDefinition valueSerDef = storeDefinition.getValueSerializer(); try { validateIfAvroSchema(valueSerDef); } catch(Exception e) { logger.error("Validating value schema failed for store: " + storeDefinition.getName()); throw new VoldemortException("Error validating value schema for store: " + storeDefinition.getName() + " " + e.getMessage(), e); } } /** * Validate store schema for things like backwards compatibility, * parseability * * @param storeDefinitions the list of store definition to check on */ public static void validateSchemasAsNeeded(Collection<StoreDefinition> storeDefinitions) { for(StoreDefinition storeDefinition: storeDefinitions) { validateSchemaAsNeeded(storeDefinition); } } /** * Ensure that new store definitions that are specified for an update do not include breaking changes to the store. * @param oldStoreDefs * @param newStoreDefs */ public static void validateNewStoreDefsAreNonBreaking(List<StoreDefinition> oldStoreDefs, List<StoreDefinition> newStoreDefs){ Map<String, StoreDefinition> oldStoreMap = new HashMap<String, StoreDefinition>(); Map<String, StoreDefinition> newStoreMap = new HashMap<String, StoreDefinition>(); for (StoreDefinition storeDef : oldStoreDefs){ oldStoreMap.put(storeDef.getName(), storeDef); } for (StoreDefinition storeDef : newStoreDefs){ newStoreMap.put(storeDef.getName(), storeDef); } for (String storeName : oldStoreMap.keySet()){ if (newStoreMap.containsKey(storeName)){ validateNewStoreDefIsNonBreaking(oldStoreMap.get(storeName), newStoreMap.get(storeName)); } } } /** * Ensure that new store definitions that are specified for an update do not include breaking changes to the store. * * Non-breaking changes include changes to * description * preferredWrites * requiredWrites * preferredReads * requiredReads * retentionPeriodDays * retentionScanThrottleRate * retentionFrequencyDays * viewOf * zoneCountReads * zoneCountWrites * owners * memoryFootprintMB * * non breaking changes include the serializer definition, as long as the type (name field) is unchanged for * keySerializer * valueSerializer * transformSerializer * * @param oldStoreDef * @param newStoreDef */ public static void validateNewStoreDefIsNonBreaking(StoreDefinition oldStoreDef, StoreDefinition newStoreDef){ if (!oldStoreDef.getName().equals(newStoreDef.getName())){ throw new VoldemortException("Cannot compare stores of different names: " + oldStoreDef.getName() + " and " + newStoreDef.getName()); } String store = oldStoreDef.getName(); verifySamePropertyForUpdate(oldStoreDef.getReplicationFactor(), newStoreDef.getReplicationFactor(), "ReplicationFactor", store); verifySamePropertyForUpdate(oldStoreDef.getType(), newStoreDef.getType(), "Type", store); verifySameSerializerType(oldStoreDef.getKeySerializer(), newStoreDef.getKeySerializer(), "KeySerializer", store); verifySameSerializerType(oldStoreDef.getValueSerializer(), newStoreDef.getValueSerializer(), "ValueSerializer", store); verifySameSerializerType(oldStoreDef.getTransformsSerializer(), newStoreDef.getTransformsSerializer(), "TransformSerializer", store); verifySamePropertyForUpdate(oldStoreDef.getRoutingPolicy(), newStoreDef.getRoutingPolicy(), "RoutingPolicy", store); verifySamePropertyForUpdate(oldStoreDef.getRoutingStrategyType(), newStoreDef.getRoutingStrategyType(), "RoutingStrategyType", store); verifySamePropertyForUpdate(oldStoreDef.getZoneReplicationFactor(), newStoreDef.getZoneReplicationFactor(), "ZoneReplicationFactor", store); verifySamePropertyForUpdate(oldStoreDef.getValueTransformation(), newStoreDef.getValueTransformation(), "ValueTransformation", store); verifySamePropertyForUpdate(oldStoreDef.getSerializerFactory(), newStoreDef.getSerializerFactory(), "SerializerFactory", store); verifySamePropertyForUpdate(oldStoreDef.getHintedHandoffStrategyType(), newStoreDef.getHintedHandoffStrategyType(), "HintedHandoffStrategyType", store); verifySamePropertyForUpdate(oldStoreDef.getHintPrefListSize(), newStoreDef.getHintPrefListSize(), "HintPrefListSize", store); } private static void verifySameSerializerType(SerializerDefinition oldSerializer, SerializerDefinition newSerializer, String property, String store){ boolean same; if (oldSerializer == null && newSerializer == null){ same = true; } else if (oldSerializer == null || newSerializer == null){ same = false; } else { same = oldSerializer.getName().equals(newSerializer.getName()); } if (!same){ throw new VoldemortException("Cannot change " + property + " Type from " + oldSerializer.getName() + " to " + newSerializer.getName() + " for store " + store); } } private static void verifySamePropertyForUpdate(Object oldObj, Object newObj, String property, String store){ boolean same; if (oldObj == null && newObj == null){ same = true; } else if (oldObj == null || newObj == null){ /* not both null, so only one is null */ same = false; } else { same = oldObj.equals(newObj); } if (! same){ throw new VoldemortException("Cannot change " + property + " of store " + store + " from " + oldObj + " to " + newObj); } } public static StoreDefinitionBuilder getBuilderForStoreDef(StoreDefinition storeDef) { return new StoreDefinitionBuilder().setName(storeDef.getName()) .setType(storeDef.getType()) .setDescription(storeDef.getDescription()) .setOwners(storeDef.getOwners()) .setKeySerializer(storeDef.getKeySerializer()) .setValueSerializer(storeDef.getValueSerializer()) .setRoutingPolicy(storeDef.getRoutingPolicy()) .setRoutingStrategyType(storeDef.getRoutingStrategyType()) .setReplicationFactor(storeDef.getReplicationFactor()) .setPreferredReads(storeDef.getPreferredReads()) .setRequiredReads(storeDef.getRequiredReads()) .setPreferredWrites(storeDef.getPreferredWrites()) .setRequiredWrites(storeDef.getRequiredWrites()) .setRetentionPeriodDays(storeDef.getRetentionDays()) .setRetentionScanThrottleRate(storeDef.getRetentionScanThrottleRate()) .setRetentionFrequencyDays(storeDef.getRetentionFrequencyDays()) .setZoneReplicationFactor(storeDef.getZoneReplicationFactor()) .setZoneCountReads(storeDef.getZoneCountReads()) .setZoneCountWrites(storeDef.getZoneCountWrites()) .setHintedHandoffStrategy(storeDef.getHintedHandoffStrategyType()) .setHintPrefListSize(storeDef.getHintPrefListSize()) .setMemoryFootprintMB(storeDef.getMemoryFootprintMB()); } }
45.813158
167
0.620484
d627c5900b6b8c8d0dd0c364c71be3124a41fcb3
3,530
package jetbrains.mps.lang.editor.test.generation.editor; /*Generated by MPS */ import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.openapi.editor.EditorContext; import jetbrains.mps.openapi.editor.cells.EditorCell; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.openapi.editor.menus.transformation.SPropertyInfo; import jetbrains.mps.lang.editor.cellProviders.PropertyCellProvider; import jetbrains.mps.nodeEditor.cells.EditorCell_Property; import jetbrains.mps.nodeEditor.cells.ModelAccessor; import jetbrains.mps.nodeEditor.cells.TransactionalPropertyAccessor; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations; import jetbrains.mps.openapi.editor.style.Style; import jetbrains.mps.editor.runtime.style.StyleImpl; import jetbrains.mps.lang.editor.test.generation.editor.TestTargetStyleSheet_StyleSheet.testParentStyleStyleClass; import jetbrains.mps.nodeEditor.EditorManager; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; /*package*/ class TransactionalProperty_ICellStyle_ComponentBuilder_a extends AbstractEditorBuilder { @NotNull private SNode myNode; public TransactionalProperty_ICellStyle_ComponentBuilder_a(@NotNull EditorContext context, @NotNull SNode node) { super(context); myNode = node; } @NotNull @Override public SNode getNode() { return myNode; } /*package*/ EditorCell createCell() { return createTransactionalProperty_0(); } private EditorCell createTransactionalProperty_0() { getCellFactory().pushCellContext(); try { SProperty property = PROPS.theProperty$q6LT; getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property)); PropertyCellProvider provider = new PropertyCellProvider(myNode, property, getEditorContext()); EditorCell_Property editorCell = null; { ModelAccessor modelAccessor = new TransactionalPropertyAccessor(myNode, property, false, false, getEditorContext()) { public void doCommit0(final Object oldValue, final Object newValue) { doCommitImpl(SPropertyOperations.castString(oldValue), SPropertyOperations.castString(newValue)); } public void doCommitImpl(final String oldValue, final String newValue) { } }; editorCell = EditorCell_Property.create(getEditorContext(), modelAccessor, myNode); editorCell.setCellId("TransactionalProperty_b29fir_a"); Style style = new StyleImpl(); new testParentStyleStyleClass(getEditorContext(), getNode()).apply(style, editorCell); editorCell.getStyle().putAll(style); editorCell.setDefaultText("<no theProperty>"); setCellContext(editorCell); editorCell.setCommitInCommand(false); } SNode attributeConcept = provider.getRoleAttribute(); if (attributeConcept != null) { EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext()); return manager.createNodeRoleAttributeCell(attributeConcept, provider.getRoleAttributeKind(), editorCell); } else return editorCell; } finally { getCellFactory().popCellContext(); } } private static final class PROPS { /*package*/ static final SProperty theProperty$q6LT = MetaAdapterFactory.getProperty(0xeaa98d49af584b80L, 0xb585c05e7b5fd335L, 0xbde89531aadcccL, 0xbde89531aae3a9L, "theProperty"); } }
43.04878
184
0.768839
f13dbbab58a6937da3abeaaf67e99560d6cf9e09
3,238
package pollingPack; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class ElectionCommissioner { String comm_id,vid,name,ed_qualification,experience; String f; byte []photo=null; Connection con=null; PreparedStatement pst=null; ResultSet rs=null; public String getComm_id() { return comm_id; } public void setComm_id(String comm_id) { this.comm_id = comm_id; } public String getVid() { return vid; } public void setVid(String vid) { this.vid = vid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEd_qualification() { return ed_qualification; } public void setEd_qualification(String ed_qualification) { this.ed_qualification = ed_qualification; } public String getExperience() { return experience; } public void setExperience(String experience) { this.experience = experience; } public String getF() { return f; } public void setF(String f) { this.f = f; } public byte[] getPhoto() { return photo; } public void setPhoto(byte[] photo) { this.photo = photo; } public void dbConnection() { try { Class.forName("com.ibm.db2.jcc.DB2Driver"); //Driver Load con=DriverManager.getConnection("jdbc:db2://localhost:50000/GENPOL","db2admin","db2admin"); //create connection } catch(Exception e) { e.printStackTrace(); } } public void dbClose() { try { con.close(); } catch(Exception e) { e.printStackTrace(); } } public int newCommInsert() { int n=0; try { pst=con.prepareStatement("insert into db2admin.election_commissioner values(?,?,?,?,?,?,?)"); pst.setString(1, comm_id); pst.setString(2, name); pst.setString(3, vid); pst.setString(4, ed_qualification); pst.setString(5, experience); pst.setBytes(6, photo); pst.setString(7,f); n=pst.executeUpdate(); //sql statement execute } catch(Exception e) { e.printStackTrace(); } return n; } public int update() { int n=0; try { pst=con.prepareStatement("update db2admin.election_commissioner set ed_qualification=?,prof_experience=?,image=?,image_file=? where comm_id=?"); pst.setString(1, ed_qualification); pst.setString(2, experience); pst.setBytes(3, photo); pst.setString(4, f); pst.setString(5, comm_id); n=pst.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } return n; } public ResultSet viewProfile() { try { pst=con.prepareStatement("select * from db2admin.election_commissioner where comm_id=?"); pst.setString(1,comm_id); rs=pst.executeQuery(); } catch(Exception e) { e.printStackTrace(); } return rs; } public ResultSet viewName() { try { pst=con.prepareStatement("select name from db2admin.election_commissioner where comm_id=?"); pst.setString(1,comm_id); rs=pst.executeQuery(); } catch(Exception e) { e.printStackTrace(); } return rs; } }
20.493671
149
0.636504
fb972056dc0931a99251122f7474053306e406c4
2,079
//////////////////////////////////////////////////////////////////////////////// // // Created by MJesser on 09.01.2018. // // Copyright (c) 2006 - 2018 FORCAM GmbH. All rights reserved. //////////////////////////////////////////////////////////////////////////////// package com.forcam.na.ffwebservices.client.statusdefinition.request; import com.forcam.na.ffwebservices.model.definition.WorkplaceState; import com.forcam.na.common.webserviceaccess.util.ToStringUtility;; import org.apache.commons.lang3.builder.ToStringStyle; /** * Contains an ID and values that determine what shall be embedded. */ public class GetWorkplaceStateRequest extends GetStatusDefinitionRequest { // ------------------------------------------------------------------------ // members // ------------------------------------------------------------------------ /** A workplace state ID. */ private WorkplaceState mId; // ------------------------------------------------------------------------ // constructors // ------------------------------------------------------------------------ /** * Creates a new {@link GetWorkplaceStateRequest} object with a workplace state ID. * * @param workplaceStateId The workplace state ID. */ public GetWorkplaceStateRequest(WorkplaceState workplaceStateId) { mId = workplaceStateId; } // ------------------------------------------------------------------------ // methods // ------------------------------------------------------------------------ @Override public String toString() { return ToStringUtility.newToStringBuilder(this) .append("id", mId) .appendSuper(super.toString()) .toString(); } // ------------------------------------------------------------------------ // getters/setters // ------------------------------------------------------------------------ public WorkplaceState getId() { return mId; } public void setId(WorkplaceState id) { mId = id; } }
34.081967
87
0.416546
297e3bdad7ced7879a0339ff8c5c28bf3a44a0e6
446
package com.kagmole.workshops.basicchat.webservice.shared.exceptions; public enum ApplicationExceptionType { ERROR ("Error"), ENTITY_NOT_FOUND ("Entity Not Found"), VALIDATION_FAILED ("Validation Failed"), USERNAME_ALREADY_TAKEN ("Username Already Taken"); private String message; private ApplicationExceptionType(String message) { this.message = message; } @Override public String toString() { return message; } }
20.272727
69
0.746637
d3a159c2e21f4860b3a59118978d49673588880e
1,887
package cz.ackee.androidskeleton.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import cz.ackee.androidskeleton.R; import cz.ackee.androidskeleton.model.Upload; /** * Adapter for list of attachements * <p/> * Created by Petr Schneider[[email protected]] on 26.4.2015. */ public class AttachmentAdapter extends ArrayAdapter<Upload> { public static final String TAG = TaskAdapter.class.getName(); List<Upload> mData = new ArrayList<>(); public AttachmentAdapter(Context context) { super(context, 0); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_attachment, parent, false); } TextView txtTitle = (TextView) convertView.findViewById(R.id.attachmentTitle); ImageView remove = (ImageView) convertView.findViewById(R.id.remove); Upload upload = getItem(position); txtTitle.setText(upload.filename); return convertView; } @Override public int getCount() { return mData.size(); } @Override public Upload getItem(int position) { return mData.get(position); } public void appendData(List<Upload> data) { mData.addAll(data); notifyDataSetChanged(); } public void append(Upload data) { mData.add(data); } public void setData(List<Upload> uploads) { mData = uploads; notifyDataSetChanged(); } @Override public void clear() { super.clear(); mData.clear(); } }
24.828947
114
0.674086
f09d1fb96b7f806bae2e0cfa5442627c5da3877f
6,682
/* * Geotoolkit - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2011, Geomatys * * 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; * version 2.1 of the 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. */ package com.examind.process.admin.yamlReader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import org.apache.sis.parameter.DefaultParameterValue; import org.constellation.business.IServiceBusiness; import org.constellation.dto.process.ServiceProcessReference; import org.constellation.dto.service.ServiceComplete; import org.constellation.process.AbstractCstlProcess; import org.geotoolkit.process.Process; import org.geotoolkit.process.ProcessDescriptor; import org.geotoolkit.process.ProcessException; import org.geotoolkit.process.ProcessFinder; import org.opengis.parameter.*; import org.opengis.util.NoSuchIdentifierException; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class ProcessFromYamlProcess extends AbstractCstlProcess { /** * ServiceBusiness used for provider GUI editors data */ @Inject private IServiceBusiness serviceBusiness; private static final String PROCESS_FACTORY_NAME = "factory_name"; private static final String PROCESS_NAME_PARAMETER = "process_name"; public ProcessFromYamlProcess(ProcessDescriptor desc, ParameterValueGroup parameter) { super(desc, parameter); } @Override protected void execute() throws ProcessException { LOGGER.info("executing process from yaml reader"); final String yamlPath = inputParameters.getValue(ProcessFromYamlProcessDescriptor.YAML_PATH); ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); File file = new File(yamlPath); try { // Retrieve and map config from yaml file. Map configMap = mapper.readValue(file, Map.class); String factoryName = (String) configMap.get(PROCESS_FACTORY_NAME); String processName = (String) configMap.get(PROCESS_NAME_PARAMETER); // Setting process name parameter to create the correct process type. ProcessDescriptor desc = ProcessFinder.getProcessDescriptor(factoryName, processName); ParameterValueGroup in = desc.getInputDescriptor().createValue(); final List<GeneralParameterDescriptor> descriptors = in.getDescriptor().descriptors(); for (GeneralParameterDescriptor genParamDesc : descriptors) { ParameterDescriptor parameterDescriptor = (ParameterDescriptor) genParamDesc; final Class valueClass = parameterDescriptor.getValueClass(); if (configMap.get(parameterDescriptor.getName().getCode()) != null) { if (valueClass==String.class) { if (configMap.get(parameterDescriptor.getName().getCode()).getClass()==String.class) { final String configValue = (String) configMap.get(parameterDescriptor.getName().getCode()); in.parameter(parameterDescriptor.getName().getCode()).setValue(configValue); } else if (configMap.get(parameterDescriptor.getName().getCode()).getClass() == java.util.ArrayList.class) { // Little trick to add multiple time the same value to the process. List<Object> valueList = (List<Object>) configMap.get(parameterDescriptor.getName().getCode()); for (Object value : valueList) { ParameterValue<String> parameterValue = new DefaultParameterValue(parameterDescriptor); parameterValue.setValue(value.toString()); // toString here is not redundant as the value might be an Integer for example. in.values().add(parameterValue); } } } else if (valueClass==ServiceProcessReference.class) { if (configMap.get(parameterDescriptor.getName().getCode()).getClass()==LinkedHashMap.class) { LinkedHashMap value = (LinkedHashMap) configMap.get(parameterDescriptor.getName().getCode()); Collection<LinkedHashMap> collection = value.values(); for (LinkedHashMap linkedValue : collection) { final String type = (String) linkedValue.get("type"); final String identifier = (String) linkedValue.get("identifier"); ServiceComplete service = serviceBusiness.getServiceByIdentifierAndType(type, identifier); // not null if a service has been found. if (service != null) { ServiceProcessReference serviceProcessReference = new ServiceProcessReference(service.getId(), service.getType(), service.getIdentifier()); ParameterValue<ServiceProcessReference> parameterValue = new DefaultParameterValue(parameterDescriptor); parameterValue.setValue(serviceProcessReference); in.values().add(parameterValue); } } } } else if (valueClass==Boolean.class) { final Boolean configValue = (Boolean) configMap.get(parameterDescriptor.getName().getCode()); in.parameter(parameterDescriptor.getName().getCode()).setValue(configValue); } } } Process process = desc.createProcess(in); process.call(); } catch (IOException | NoSuchIdentifierException e) { throw new ProcessException("An error occured while executing the ProcessFromYamlProcess", this, e); } outputParameters.getOrCreate(ProcessFromYamlProcessDescriptor.PROCESS_OUTPUT).setValue(true); } }
51.4
175
0.642173
aacf8650bce74b50c77057d884331bd65995359c
4,512
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.util.stub; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.security.SecureClassLoader; import java.security.cert.Certificate; class Util { static String getPackageName(Class clazz) { String class_name = clazz.getName(); int idx = class_name.lastIndexOf('.'); if (idx == -1) { return null; } else { return class_name.substring(0, idx); } } static String getClassName(Class clazz) { String class_name = clazz.getName(); int idx = class_name.lastIndexOf('.'); if (idx == -1) { return class_name; } else { return class_name.substring(idx + 1); } } static private java.lang.reflect.Method defineClassMethod; static { try { // get the method object defineClassMethod = (SecureClassLoader.class).getDeclaredMethod( "defineClass", new Class[] { String.class, byte[].class, Integer.TYPE, Integer.TYPE, CodeSource.class }); } catch (Error ex) { throw ex; } catch (RuntimeException ex) { throw ex; } catch (Throwable ex) { throw new Error("unexpected exception: " + ex.getMessage(), ex); } } static Class defineClass(final ClassLoader loader, String className, byte[] data, int off, int len) { final Object[] args = new Object[5]; try { args[0] = className; args[1] = data; args[2] = new Integer(off); args[3] = new Integer(len); args[4] = new CodeSource(new URL("file:stub"), new Certificate[0]); } catch (java.net.MalformedURLException ex) { throw new Error(ex.getMessage(), ex); } return (Class) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ClassLoader the_loader = (loader == null ? (SecureClassLoader) Thread .currentThread().getContextClassLoader() : (SecureClassLoader) loader); // make it accessible defineClassMethod.setAccessible(true); try { return defineClassMethod.invoke(the_loader, args); } catch (IllegalAccessException ex) { throw new Error("internal error", ex); } catch (IllegalArgumentException ex) { throw new Error("internal error", ex); } catch (InvocationTargetException ex) { Throwable th = ex.getTargetException(); if (th instanceof Error) { throw (Error) th; } else if (th instanceof RuntimeException) { throw (RuntimeException) th; } else { throw new Error("unexpected exception: " + ex.getMessage(), ex); } } } }); } static String methodFieldName(int i) { return "__method$" + i; } static String handlerFieldName() { return "__handler"; } static String initializerFieldName() { return "__initializer"; } static String handlerDataFieldName() { return "__data"; } static String getSuperMethodName(String name) { return "__super_" + name + "$" + Integer.toHexString(name.hashCode() & 0xffff); } }
33.671642
88
0.582447
828cb2d3c163040b83760beaa5e8be14afe21a9e
2,683
package mp.jprime.files.json.beans; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.Date; /** * Описание ответа после загрузки файла */ @JsonPropertyOrder({ "fileCode", "name", "createdDate", "length" }) @JsonInclude(JsonInclude.Include.NON_NULL) public class JsonFileInfo { /** * Уникальный код файла */ private final String fileCode; /** * Имя файла */ private final String name; /** * Дата начала формирования файла */ private final Date createdDate; /** * Размер файла */ private final Long length; public String getFileCode() { return fileCode; } public String getName() { return name; } public Date getCreatedDate() { return createdDate; } public Long getLength() { return length; } /** * Конструктор * * @param fileCode Уникальный код файла * @param name Имя файла * @param createdDate Дата начала формирования файла * @param length Размер файла */ private JsonFileInfo(String fileCode, String name, Long length, Date createdDate) { this.fileCode = fileCode; this.name = name; this.length = length; this.createdDate = createdDate; } /** * Построитель FileUpload * * @return Builder */ public static Builder newBuilder() { return new Builder(); } /** * Построитель FileUpload */ public static final class Builder { private String fileCode; private String name; private Long length; private Date createdDate; private Builder() { } /** * Уникальный код файла * * @param fileCode Уникальный код файла * @return Builder */ public Builder fileCode(String fileCode) { this.fileCode = fileCode; return this; } /** * Имя файла * * @param name Имя файла * @return Builder */ public Builder name(String name) { this.name = name; return this; } /** * Дата начала формирования файла * * @param createdDate Дата начала формирования файла * @return Builder */ public Builder createdDate(Date createdDate) { this.createdDate = createdDate; return this; } /** * Размер файла * * @param length Размер файла * @return Builder */ public Builder length(Long length) { this.length = length; return this; } /** * Создаем FileUpload * * @return FileUpload */ public JsonFileInfo build() { return new JsonFileInfo(fileCode, name, length, createdDate); } } }
18.631944
85
0.613865
7998648a8b80f6b29611efead7b5fa0f19ce08ad
6,416
package sh.isaac.model.observable.coordinate; import javafx.beans.property.ObjectProperty; import javafx.beans.value.ObservableValue; import sh.isaac.api.component.concept.ConceptSpecification; import sh.isaac.api.coordinate.EditCoordinate; import sh.isaac.api.coordinate.EditCoordinateImmutable; import sh.isaac.api.observable.coordinate.ObservableEditCoordinate; import sh.isaac.model.observable.equalitybased.SimpleEqualityBasedObjectProperty; import sh.isaac.model.observable.override.ObjectPropertyWithOverride; public class ObservableEditCoordinateWithOverride extends ObservableEditCoordinateBase { //~--- constructors -------------------------------------------------------- /** * Instantiates a new observable edit coordinate impl. * * @param editCoordinate the edit coordinate */ public ObservableEditCoordinateWithOverride(ObservableEditCoordinate editCoordinate, String coordinateName) { super(editCoordinate, coordinateName); if (editCoordinate instanceof ObservableEditCoordinateWithOverride) { throw new IllegalStateException("Cannot override an overridden Coordinate. "); } } @Override protected EditCoordinateImmutable baseCoordinateChangedListenersRemoved(ObservableValue<? extends EditCoordinateImmutable> observable, EditCoordinateImmutable oldValue, EditCoordinateImmutable newValue) { if (!this.authorForChangesProperty().isOverridden()) { this.authorForChangesProperty().setValue(newValue.getAuthorForChanges()); } if (!this.defaultModuleProperty().isOverridden()) { this.defaultModuleProperty().setValue(newValue.getDefaultModule()); } if (!this.destinationModuleProperty().isOverridden()) { this.destinationModuleProperty().setValue(newValue.getDestinationModule()); } if (!this.promotionPathProperty().isOverridden()) { this.promotionPathProperty().setValue(newValue.getPromotionPath()); } /* int authorNid, int defaultModuleNid, int promotionPathNid, int destinationModuleNid */ return EditCoordinateImmutable.make(this.authorForChangesProperty().get().getNid(), this.defaultModuleProperty().get().getNid(), this.promotionPathProperty().get().getNid(), this.destinationModuleProperty().get().getNid()); } public ObservableEditCoordinateWithOverride(ObservableEditCoordinate editCoordinate) { this(editCoordinate, editCoordinate.getName()); } @Override public ObjectPropertyWithOverride<ConceptSpecification> authorForChangesProperty() { return (ObjectPropertyWithOverride<ConceptSpecification>) super.authorForChangesProperty(); } @Override public ObjectPropertyWithOverride<ConceptSpecification> defaultModuleProperty() { return (ObjectPropertyWithOverride<ConceptSpecification>) super.defaultModuleProperty(); } @Override public ObjectPropertyWithOverride<ConceptSpecification> promotionPathProperty() { return (ObjectPropertyWithOverride<ConceptSpecification>) super.promotionPathProperty(); } @Override public ObjectPropertyWithOverride<ConceptSpecification> destinationModuleProperty() { return (ObjectPropertyWithOverride<ConceptSpecification>) super.destinationModuleProperty(); } @Override public void setExceptOverrides(EditCoordinateImmutable updatedCoordinate) { if (hasOverrides()) { ConceptSpecification author = updatedCoordinate.getAuthorForChanges(); if (authorForChangesProperty().isOverridden()) { author = authorForChangesProperty().get(); }; ConceptSpecification defaultModule = updatedCoordinate.getDefaultModule(); if (defaultModuleProperty().isOverridden()) { defaultModule = defaultModuleProperty().get(); }; ConceptSpecification promotionPath = updatedCoordinate.getPromotionPath(); if (promotionPathProperty().isOverridden()) { promotionPath = promotionPathProperty().get(); }; ConceptSpecification destinationModule = updatedCoordinate.getDestinationModule(); if (destinationModuleProperty().isOverridden()) { destinationModule = destinationModuleProperty().get(); }; setValue(EditCoordinateImmutable.make(author, defaultModule, promotionPath, destinationModule)); } else { setValue(updatedCoordinate); } } @Override protected SimpleEqualityBasedObjectProperty<ConceptSpecification> makePromotionPathProperty(EditCoordinate editCoordinate) { ObservableEditCoordinate observableEditCoordinate = (ObservableEditCoordinate) editCoordinate; return new ObjectPropertyWithOverride<>(observableEditCoordinate.promotionPathProperty(), this); } @Override protected SimpleEqualityBasedObjectProperty<ConceptSpecification> makeDefaultModuleProperty(EditCoordinate editCoordinate) { ObservableEditCoordinate observableEditCoordinate = (ObservableEditCoordinate) editCoordinate; return new ObjectPropertyWithOverride<>(observableEditCoordinate.defaultModuleProperty(), this); } @Override protected SimpleEqualityBasedObjectProperty<ConceptSpecification> makeAuthorForChangesProperty(EditCoordinate editCoordinate) { ObservableEditCoordinate observableEditCoordinate = (ObservableEditCoordinate) editCoordinate; return new ObjectPropertyWithOverride<>(observableEditCoordinate.authorForChangesProperty(), this); } @Override protected SimpleEqualityBasedObjectProperty<ConceptSpecification> makeDestinationModuleProperty(EditCoordinate editCoordinate) { ObservableEditCoordinate observableEditCoordinate = (ObservableEditCoordinate) editCoordinate; return new ObjectPropertyWithOverride<>(observableEditCoordinate.destinationModuleProperty(), this); } @Override public EditCoordinateImmutable getOriginalValue() { return EditCoordinateImmutable.make(authorForChangesProperty().getOriginalValue(), defaultModuleProperty().getOriginalValue(), promotionPathProperty().getOriginalValue(), destinationModuleProperty().getOriginalValue()); } }
47.525926
208
0.732544
72bf177ac98c3f691d4a73976838f0d0a999f12a
1,118
package com.piggysnow.boss.core.domain; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.wds.base.dao.BaseEntity; @Entity @Table(name = "t_visit_count") public class VisitCount extends BaseEntity implements Serializable{ @Column public String route; @Column public String subId; @Column public int visitCount; @Column public int editCount; @Column public Date lastVisit; public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } public String getSubId() { return subId; } public void setSubId(String subId) { this.subId = subId; } public int getVisitCount() { return visitCount; } public void setVisitCount(int visitCount) { this.visitCount = visitCount; } public Date getLastVisit() { return lastVisit; } public void setLastVisit(Date lastVisit) { this.lastVisit = lastVisit; } public int getEditCount() { return editCount; } public void setEditCount(int editCount) { this.editCount = editCount; } }
18.633333
67
0.739714
0f188374ff4cebe4d43641815bcb8998f941046e
941
package cn.edu.imufe.service; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.edu.imufe.entity.Answerhistory; import cn.edu.imufe.entity.AnswerhistoryExample; public interface AnswerHistoryService { int countByExample(AnswerhistoryExample example); int deleteByExample(AnswerhistoryExample example); int deleteByPrimaryKey(Integer id); int insert(Answerhistory record); int insertSelective(Answerhistory record); List<Answerhistory> selectByExample(AnswerhistoryExample example); Answerhistory selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Answerhistory record, @Param("example") AnswerhistoryExample example); int updateByExample(@Param("record") Answerhistory record, @Param("example") AnswerhistoryExample example); int updateByPrimaryKeySelective(Answerhistory record); int updateByPrimaryKey(Answerhistory record); }
28.515152
120
0.792774
9e9e45b88a57ff3008fe460bd14dc809c2648a4d
11,083
package physics.external.combatSystem; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import messenger.external.*; import physics.external.PhysicsBody; import physics.external.PhysicsSystem; import xml.XMLParser; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.lang.Math.PI; /* Responsible for processing CombatActionEvent posted to the message bus and parsing XML to send hitbox and hurtbox related data to physics system @author xp19 */ public class CombatSystem { EventBus eventBus; private PlayerManager playerManager; private PhysicsSystem physicsSystem; private List<Integer> botList; private HashMap<Integer, Point2D> playerMap; private XMLParser xmlParser; private File gameDir; private HashMap<Integer, ArrayList<Double>> characterStats; private HashMap<Integer, Rectangle2D> tileMap; private static final int TILE_STARTING_ID = 1000; private static int tileID = TILE_STARTING_ID; private static final int PLAYER_STARTING_ID = 0; private static int playerID = PLAYER_STARTING_ID; // public CombatSystem(Player bot){ // eventBus = EventBusFactory.getEventBus(); // bot.id = 1; // playerManager = new PlayerManager(1); // } public CombatSystem(HashMap<Integer, Point2D> playerMap, HashMap<Integer, Rectangle2D> tileMap, PhysicsSystem physicsSystem, File gameDir, Map<Integer, String> characterNames){ characterStats = new HashMap<>(); tileID = TILE_STARTING_ID; playerID = PLAYER_STARTING_ID; // get character stats for(int id: characterNames.keySet()){ String name = characterNames.get(id); xmlParser = new XMLParser(Paths.get(gameDir.getPath(), "characters", name, "characterproperties.xml").toFile()); HashMap<String, ArrayList<String>> map = xmlParser.parseFileForElement("character"); ArrayList<Double> stats = new ArrayList<>(); // get attack damage Double damage = Double.parseDouble(map.get("attack").get(0)); // get defense Double defense = Double.parseDouble(map.get("defense").get(0)); // get health Double health = Double.parseDouble(map.get("health").get(0)); stats.add(damage); stats.add(defense); stats.add(health); characterStats.put(id, stats); } eventBus = EventBusFactory.getEventBus(); this.playerMap = playerMap; // playerManager = new PlayerManager(playerMap.keySet().size()); this.physicsSystem = physicsSystem; this.tileMap = tileMap; // register players to physics engine for(int i = 0; i < playerMap.keySet().size(); i++){ // System.out.println("MIN X: " + playerMap.get(i).getX()); physicsSystem.addPhysicsObject(playerID, PhysicsSystem.DEFAULT_MASS, playerMap.get(i).getX(), playerMap.get(i).getY(),40,60, (int)playerMap.get(i).getX(), (int)playerMap.get(i).getY()); playerID++; } // register tiles to physics engine for(int i=0;i < tileMap.keySet().size(); i++){ physicsSystem.addPhysicsObject(tileID,0, tileMap.get(i).getX(),tileMap.get(i).getY(),tileMap.get(i).getWidth(),tileMap.get(i).getHeight(), (int)tileMap.get(i).getX(), (int)tileMap.get(i).getY()); tileID++; } // get hit boxes and hurt boxes information for(int id: characterNames.keySet()){ String name = characterNames.get(id); xmlParser = new XMLParser(Paths.get(gameDir.getPath(), "characters", name, "attacks", "attackproperties.xml").toFile()); HashMap<String, ArrayList<String>> map = xmlParser.parseFileForElement("frame"); double animationWidth = Double.parseDouble(xmlParser.parseFileForElement("attack").get("width").get(0)); double animationHeight = Double.parseDouble(xmlParser.parseFileForElement("attack").get("height").get(0)); double hitX = Double.parseDouble(map.get("hitXPos").get(0)); double hitY = Double.parseDouble(map.get("hitYPos").get(0)); double hitW = Double.parseDouble(map.get("hitWidth").get(0)); double hitH = Double.parseDouble(map.get("hitHeight").get(0)); double hurtX = Double.parseDouble(map.get("hurtXPos").get(0)); double hurtY = Double.parseDouble(map.get("hurtYPos").get(0)); double hurtW = Double.parseDouble(map.get("hurtWidth").get(0)); double hurtH = Double.parseDouble(map.get("hurtHeight").get(0)); hitX = hitX*40/animationWidth; hitY = hitY*60/animationHeight; hurtX = hurtX*40/animationWidth; hurtY = hurtY*60/animationHeight; hitW = hitW*40/animationWidth; hitH = hitH*60/animationHeight; hurtW = hurtW*40/animationWidth; hurtH = hurtH*60/animationHeight; System.out.println(hitX); System.out.println(hitY); System.out.println(hitW); System.out.println(hitH); System.out.println(); System.out.println(hurtW); System.out.println(hurtH); System.out.println(hurtX); System.out.println(hurtY); // set hitbox physicsSystem.setHitBox(0, id, hitX, hitY, hitW, hitH); // set hurtbox physicsSystem.setHitBox(1, id, hurtX, hurtY, hurtW, hurtH); /* // set hurtbox physicsSystem.setHitBox(1, id, Double.parseDouble(map.get("hurtXPos").get(0)), Double.parseDouble(map.get("hurtYPos").get(0)), Double.parseDouble(map.get("hurtWidth").get(0)), Double.parseDouble(map.get("hurtHeight").get(0)));*/ } } /** Returns the {@code PlayerState} of the player specified * @param id The player to retrieve the state for */ public PlayerState getPlayerState(int id){ return playerManager.getPlayerByID(id).getPlayerState(); } @Subscribe public void onCombatEvent(CombatActionEvent event){ int id = event.getInitiatorID(); // if(!botList.contains(id)){ playerManager.changePlayerStateByIDOnEvent(id, event); // } // else{ // System.out.println("Bot id: " + id); // } } @Subscribe public void onIdleEvent(IdleEvent idleEvent){ int id = idleEvent.getId(); if(!characterStats.keySet().contains(id)) return; if(playerManager.getPlayerByID(id).getPlayerState()!=PlayerState.SINGLE_JUMP && playerManager.getPlayerByID(id).getPlayerState()!=PlayerState.DOUBLE_JUMP){ playerManager.setToInitialStateByID(id); } } @Subscribe public void onAttackSuccessfulEvent(AttackSuccessfulEvent event){ // System.out.println("Attack!!!"); physicsSystem.attack(event.getInitiatorID()); } @Subscribe public void onMoveSuccessfulEvent(MoveSuccessfulEvent event){ boolean direction = event.getDirection(); // System.out.println("Move" + direction); // move left if(direction){ physicsSystem.move(event.getInitiatorID(), PI); } // move right else{ physicsSystem.move(event.getInitiatorID(), 0); } } @Subscribe public void onGroundIntersectEvent(GroundIntersectEvent event){ List<Integer> playersOnGround = event.getGroundedPlayers(); for(int id: playersOnGround){ playerManager.setToInitialStateByID(id); } } @Subscribe public void onAttackIntersectEvent(AttackIntersectEvent event){ Map<Integer, Double> playersBeingRekt = new HashMap<>(); for(List<Integer> list: event.getAttackPlayers()){ Player playerBeingAttacked = playerManager.getPlayerByID(list.get(0)); Player playerAttacking = playerManager.getPlayerByID(list.get(1)); playerAttacking.addAttackingTargets(playerBeingAttacked); boolean result = playerManager.hurt(list.get(0), list.get(1)); if(result){ eventBus.post(new GameOverEvent(playerManager.winnerID, playerManager.getRanking())); } playersBeingRekt.put(playerBeingAttacked.id, playerManager.getPlayerByID(list.get(0)).getHealth()); } eventBus.post(new GetRektEvent(playersBeingRekt)); } @Subscribe public void onJumpSuccessfulEvent(JumpSuccessfulEvent event){ physicsSystem.jump(event.getInitiatorID()); } @Subscribe public void onGameStart(GameStartEvent gameStartEvent){ botList = gameStartEvent.getBots(); playerManager = new PlayerManager(playerMap.size(), characterStats); playerManager.setBots(botList, physicsSystem); String type = gameStartEvent.getGameType().toLowerCase(); if(type.equals("stock")){ int life = gameStartEvent.getTypeValue(); playerManager.setNumOfLives(life); } else{ // timed } PlayerGraph graph = new PlayerGraph(playerManager, physicsSystem.getPositionsMap()); for(int id: botList){ ((Bot)playerManager.getPlayerByID(id)).setPlayerGraph(graph); } for(int id: botList){ ((HardBot)playerManager.getPlayerByID(id)).start(); } } @Subscribe public void onTimeUpEvent(TimeUpEvent timeUpEvent){ eventBus.post(new GameOverEvent(playerManager.winnerID, playerManager.getRanking())); } @Subscribe public void onPlayerDeath(PlayerDeathEvent playerDeathEvent){ int id = playerDeathEvent.getId(); playerManager.respawnPlayer(id, characterStats.get(id)); ((PhysicsBody)physicsSystem.getGameObjects().get(id)).respawn(); // physicsSystem.addPhysicsObject(id, physicsSystem.DEFAULT_MASS, tileMap.get(id).getX(), tileMap.get(id).getY(), 40, 60); } @Subscribe public void onPositionUpdate(PositionsUpdateEvent positionsUpdateEvent){ Map<Integer, Point2D> positionMap = positionsUpdateEvent.getPositions(); for(int id: positionMap.keySet()){ Point2D pos = positionMap.get(id); if(pos.getX()+40<0||pos.getX()-40>1200||pos.getY()+60<0||pos.getY()-60>800){ int remainingLife = playerManager.outOfScreen(id); eventBus.post(new PlayerDeathEvent(id, remainingLife)); } } } @Subscribe public void onGameOver(GameOverEvent gameOverEvent){ for(int id: characterStats.keySet()){ if(playerManager.getPlayerByID(id).isBot()){ ((HardBot)playerManager.getPlayerByID(id)).stop(); } } } }
38.887719
207
0.637102
09760590aa5e9e60a2f011058c99c055c3c859da
238
package edu.utexas.utmpc.beaconobserver.utility; import android.bluetooth.BluetoothDevice; import android.bluetooth.le.ScanRecord; public interface Beacon { String getDeviceAddress(); String getName(); byte[] getBeacon(); }
21.636364
48
0.764706
5862fe819ece926af5790b41dc00fef2206c9909
413
//: Connection.java package com.wuroc.chaptersix2; /** * @author WuRoc * @GitHub www.github.com/WuRoc * @version 1.0 * @2020年7月15日 * import static com.wuroc.util.Print.*; * */ public class Connection { private static int counter = 0; private int id = counter++; Connection(){} public String toString() { return "Connection " + id; } public void doSomething() {} }
15.296296
41
0.617433
67ed6fafb5c32a89a0d9e474bdb23607a1f3f998
11,179
package com.github.anno4j.model.impl; import com.github.anno4j.Anno4j; import com.github.anno4j.model.*; import com.github.anno4j.model.impl.style.CssStylesheet; import com.github.anno4j.model.impl.targets.SpecificResource; import com.github.anno4j.querying.QueryService; import org.apache.marmotta.ldpath.parser.ParseException; import org.junit.Before; import org.junit.Test; import org.openrdf.annotations.Iri; import org.openrdf.model.Resource; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.UpdateExecutionException; import org.openrdf.repository.RepositoryException; import org.openrdf.rio.RDFFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AnnotationTest { private Anno4j anno4j; @Before public void setUp() throws Exception { this.anno4j = new Anno4j(); } @Test public void testPersistAnnotation() throws Exception { String timestamp = "2015-01-28T12:00:00Z"; // Create test annotation Annotation annotation = anno4j.createObject(Annotation.class); annotation.setGenerated(timestamp); annotation.setCreated(timestamp); // query persisted object Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(annotation.getResource().toString(), result.getResource().toString()); assertEquals(annotation.getCreated(), result.getCreated()); assertEquals(annotation.getGenerated(), result.getGenerated()); } @Test public void testResourceDefinition() throws Exception { // Create annotation Annotation annotation = anno4j.createObject(Annotation.class, (Resource) new URIImpl("http://www.somepage.org/resource1/")); // Query persisted object Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); // Tests assertEquals(annotation.getResource(), result.getResource()); } @Test public void testSingleTarget() throws RepositoryException, InstantiationException, IllegalAccessException, UpdateExecutionException, MalformedQueryException { // Create annotation Annotation annotation = anno4j.createObject(Annotation.class); // Create specific resource SpecificResource specificResource = anno4j.createObject(SpecificResource.class); ResourceObject resourceObject = anno4j.createObject(ResourceObject.class); resourceObject.setResourceAsString("http://www.somepage.org/resource1/"); specificResource.setSource(resourceObject); annotation.addTarget(specificResource); // Query annotation Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); // Tests assertEquals(1, result.getTargets().size()); assertEquals(("http://www.somepage.org/resource1/"), ((SpecificResource) result.getTargets().toArray()[0]).getSource().getResource().toString()); } @Test public void testMultipleTargets() throws RepositoryException, InstantiationException, IllegalAccessException, UpdateExecutionException, MalformedQueryException { // Create annotation Annotation annotation = anno4j.createObject(Annotation.class); // Create specific resource1 SpecificResource specificResource = anno4j.createObject(SpecificResource.class); ResourceObject resourceObject = anno4j.createObject(ResourceObject.class); resourceObject.setResourceAsString("http://www.somepage.org/resource1/"); specificResource.setSource(resourceObject); annotation.addTarget(specificResource); // Create specific resource2 SpecificResource specificResource2 = anno4j.createObject(SpecificResource.class); ResourceObject resourceObject2 = anno4j.createObject(ResourceObject.class); resourceObject2.setResourceAsString("http://www.somepage.org/resource2/"); specificResource2.setSource(resourceObject2); annotation.addTarget(specificResource2); // Query annotation Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); // Tests List<String> urls = new ArrayList<>(); for(Target target : result.getTargets()) { urls.add(((SpecificResource) target).getSource().getResource().toString()); } assertTrue(urls.contains("http://www.somepage.org/resource1/")); assertTrue(urls.contains("http://www.somepage.org/resource2/")); assertEquals(2, result.getTargets().size()); } @Test public void testSerializedAtAndAnnotatedAt() throws RepositoryException, IllegalAccessException, InstantiationException { int year = 2015; int month = 12; int day = 16; int hours = 12; int minutes = 0; int seconds = 0; String timezone = "UTC"; int hours2 = 0; int minutes2 = 5; int seconds2 = 16; Annotation annotation = anno4j.createObject(Annotation.class); annotation.setGenerated(year, month, day, hours, minutes, seconds, timezone); annotation.setCreated(year, month, day, hours2, minutes2, seconds2, timezone); // Query annotation Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals("2015-12-16T12:00:00Z", result.getGenerated()); assertEquals("2015-12-16T00:05:16Z", result.getCreated()); } @Test public void testMotivation() throws RepositoryException, IllegalAccessException, InstantiationException { Annotation annotation = anno4j.createObject(Annotation.class); Motivation comment = MotivationFactory.getCommenting(this.anno4j); Motivation bookmark = MotivationFactory.getBookmarking(this.anno4j); Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(0, result.getMotivatedBy().size()); annotation.addMotivation(comment); result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(1, result.getMotivatedBy().size()); HashSet<Motivation> motivations = new HashSet<Motivation>(); motivations.add(comment); motivations.add(bookmark); annotation.setMotivatedBy(motivations); result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(2, result.getMotivatedBy().size()); } @Test public void testBodyText() throws RepositoryException, IllegalAccessException, InstantiationException { Annotation annotation = this.anno4j.createObject(Annotation.class); annotation.addBodyText("test1"); Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertTrue(result.getBodyTexts().contains("test1")); HashSet<String> set = new HashSet<String>(); set.add("test2"); set.add("test3"); annotation.setBodyTexts(set); result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(2, result.getBodyTexts().size()); assertTrue(result.getBodyTexts().contains("test2")); assertTrue(result.getBodyTexts().contains("test3")); } @Test public void testAnnotationWithCreation() throws RepositoryException, IllegalAccessException, InstantiationException { Annotation anno = this.anno4j.createObject(Annotation.class); anno.setCreated("2015-01-28T12:00:00Z"); SpecificResource target = this.anno4j.createObject(SpecificResource.class); target.setCreated("2015-01-28T12:00:00+01:00"); anno.addTarget(target); Annotation result = anno4j.findByID(Annotation.class, anno.getResourceAsString()); assertEquals(anno.getCreated(), result.getCreated()); assertEquals(((SpecificResource) anno.getTargets().toArray()[0]).getCreated(), ((SpecificResource) result.getTargets().toArray()[0]).getCreated()); } @Test public void testAudiences() throws RepositoryException, IllegalAccessException, InstantiationException, ParseException, MalformedQueryException, QueryEvaluationException { Annotation annotation = this.anno4j.createObject(Annotation.class); Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(0, result.getAudiences().size()); TestAudience audience = this.anno4j.createObject(TestAudience.class); annotation.addAudience(audience); QueryService qs = this.anno4j.createQueryService(); qs.addPrefix("schema", "https://schema.org/"); qs.addCriteria("schema:audience[is-a schema:TestAudience]"); List<Annotation> results = qs.execute(Annotation.class); result = results.get(0); assertEquals(1, result.getAudiences().size()); HashSet<Audience> audiences = new HashSet<>(); audiences.add(this.anno4j.createObject(TestAudience.class)); audiences.add(this.anno4j.createObject(TestAudience.class)); annotation.setAudiences(audiences); result = anno4j.findByID(Annotation.class, annotation.getResourceAsString()); assertEquals(2, result.getAudiences().size()); } @Iri("https://schema.org/TestAudience") public interface TestAudience extends Audience { } @Test public void testStyle() throws RepositoryException, IllegalAccessException, InstantiationException, ParseException, MalformedQueryException, QueryEvaluationException { Annotation annotation = this.anno4j.createObject(Annotation.class); CssStylesheet sheet = this.anno4j.createObject(CssStylesheet.class); annotation.setStyledBy(sheet); QueryService qs = this.anno4j.createQueryService(); qs.addCriteria("oa:styledBy[is-a oa:CssStyle]"); List<Annotation> result = qs.execute(Annotation.class); assertEquals(1, result.size()); } @Test public void testGetTriples() throws RepositoryException, IllegalAccessException, InstantiationException, UpdateExecutionException, MalformedQueryException { Annotation annotation = this.anno4j.createObject(Annotation.class); // Create specific resource1 SpecificResource specificResource = anno4j.createObject(SpecificResource.class); ResourceObject resourceObject = anno4j.createObject(ResourceObject.class); resourceObject.setResourceAsString("http://www.somepage.org/resource1/"); specificResource.setSource(resourceObject); annotation.addTarget(specificResource); Motivation comment = MotivationFactory.getCommenting(this.anno4j); annotation.addTarget(specificResource); annotation.addMotivation(comment); System.out.println(annotation.getTriples(RDFFormat.RDFXML)); } }
40.357401
175
0.715091
86c1d6d20a951a949eeadb5a43de0f15311b7254
1,410
package org.firstinspires.ftc.teamcode.testOpModes; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import org.firstinspires.ftc.teamcode.RobotClass; @Disabled public class testMotors extends OpMode { private RobotClass robot = new RobotClass(); @Override public void init() { robot.init(hardwareMap); telemetry.addData("ready",""); } @Override public void loop() { robot.drive.setMotorPowers(1,1,1,1); long time = System.currentTimeMillis(); while (System.currentTimeMillis() < time + 1000) { telemetry.addData("bl",robot.BackLeft.getCurrentPosition()); telemetry.addData("br",robot.BackRight.getCurrentPosition()); telemetry.addData("fl",robot.FrontLeft.getCurrentPosition()); telemetry.addData("fr",robot.FrontRight.getCurrentPosition()); telemetry.update(); } robot.drive.STOP(); time = System.currentTimeMillis(); while (true) { telemetry.addData("bl",robot.BackLeft.getCurrentPosition()); telemetry.addData("br",robot.BackRight.getCurrentPosition()); telemetry.addData("fl",robot.FrontLeft.getCurrentPosition()); telemetry.addData("fr",robot.FrontRight.getCurrentPosition()); telemetry.update(); } } }
32.790698
74
0.653191
977b99f2bd958ca8ca0fc082f8e2401246f09c2c
5,678
/* * Copyright (C) 2017 Republic Wireless * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rw.legion.columncheck; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class IntegerCheckerTest { private IntegerChecker icUnspecified; private IntegerChecker icShortUpper; private IntegerChecker icShort; private IntegerChecker icInt; private IntegerChecker icLong; private String intTypeShortUpper = "ShOrT"; private String intTypeShort = "short"; private String intTypeInt = "int"; private String intTypeLong = "long"; private String intTypeInvalid = "fooBar"; private int safeLengthShort = 4; private int safeLengthInt = 9; private int safeLengthLong = 18; private String validShort = "1234"; private String validShortNeg = "-1234"; private String validInt = "123456789"; private String validIntNeg = "-123456789"; private String validLong = "123456789012345"; private String validLongNeg = "-123456789012345"; private String invalidFloat = "1f"; private String invalidDouble = "1.0"; private String invalidString = "FooBar"; private JsonObject buildJson (String intType) { if (intType == null) { return new JsonObject(); } String json = "\n" + "{\n" + " \"intType\": \"" + intType + "\"\n" + "}"; JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(json).getAsJsonObject(); return obj; } @BeforeEach void setUp() throws IntegerChecker.InvalidIntTypeException { icUnspecified = new IntegerChecker(buildJson(null)); icShortUpper = new IntegerChecker(buildJson(intTypeShortUpper)); icShort = new IntegerChecker(buildJson(intTypeShort)); icInt = new IntegerChecker(buildJson(intTypeInt)); icLong = new IntegerChecker(buildJson(intTypeLong)); } @Test void throwsInvalidIntTypeException() { assertThrows(IntegerChecker.InvalidIntTypeException.class, () -> new IntegerChecker(buildJson(intTypeInvalid))); } @Test void validatesShortUpperVars() { assertEquals(intTypeShort, icShortUpper.getIntType()); assertEquals(safeLengthShort, icShortUpper.getSafeLength()); } @Test void validatesShortVars() { assertEquals(intTypeShort, icShort.getIntType()); assertEquals(safeLengthShort, icShort.getSafeLength()); } @Test void validatesShortPos() { assertEquals(true, icShort.validates(validShort)); assertEquals(false, icShort.validates(validInt)); assertEquals(false, icShort.validates(validLong)); } @Test void validatesShortNeg() { assertEquals(true, icShort.validates(validShortNeg)); assertEquals(false, icShort.validates(validIntNeg)); assertEquals(false, icShort.validates(validLongNeg)); } @Test void validatesShortNan() { assertEquals(false, icShort.validates(invalidFloat)); assertEquals(false, icShort.validates(invalidDouble)); assertEquals(false, icShort.validates(invalidString)); } @Test void validatesIntVars() { assertEquals(intTypeInt, icInt.getIntType()); assertEquals(safeLengthInt, icInt.getSafeLength()); } @Test void validatesIntPos() { assertEquals(true, icInt.validates(validShort)); assertEquals(true, icInt.validates(validInt)); assertEquals(false, icInt.validates(validLong)); } @Test void validatesIntNeg() { assertEquals(true, icInt.validates(validShortNeg)); assertEquals(true, icInt.validates(validIntNeg)); assertEquals(false, icInt.validates(validLongNeg)); } @Test void validatesIntNan() { assertEquals(false, icInt.validates(invalidFloat)); assertEquals(false, icInt.validates(invalidDouble)); assertEquals(false, icInt.validates(invalidString)); } @Test void validatesLongVars() { assertEquals(intTypeLong, icLong.getIntType()); assertEquals(safeLengthLong, icLong.getSafeLength()); } @Test void validatesLongPos() { assertEquals(true, icLong.validates(validShort)); assertEquals(true, icLong.validates(validInt)); assertEquals(true, icLong.validates(validLong)); } @Test void validatesLongNeg() { assertEquals(true, icLong.validates(validShortNeg)); assertEquals(true, icLong.validates(validIntNeg)); assertEquals(true, icLong.validates(validLongNeg)); } @Test void validatesLongNan() { assertEquals(false, icLong.validates(invalidFloat)); assertEquals(false, icLong.validates(invalidDouble)); assertEquals(false, icLong.validates(invalidString)); } @Test void validatesUnspecifiedVars() { assertEquals(intTypeInt, icUnspecified.getIntType()); assertEquals(safeLengthInt, icInt.getSafeLength()); } }
31.898876
120
0.680521
c5701428356a304a267faf868a26fbbc19ef5953
614
public static File gzipLog() throws IOException { RunnerClass.nfh.flush(); File log = new File(RunnerClass.homedir + "pj.log"); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(log.getCanonicalPath() + ".pjl"))); FileInputStream in = new FileInputStream(log); int bufferSize = 4 * 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); return new File(log.getCanonicalPath() + ".pjl"); }
43.857143
117
0.615635
c04e01dd6b969e5a140912989fbf43e7f08ecff8
1,199
/* * This file is generated by jOOQ. */ package org.jooq.mcve.java.packages.types.udt.records; import java.util.Arrays; import java.util.Collection; import org.jooq.impl.ArrayRecordImpl; import org.jooq.impl.SQLDataType; import org.jooq.mcve.java.Devsb; import org.jooq.mcve.java.packages.Types; /** * This class is generated by jOOQ. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class TAssociativearrayRecord extends ArrayRecordImpl<String> { private static final long serialVersionUID = 1L; /** * Create a new <code>DEVSB.TYPES.T_ASSOCIATIVEARRAY</code> record */ public TAssociativearrayRecord() { super(Devsb.DEVSB, Types.TYPES, "T_ASSOCIATIVEARRAY", SQLDataType.VARCHAR(240)); } /** * Create a new <code>DEVSB.TYPES.T_ASSOCIATIVEARRAY</code> record */ public TAssociativearrayRecord(String... array) { this(); if (array != null) addAll(Arrays.asList(array)); } /** * Create a new <code>DEVSB.TYPES.T_ASSOCIATIVEARRAY</code> record */ public TAssociativearrayRecord(Collection<? extends String> collection) { this(); addAll(collection); } }
24.979167
88
0.673061
9adacc84bdeb1c4361aa72e28919efaf655a6aeb
5,977
package com.project.qa.ui.helpers; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JSWaiter { private static final Logger LOGGER = LoggerFactory.getLogger(JSWaiter.class); private static WebDriver jsWaitDriver; private static WebDriverWait jsWait; private static JavascriptExecutor jsExec; //Get the driver @Deprecated public static void setDriver(WebDriver driver) { jsWaitDriver = driver; jsWait = new WebDriverWait(jsWaitDriver, 10); jsExec = (JavascriptExecutor) jsWaitDriver; } private void ajaxComplete() { jsExec.executeScript("var callback = arguments[arguments.length - 1];" + "var xhr = new XMLHttpRequest();" + "xhr.open('GET', '/Ajax_call', true);" + "xhr.onreadystatechange = function() {" + " if (xhr.readyState == 4) {" + " callback(xhr.responseText);" + " }" + "};" + "xhr.send();"); } private void waitForJQueryLoad() { try { ExpectedCondition<Boolean> jQueryLoad = driver -> ((Long) ((JavascriptExecutor) this.jsWaitDriver) .executeScript("return jQuery.active") == 0); boolean jqueryReady = (Boolean) jsExec.executeScript("return jQuery.active==0"); if (!jqueryReady) { jsWait.until(jQueryLoad); } } catch (WebDriverException ignored) { } } private void waitForAngularLoad() { String angularReadyScript = "return angular.element(document).injector().get('$http').pendingRequests.length === 0"; angularLoads(angularReadyScript); } private void waitUntilJSReady() { try { ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) this.jsWaitDriver) .executeScript("return document.readyState").toString().equals("complete"); boolean jsReady = jsExec.executeScript("return document.readyState").toString().equals("complete"); if (!jsReady) { jsWait.until(jsLoad); } } catch (WebDriverException ignored) { } } private void waitUntilJQueryReady() { Boolean jQueryDefined = (Boolean) jsExec.executeScript("return typeof jQuery != 'undefined'"); if (jQueryDefined) { poll(20); waitForJQueryLoad(); poll(20); } } public void waitUntilAngularReady() { try { Boolean angularUnDefined = (Boolean) jsExec.executeScript("return window.angular === undefined"); if (!angularUnDefined) { Boolean angularInjectorUnDefined = (Boolean) jsExec.executeScript("return angular.element(document).injector() === undefined"); if (!angularInjectorUnDefined) { poll(20); waitForAngularLoad(); poll(20); } } } catch (WebDriverException ignored) { } } public void waitUntilAngular5Ready() { try { Object angular5Check = jsExec.executeScript("return getAllAngularRootElements()[0].attributes['ng-version']"); if (angular5Check != null) { Boolean angularPageLoaded = (Boolean) jsExec.executeScript("return window.getAllAngularTestabilities().findIndex(x=>!x.isStable()) === -1"); if (!angularPageLoaded) { poll(20); waitForAngular5Load(); poll(20); } } } catch (WebDriverException ignored) { } } private void waitForAngular5Load() { String angularReadyScript = "return window.getAllAngularTestabilities().findIndex(x=>!x.isStable()) === -1"; angularLoads(angularReadyScript); } private void angularLoads(String angularReadyScript) { try { ExpectedCondition<Boolean> angularLoad = driver -> Boolean.valueOf(((JavascriptExecutor) driver) .executeScript(angularReadyScript).toString()); boolean angularReady = Boolean.valueOf(jsExec.executeScript(angularReadyScript).toString()); if (!angularReady) { jsWait.until(angularLoad); } } catch (WebDriverException ignored) { } } public void waitAllRequest() { LOGGER.info("waiting for all js requests to complete..."); waitUntilJSReady(); ajaxComplete(); waitUntilJQueryReady(); waitUntilAngularReady(); waitUntilAngular5Ready(); LOGGER.info("all js requests loaded successfully..."); } /** * Method to make sure a specific element has loaded on the page * * @param by * @param expected */ public void waitForElementAreComplete(By by, int expected) { ExpectedCondition<Boolean> angularLoad = driver -> { int loadingElements = this.jsWaitDriver.findElements(by).size(); return loadingElements >= expected; }; jsWait.until(angularLoad); } /** * Waits for the elements animation to be completed * * @param css */ public void waitForAnimationToComplete(String css) { ExpectedCondition<Boolean> angularLoad = driver -> { int loadingElements = this.jsWaitDriver.findElements(By.cssSelector(css)).size(); return loadingElements == 0; }; jsWait.until(angularLoad); } private void poll(long milis) { try { Thread.sleep(milis); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }
33.960227
156
0.603145
ca044be2d1615a54b161cf3de4e2e6349d849b10
2,315
package com.liulishuo.engzo.todo; import com.liulishuo.demo.R; import com.liulishuo.engzo.MainActivity; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import android.app.Activity; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.notNullValue; @RunWith(AndroidJUnit4.class) public class EspressoTest { @Rule public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class); @Test public void mainActivityTest() { onView(withId(R.id.user_info_tv)).perform(click()); onView(allOf(withId(R.id.user_info_tv), isDisplayed())) .check(matches(notNullValue())); Activity mainActivity = rule.getActivity(); // test toast // onView(withText("用户名不能为空")).inRoot(withDecorView(not(mainActivity.getWindow().getDecorView()))).check(matches(isDisplayed())); } /*@Test public void testPasswordNotEmpty() { //注入用户名 onView(withId(R.id.login_username)).perform(click(), clearText(), typeText("1234567"), closeSoftKeyboard()); //点击登录按钮 onView(withId(R.id.login_login_btn)).perform(click()); //弹窗提示 onView(withText("密码不能为空")).inRoot(withDecorView(not(mainActivity.getWindow().getDecorView()))).check(matches(isDisplayed())); } @Test public void testLogin () { //注入用户名 onView(withId(R.id.login_username)).perform(typeText("1234567"), closeSoftKeyboard()); //注入密码 onView(withId(R.id.login_password)).perform(typeText("123456"), closeSoftKeyboard()); //点击登录按钮 onView(withId(R.id.login_login_btn)).perform(click()); //弹窗提示 登录成功 onView(withText("登录成功")).inRoot(withDecorView(not(mainActivity.getWindow().getDecorView()))).check(matches(isDisplayed())); }}*/ }
33.550725
136
0.710583
4d5c3964dfe32fc21727d896440e78171d92c9a4
17,061
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.textclassifier; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.RestrictTo; import androidx.collection.ArrayMap; import androidx.core.os.LocaleListCompat; import androidx.core.util.Preconditions; import androidx.textclassifier.TextClassifier.EntityType; import java.util.Locale; import java.util.Map; /** * Information about where text selection should be. */ public final class TextSelection { private static final String EXTRA_START_INDEX = "start"; private static final String EXTRA_END_INDEX = "end"; private static final String EXTRA_ENTITY_CONFIDENCE = "entity_conf"; private static final String EXTRA_ID = "id"; private static final String EXTRA_EXTRAS = "extras"; private final int mStartIndex; private final int mEndIndex; @NonNull private final EntityConfidence mEntityConfidence; @Nullable private final String mId; @NonNull private final Bundle mExtras; TextSelection( int startIndex, int endIndex, @NonNull EntityConfidence entityConfidence, @Nullable String id, @NonNull Bundle extras) { mStartIndex = startIndex; mEndIndex = endIndex; mEntityConfidence = entityConfidence; mId = id; mExtras = extras; } /** * Returns the start index of the text selection. */ public int getSelectionStartIndex() { return mStartIndex; } /** * Returns the end index of the text selection. */ public int getSelectionEndIndex() { return mEndIndex; } /** * Returns the number of entities found in the classified text. */ @IntRange(from = 0) public int getEntityCount() { return mEntityConfidence.getEntities().size(); } /** * Returns the entity at the specified index. Entities are ordered from high confidence * to low confidence. * * @throws IndexOutOfBoundsException if the specified index is out of range. * @see #getEntityCount() for the number of entities available. */ @NonNull public @EntityType String getEntity(int index) { return mEntityConfidence.getEntities().get(index); } /** * Returns the confidence score for the specified entity. The value ranges from * 0 (low confidence) to 1 (high confidence). 0 indicates that the entity was not found for the * classified text. */ @FloatRange(from = 0.0, to = 1.0) public float getConfidenceScore(@EntityType String entity) { return mEntityConfidence.getConfidenceScore(entity); } /** * Returns the id, if one exists, for this object. */ @Nullable public String getId() { return mId; } /** * Returns the extended, vendor specific data. * * <p><b>NOTE: </b>Each call to this method returns a new bundle copy so clients should * prefer to hold a reference to the returned bundle rather than frequently calling this * method. Avoid updating the content of this bundle. On pre-O devices, the values in the * Bundle are not deep copied. */ @NonNull public Bundle getExtras() { return BundleUtils.deepCopy(mExtras); } @Override public String toString() { return String.format( Locale.US, "TextSelection {id=%s, startIndex=%d, endIndex=%d, entities=%s}", mId, mStartIndex, mEndIndex, mEntityConfidence); } /** * Adds this selection to a Bundle that can be read back with the same parameters * to {@link #createFromBundle(Bundle)}. */ @NonNull public Bundle toBundle() { final Bundle bundle = new Bundle(); bundle.putInt(EXTRA_START_INDEX, mStartIndex); bundle.putInt(EXTRA_END_INDEX, mEndIndex); BundleUtils.putMap(bundle, EXTRA_ENTITY_CONFIDENCE, mEntityConfidence.getConfidenceMap()); bundle.putString(EXTRA_ID, mId); bundle.putBundle(EXTRA_EXTRAS, mExtras); return bundle; } /** * Extracts a selection from a bundle that was added using {@link #toBundle()}. */ @NonNull public static TextSelection createFromBundle(@NonNull Bundle bundle) { final Builder builder = new Builder( bundle.getInt(EXTRA_START_INDEX), bundle.getInt(EXTRA_END_INDEX)) .setId(bundle.getString(EXTRA_ID)) .setExtras(bundle.getBundle(EXTRA_EXTRAS)); for (Map.Entry<String, Float> entityConfidence : BundleUtils.getFloatStringMapOrThrow( bundle, EXTRA_ENTITY_CONFIDENCE).entrySet()) { builder.setEntityType(entityConfidence.getKey(), entityConfidence.getValue()); } return builder.build(); } /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) @RequiresApi(26) @NonNull @SuppressLint("RestrictedApi") static TextSelection fromPlatform( @NonNull android.view.textclassifier.TextSelection textSelection) { Preconditions.checkNotNull(textSelection); Builder builder = new Builder( textSelection.getSelectionStartIndex(), textSelection.getSelectionEndIndex()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { builder.setId(textSelection.getId()); } final int entityCount = textSelection.getEntityCount(); for (int i = 0; i < entityCount; i++) { String entity = textSelection.getEntity(i); builder.setEntityType(entity, textSelection.getConfidenceScore(entity)); } return builder.build(); } /** * @hide */ @SuppressLint("WrongConstant") // Lint does not know @EntityType in platform and here are same. @RestrictTo(RestrictTo.Scope.LIBRARY) @RequiresApi(26) @NonNull Object toPlatform() { android.view.textclassifier.TextSelection.Builder builder = new android.view.textclassifier.TextSelection.Builder( getSelectionStartIndex(), getSelectionEndIndex()); if (getId() != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { builder.setId(getId()); } final int entityCount = getEntityCount(); for (int i = 0; i < entityCount; i++) { String entity = getEntity(i); builder.setEntityType(entity, getConfidenceScore(entity)); } return builder.build(); } /** * Builder used to build {@link TextSelection} objects. */ public static final class Builder { private final int mStartIndex; private final int mEndIndex; @NonNull private final Map<String, Float> mEntityConfidence = new ArrayMap<>(); @Nullable private String mId; @Nullable private Bundle mExtras; /** * Creates a builder used to build {@link TextSelection} objects. * * @param startIndex the start index of the text selection. * @param endIndex the end index of the text selection. Must be greater than startIndex */ @SuppressLint("RestrictedApi") public Builder(@IntRange(from = 0) int startIndex, @IntRange(from = 0) int endIndex) { Preconditions.checkArgument(startIndex >= 0); Preconditions.checkArgument(endIndex > startIndex); mStartIndex = startIndex; mEndIndex = endIndex; } /** * Sets an entity type for the classified text and assigns a confidence score. * * @param confidenceScore a value from 0 (low confidence) to 1 (high confidence). * 0 implies the entity does not exist for the classified text. * Values greater than 1 are clamped to 1. */ @NonNull public Builder setEntityType( @NonNull @EntityType String type, @FloatRange(from = 0.0, to = 1.0) float confidenceScore) { mEntityConfidence.put(type, confidenceScore); return this; } /** * Sets an id for the TextSelection object. */ @NonNull public Builder setId(@Nullable String id) { mId = id; return this; } /** * Sets the extended, vendor specific data. */ @NonNull public Builder setExtras(@Nullable Bundle extras) { mExtras = extras; return this; } /** * Builds and returns {@link TextSelection} object. */ @NonNull public TextSelection build() { return new TextSelection( mStartIndex, mEndIndex, new EntityConfidence(mEntityConfidence), mId, mExtras == null ? Bundle.EMPTY : BundleUtils.deepCopy(mExtras)); } } /** * A request object for generating TextSelection. */ public static final class Request { private static final String EXTRA_TEXT = "text"; private static final String EXTRA_START_INDEX = "start"; private static final String EXTRA_END_INDEX = "end"; private static final String EXTRA_DEFAULT_LOCALES = "locales"; private static final String EXTRA_CALLING_PACKAGE_NAME = "calling_package"; private final CharSequence mText; private final int mStartIndex; private final int mEndIndex; @Nullable private final LocaleListCompat mDefaultLocales; @NonNull private final Bundle mExtras; Request( CharSequence text, int startIndex, int endIndex, LocaleListCompat defaultLocales, Bundle extras) { mText = text; mStartIndex = startIndex; mEndIndex = endIndex; mDefaultLocales = defaultLocales; mExtras = extras; } /** * Returns the text providing context for the selected text (which is specified by the * sub sequence starting at startIndex and ending at endIndex). */ @NonNull public CharSequence getText() { return mText; } /** * Returns start index of the selected part of text. */ @IntRange(from = 0) public int getStartIndex() { return mStartIndex; } /** * Returns end index of the selected part of text. */ @IntRange(from = 0) public int getEndIndex() { return mEndIndex; } /** * @return ordered list of locale preferences that can be used to disambiguate the * provided text. */ @Nullable public LocaleListCompat getDefaultLocales() { return mDefaultLocales; } /** * Returns the extended, vendor specific data. * * <p><b>NOTE: </b>Each call to this method returns a new bundle copy so clients should * prefer to hold a reference to the returned bundle rather than frequently calling this * method. Avoid updating the content of this bundle. On pre-O devices, the values in the * Bundle are not deep copied. */ @NonNull public Bundle getExtras() { return BundleUtils.deepCopy(mExtras); } /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) @RequiresApi(28) @NonNull static TextSelection.Request fromPlatfrom( @NonNull android.view.textclassifier.TextSelection.Request request) { return new TextSelection.Request.Builder( request.getText(), request.getStartIndex(), request.getEndIndex()) .setDefaultLocales(ConvertUtils.wrapLocalList(request.getDefaultLocales())) .build(); } /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) @RequiresApi(28) @NonNull Object toPlatform() { return new android.view.textclassifier.TextSelection.Request.Builder( mText, mStartIndex, mEndIndex) .setDefaultLocales(ConvertUtils.unwrapLocalListCompat(mDefaultLocales)) .build(); } /** * A builder for building TextSelection requests. */ public static final class Builder { private final CharSequence mText; private final int mStartIndex; private final int mEndIndex; private Bundle mExtras; @Nullable private LocaleListCompat mDefaultLocales; /** * @param text text providing context for the selected text (which is specified by the * sub sequence starting at selectionStartIndex and ending at selectionEndIndex) * @param startIndex start index of the selected part of text * @param endIndex end index of the selected part of text */ @SuppressLint("RestrictedApi") public Builder( @NonNull CharSequence text, @IntRange(from = 0) int startIndex, @IntRange(from = 0) int endIndex) { Preconditions.checkArgument(text != null); Preconditions.checkArgument(startIndex >= 0); Preconditions.checkArgument(endIndex <= text.length()); Preconditions.checkArgument(endIndex > startIndex); mText = text; mStartIndex = startIndex; mEndIndex = endIndex; } /** * @param defaultLocales ordered list of locale preferences that may be used to * disambiguate the provided text. If no locale preferences exist, set this to null * or an empty locale list. * * @return this builder. */ @NonNull public Builder setDefaultLocales(@Nullable LocaleListCompat defaultLocales) { mDefaultLocales = defaultLocales; return this; } /** * Sets the extended, vendor specific data. * * @return this builder */ @NonNull public Builder setExtras(@Nullable Bundle extras) { mExtras = extras; return this; } /** * Builds and returns the request object. */ @NonNull public Request build() { return new Request(mText, mStartIndex, mEndIndex, mDefaultLocales, mExtras == null ? Bundle.EMPTY : BundleUtils.deepCopy(mExtras)); } } /** * Adds this Request to a Bundle that can be read back with the same parameters * to {@link #createFromBundle(Bundle)}. */ @NonNull public Bundle toBundle() { final Bundle bundle = new Bundle(); bundle.putCharSequence(EXTRA_TEXT, mText); bundle.putInt(EXTRA_START_INDEX, mStartIndex); bundle.putInt(EXTRA_END_INDEX, mEndIndex); BundleUtils.putLocaleList(bundle, EXTRA_DEFAULT_LOCALES, mDefaultLocales); bundle.putBundle(EXTRA_EXTRAS, mExtras); return bundle; } /** * Extracts a Request from a bundle that was added using {@link #toBundle()}. */ @NonNull public static Request createFromBundle(@NonNull Bundle bundle) { final Builder builder = new Builder( bundle.getString(EXTRA_TEXT), bundle.getInt(EXTRA_START_INDEX), bundle.getInt(EXTRA_END_INDEX)) .setDefaultLocales(BundleUtils.getLocaleList(bundle, EXTRA_DEFAULT_LOCALES)) .setExtras(bundle.getBundle(EXTRA_EXTRAS)); final Request request = builder.build(); return request; } } }
34.606491
100
0.602778
20eea70952020160e2531f69b4126a7fdcc17642
7,137
package org.frekele.fiscal.focus.nfe.client.model.entities.requisicao.cancelamento; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import org.frekele.fiscal.focus.nfe.client.converter.OffsetDateTimeJsonConverter; import org.frekele.fiscal.focus.nfe.client.core.FocusNFeEntity; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.time.OffsetDateTime; /** * Requisicao Cancelamento, Inclui os dados completos da requisição de cancelamento da nota fiscal - 'requisicao_cancelamento'. * * @author frekele - Leandro Kersting de Freitas */ @JsonInclude(JsonInclude.Include.NON_NULL) @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class NFeRequisicaoCancelamento implements FocusNFeEntity { private static final long serialVersionUID = 1L; @JsonProperty("versao") private String versao; @JsonProperty("id_tag") private String idTag; @JsonProperty("codigo_orgao") private String codigoOrgao; @JsonProperty("ambiente") private String ambiente; @JsonProperty("cnpj") private String cnpj; @JsonProperty("chave_nfe") private String chaveNfe; //Formato padrão ISO, exemplo: “2016-12-25T12:00-0300”. @OffsetDateTimeJsonConverter @JsonProperty("data_evento") private OffsetDateTime dataEvento; @JsonProperty("tipo_evento") private String tipoEvento; @JsonProperty("numero_sequencial_evento") private String numeroSequencialEvento; @JsonProperty("versao_evento") private String versaoEvento; @JsonProperty("descricao_evento") private String descricaoEvento; @JsonProperty("protocolo") private String protocolo; @JsonProperty("justificativa") private String justificativa; public NFeRequisicaoCancelamento() { super(); } private NFeRequisicaoCancelamento(Builder builder) { setVersao(builder.versao); setIdTag(builder.idTag); setCodigoOrgao(builder.codigoOrgao); setAmbiente(builder.ambiente); setCnpj(builder.cnpj); setChaveNfe(builder.chaveNfe); setDataEvento(builder.dataEvento); setTipoEvento(builder.tipoEvento); setNumeroSequencialEvento(builder.numeroSequencialEvento); setVersaoEvento(builder.versaoEvento); setDescricaoEvento(builder.descricaoEvento); setProtocolo(builder.protocolo); setJustificativa(builder.justificativa); } public static Builder newBuilder() { return new Builder(); } public String getVersao() { return versao; } public void setVersao(String versao) { this.versao = versao; } public String getIdTag() { return idTag; } public void setIdTag(String idTag) { this.idTag = idTag; } public String getCodigoOrgao() { return codigoOrgao; } public void setCodigoOrgao(String codigoOrgao) { this.codigoOrgao = codigoOrgao; } public String getAmbiente() { return ambiente; } public void setAmbiente(String ambiente) { this.ambiente = ambiente; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getChaveNfe() { return chaveNfe; } public void setChaveNfe(String chaveNfe) { this.chaveNfe = chaveNfe; } public OffsetDateTime getDataEvento() { return dataEvento; } public void setDataEvento(OffsetDateTime dataEvento) { this.dataEvento = dataEvento; } public String getTipoEvento() { return tipoEvento; } public void setTipoEvento(String tipoEvento) { this.tipoEvento = tipoEvento; } public String getNumeroSequencialEvento() { return numeroSequencialEvento; } public void setNumeroSequencialEvento(String numeroSequencialEvento) { this.numeroSequencialEvento = numeroSequencialEvento; } public String getVersaoEvento() { return versaoEvento; } public void setVersaoEvento(String versaoEvento) { this.versaoEvento = versaoEvento; } public String getDescricaoEvento() { return descricaoEvento; } public void setDescricaoEvento(String descricaoEvento) { this.descricaoEvento = descricaoEvento; } public String getProtocolo() { return protocolo; } public void setProtocolo(String protocolo) { this.protocolo = protocolo; } public String getJustificativa() { return justificativa; } public void setJustificativa(String justificativa) { this.justificativa = justificativa; } /** * NFeRequisicaoCancelamento Builder Pattern. */ public static final class Builder { private String versao; private String idTag; private String codigoOrgao; private String ambiente; private String cnpj; private String chaveNfe; private OffsetDateTime dataEvento; private String tipoEvento; private String numeroSequencialEvento; private String versaoEvento; private String descricaoEvento; private String protocolo; private String justificativa; private Builder() { } public Builder withVersao(String val) { versao = val; return this; } public Builder withIdTag(String val) { idTag = val; return this; } public Builder withCodigoOrgao(String val) { codigoOrgao = val; return this; } public Builder withAmbiente(String val) { ambiente = val; return this; } public Builder withCnpj(String val) { cnpj = val; return this; } public Builder withChaveNfe(String val) { chaveNfe = val; return this; } public Builder withDataEvento(OffsetDateTime val) { dataEvento = val; return this; } public Builder withTipoEvento(String val) { tipoEvento = val; return this; } public Builder withNumeroSequencialEvento(String val) { numeroSequencialEvento = val; return this; } public Builder withVersaoEvento(String val) { versaoEvento = val; return this; } public Builder withDescricaoEvento(String val) { descricaoEvento = val; return this; } public Builder withProtocolo(String val) { protocolo = val; return this; } public Builder withJustificativa(String val) { justificativa = val; return this; } public NFeRequisicaoCancelamento build() { return new NFeRequisicaoCancelamento(this); } } }
23.949664
127
0.644809
b5ad09f8ffea140cc8dad753b9c4cb89d2067751
1,408
package org.jabref.gui.fieldeditors; import org.jabref.gui.autocompleter.AutoCompleteSuggestionProvider; import org.jabref.logic.integrity.FieldCheckers; import org.jabref.logic.l10n.Localization; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; public class TypeEditorViewModel extends MapBasedEditorViewModel<String> { private BiMap<String, String> itemMap = HashBiMap.create(8); public TypeEditorViewModel(String fieldName, AutoCompleteSuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) { super(fieldName, suggestionProvider, fieldCheckers); itemMap.put("mathesis", Localization.lang("Master's thesis")); itemMap.put("phdthesis", Localization.lang("PhD thesis")); itemMap.put("candthesis", Localization.lang("Candidate thesis")); itemMap.put("techreport", Localization.lang("Technical report")); itemMap.put("resreport", Localization.lang("Research report")); itemMap.put("software", Localization.lang("Software")); itemMap.put("datacd", Localization.lang("Data CD")); itemMap.put("audiocd", Localization.lang("Audio CD")); } @Override protected BiMap<String, String> getItemMap() { return itemMap; } @Override public String convertToDisplayText(String object) { return object; } }
38.054054
134
0.706676
2cc8ef8b5684d5ac200e7b3d5335c55374c7a25a
4,551
package Infra; import java.time.Duration; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Class that stores a temporal graph. * * @param <V> Vertex type. * TODO: implement edges if needed */ public class TemporalGraph<V> { //region --[Classes: Private]-------------------------------------- /** Represents a vertex over the given interval. */ private class TemporalVertex<V> { public Interval interval; public V vertex; public TemporalVertex(Interval interval, V vertex) { this.interval = interval; this.vertex = vertex; } } //endregion //region --[Fields: Private]--------------------------------------- /** Minimum timespan between timestamps. */ private Duration granularity; /** Map from vertex id to a list of temporal vertices. */ private HashMap<String, List<TemporalVertex<V>>> temporalVerticesById = new HashMap<>(); //endregion //region --[Constructors]------------------------------------------ /** * Creates a TemporalGraph. * @param granularity Minimum timespan between timestamps. */ public TemporalGraph(Duration granularity) { this.granularity = granularity; } //endregion //region --[Methods: Public]--------------------------------------- /** * Adds a vertex at the given timestamp. * @param vertex Vertex to add. * @param vertexId Id of vertex. * @param timestamp Timestamp. */ public void addVertex(V vertex, String vertexId, LocalDate timestamp) { // TODO: extract vertexId from vertex and remove vertexId parameter [2021-02-24] var temporalVertices = temporalVerticesById.get(vertexId); if (temporalVertices == null) { temporalVertices = new ArrayList<>(); temporalVertices.add(new TemporalVertex<>(new Interval(timestamp, timestamp), vertex)); temporalVerticesById.put(vertexId, temporalVertices); return; } TemporalVertex latestTemporalVertex = null; for (var temporalVertex : temporalVertices) { // TODO: throw exception if argument vertex != temporal vertex [2021-02-24] if (temporalVertex.interval.contains(timestamp)) return ; if (latestTemporalVertex == null || latestTemporalVertex.interval.getEnd().isAfter(temporalVertex.interval.getEnd())) { latestTemporalVertex = temporalVertex; } } var sinceEnd = Duration.between( latestTemporalVertex.interval.getEnd().atStartOfDay(), timestamp.atStartOfDay()); var comparison = sinceEnd.compareTo(granularity); if (comparison > 0) { // Time since end is greater than the granularity so add a new interval. // This represents that the vertex did not exist between the latestTemporalVertex.end and newInterval.start. temporalVertices.add(new TemporalVertex<>(new Interval(timestamp, timestamp), vertex)); } else if (comparison == 0) { // Time since end is the granularity so extend the last interval. // This represents that the vertex continued existing for this interval. latestTemporalVertex.interval.setEnd(timestamp); } else { throw new IllegalArgumentException(String.format( "Timestamp `%s` is less than the granularity `%s` away from the latest interval end `%s` in the TemporalGraph", timestamp.toString(), granularity.toString(), latestTemporalVertex.interval.getEnd().toString())); } } /** * Gets a vertex at the given timestamp. * @param vertexId Id of the vertex. * @param timestamp Timestamp. */ public V getVertex(String vertexId, LocalDate timestamp) { var temporalVertices = temporalVerticesById.get(vertexId); if (temporalVertices == null) throw new IllegalArgumentException(String.format("vertex %s does not exist", vertexId)); for (var temporalVertex : temporalVertices) { if (temporalVertex.interval.contains(timestamp)) { return temporalVertex.vertex; } } throw new IllegalArgumentException(String.format("vertex %s does not exist at %s", vertexId, timestamp)); } //endregion }
35.007692
127
0.604702
04a66399f3e5bd9fed1a6cbfa42ca2ae66950d66
1,072
/** * * @author user10 */ public class UseVehicle { public static void main(String[] args) { Vehicle auto1 = new Vehicle(); auto1.printStates(); auto1.speedUp(5); auto1.printStates(); auto1.changeGear(2); auto1.printStates(); auto1.setSpeed(500); int velocidad = auto1.getSpeed(); Truck troca = new Truck(20, 0, 1); troca.changeGear(3); troca.speedUp(80); troca.printStates(); //int peso = troca.getLoadWeight(); //System.out.println("El Peso de la troca es : " + peso); //System.out.println("El Peso de la troca es : " + troca.getLoadWeight() ); Car carro = new Car(0, 1, 2); carro.speedUp(80); carro.printStates(); IVehicle v1, v2, v3; v1 = new Vehicle(10,4); v2 = new Car(20, 2, 4); v3 = new Truck(50, 40, 3); v1.printState(); v2.printState(); v3.printState(); } }
24.363636
83
0.487873
1f9ab7a720f6e52a7ad8ccca55fb558d78b42b9f
1,946
package liquibase.parser.core.yaml; import liquibase.changelog.ChangeLogParameters; import liquibase.changelog.DatabaseChangeLog; import liquibase.exception.ChangeLogParseException; import liquibase.resource.ResourceAccessor; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; public class YamlChangeLogParserTest { private String changeLogText = "databaseChangeLog:\n" + " - changeSet:\n" + " id: test1\n" + " author: nvoxland\n" + " runOnChange: true\n" + " changes:\n" + " - createTable:\n" + " tableName: testTable\n" + " columns:\n" + " - column:\n" + " name: id\n" + " type: int\n" + " - column:\n" + " name: name\n" + " type: varchar(255)\n"; @Test public void parse() throws ChangeLogParseException { DatabaseChangeLog changeLog = new YamlChangeLogParser().parse("test.yaml", new ChangeLogParameters(), new ResourceAccessor() { @Override public InputStream getResourceAsStream(String file) throws IOException { return new ByteArrayInputStream(changeLogText.getBytes()); } @Override public Enumeration<URL> getResources(String packageName) throws IOException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public ClassLoader toClassLoader() { return null; //To change body of implemented methods use File | Settings | File Templates. } }); System.out.println(changeLog); } }
34.140351
134
0.571429
a3b80bc3e0410e23a31a24aaeca4f50a09789c81
1,009
package com.dungeonstory.ui.view.admin.grid; import java.util.EnumSet; import com.dungeonstory.backend.data.enums.Language; import com.vaadin.data.converter.StringToBooleanConverter; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.icons.VaadinIcons; public class LanguageGrid extends ReadOnlyGrid<Language> { private static final long serialVersionUID = -8818716671121858460L; public LanguageGrid() { super(); StringToBooleanConverter converter = new StringToBooleanConverter("", VaadinIcons.CHECK_CIRCLE_O.getHtml(), VaadinIcons.CIRCLE_THIN.getHtml()); addColumn(Language::getName).setCaption("Nom").setId("name"); addColumn(Language::getScript).setCaption("Alphabet").setId("script"); // addColumn(language -> converter.convertToPresentation(language.getPlayable(), new ValueContext()), new HtmlRenderer()).setCaption("Jouable"); setDataProvider(new ListDataProvider<>(EnumSet.allOf(Language.class))); } }
40.36
151
0.747275
f82720ac6ae71e72d093248a4e42c3f98c17a0e0
279
package io.ketill.psx; import io.ketill.AdapterSupplier; import org.jetbrains.annotations.NotNull; class MockPsxController extends PsxController { MockPsxController(@NotNull AdapterSupplier<?> adapterSupplier) { super("psx", adapterSupplier, null, null); } }
21.461538
68
0.752688
8870bf959179950a76ac32e2cc24a712b3e6a388
1,131
package pavlik.john.dungeoncrawl.model.events.conditionals; import java.util.Objects; import pavlik.john.dungeoncrawl.model.Character; import pavlik.john.dungeoncrawl.model.events.Conditional; import pavlik.john.dungeoncrawl.model.events.XMLAttribute; /** * PlayerHasMoneyConditional checks to see if the player has at least as much as the specified * amount of money. * * @author John * @version 1.3 * @since 1.3 */ public class PlayerHasMoneyConditional extends Conditional { /** * */ private static final long serialVersionUID = 1L; Integer f_money; /** * Public Constructor * * @param money * The integer amount of money to check for. * @param tag * The XML tag to use to identify this {@link XMLAttribute} */ public PlayerHasMoneyConditional(Integer money, String tag) { super(tag, money.toString()); f_money = Objects.requireNonNull(money, "PlayerHasMoneyConditional money cannot be null"); } @Override public boolean meetsConditions(Character player) { return player.getMoney() >= f_money; } }
26.302326
95
0.687887
c3901a0e2e9e73c1bad22138cb32b276a3db4279
3,004
package com.codepath.moviemoose; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.*; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; public class MainActivity extends Activity { final String API_KEY = "7317527cae59a90e9b7f1a166d224d83"; final String BASE_URL = "http://api.themoviedb.org/3"; List<Movie> movieList; ListView lvMovies; MoviesAdapter moviesAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fetchAllMovies(); lvMovies = (ListView)findViewById(R.id.lvMovies); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } // Networking private void fetchAllMovies() { AsyncHttpClient client = new AsyncHttpClient(); String url = "http://api.themoviedb.org/3/movie/now_playing?api_key=7317527cae59a90e9b7f1a166d224d83"; client.get(url, null, new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { // Root JSON in response is an dictionary i.e { "data : [ ... ] } // Handle resulting parsed JSON response here Gson gson = new GsonBuilder().create(); movieList = NowPlayingMoviesResponse.parseJSON(response).movieList; moviesAdapter = new MoviesAdapter(getApplicationContext(), movieList); lvMovies.setAdapter(moviesAdapter); } @Override // public void onFailure(int statusCode, Header[] headers, Throwable t, JSONObject object) { public void onFailure(int statusCode, Header[] headers, String responseString, Throwable t) { // public void onFailure(int statusCode, Header[] headers, String failure, Throwable t) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) // System.out.println("failure: " + failure); } }); } }
35.341176
110
0.661784
61cb12051356bc82eefd6f5fdf5a9c31c0b8bd4c
569
package com.sqh.market.constant; /** * 这里定义了一些结果代码 */ public class Codes { /** * 登录检查结果代码 */ public enum LOGIN_CHECK_CODES { LOGIN_SUCCESS(1, "登陆成功"), LOGOUT(-1, "未登录或已注销"), UNCHECK(0, "不需要进行登录检查"); int code; String message; LOGIN_CHECK_CODES(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } }
17.78125
53
0.502636
83903e4501b2fcdce45d834aa39d4c373799b33c
1,398
package com.gnopai.ji65.interpreter.instruction; import com.gnopai.ji65.Cpu; import com.gnopai.ji65.InstructionType; import com.gnopai.ji65.interpreter.Operand; import static java.lang.Byte.toUnsignedInt; public class Sbc implements Instruction { private final OperandResolver operandResolver = new OperandResolver(); @Override public InstructionType getInstructionType() { return InstructionType.SBC; } @Override public void run(Cpu cpu, Operand operand) { int accumulatorValue = toUnsignedInt(cpu.getAccumulator()); int operandValue = toUnsignedInt(operandResolver.resolveOperand(cpu, operand)); int carryValue = cpu.isCarryFlagSet() ? 0 : 1; int difference = accumulatorValue - operandValue - carryValue; cpu.setCarryFlag(difference >= 0); byte resultByte = (byte) (difference + 0x100); cpu.setAccumulator(resultByte); cpu.updateNegativeFlag(resultByte); cpu.updateZeroFlag(resultByte); boolean overflowFlag = calculateOverflow(accumulatorValue, operandValue, toUnsignedInt(resultByte)); cpu.setOverflowFlag(overflowFlag); } private boolean calculateOverflow(int firstValue, int secondValue, int result) { int secondValueComplement = 255 - secondValue; return ((firstValue ^ result) & (secondValueComplement ^ result) & 0x80) == 0x80; } }
35.846154
108
0.716023
5ab8c5e7fbf118522e1de821d2832bddea187f57
14,765
/* * $Id$ * $URL$ * * ==================================================================== * Ikasan Enterprise Integration Platform * * Distributed under the Modified BSD License. * Copyright notice: The copyright for this software and a full listing * of individual contributors are as shown in the packaged copyright.txt * file. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the ORGANIZATION nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ package org.ikasan.connector.ftp.outbound; import java.io.Serializable; import javax.resource.ResourceException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import com.google.common.cache.Cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.ikasan.connector.base.command.TransactionalCommandConnection; import org.ikasan.connector.base.command.TransactionalResource; import org.ikasan.connector.basefiletransfer.net.ClientConnectionException; import org.ikasan.connector.basefiletransfer.net.ClientInitialisationException; import org.ikasan.connector.BaseFileTransferConnection; import org.ikasan.connector.basefiletransfer.outbound.persistence.BaseFileTransferDao; import org.ikasan.connector.ftp.net.FileTransferProtocol; import org.ikasan.connector.ftp.net.FileTransferProtocolClient; import org.ikasan.connector.ftp.net.FileTransferProtocolSSLClient; import org.ikasan.connector.util.chunking.model.dao.FileChunkDao; import org.slf4j.event.Level; /** * This EJB implements the ManagedConnection for the FTP resource adapter. This * is a representation of a real, physical connection to the server, so it has * an object instance variable which remains allocated to a server for the life * of this object. This class is responsible for creating virtual connections, * of class EISConnection, when the application server calls getConnection() * * It extends a (1 Phase Commit and 2 Phase commit) managed connection * * TODO Max retry attempts is really a client parameter, which brings us the * question of whether we even want to open a connection at this stage * * @author Ikasan Development Team */ public class FTPManagedConnection extends TransactionalCommandConnection implements Serializable { /** Generated GUID */ private static final long serialVersionUID = 8623781620439053263L; /** The logger instance. */ public static Logger logger = LoggerFactory.getLogger(FTPManagedConnection.class); /** Common library used by both inbound and outbound connectors */ private FileTransferProtocol ftpClient; /** * The client specific connection spec used to override the MFC values where * necessary. */ private FTPConnectionRequestInfo fcri; private String clientID; /** * Constructor, sets the managed connection factory and the hibernate filter * table * * client ID sits on EISManagedConnection * * @param fcri connection request info */ public FTPManagedConnection(FTPConnectionRequestInfo fcri) { logger.debug("Called constructor."); //$NON-NLS-1$ this.fcri = fcri; this.clientID = this.fcri.getClientID(); instanceCount++; instanceOrdinal = instanceCount; } /** * Create a virtual connection (a BaseFileTransferConnection object) and * add it to the list of managed instances before returning it to the client. * * @param fileChunkDao * @param baseFileTransferDao * @return */ public Object getConnection( FileChunkDao fileChunkDao, BaseFileTransferDao baseFileTransferDao, int testtodo) { return getConnection(fileChunkDao, baseFileTransferDao, null); } /** * Create a virtual connection (a BaseFileTransferConnection object) and * add it to the list of managed instances before returning it to the client. * * @param fileChunkDao * @param baseFileTransferDao * @param duplicatesFileCache * @return */ public Object getConnection( FileChunkDao fileChunkDao, BaseFileTransferDao baseFileTransferDao, Cache<String, Boolean> duplicatesFileCache) { logger.debug("Called getConnection()"); //$NON-NLS-1$ BaseFileTransferConnection connection = new FTPConnectionImpl(this, fileChunkDao, baseFileTransferDao, duplicatesFileCache); return connection; } public String getClientID() { return clientID; } // //////////////////////////////////////// // Connection API Calls // //////////////////////////////////////// /** * openSession initiates the physical connection to the server and logs us * in. This method is called by FTPManagedConnectionFactory immediately * after creating the instance of this class. * * In this implementation of an FTP connector there is no real concept of a * session (a connection is made per method call), openSession is left here * as it initialises the ftpClient and also provides a starting point for * true session functionality to be added if required * * @throws ResourceException Exception thrown by Connector */ public void openSession() throws ResourceException { logger.debug("Called openSession."); //$NON-NLS-1$ createFTPClient(); this.ftpClient.echoConfig(); } /* * Helper Methods / */ /** * Close the FileTransferProtocolClient session */ protected void closeSession() { if(this.ftpClient == null) { logger.debug("FTPClient is null. Closing Session aborted."); //$NON-NLS-1$ } else { if(this.ftpClient.isConnected()) { logger.debug("Closing FTP connection!"); //$NON-NLS-1$ this.ftpClient.disconnect(); logger.debug("Disconnected from FTP host."); //$NON-NLS-1$ } else { logger.info("Client was already disconnected. Closing Session aborted."); //$NON-NLS-1$ } } } /** * Creates the FileTransferProtocolClient based off the properties from the * ConnectionRequestInfo, and opens the connection * * @throws ResourceException Exception thrown by connector */ private void createFTPClient() throws ResourceException { logger.debug("Called createFTPClient \n" + "active [" + this.fcri.getActive() + "]\n" + "host [" + this.fcri.getRemoteHostname() + "]\n" + "maxretry [" + this.fcri.getMaxRetryAttempts() + "]\n" + "password [" + this.fcri.getPassword() + "]\n" + "port [" + this.fcri.getRemotePort() + "]\n" + "user [" + this.fcri.getUsername() + "]"); // Active boolean active = this.fcri.getActive(); // Hostname String remoteHostname = null; if(this.fcri.getRemoteHostname() != null) { remoteHostname = this.fcri.getRemoteHostname(); } else { throw new ResourceException("Remote hostname is null."); //$NON-NLS-1$ } // Max retry attempts (Integer unboxes to int) int maxRetryAttempts; if(this.fcri.getMaxRetryAttempts() != null) { maxRetryAttempts = this.fcri.getMaxRetryAttempts(); } else { throw new ResourceException("max retry attempts is null"); //$NON-NLS-1$ } // Password String password; if(this.fcri.getPassword() != null) { password = this.fcri.getPassword(); } else { throw new ResourceException("password is null"); //$NON-NLS-1$ } // Port (Integer unboxes to int) int remotePort; if(this.fcri.getRemotePort() != null) { remotePort = this.fcri.getRemotePort(); } else { throw new ResourceException("Remote port is null"); //$NON-NLS-1$ } // Username String username = null; if(this.fcri.getUsername() != null) { username = this.fcri.getUsername(); } else { throw new ResourceException("username is null"); //$NON-NLS-1$ } String localHostname = "localhost"; String systemKey = this.fcri.getSystemKey(); Integer connectionTimeout = this.fcri.getConnectionTimeout(); Integer dataTimeout = this.fcri.getDataTimeout(); Integer soTimeout = this.fcri.getSocketTimeout(); // Create a FileTransferProtocolClient if (fcri.getFTPS()) { Boolean FTPS = true; Integer ftpsPort = fcri.getFtpsPort(); String ftpsProtocol = fcri.getFtpsProtocol(); Boolean ftpsIsImplicit = fcri.getFtpsIsImplicit(); String ftpsKeyStoreFilePath = fcri.getFtpsKeyStoreFilePath(); String ftpsKeyStoreFilePassword = fcri.getFtpsKeyStoreFilePassword(); this.ftpClient = new FileTransferProtocolSSLClient(active, remoteHostname, localHostname, maxRetryAttempts, password, remotePort, username, systemKey, connectionTimeout, dataTimeout, soTimeout, FTPS, ftpsPort, ftpsProtocol, ftpsIsImplicit, ftpsKeyStoreFilePath, ftpsKeyStoreFilePassword); } else { this.ftpClient = new FileTransferProtocolClient(active, remoteHostname, localHostname, maxRetryAttempts, password, remotePort, username, systemKey, connectionTimeout, dataTimeout, soTimeout); } try { this.ftpClient.validateConstructorArgs(); } catch (ClientInitialisationException e) { throw new ResourceException(e); } // attempts to open the connection try { ftpClient.connect(); } catch (ClientConnectionException e) { throw new ResourceException("Failed to open connection when creating FTPManagedConnection", e); //$NON-NLS-1$ } // attempts to login try { ftpClient.login(); } catch (ClientConnectionException e) { throw new ResourceException("Failed to login when creating FTPManagedConnection", e); //$NON-NLS-1$ } } // ///////////////////////////////////// // TXN API calls // ///////////////////////////////////// /** * Deal with forgetting this unit of work as a txn, in this case do nothing * * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#forget(javax.transaction.xa.Xid) */ @Override public void forget(Xid arg0) { logger.info("in forget"); //$NON-NLS-1$ } /** * Return the Transaction timeout, always set to 0 * * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#getTransactionTimeout() * @return 0 */ @Override public int getTransactionTimeout() { logger.debug("in getTransactionTimeout"); //$NON-NLS-1$ return 0; } /** * Get the XA resource for this managed connection, in this case, itself. * * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#getXAResource() */ @Override public XAResource getXAResource() { logger.debug("in getXAResource"); //$NON-NLS-1$ return this; } /** * Return whether or not this resource manager is the same, always return * false * * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#isSameRM(javax.transaction.xa.XAResource) * @return false */ @Override public boolean isSameRM(XAResource arg0) { logger.debug("in isSameRM"); //$NON-NLS-1$ return false; } /** * Set the txn timeout, always return false * * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#setTransactionTimeout(int) * @return false */ @Override public boolean setTransactionTimeout(int arg0) { logger.debug("in setTransactionTimeout"); //$NON-NLS-1$ return false; } @Override protected TransactionalResource getTransactionalResource() { return ftpClient; } /** * Hook method to allow any connector specific post rollback functionality * * @param arg0 Transaction Id */ @Override protected void postRollback(Xid arg0) { logger.info("in postRollback"); //$NON-NLS-1$ } /** * Hook method to allow any connector specific post commit functionality * * @param arg0 Transaction Id */ @Override protected void postCommit(Xid arg0) { logger.info("in postCommit"); //$NON-NLS-1$ } @Override protected boolean cleanupJournalOnComplete() { return fcri.cleanupJournalOnComplete(); } }
35.238663
162
0.631019
e5a89701a89598d2723aedb13b5155818d81c4d4
65
package com.amituofo.xscript; public class ScriptContainer { }
10.833333
30
0.784615
304a84d581a186746fe5a40d0d74dbece388de32
2,077
package com.company.android.dictionary.upload.io; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import android.util.Log; public class DictionaryReader implements IDictionaryReader { private BufferedReader reader; private String delimiter; private int counter; private int skipCount; private final int batchSize; public DictionaryReader(Reader reader, String delimiter, int batchSize) { this.delimiter = delimiter; this.reader = new BufferedReader(reader); this.batchSize = batchSize; } @Override public List<WordDefinition> nextBatch() { long startTime = System.currentTimeMillis(); List<WordDefinition> batch = null; try { batch = createRecordsBatch(); Log.d("DictionaryReader", "File WordDefinition Parsed Count: " + counter); } catch (IOException e) { e.printStackTrace(); } long timeTaken = (System.currentTimeMillis() - startTime); Log.d("DictionaryReader", "Time Taken For a Batch Reading: " + timeTaken + " milli-seconds !"); return batch; } private List<WordDefinition> createRecordsBatch() throws IOException { String line = null; List<WordDefinition> records = new ArrayList<WordDefinition>(); for(int index = 0; index < batchSize; index++) { if((line = reader.readLine()) == null) break; // File End WordDefinition record = createRecord(line); if(record == null) continue; records.add(record); counter++; } return records; } private WordDefinition createRecord(String line) { StringTokenizer tokenizer = new StringTokenizer(line, delimiter); if(tokenizer.countTokens() < 2) { Log.d("InsertionTask", "Skipping Invalid Row: " + line); skipCount++; return null; } String word = tokenizer.nextToken(); String definition = tokenizer.nextToken(); return new WordDefinition(word, definition); } @Override public int getSkipCount() { return skipCount; } @Override public int getParsedCount() { return counter; } }
25.024096
97
0.717862
e68d725b0f4cbd8677d5266a724cec350fa714ca
3,951
package id.sch.smktelkom_mlg.project2.xirpl109103235.spotin; import com.cloudant.sync.datastore.DocumentRevision; import java.util.HashMap; import java.util.Map; class Task { // Doc type diperlukan untuk mengidentifikasi dan mengelompokkan tipe kolektif di datastore. private static final String DOC_TYPE = "com.xirpl109103235.spotin"; // Ini adalah nomor revisi dalam database yang mewakili tugas ini. private DocumentRevision rev; private String type = DOC_TYPE; // Variabel untuk tanda centang selesai. private boolean completed; // Teks tugas utama private String id; private String judul; private String lokasi; private String harga; private String gambar; private String deskripsi; private String telepon; private String koordinat; private String lokKota; private String tipe; private Task() { } Task(String desc) { this.setJudul(desc); this.setCompleted(false); this.setType(DOC_TYPE); } // Buat objek tugas berdasarkan revisi doc dari datastore. static Task fromRevision(DocumentRevision rev) { Task t = new Task(); t.rev = rev; Map<String, Object> map = rev.asMap(); t.setJudul((String) map.get("nama")); t.setHarga((String) map.get("tarif")); t.setLokasi((String) map.get("lokasi")); t.setGambar((String) map.get("gambar")); t.setDeskripsi((String) map.get("deskripsi")); t.setKoordinat((String) map.get("koordinat")); t.setLokKota((String) map.get("kota")); t.setTelepon((String) map.get("cp")); t.setTipe((String) map.get("tipe")); t.setId((String) map.get("_id")); return t; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTipe() { return tipe; } public void setTipe(String tipe) { this.tipe = tipe; } public String getTelepon() { return telepon; } public void setTelepon(String telepon) { this.telepon = telepon; } public String getKoordinat() { return koordinat; } public void setKoordinat(String koordinat) { this.koordinat = koordinat; } public String getDeskripsi() { return deskripsi; } public void setDeskripsi(String deskripsi) { this.deskripsi = deskripsi; } public String getGambar() { return gambar; } public void setGambar(String gambar) { this.gambar = gambar; } public String getLokasi() { return lokasi; } public void setLokasi(String lokasi) { this.lokasi = lokasi; } public String getHarga() { return harga; } public void setHarga(String harga) { this.harga = harga; } DocumentRevision getDocumentRevision() { return rev; } private void setType(String type) { this.type = type; } boolean isCompleted() { return this.completed; } void setCompleted(boolean completed) { this.completed = completed; } String getJudul() { return this.judul; } void setJudul(String desc) { this.judul = desc; } @Override public String toString() { return "{ nama: " + getJudul() + ", lokasi: " + getLokasi() + ", tarif: " + getHarga() + "}"; } // Return tugas sebagai Hash Map agar mudah dikonsumsi oleh replicators dan datastores. Map<String, Object> asMap() { HashMap<String, Object> map = new HashMap<>(); map.put("type", type); map.put("completed", completed); map.put("judul", judul); return map; } public String getLokKota() { return lokKota; } public void setLokKota(String lokKota) { this.lokKota = lokKota; } }
23.945455
101
0.59757
088c240451f9ffa2e032c0b8c9c1dbb8e8ec80b8
2,919
/* * Copyright (c) 2002-2016 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.javascript.host.crypto; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.EDGE; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.IE; import java.util.Random; import com.gargoylesoftware.htmlunit.javascript.SimpleScriptable; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction; import com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser; import com.gargoylesoftware.htmlunit.javascript.host.Window; import com.gargoylesoftware.htmlunit.javascript.host.arrays.ArrayBufferViewBase; import net.sourceforge.htmlunit.corejs.javascript.Context; /** * A JavaScript object for {@code Crypto}. * * @author Ahmed Ashour * @author Marc Guillemot */ @JsxClass public class Crypto extends SimpleScriptable { /** * Creates an instance. */ @JsxConstructor({ @WebBrowser(CHROME), @WebBrowser(FF), @WebBrowser(EDGE) }) public Crypto() { } /** * Facility constructor. * @param window the owning window */ public Crypto(final Window window) { setParentScope(window); setPrototype(window.getPrototype(Crypto.class)); } /** * Fills array with random values. * @param array the array to fill * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues">MDN Doc</a> */ @JsxFunction({ @WebBrowser(FF), @WebBrowser(value = IE, minVersion = 10), @WebBrowser(CHROME) }) public void getRandomValues(final ArrayBufferViewBase array) { if (array == null) { throw Context.reportRuntimeError("TypeError: Argument 1 of Crypto.getRandomValues is not an object."); } final Random random = new Random(); for (int i = 0; i < array.getLength(); i++) { array.put(i, array, random.nextInt()); } } }
38.407895
115
0.717026
5b62e106e85d60635d76edacd8b2272be145b071
986
package com.example.procare.main.pets.newPets; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.example.procare.database.ProCareDatabase; import com.example.procare.database.ProCareDbHelper; public class NewPetsModel { ProCareDbHelper dbHelper; NewPetsModel(Context ctx) { dbHelper = new ProCareDbHelper(ctx); } public boolean saveNewPet(String name, String type, Integer userId) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(ProCareDatabase.PetTable.COLUMN_NAME_PETNAME, name); values.put(ProCareDatabase.PetTable.COLUMN_NAME_TYPE, type); values.put(ProCareDatabase.PetTable.COLUMN_NAME_ID_OWNER, userId); long newRowId = db.insert(ProCareDatabase.PetTable.TABLE_NAME, null, values); if (newRowId == -1) return false; else return true; } }
29.878788
85
0.737323
19f4f2d92e1e021d99dae5cd2df867f7d8781c8f
4,956
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package stats; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * * @author Dibyendu1363 */ public class SpeedStateMatrix { public static void main(String args[]) throws FileNotFoundException, IOException, ParseException { // time slots ArrayList<String> time_slots = new ArrayList<String>(); String myTime = "00:00:00"; for (int t = 0; t < 24; t++) { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); Date d = df.parse(myTime); Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.SECOND, 3599); String newTime = df.format(cal.getTime()); time_slots.add(myTime + "-" + newTime); d = df.parse(newTime); cal.setTime(d); cal.add(Calendar.SECOND, 1); myTime = df.format(cal.getTime()); } // points all ArrayList<String> points = new ArrayList<String>(); FileReader fr1 = new FileReader("C:\\Users\\Server\\Documents\\NetBeansProjects\\MapBusesRoute\\statsFolder\\mumbai_points_82_routeids.txt"); BufferedReader br1 = new BufferedReader(fr1); String line1; while ((line1 = br1.readLine()) != null) { String parts[] = line1.split("-"); points.add(parts[1]); } // stats finding from data double speeds[][] = new double[points.size()][24]; int count[][] = new int[points.size()][24]; String speed_state[][] = new String[points.size()][24]; FileReader fr = new FileReader("C:\\Users\\Server\\Documents\\NetBeansProjects\\MapBusesRoute\\statsFolder\\mumbai_data_google_82_routeids.txt"); BufferedReader br = new BufferedReader(fr); String line; br.readLine(); while ((line = br.readLine()) != null) { String parts[] = line.split("--"); for (int i = 0; i < points.size(); i++) { if (points.get(i).equals(parts[3])) { String space[] = parts[0].split("\\s\\s"); DateFormat sdf1 = new SimpleDateFormat("HH:mm:ss"); Date time_got = sdf1.parse(space[1]); for (int j = 0; j < time_slots.size(); j++) { String splitter[] = time_slots.get(j).split("-"); DateFormat sdf11 = new SimpleDateFormat("HH:mm:ss"); Date slot_first = sdf11.parse(splitter[0]); DateFormat sdf12 = new SimpleDateFormat("HH:mm:ss"); Date slot_end = sdf12.parse(splitter[1]); if (slot_first.before(time_got) && slot_end.after(time_got)) { speeds[i][j] = speeds[i][j] + Double.parseDouble(parts[6]); count[i][j] = count[i][j] + 1; } else { if (slot_first.toString().equals(time_got.toString()) && slot_end.toString().equals(time_got.toString())) { speeds[i][j] = speeds[i][j] + Double.parseDouble(parts[6]); count[i][j] = count[i][j] + 1; } } } } } } for (int i = 0; i < points.size(); i++) { for (int j = 0; j < time_slots.size(); j++) { double final_speed = speeds[i][j] / count[i][j]; String final_state = ""; String final_color = ""; // System.out.println(speeds[i][j]); // System.out.println(count[i][j]); // System.out.println(final_speed); // System.out.println(speed_traffic); // System.exit(0); if (final_speed > 50.0) { final_state = "Mild"; final_color = "#00ff00"; } else if (final_speed <= 50 && final_speed > 25) { final_state = "Medium"; final_color = "#ffff00"; } else { final_state = "Heavy"; final_color = "#ff0000"; } speed_state[i][j] = final_state + "," + final_color; } } for (int i = 0; i < points.size(); i++) { System.out.print(points.get(i) + "\t"); for (int j = 0; j < time_slots.size(); j++) { System.out.print(speed_state[i][j] + "\t"); } System.out.println(); } } }
40.958678
153
0.503632
62d792c99ef347c056a089615b9b98db8a47967b
73,650
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * ag * bz * net.runelite.mapping.Export * net.runelite.mapping.Implements * net.runelite.mapping.ObfuscatedName * net.runelite.mapping.ObfuscatedSignature */ import java.lang.reflect.Array; import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName(value="be") @Implements(value="Scene") public class Scene { @ObfuscatedName(value="ac") static int field361 = 0; @ObfuscatedName(value="ag") static int field364 = 0; @ObfuscatedName(value="ao") static int field368 = 0; @ObfuscatedName(value="ap") static int field369 = 0; @ObfuscatedName(value="ar") @Export(value="Scene_drawnCount") static int Scene_drawnCount = 0; @ObfuscatedName(value="au") static int field373 = 0; @ObfuscatedName(value="aw") @Export(value="Scene_plane") static int Scene_plane = 0; @ObfuscatedName(value="ay") static int field376 = 0; @ObfuscatedName(value="az") static int field377 = 0; @ObfuscatedName(value="ba") @ObfuscatedSignature(descriptor="[Lag;") static Occluder[] field378; @ObfuscatedName(value="bb") @Export(value="Scene_planeOccluderCounts") static int[] Scene_planeOccluderCounts; @ObfuscatedName(value="bd") public static int field381 = 0; @ObfuscatedName(value="bg") static int field384 = 0; @ObfuscatedName(value="bh") static boolean field385 = false; @ObfuscatedName(value="bj") @ObfuscatedSignature(descriptor="[Lco;") @Export(value="gameObjects") static GameObject[] gameObjects; @ObfuscatedName(value="bm") @Export(value="Scene_planesCount") static int Scene_planesCount = 0; @ObfuscatedName(value="bn") static final int[] field391; @ObfuscatedName(value="bo") static final int[] field392; @ObfuscatedName(value="bp") static int field393 = 0; @ObfuscatedName(value="bq") static int field394 = 0; @ObfuscatedName(value="br") public static int field395 = 0; @ObfuscatedName(value="bx") @Export(value="Scene_currentOccludersCount") static int Scene_currentOccludersCount = 0; @ObfuscatedName(value="by") static final int[] field402; @ObfuscatedName(value="ca") @Export(value="Scene_viewportXCenter") static int Scene_viewportXCenter = 0; @ObfuscatedName(value="cj") @Export(value="Scene_viewportYMin") static int Scene_viewportYMin = 0; @ObfuscatedName(value="ck") static boolean[][][][] field410; @ObfuscatedName(value="cw") static final int[] field417; @ObfuscatedName(value="cx") @Export(value="Scene_viewportYMax") static int Scene_viewportYMax; @ObfuscatedName(value="ad") static int field362 = 0; @ObfuscatedName(value="ak") @Export(value="Scene_isLowDetail") public static boolean Scene_isLowDetail = true; @ObfuscatedName(value="at") static int field372 = 0; @ObfuscatedName(value="av") static int field374 = 0; @ObfuscatedName(value="bc") public static int field380 = 0; @ObfuscatedName(value="bi") static int field386 = 0; @ObfuscatedName(value="bl") static final int[] field389; @ObfuscatedName(value="bs") static final int[] field396; @ObfuscatedName(value="bu") static final int[] field398; @ObfuscatedName(value="bv") @ObfuscatedSignature(descriptor="[[Lag;") static Occluder[][] field399; @ObfuscatedName(value="bz") static boolean field403 = false; @ObfuscatedName(value="cb") static boolean[][] field405; @ObfuscatedName(value="cg") @ObfuscatedSignature(descriptor="Lcw;") static class47 field407; @ObfuscatedName(value="cn") @Export(value="Scene_viewportYCenter") static int Scene_viewportYCenter = 0; @ObfuscatedName(value="cs") @Export(value="Scene_viewportXMax") static int Scene_viewportXMax; @ObfuscatedName(value="ct") @Export(value="Scene_viewportXMin") static int Scene_viewportXMin; @ObfuscatedName(value="bf") static int field383 = 0; @ObfuscatedName(value="bw") @ObfuscatedSignature(descriptor="Lfe;") @Export(value="Scene_tilesDeque") static NodeDeque Scene_tilesDeque; @ObfuscatedName(value="bk") public static int field388 = 0; @ObfuscatedName(value="cp") @ObfuscatedSignature(descriptor="Lba;") static class19 field413; @ObfuscatedName(value="aa") @ObfuscatedSignature(descriptor="[Lco;") @Export(value="tempGameObjects") GameObject[] tempGameObjects = new GameObject[5000]; @ObfuscatedName(value="ae") @Export(value="pixelsPerTile") int pixelsPerTile; @ObfuscatedName(value="ah") @Export(value="tileHeights") int[][][] tileHeights; @ObfuscatedName(value="aj") @Export(value="minPlane") int minPlane = 0; @ObfuscatedName(value="al") @Export(value="tempGameObjectsCount") int tempGameObjectsCount = 0; @ObfuscatedName(value="as") @ObfuscatedSignature(descriptor="[[[Lbz;") @Export(value="tiles") Tile[][][] tiles; @ObfuscatedName(value="cf") @Export(value="tileRotation2D") int[][] tileRotation2D; @ObfuscatedName(value="cv") @Export(value="tileShape2D") int[][] tileShape2D; @ObfuscatedName(value="ai") @Export(value="xSize") int xSize; @ObfuscatedName(value="ax") @Export(value="ySize") int ySize; @ObfuscatedName(value="ab") int[][][] field420; static { gameObjects = new GameObject[100]; field385 = false; field394 = 0; field395 = 0; field388 = 0; field381 = -1; field380 = -1; field403 = false; Scene_planesCount = 4; Scene_planeOccluderCounts = new int[Scene_planesCount]; field399 = (Occluder[][])Array.newInstance(ag.class, Scene_planesCount, 500); Scene_currentOccludersCount = 0; field378 = new Occluder[500]; Scene_tilesDeque = new NodeDeque(); field389 = new int[]{19, 55, 38, 155, 255, 110, 137, 205, 76}; field398 = new int[]{160, 192, 80, 96, 0, 144, 80, 48, 160}; field391 = new int[]{76, 8, 137, 4, 0, 1, 38, 2, 19}; field396 = new int[]{0, 0, 2, 0, 0, 2, 1, 1, 0}; field402 = new int[]{2, 0, 0, 2, 0, 0, 0, 4, 4}; field392 = new int[]{0, 4, 4, 8, 0, 0, 8, 0, 0}; field417 = new int[]{1, 1, 0, 0, 0, 8, 0, 0, 8}; field410 = (boolean[][][][])Array.newInstance(Boolean.TYPE, 8, 32, 51, 51); } public Scene(int n, int n2, int n3, int[][][] arrn) { int[] arrn2 = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int[] arrn3 = new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int[] arrn4 = new int[]{1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1}; int[] arrn5 = new int[]{1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0}; int[] arrn6 = new int[]{1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1}; int[] arrn7 = new int[]{1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0}; int[] arrn8 = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0}; int[] arrn9 = new int[]{1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0}; int[] arrn10 = new int[]{0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1}; int[] arrn11 = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1}; this.tileShape2D = new int[][]{arrn2, arrn3, arrn4, arrn5, {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1}, {0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, arrn6, arrn7, arrn8, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1}, arrn9, arrn10, arrn11}; arrn2 = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; arrn3 = new int[]{3, 7, 11, 15, 2, 6, 10, 14, 1, 5, 9, 13, 0, 4, 8, 12}; this.tileRotation2D = new int[][]{arrn2, {12, 8, 4, 0, 13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3}, {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, arrn3}; this.pixelsPerTile = n; this.xSize = n2; this.ySize = n3; this.tiles = (Tile[][][])Array.newInstance(bz.class, n, n2, n3); this.field420 = (int[][][])Array.newInstance(Integer.TYPE, n, n2 + 1, n3 + 1); this.tileHeights = arrn; this.init7(); } @ObfuscatedName(value="aa") @ObfuscatedSignature(descriptor="(IIIILbw;Lbw;IIJI)V") @Export(value="newBoundaryObject") public void newBoundaryObject(int n, int n2, int n3, int n4, Entity entity, Entity entity2, int n5, int n6, long l, int n7) { if (entity == null && entity2 == null) { return; } BoundaryObject boundaryObject = new BoundaryObject(); boundaryObject.tag = l; boundaryObject.flags = n7; boundaryObject.field445 = n2 * 128 - -64; boundaryObject.field447 = n3 * 128 - -64; boundaryObject.field449 = n4; boundaryObject.entity1 = entity; boundaryObject.entity2 = entity2; boundaryObject.field452 = n5; boundaryObject.field446 = n6; n4 = n; while (true) { if (n4 >= 0) { if (this.tiles[n4][n2][n3] == null) { this.tiles[n4][n2][n3] = new Tile(n4, n2, n3); } } else { this.tiles[n][n2][n3].boundaryObject = boundaryObject; return; } --n4; } } @ObfuscatedName(value="ae") @Export(value="init") public void init(int n) { this.minPlane = n; int n2 = 0; block0: while (n2 < this.xSize) { int n3 = 0; while (true) { if (n3 < this.ySize) { if (this.tiles[n][n2][n3] == null) { this.tiles[n][n2][n3] = new Tile(n, n2, n3); } } else { ++n2; continue block0; } ++n3; } break; } return; } @ObfuscatedName(value="af") @ObfuscatedSignature(descriptor="(IIIIIILbw;IJI)Z") public boolean method705(int n, int n2, int n3, int n4, int n5, int n6, Entity entity, int n7, long l, int n8) { if (entity == null) { return true; } return this.newGameObject(n, n2, n3, n5, n6, n5 * 64 + n2 * 128, n6 * 64 + n3 * 128, n4, entity, n7, false, l, n8); } @ObfuscatedName(value="ah") @Export(value="setTileMinPlane") public void setTileMinPlane(int n, int n2, int n3, int n4) { if (this.tiles[n][n2][n3] == null) { return; } this.tiles[n][n2][n3].minPlane = n4; } @ObfuscatedName(value="aj") @ObfuscatedSignature(descriptor="(IIIILbw;JI)V") @Export(value="newFloorDecoration") public void newFloorDecoration(int n, int n2, int n3, int n4, Entity entity, long l, int n5) { if (entity == null) { return; } FloorDecoration floorDecoration = new FloorDecoration(); floorDecoration.entity = entity; floorDecoration.x = n2 * 128 + 64; floorDecoration.y = n3 * -2013265920 + -1006632960; floorDecoration.tileHeight = n4; floorDecoration.tag = l; floorDecoration.flags = n5; if (this.tiles[n][n2][n3] == null) { this.tiles[n][n2][n3] = new Tile(n, n2, n3); } this.tiles[n][n2][n3].floorDecoration = floorDecoration; } /* * WARNING - void declaration * Enabled aggressive block sorting */ @ObfuscatedName(value="al") @ObfuscatedSignature(descriptor="(IIIILbw;JLbw;Lbw;)V") @Export(value="newGroundItemPile") public void newGroundItemPile(int n, int n2, int n3, int n4, Entity node, long l, Entity entity, Entity entity2) { void var9_9; Model model; void var6_7; TileItemPile tileItemPile = new TileItemPile(); tileItemPile.first = node; tileItemPile.field296 = n2 * 128 - -64; tileItemPile.field298 = n3 * 128 + 64; tileItemPile.field300 = n4; tileItemPile.field299 = var6_7; tileItemPile.field297 = model; tileItemPile.field302 = var9_9; Tile tile = this.tiles[n][n2][n3]; n4 = 0; if (tile != null) { n4 = 0; for (int i = 0; i < tile.field4682 * -1; ++i) { int n5 = n4; if ((tile.gameObjects[i].flags & 0x100) == 256) { n5 = n4; if (tile.gameObjects[i].entity instanceof Model) { model = (Model)tile.gameObjects[i].entity; model.calculateBoundsCylinder(); n5 = n4; if (model.height > n4) { n5 = model.height; } } } n4 = n5; } } tileItemPile.field301 = n4; if (this.tiles[n][n2][n3] == null) { this.tiles[n][n2][n3] = new Tile(n, n2, n3); } this.tiles[n][n2][n3].tileItemPile = tileItemPile; } @ObfuscatedName(value="am") @ObfuscatedSignature(descriptor="(IIIIILbw;IJIIII)Z") @Export(value="addNullableObject") public boolean addNullableObject(int n, int n2, int n3, int n4, int n5, Entity entity, int n6, long l, int n7, int n8, int n9, int n10) { if (entity == null) { return true; } return this.newGameObject(n, n7, n8, n9 - n7 + 1, n10 - n8 + 1, n2, n3, n4, entity, n6, true, l, 0); } @ObfuscatedName(value="an") @ObfuscatedSignature(descriptor="(IIIIIIIILbw;IZJI)Z") @Export(value="newGameObject") boolean newGameObject(int n, int n2, int n3, int n4, int n5, int n6, int n7, int n8, Entity object, int n9, boolean bl, long l, int n10) { int n11 = n2; while (true) { Object object2; int n12; if (n11 < (n12 = n2 + n4)) { } else { object2 = new GameObject(); ((GameObject)object2).tag = l; ((GameObject)object2).flags = n10; ((GameObject)object2).plane = n; ((GameObject)object2).centerX = n6; ((GameObject)object2).centerY = n7; ((GameObject)object2).height = n8; ((GameObject)object2).entity = object; ((GameObject)object2).orientation = n9; ((GameObject)object2).startX = n2; ((GameObject)object2).startY = n3; ((GameObject)object2).endX = n8 = n12 - 1; n9 = n3 + n5; ((GameObject)object2).endY = n10 = n9 - 1; n6 = n2; while (true) { if (n6 < n12) { } else { if (bl) { object = this.tempGameObjects; n = this.tempGameObjectsCount; this.tempGameObjectsCount = n + 1; object[n] = object2; } return true; } block2: for (n7 = n3; n7 < n9; ++n7) { n5 = n6 > n2 ? 1 : 0; n4 = n5; if (n6 < n8) { n4 = n5 + 4; } n5 = n4; if (n7 > n3) { n5 = n4 + 8; } n4 = n5; if (n7 < n10) { n4 = n5 + 2; } n5 = n; while (true) { if (n5 >= 0) { if (this.tiles[n5][n6][n7] == null) { this.tiles[n5][n6][n7] = new Tile(n5, n6, n7); } } else { object = this.tiles[n][n6][n7]; object.gameObjects[object.field4682 * -1] = object2; object.gameObjectEdgeMasks[object.field4682 * -1] = n4; object.field4689 |= n4; --object.field4682; continue block2; } --n5; } } ++n6; } } for (n12 = n3; n12 < n3 + n5; ++n12) { if (n11 >= 0 && n12 >= 0 && n11 < this.xSize) { if (n12 >= this.ySize) { return false; } object2 = this.tiles[n][n11][n12]; if (object2 == null || ((Tile)object2).field4682 * -1 < 5) continue; return false; } return false; } ++n11; } } @ObfuscatedName(value="aq") @ObfuscatedSignature(descriptor="(IIIIILbw;IJZ)Z") @Export(value="drawEntity") public boolean drawEntity(int n, int n2, int n3, int n4, int n5, Entity entity, int n6, long l, boolean bl) { int n7; int n8; int n9; int n10; int n11; block10: { int n12; int n13; block12: { int n14; block11: { if (entity == null) { return true; } n13 = n2 - n5; n14 = n3 - n5; n12 = n5 + n2; n10 = n11 = n3 + n5; n9 = n13; n8 = n14; n7 = n12; if (!bl) break block10; n5 = n11; if (n6 > 640) { n5 = n11; if (n6 < 1408) { n5 = n11 + 128; } } n11 = n12; if (n6 > 1152) { n11 = n12; if (n6 < 1920) { n11 = n12 + 128; } } if (n6 > 1664) break block11; n12 = n14; if (n6 >= 384) break block12; } n12 = n14 - 128; } n10 = n5; n9 = n13; n8 = n12; n7 = n11; if (n6 > 128) { n10 = n5; n9 = n13; n8 = n12; n7 = n11; if (n6 < 896) { n9 = n13 - 128; n7 = n11; n8 = n12; n10 = n5; } } } n5 = n9 / 128; n11 = n8 / 128; return this.newGameObject(n, n5, n11, n7 / 128 - n5 + 1, n10 / 128 - n11 + 1, n2, n3, n4, entity, n6, true, l, 0); } @ObfuscatedName(value="ar") public void method717(int n, int n2, int n3, int n4) { Object object = this.tiles[n][n2][n3]; if (object == null) { return; } object = ((Tile)object).wallDecoration; if (object == null) { return; } ((WallDecoration)object).xOffset = n4 * ((WallDecoration)object).xOffset / 16; ((WallDecoration)object).yOffset = n4 * ((WallDecoration)object).yOffset / 16; } @ObfuscatedName(value="as") @Export(value="addTile") public void addTile(int n, int n2, int n3, int n4, int n5, int n6, int n7, int n8, int n9, int n10, int n11, int n12, int n13, int n14, int n15, int n16, int n17, int n18, int n19, int n20) { if (n4 != 0) { boolean bl = true; if (n4 == 1) { if (n8 != n7 || n7 != n9 || n10 != n7) { bl = false; } TilePaint tilePaint = new TilePaint(n15, n16, n17, n18, n6, n20, bl); n4 = n; while (true) { if (n4 >= 0) { if (this.tiles[n4][n2][n3] == null) { this.tiles[n4][n2][n3] = new Tile(n4, n2, n3); } } else { this.tiles[n][n2][n3].paint = tilePaint; return; } --n4; } } TileModel tileModel = new TileModel(n4, n5, n6, n2, n3, n7, n8, n9, n10, n11, n12, n13, n14, n15, n16, n17, n18, n19, n20); n4 = n; while (true) { if (n4 >= 0) { if (this.tiles[n4][n2][n3] == null) { this.tiles[n4][n2][n3] = new Tile(n4, n2, n3); } } else { this.tiles[n][n2][n3].model = tileModel; return; } --n4; } } TilePaint tilePaint = new TilePaint(n11, n12, n13, n14, -1, n19, false); n4 = n; while (true) { if (n4 >= 0) { if (this.tiles[n4][n2][n3] == null) { this.tiles[n4][n2][n3] = new Tile(n4, n2, n3); } } else { this.tiles[n][n2][n3].paint = tilePaint; return; } --n4; } } /* * Exception decompiling */ @ObfuscatedName(value="aw") @ObfuscatedSignature(descriptor="(Lco;)V") @Export(value="removeGameObject") void removeGameObject(GameObject var1_1) { /* * This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file. * org.benf.cfr.reader.util.ConfusedCFRException: Tried to end blocks [0[UNCONDITIONALDOLOOP]], but top level block is 2[FORLOOP] * org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.processEndingBlocks(Op04StructuredStatement.java:429) * org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:478) * org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:728) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:806) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:258) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:192) * org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94) * org.benf.cfr.reader.entities.Method.analyse(Method.java:521) * org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1035) * org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:922) * org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:253) * org.benf.cfr.reader.Driver.doJar(Driver.java:135) * org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:65) * org.benf.cfr.reader.Main.main(Main.java:49) */ throw new IllegalStateException(Decompilation failed); } @ObfuscatedName(value="ay") @Export(value="clearTempGameObjects") public void clearTempGameObjects() { for (int i = 0; i < this.tempGameObjectsCount; ++i) { this.removeGameObject(this.tempGameObjects[i]); this.tempGameObjects[i] = null; } this.tempGameObjectsCount = 0; } /* * Unable to fully structure code * Enabled aggressive block sorting * Lifted jumps to return sites */ @ObfuscatedName(value="ba") @Export(value="occlude") void occlude() { var7_1 = Scene.Scene_planeOccluderCounts[Scene.Scene_plane]; var9_2 = Scene.field399[Scene.Scene_plane]; Scene.Scene_currentOccludersCount = 0; var4_3 = 0; while (var4_3 < var7_1) { block19: { block23: { block27: { block26: { block17: { block22: { block25: { block24: { block16: { block20: { block21: { block18: { var10_10 = var9_2[var4_3]; var2_5 = var10_10.type * -693388489; var1_4 = 50; var3_6 = 1; if (var2_5 * 137423495 != 1) break block18; var6_8 = var10_10.minTileX - Scene.field374 + 25; if (var6_8 < 0 || var6_8 > 50) break block19; var2_5 = var5_7 = var10_10.minTileY - Scene.field362 + 25; if (var5_7 < 0) { var2_5 = 0; } if ((var5_7 = var10_10.maxTileY - Scene.field362 + 25) > 50) break block20; var1_4 = var5_7; break block20; } if (var10_10.type != 2) break block21; var5_7 = var10_10.minTileY - Scene.field362 + 25; if (var5_7 < 0 || var5_7 > 50) break block19; var2_5 = var3_6 = var10_10.minTileX - Scene.field374 + 25; if (var3_6 < 0) { var2_5 = 0; } if ((var3_6 = var10_10.maxTileX - Scene.field374 + 25) > 50) break block22; var1_4 = var3_6; break block22; } if (var10_10.type != 4 || (var8_9 = var10_10.minY - Scene.field361) <= 128) break block19; var2_5 = var3_6 = var10_10.minTileY - Scene.field362 + 25; if (var3_6 < 0) { var2_5 = 0; } var5_7 = var3_6 = var10_10.maxTileY - Scene.field362 + 25; if (var3_6 > 50) { var5_7 = 50; } if (var2_5 > var5_7) break block19; var3_6 = var6_8 = var10_10.minTileX - Scene.field374 + 25; if (var6_8 < 0) { var3_6 = 0; } if ((var6_8 = var10_10.maxTileX - Scene.field374 + 25) > 50) break block23; var1_4 = var6_8; break block23; } while (var2_5 <= var1_4) { if (Scene.field405[var6_8][var2_5]) { var1_4 = var3_6; break block16; } ++var2_5; } var1_4 = 0; } if (var1_4 == 0) break block19; var1_4 = Scene.field364 - var10_10.minX; if (var1_4 <= 32) break block24; var10_10.field40 = 1; break block25; } if (var1_4 >= -32) break block19; var10_10.field40 = 2; var1_4 = -var1_4; } var10_10.field45 = (var10_10.minZ - Scene.field373 << 8) / var1_4; var10_10.field43 = (var10_10.maxZ - Scene.field373 << 8) / var1_4; var10_10.field41 = (var10_10.minY - Scene.field361 << 8) / var1_4; var10_10.field39 = (var10_10.maxY - Scene.field361 << 8) / var1_4; var11_11 = Scene.field378; var1_4 = Scene.Scene_currentOccludersCount; Scene.Scene_currentOccludersCount = var1_4 + 1; var11_11[var1_4] = var10_10; break block19; } while (var2_5 <= var1_4) { if (Scene.field405[var2_5][var5_7]) { var1_4 = 1; break block17; } ++var2_5; } var1_4 = 0; } if (var1_4 == 0) break block19; var1_4 = Scene.field373 - var10_10.minZ; if (var1_4 <= 32) break block26; var10_10.field40 = 3; break block27; } if (var1_4 >= -32) break block19; var10_10.field40 = 4; var1_4 = -var1_4; } var10_10.field37 = (var10_10.minX - Scene.field364 << 8) / var1_4; var10_10.field38 = (var10_10.maxX - Scene.field364 << 8) / var1_4; var10_10.field41 = (var10_10.minY - Scene.field361 << 8) / var1_4; var10_10.field39 = (var10_10.maxY - Scene.field361 << 8) / var1_4; var11_11 = Scene.field378; var1_4 = Scene.Scene_currentOccludersCount; Scene.Scene_currentOccludersCount = var1_4 + 1; var11_11[var1_4] = var10_10; break block19; } block3: while (true) { block28: { if (var3_6 <= var1_4) break block28; var1_4 = 0; ** GOTO lbl111 } for (var6_8 = var2_5; var6_8 <= var5_7; ++var6_8) { if (!Scene.field405[var3_6][var6_8]) continue; var1_4 = 1; lbl111: // 2 sources if (var1_4 == 0) break block3; var10_10.field40 = 5; var10_10.field37 = (var10_10.minX - Scene.field364 << 8) / var8_9; var10_10.field38 = (var10_10.maxX - Scene.field364 << 8) / var8_9; var10_10.field45 = (var10_10.minZ - Scene.field373 << 8) / var8_9; var10_10.field43 = (var10_10.maxZ - Scene.field373 << 8) / var8_9; var11_11 = Scene.field378; var1_4 = Scene.Scene_currentOccludersCount; Scene.Scene_currentOccludersCount = var1_4 + 1; var11_11[var1_4] = var10_10; break block3; } ++var3_6; } } ++var4_3; } } /* * Enabled aggressive block sorting */ @ObfuscatedName(value="bb") @ObfuscatedSignature(descriptor="(Lba;IIIIII)V") @Export(value="drawTileOverlay") public void drawTileOverlay(class19 arrtile, int n, int n2, int n3, int n4, int n5, int n6) { int n7; field413 = arrtile; field407 = field413.vmethod7589(); if (n < 0) { n7 = 0; } else { n7 = n; if (n >= this.xSize * 128) { n7 = this.xSize * 128 - 1; } } if (n3 < 0) { n = 0; } else { n = n3; if (n3 >= this.ySize * 128) { n = this.ySize * 128 - 1; } } if (n4 < 128) { n3 = 128; } else { n3 = n4; if (n4 > 383) { n3 = 383; } } ++Scene_drawnCount; field393 = Rasterizer3D.Rasterizer3D_sine[n3]; field386 = Rasterizer3D.Rasterizer3D_cosine[n3]; field384 = Rasterizer3D.Rasterizer3D_sine[n5]; field383 = Rasterizer3D.Rasterizer3D_cosine[n5]; field405 = field410[(n3 - 128) / 32][n5 / 64]; field364 = n7; field361 = n2; field373 = n; field374 = n7 / 128; field362 = n / 128; Scene_plane = n6; field369 = field374 - 25; if (field369 < 0) { field369 = 0; } if ((field377 = field362 - 25) < 0) { field377 = 0; } if ((field368 = field374 + 25) > this.xSize) { field368 = this.xSize; } if ((field372 = field362 + 25) > this.ySize) { field372 = this.ySize; } this.occlude(); field376 = 0; n = this.minPlane; block0: while (true) { Tile tile; block38: { if (n < this.pixelsPerTile) break block38; n = this.minPlane; block1: while (true) { block39: { if (n < this.pixelsPerTile) break block39; n = this.minPlane; block2: while (true) { if (n >= this.pixelsPerTile) { field385 = false; return; } arrtile = this.tiles[n]; n2 = -25; while (true) { block41: { block42: { block40: { if (n2 > 0) break block40; n4 = n2 + field374; n5 = field374 - n2; if (n4 < field369 && n5 >= field368) break block41; break block42; } ++n; continue block2; } for (n3 = -25; n3 <= 0; ++n3) { n6 = n3 + field362; n7 = field362 - n3; if (n4 >= field369) { if (n6 >= field377 && (tile = arrtile[n4][n6]) != null && tile.field4697) { this.drawTile(tile, false); } if (n7 < field372 && (tile = arrtile[n4][n7]) != null && tile.field4697) { this.drawTile(tile, false); } } if (n5 < field368) { if (n6 >= field377 && (tile = arrtile[n5][n6]) != null && tile.field4697) { this.drawTile(tile, false); } if (n7 < field372 && (tile = arrtile[n5][n7]) != null && tile.field4697) { this.drawTile(tile, false); } } if (field376 != 0) continue; field385 = false; return; } } ++n2; } break; } } arrtile = this.tiles[n]; n2 = -25; while (true) { block44: { block45: { block43: { if (n2 > 0) break block43; n4 = n2 + field374; n5 = field374 - n2; if (n4 < field369 && n5 >= field368) break block44; break block45; } ++n; continue block1; } for (n3 = -25; n3 <= 0; ++n3) { n6 = n3 + field362; n7 = field362 - n3; if (n4 >= field369) { if (n6 >= field377 && (tile = arrtile[n4][n6]) != null && tile.field4697) { this.drawTile(tile, true); } if (n7 < field372 && (tile = arrtile[n4][n7]) != null && tile.field4697) { this.drawTile(tile, true); } } if (n5 < field368) { if (n6 >= field377 && (tile = arrtile[n5][n6]) != null && tile.field4697) { this.drawTile(tile, true); } if (n7 < field372 && (tile = arrtile[n5][n7]) != null && tile.field4697) { this.drawTile(tile, true); } } if (field376 != 0) continue; field385 = false; return; } } ++n2; } break; } } arrtile = this.tiles[n]; n3 = field369; while (true) { if (n3 < field368) { } else { ++n; continue block0; } for (n4 = field377; n4 < field372; ++n4) { tile = arrtile[n3][n4]; if (tile == null) continue; if (tile.minPlane <= n6 && (field405[n3 - field374 + 25][n4 - field362 + 25] || this.tileHeights[n][n3][n4] - n2 >= 2000)) { tile.field4697 = true; tile.drawSecondary = true; tile.field4691 = tile.field4682 * -1 > 0; ++field376; continue; } tile.field4697 = false; tile.drawSecondary = false; tile.field4690 = 0; } ++n3; } break; } } @ObfuscatedName(value="bg") public long method728(int n, int n2, int n3) { Tile tile = this.tiles[n][n2][n3]; if (tile == null) { return 0L; } for (n = 0; n < tile.field4682 * -1; ++n) { GameObject gameObject = tile.gameObjects[n]; if (!class76.method4320(gameObject.tag) || n2 != gameObject.startX || n3 != gameObject.startY) continue; return gameObject.tag; } return 0L; } /* * Exception decompiling */ @ObfuscatedName(value="bh") public void method729(int var1_1, int var2_2, int var3_3) { /* * This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file. * org.benf.cfr.reader.util.ConfusedCFRException: Tried to end blocks [0[UNCONDITIONALDOLOOP]], but top level block is 2[UNCONDITIONALDOLOOP] * org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.processEndingBlocks(Op04StructuredStatement.java:429) * org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:478) * org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:728) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:806) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:258) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:192) * org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94) * org.benf.cfr.reader.entities.Method.analyse(Method.java:521) * org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1035) * org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:922) * org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:253) * org.benf.cfr.reader.Driver.doJar(Driver.java:135) * org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:65) * org.benf.cfr.reader.Main.main(Main.java:49) */ throw new IllegalStateException(Decompilation failed); } @ObfuscatedName(value="bj") @Export(value="getObjectFlags") public int getObjectFlags(int n, int n2, int n3, long l) { Tile tile = this.tiles[n][n2][n3]; if (tile == null) { return -1; } if (tile.boundaryObject != null && tile.boundaryObject.tag == l) { n = tile.boundaryObject.flags * 1274151005; n2 = 1240323061; } else if (tile.wallDecoration != null && tile.wallDecoration.tag == l) { n = tile.wallDecoration.flags * -508968795; n2 = -326097107; } else { if (tile.floorDecoration != null && tile.floorDecoration.tag == l) { return tile.floorDecoration.flags & 0xFF; } for (n = 0; n < tile.field4682 * -1; ++n) { if (tile.gameObjects[n].tag != l) continue; return tile.gameObjects[n].flags & 0xFF; } return -1; } return n2 * n & 0xFF; } @ObfuscatedName(value="bn") boolean method734(int n, int n2, int n3, int n4, int n5, int n6) { if (n3 == n2 && n5 == n4) { Object object; if (!this.method743(n, n2, n4)) { return false; } int n7 = n2 << 7; n3 = n7 + 1; int n8 = this.tileHeights[n][n2][n4]; n5 = n4 << 7; Object object2 = n5 + 1; return this.method739(n3, n8 - n6, (int)object2) && this.method739(n7 = n7 + 128 - 1, (object = this.tileHeights[n])[n8 = n2 + 1][n4] - n6, (int)object2) && this.method739(n7, (object2 = (Object)(object = (Object)this.tileHeights[n][n8])[++n4]) - n6, n5 = n5 + 128 - 1) && this.method739(n3, this.tileHeights[n][n2][n4] - n6, n5); } int n9 = n2; while (true) { int n10; if (n9 <= n3) { } else { n9 = (n2 << 7) + 1; n10 = (n4 << 7) + 2; if (!this.method739(n9, n = this.tileHeights[n][n2][n4] - n6, n10)) { return false; } n2 = (n3 << 7) - 1; if (!this.method739(n2, n, n10)) { return false; } n3 = (n5 << 7) - 1; if (!this.method739(n9, n, n3)) { return false; } return this.method739(n2, n, n3); } for (n10 = n4; n10 <= n5; ++n10) { if (this.field420[n][n9][n10] != -Scene_drawnCount) continue; return false; } ++n9; } } @ObfuscatedName(value="bp") public long method736(int n, int n2, int n3) { Tile tile = this.tiles[n][n2][n3]; if (tile != null && tile.boundaryObject != null) { return tile.boundaryObject.tag; } return 0L; } @ObfuscatedName(value="bq") @ObfuscatedSignature(descriptor="(Lbk;III)V") void method737(ModelData modelData, int n, int n2, int n3) { Tile tile; if (n2 < this.xSize && (tile = this.tiles[n][n2 + 1][n3]) != null && tile.floorDecoration != null && tile.floorDecoration.entity instanceof ModelData) { ModelData.method13916(modelData, (ModelData)tile.floorDecoration.entity, 128, 0, 0, true); } if (n3 < this.xSize && (tile = this.tiles[n][n2][n3 + 1]) != null && tile.floorDecoration != null && tile.floorDecoration.entity instanceof ModelData) { ModelData.method13916(modelData, (ModelData)tile.floorDecoration.entity, 0, 0, 128, true); } if (n2 < this.xSize && n3 < this.ySize && (tile = this.tiles[n][n2 + 1][n3 + 1]) != null && tile.floorDecoration != null && tile.floorDecoration.entity instanceof ModelData) { ModelData.method13916(modelData, (ModelData)tile.floorDecoration.entity, 128, 0, 128, true); } if (n2 < this.xSize && n3 > 0 && (tile = this.tiles[n][n2 + 1][n3 - 1]) != null && tile.floorDecoration != null && tile.floorDecoration.entity instanceof ModelData) { ModelData.method13916(modelData, (ModelData)tile.floorDecoration.entity, 128, 0, -128, true); } } @ObfuscatedName(value="br") @ObfuscatedSignature(descriptor="(Lbk;IIIII)V") void method738(ModelData modelData, int n, int n2, int n3, int n4, int n5) { int n6 = n2 + n4; int n7 = n3 + n5; int n8 = n2; boolean bl = true; for (int i = n; i <= n + 1; ++i) { if (i == this.pixelsPerTile) continue; int n9 = n8; while (n9 <= n6) { int n10 = n6; int n11 = n9; if (n9 >= 0) { if (n9 >= this.xSize) { n10 = n6; n11 = n9; } else { int n12 = n3 - 1; while (true) { Tile tile; Object object = this; n10 = n6; n11 = n9; if (n12 > n7) break; if (n12 >= 0 && n12 < ((Scene)object).ySize && (!bl || n9 >= n6 || n12 >= n7 || n12 < n3 && n2 != n9) && (tile = ((Scene)object).tiles[i][n9][n12]) != null) { n10 = ((Scene)object).tileHeights[i][n9][n12]; Object object2 = ((Scene)object).tileHeights[i]; n11 = n9 + 1; int n13 = object2[n11][n12]; object2 = ((Scene)object).tileHeights[i][n9]; int n14 = n12 + 1; n10 = (n10 + n13 + ((Scene)object).tileHeights[i][n11][n14] + object2[n14]) / 4; n11 = ((Scene)object).tileHeights[n][n2][n3]; object2 = ((Scene)object).tileHeights[n]; n13 = n2 + 1; n14 = object2[n13][n3]; object2 = ((Scene)object).tileHeights[n][n2]; int n15 = n3 + 1; n11 = n10 - (n11 + n14 + ((Scene)object).tileHeights[n][n13][n15] + object2[n15]) / 4; object = tile.boundaryObject; if (object != null) { if (((BoundaryObject)object).entity1 instanceof ModelData) { ModelData.method13916(modelData, (ModelData)((BoundaryObject)object).entity1, (1 - n4) * 64 + (n9 - n2) * 128, n11, (n12 - n3) * 128 + (1 - n5) * 64, bl); } if (((BoundaryObject)object).entity2 instanceof ModelData) { ModelData.method13916(modelData, (ModelData)((BoundaryObject)object).entity2, (1 - n4) * 64 + (n9 - n2) * 128, n11, (n12 - n3) * 128 + (1 - n5) * 64, bl); } } for (n10 = 0; n10 < tile.field4682 * -1; ++n10) { object = tile.gameObjects[n10]; if (object == null || !(((GameObject)object).entity instanceof ModelData)) continue; object2 = (ModelData)((GameObject)object).entity; n13 = ((GameObject)object).endX * -1674187619; n14 = ((GameObject)object).startX * -1026948801; n15 = ((GameObject)object).endY * 572583791; int n16 = ((GameObject)object).startY * -1756545293; ModelData.method13916(modelData, (ModelData)object2, (n13 * -919078475 - n14 * -1321177409 + 1 - n4) * 64 + (((GameObject)object).startX - n2) * 128, n11, (((GameObject)object).startY - n3) * 128 + (n15 * -365342833 - n16 * 26151483 + 1 - n5) * 64, bl); } } ++n12; } } } n9 = n11 + 1; n6 = n10; } --n8; bl = false; } } /* * Enabled aggressive block sorting */ @ObfuscatedName(value="ai") @Export(value="setLinkBelow") public void setLinkBelow(int n, int n2) { Tile tile = this.tiles[0][n][n2]; int n3 = 0; block0: while (n3 < 3) { Tile tile2; Tile[] arrtile = this.tiles[n3][n]; Tile[][][] arrtile2 = this.tiles; int n4 = n3 + 1; arrtile[n2] = tile2 = arrtile2[n4][n][n2]; n3 = n4; if (tile2 == null) continue; ++tile2.plane; int n5 = 0; while (true) { n3 = n4; if (n5 >= tile2.field4682 * -1) continue block0; GameObject gameObject = tile2.gameObjects[n5]; if (class76.method4320(gameObject.tag) && gameObject.startX == n && n2 == gameObject.startY) { gameObject.plane += -1; } ++n5; } } if (this.tiles[0][n][n2] == null) { this.tiles[0][n][n2] = new Tile(0, n, n2); } this.tiles[0][n][n2].linkedBelowTile = tile; this.tiles[3][n][n2] = null; } @ObfuscatedName(value="ak") @Export(value="init7") public void init7() { int n = 0; int n2 = 0; block0: while (true) { int n3; if (n2 >= this.pixelsPerTile) { n2 = 0; while (true) { if (n2 < Scene_planesCount) { } else { for (n2 = 0; n2 < this.tempGameObjectsCount; ++n2) { this.tempGameObjects[n2] = null; } this.tempGameObjectsCount = 0; for (n2 = n; n2 < gameObjects.length; ++n2) { Scene.gameObjects[n2] = null; } return; } for (n3 = 0; n3 < Scene_planeOccluderCounts[n2]; ++n3) { Scene.field399[n2][n3] = null; } Scene.Scene_planeOccluderCounts[n2] = 0; ++n2; } } n3 = 0; while (true) { if (n3 < this.xSize) { } else { ++n2; continue block0; } for (int i = 0; i < this.ySize; ++i) { this.tiles[n2][n3][i] = null; } ++n3; } break; } } @ObfuscatedName(value="av") @Export(value="removeWallDecoration") public void removeWallDecoration(int n, int n2, int n3) { Tile tile = this.tiles[n][n2][n3]; if (tile == null) { return; } tile.tileItemPile = null; } @ObfuscatedName(value="bi") public long method730(int n, int n2, int n3) { Tile tile = this.tiles[n][n2][n3]; if (tile != null && tile.wallDecoration != null) { return tile.wallDecoration.tag; } return 0L; } @ObfuscatedName(value="bl") boolean method733(int n, int n2, int n3, int n4) { if (!this.method743(n, n2, n3)) { return false; } int n5 = n2 << 7; int n6 = n3 << 7; int n7 = this.tileHeights[n][n2][n3] - 1; n3 = n7 - 120; n2 = n7 - 230; if (n4 < 16) { if (n4 == 1) { if (n5 > field364) { if (!this.method739(n5, n7, n6)) { return false; } if (!this.method739(n5, n7, n6 + 128)) { return false; } } if (n > 0) { if (!this.method739(n5, n3, n6)) { return false; } if (!this.method739(n5, n3, n6 + 128)) { return false; } } if (!this.method739(n5, n2, n6)) { return false; } return this.method739(n5, n2, n6 + 128); } if (n4 == 2) { if (n6 < field373) { n4 = n6 + 128; if (!this.method739(n5, n7, n4)) { return false; } if (!this.method739(n5 + 128, n7, n4)) { return false; } } if (n > 0) { n = n6 + 128; if (!this.method739(n5, n3, n)) { return false; } if (!this.method739(n5 + 128, n3, n)) { return false; } } if (!this.method739(n5, n2, n = n6 + 128)) { return false; } return this.method739(n5 + 128, n2, n); } if (n4 == 4) { if (n5 < field364) { n4 = n5 + 128; if (!this.method739(n4, n7, n6)) { return false; } if (!this.method739(n4, n7, n6 + 128)) { return false; } } if (n > 0) { n = n5 + 128; if (!this.method739(n, n3, n6)) { return false; } if (!this.method739(n, n3, n6 + 128)) { return false; } } if (!this.method739(n = n5 + 128, n2, n6)) { return false; } return this.method739(n, n2, n6 + 128); } if (n4 == 8) { if (n6 > field373) { if (!this.method739(n5, n7, n6)) { return false; } if (!this.method739(n5 + 128, n7, n6)) { return false; } } if (n > 0) { if (!this.method739(n5, n3, n6)) { return false; } if (!this.method739(n5 + 128, n3, n6)) { return false; } } if (!this.method739(n5, n2, n6)) { return false; } return this.method739(n5 + 128, n2, n6); } } if (!this.method739(n5 + 64, n7 - 238, n6 + 64)) { return false; } if (n4 == 16) { return this.method739(n5, n2, n6 + 128); } if (n4 == 32) { return this.method739(n5 + 128, n2, n6 + 128); } if (n4 == 64) { return this.method739(n5 + 128, n2, n6); } if (n4 == 128) { return this.method739(n5, n2, n6); } return true; } @ObfuscatedName(value="bs") boolean method739(int n, int n2, int n3) { for (int i = 0; i < Scene_currentOccludersCount; ++i) { int n4; int n5; int n6; int n7; int n8; int n9; int n10; int n11; int n12; Occluder occluder = field378[i]; if (occluder.field40 == 1) { n12 = occluder.minX - n; if (n12 <= 0) continue; n11 = occluder.minZ * 643861331; n10 = occluder.field45 * -1756350449; n9 = occluder.maxZ * 1349627955; n8 = occluder.field43 * 1797273939; n7 = occluder.minY * -802541315; n6 = occluder.field41 * 2121030141; n5 = occluder.maxY * 1375387289; n4 = occluder.field39 * 1132353149; if (n3 < n11 * -1247153957 + (n10 * n12 * 2125444847 >> 8) || n3 > n9 * 1719716603 + (n8 * n12 * -243764517 >> 8) || n2 < (n6 * n12 * 1310542677 >> 8) + n7 * 412052565 || n2 > (n4 * n12 * -1035578667 >> 8) + n5 * 2116466089) continue; return true; } if (occluder.field40 == 2) { n12 = n - occluder.minX; if (n12 <= 0) continue; n11 = occluder.minZ * 643861331; n10 = occluder.field45 * -1756350449; n9 = occluder.maxZ * 1349627955; n8 = occluder.field43 * 1797273939; n7 = occluder.minY * -802541315; n6 = occluder.field41 * 2121030141; n5 = occluder.maxY * 1375387289; n4 = occluder.field39 * 1132353149; if (n3 < n11 * -1247153957 + (n10 * n12 * 2125444847 >> 8) || n3 > n9 * 1719716603 + (n8 * n12 * -243764517 >> 8) || n2 < (n6 * n12 * 1310542677 >> 8) + n7 * 412052565 || n2 > (n4 * n12 * -1035578667 >> 8) + n5 * 2116466089) continue; return true; } if (occluder.field40 == 3) { n12 = occluder.minZ - n3; if (n12 <= 0) continue; n11 = occluder.minX * 1984394471; n10 = occluder.field37 * 1367820281; n9 = occluder.maxX * 622131295; n8 = occluder.field38 * 132812005; n7 = occluder.minY * -802541315; n6 = occluder.field41 * 2121030141; n5 = occluder.maxY * 1375387289; n4 = occluder.field39 * 1132353149; if (n < (n10 * n12 * 1261619785 >> 8) + n11 * 2020630231 || n > (n8 * n12 * -146517779 >> 8) + n9 * 1060332447 || n2 < (n6 * n12 * 1310542677 >> 8) + n7 * 412052565 || n2 > (n4 * n12 * -1035578667 >> 8) + n5 * 2116466089) continue; return true; } if (occluder.field40 == 4) { n12 = n3 - occluder.minZ; if (n12 <= 0) continue; n11 = occluder.minX * 1984394471; n10 = occluder.field37 * 1367820281; n9 = occluder.maxX * 622131295; n8 = occluder.field38 * 132812005; n7 = occluder.minY * -802541315; n6 = occluder.field41 * 2121030141; n5 = occluder.maxY * 1375387289; n4 = occluder.field39 * 1132353149; if (n < (n10 * n12 * 1261619785 >> 8) + n11 * 2020630231 || n > (n8 * n12 * -146517779 >> 8) + n9 * 1060332447 || n2 < (n6 * n12 * 1310542677 >> 8) + n7 * 412052565 || n2 > (n4 * n12 * -1035578667 >> 8) + n5 * 2116466089) continue; return true; } if (occluder.field40 != 5 || (n12 = n2 - occluder.minY) <= 0) continue; n11 = occluder.minX * 1984394471; n10 = occluder.field37 * 1367820281; n9 = occluder.maxX * 622131295; n8 = occluder.field38 * 132812005; n7 = occluder.minZ * 643861331; n6 = occluder.field45 * -1756350449; n5 = occluder.maxZ * 1349627955; n4 = occluder.field43 * 1797273939; if (n < (n10 * n12 * 1261619785 >> 8) + n11 * 2020630231 || n > (n8 * n12 * -146517779 >> 8) + n9 * 1060332447 || n3 < n7 * -1247153957 + (n6 * n12 * 2125444847 >> 8) || n3 > n5 * 1719716603 + (n4 * n12 * -243764517 >> 8)) continue; return true; } return false; } @ObfuscatedName(value="bu") boolean method741(int n, int n2, int n3, int n4) { Object object; if (!this.method743(n, n2, n3)) { return false; } int n5 = n2 << 7; int n6 = n5 + 1; int n7 = this.tileHeights[n][n2][n3]; int n8 = n3 << 7; Object object2 = n8 + 1; return this.method739(n6, n7 - n4, (int)object2) && this.method739(n5 = n5 + 128 - 1, (object = this.tileHeights[n])[n7 = n2 + 1][n3] - n4, (int)object2) && this.method739(n5, (object2 = (Object)(object = (Object)this.tileHeights[n][n7])[++n3]) - n4, n8 = n8 + 128 - 1) && this.method739(n6, this.tileHeights[n][n2][n3] - n4, n8); } /* * Exception decompiling */ @ObfuscatedName(value="bv") @ObfuscatedSignature(descriptor="(Lbz;Z)V") @Export(value="drawTile") void drawTile(Tile var1_1, boolean var2_3) { /* * This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file. * org.benf.cfr.reader.util.ConfusedCFRException: Statement already marked as first in another block * org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.markFirstStatementInBlock(Op03SimpleStatement.java:453) * org.benf.cfr.reader.bytecode.analysis.opgraph.op3rewriters.Misc.markWholeBlock(Misc.java:232) * org.benf.cfr.reader.bytecode.analysis.opgraph.op3rewriters.ConditionalRewriter.considerAsSimpleIf(ConditionalRewriter.java:646) * org.benf.cfr.reader.bytecode.analysis.opgraph.op3rewriters.ConditionalRewriter.identifyNonjumpingConditionals(ConditionalRewriter.java:52) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:681) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:258) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:192) * org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94) * org.benf.cfr.reader.entities.Method.analyse(Method.java:521) * org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1035) * org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:922) * org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:253) * org.benf.cfr.reader.Driver.doJar(Driver.java:135) * org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:65) * org.benf.cfr.reader.Main.main(Main.java:49) */ throw new IllegalStateException(Decompilation failed); } @ObfuscatedName(value="ab") @ObfuscatedSignature(descriptor="(IIIILbw;Lbw;IIIIJI)V") @Export(value="newWallDecoration") public void newWallDecoration(int n, int n2, int n3, int n4, Entity entity, Entity entity2, int n5, int n6, int n7, int n8, long l, int n9) { if (entity == null) { return; } WallDecoration wallDecoration = new WallDecoration(); wallDecoration.tag = l; wallDecoration.flags = n9; wallDecoration.x = n2 * 128 + 64; wallDecoration.field511 = n3 * 128 - -64; wallDecoration.field513 = n4; wallDecoration.field514 = entity; wallDecoration.field506 = entity2; wallDecoration.field516 = n5; wallDecoration.field510 = n6; wallDecoration.xOffset = n7; wallDecoration.yOffset = n8; n4 = n; while (true) { if (n4 >= 0) { if (this.tiles[n4][n2][n3] == null) { this.tiles[n4][n2][n3] = new Tile(n4, n2, n3); } } else { this.tiles[n][n2][n3].wallDecoration = wallDecoration; return; } --n4; } } @ObfuscatedName(value="bf") public long method727(int n, int n2, int n3) { Tile tile = this.tiles[n][n2][n3]; if (tile != null && tile.floorDecoration != null) { return tile.floorDecoration.tag; } return 0L; } @ObfuscatedName(value="bw") boolean method743(int n, int n2, int n3) { Object object; int n4 = this.field420[n][n2][n3]; if (n4 == -Scene_drawnCount) { return false; } if (n4 == Scene_drawnCount) { return true; } int n5 = n2 << 7; n4 = n5 + 1; Object object2 = this.tileHeights[n][n2][n3]; int n6 = n3 << 7; int n7 = n6 + 1; if (this.method739(n4, (int)object2, n7) && this.method739(n5 = n5 + 128 - 1, (object = this.tileHeights[n])[object2 = n2 + 1][n3], n7) && this.method739(n5, (int)(object2 = (Object)(object = (Object)this.tileHeights[n][object2])[n7 = n3 + 1]), n6 = n6 + 128 - 1) && this.method739(n4, this.tileHeights[n][n2][n7], n6)) { this.field420[n][n2][n3] = Scene_drawnCount; return true; } this.field420[n][n2][n3] = -Scene_drawnCount; return false; } /* * Exception decompiling */ @ObfuscatedName(value="bd") @Export(value="Scene_buildVisiblityMap") public static void Scene_buildVisiblityMap(int[] var0, int var1_1, int var2_2, int var3_3, int var4_4) { /* * This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file. * org.benf.cfr.reader.util.ConfusedCFRException: Tried to end blocks [1[UNCONDITIONALDOLOOP]], but top level block is 3[UNCONDITIONALDOLOOP] * org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.processEndingBlocks(Op04StructuredStatement.java:429) * org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:478) * org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:728) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:806) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:258) * org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:192) * org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94) * org.benf.cfr.reader.entities.Method.analyse(Method.java:521) * org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1035) * org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:922) * org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:253) * org.benf.cfr.reader.Driver.doJar(Driver.java:135) * org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:65) * org.benf.cfr.reader.Main.main(Main.java:49) */ throw new IllegalStateException(Decompilation failed); } @ObfuscatedName(value="bx") @Export(value="containsBounds") static boolean containsBounds(int n, int n2, int n3, int n4, int n5, int n6, int n7, int n8) { if (n2 < n3 && n2 < n4 && n2 < n5) { return false; } if (n2 > n3 && n2 > n4 && n2 > n5) { return false; } if (n < n6 && n < n7 && n < n8) { return false; } if (n > n6 && n > n7 && n > n8) { return false; } int n9 = (n2 - n3) * (n7 - n6) - (n - n6) * (n4 - n3); n4 = (n8 - n7) * (n2 - n4) - (n - n7) * (n5 - n4); n = (n6 - n8) * (n2 - n5) - (n3 - n5) * (n - n8); if (n9 != 0) { return n9 < 0 ? n4 <= 0 && n <= 0 : n4 >= 0 && n >= 0; } if (n4 != 0) { return n4 < 0 ? n <= 0 : n >= 0; } return true; } @ObfuscatedName(value="ax") @Export(value="Scene_addOccluder") public static void Scene_addOccluder(int n, int n2, int n3, int n4, int n5, int n6, int n7, int n8) { Occluder occluder = new Occluder(); occluder.minTileX = n3 / 128; occluder.maxTileX = n4 / 128; occluder.minTileY = n5 / 128; occluder.maxTileY = n6 / 128; occluder.type = n2; occluder.minX = n3; occluder.maxX = n4; occluder.minZ = n5; occluder.maxZ = n6; occluder.minY = n7; occluder.maxY = n8; Occluder[] arroccluder = field399[n]; int[] arrn = Scene_planeOccluderCounts; n2 = arrn[n]; arrn[n] = n2 + 1; arroccluder[n2] = occluder; } @ObfuscatedName(value="bc") static boolean method679(int n, int n2, int n3) { int n4 = field384; int n5 = field383; int n6 = n3 * field383 - n * field384 >> 16; int n7 = field393 * n2 + n6 * field386 >> 16; int n8 = field386; int n9 = field393; if (n7 >= 50) { if (n7 > 3500) { return false; } n = (n4 * n3 + n * n5 >> 16) * 128 / n7 + Scene_viewportXCenter; n2 = (n8 * n2 - n6 * n9 >> 16) * 128 / n7 + Scene_viewportYCenter; if (n >= Scene_viewportXMin && n <= Scene_viewportXMax && n2 >= Scene_viewportYMin) { return n2 <= Scene_viewportYMax; } return false; } return false; } }
43.476978
342
0.447522
3ea9238ef1d9510275bd4e910706cca8537f5a98
326
package org.happykit.happyboot.sys.model.query; import org.happykit.happyboot.page.PageQuery; import lombok.Data; import lombok.EqualsAndHashCode; /** * 分页查询对象 * * @author shaoqiang * @version 1.0 2020/04/01 */ @Data @EqualsAndHashCode(callSuper = true) public class SysPermissionPageQueryParam extends PageQuery { }
17.157895
60
0.766871
d577738ca0ce29acf08c37528ca43c307976c757
1,449
package pl.kkowalewski.recipeapp.service.unitofmeasure; import org.springframework.stereotype.Service; import pl.kkowalewski.recipeapp.command.UnitOfMeasureCommand; import pl.kkowalewski.recipeapp.converter.tocommand.UnitOfMeasureToUnitOfMeasureCommand; import pl.kkowalewski.recipeapp.repository.UnitOfMeasureRepository; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @Service public class UnitOfMeasureServiceImpl implements UnitOfMeasureService { /*------------------------ FIELDS REGION ------------------------*/ private final UnitOfMeasureRepository unitOfMeasureRepository; private final UnitOfMeasureToUnitOfMeasureCommand unitOfMeasureToUnitOfMeasureCommand; /*------------------------ METHODS REGION ------------------------*/ public UnitOfMeasureServiceImpl( UnitOfMeasureRepository unitOfMeasureRepository, UnitOfMeasureToUnitOfMeasureCommand unitOfMeasureToUnitOfMeasureCommand) { this.unitOfMeasureRepository = unitOfMeasureRepository; this.unitOfMeasureToUnitOfMeasureCommand = unitOfMeasureToUnitOfMeasureCommand; } @Override public Set<UnitOfMeasureCommand> listAllUoms() { return StreamSupport.stream(unitOfMeasureRepository.findAll() .spliterator(), false) .map(unitOfMeasureToUnitOfMeasureCommand::convert) .collect(Collectors.toSet()); } }
41.4
90
0.731539
4a95265cca7e06ac9ce708e10fcf412c259a64c9
1,148
package com.ratemarkt.models; import java.util.ArrayList; import java.util.List; import org.immutables.gson.Gson; import org.immutables.value.Value; @Gson.TypeAdapters @Value.Immutable public interface Pax { List<Integer> getChildrenAges(); Integer getNumberOfAdults(); default String toPaxString() { List<String> frags = new ArrayList<String>(); frags.add(String.valueOf(getNumberOfAdults())); List<Integer> childrenAges = new ArrayList<Integer>(getChildrenAges()); childrenAges.sort((a1, a2) -> a1.compareTo(a2)); for (Integer age : childrenAges) { frags.add(String.valueOf(age)); } return String.join(",", frags); } static Pax fromPaxString(String paxString) { String[] frags = paxString.split(","); Integer numberOfAdults = Integer.valueOf(frags[0]); List<Integer> childrenAges = new ArrayList<Integer>(); for (int i = 1; i < frags.length; i++) { childrenAges.add(Integer.valueOf(frags[i])); } return new Pax() { @Override public List<Integer> getChildrenAges() { return childrenAges; } @Override public Integer getNumberOfAdults() { return numberOfAdults; } }; } }
22.076923
73
0.700348
b33aca577e74340305df624acc716cfa480be691
1,647
package com.ljc.autapi.config; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; /** * @Author Lijc * @Description * @Date 2019/5/24-12:44 **/ @Configuration @EnableAsync public class ThreadConfig implements AsyncConfigurer { /** * The {@link Executor} instance to be used when processing async * method invocations. */ @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //设置核心线程数 executor.setCorePoolSize(5); //设置最大线程数 executor.setMaxPoolSize(15); //线程池所使用的缓冲队列 executor.setQueueCapacity(25); //等待任务在关机时完成--表明等待所有线程执行完 executor.setWaitForTasksToCompleteOnShutdown(true); // 线程名称前缀 executor.setThreadNamePrefix("MyAsync-"); // 初始化线程 executor.initialize(); return executor; } /** * The {@link AsyncUncaughtExceptionHandler} instance to be used * when an exception is thrown during an asynchronous method execution * with {@code void} return type. */ @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
31.673077
79
0.724954
ce71684b78336bbd9922a9e6052b36eb29b442ef
9,368
import java.awt.Color; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JPanel; import javax.swing.JToggleButton; import javax.swing.border.BevelBorder; public class ColorRegister extends JPanel implements MouseListener, ActionListener{ private int choosingLength = 48, choiceLength = 22; private int xSpace = 33, ySpace = 18; private int colorNum = 21; private BufferedImage bufferedImg = new BufferedImage(choosingLength ,choosingLength,BufferedImage.TYPE_3BYTE_BGR), bufferedImg2 = new BufferedImage(choosingLength ,choosingLength,BufferedImage.TYPE_3BYTE_BGR); private JPanel choiceInside[] = new JPanel[colorNum]; private JPanel choiceFrame[] = new JPanel[colorNum]; private JToggleButton choosingButton1 = new JToggleButton("Color1",new ImageIcon(bufferedImg),true); private JToggleButton choosingButton2 = new JToggleButton("Color2",new ImageIcon(bufferedImg2),false); private ButtonGroup buttonGroup = new ButtonGroup(); private JButton editColor = new JButton("Edit color", new ImageIcon("img/editcolor.png")); public Paint color1,color2,drawingColor; private Graphics2D graphic; private int colorColumn1[][]={ { 0,139,255,255,255,255,255}, { 0, 0, 0,140,165,215,255}, { 0, 0, 0, 0, 0, 0, 0} }; private int colorColumn2[][]={ {169, 85, 0, 34, 50, 0,173}, {169,107,100,139,205,255,255}, {169, 47, 0, 34, 50, 0, 47} }; private int colorColumn3[][]={ {255, 75, 0, 0, 65, 30,135}, {255, 0, 0, 0,105,144,206}, {255,130,205,255,225,255,250} }; public ColorRegister(){ addMouseListener(this); this.setLayout(null); color1 = drawingColor = new Color(0,0,0); color2 = new Color(255,255,255); for(int i=0;i<choiceInside.length;i++){ choiceInside[i]=new JPanel(); choiceInside[i].setLayout(new GridLayout(1,1)); choiceInside[i].setBounds(new Rectangle(1, 1, choiceLength+1, choiceLength+1)); if(i<(colorNum/3)) choiceInside[i].setBackground(new Color(colorColumn1[0][i],colorColumn1[1][i],colorColumn1[2][i])); else if(i<(colorNum*2/3) && i>=(colorNum/3)) choiceInside[i].setBackground(new Color(colorColumn2[0][i-colorNum/3],colorColumn2[1][i-colorNum/3],colorColumn2[2][i-colorNum/3])); else choiceInside[i].setBackground(new Color(colorColumn3[0][i-colorNum*2/3],colorColumn3[1][i-colorNum*2/3],colorColumn3[2][i-colorNum*2/3])); } for(int i=0;i<choiceFrame.length;i++){ choiceFrame[i]=new JPanel(); choiceFrame[i].setLayout(null); choiceFrame[i].add(choiceInside[i]); this.add(choiceFrame[i]); if(i<colorNum/3) choiceFrame[i].setBounds(new Rectangle(2*(choosingLength+4)+i*(choiceLength+4)+xSpace, ySpace, choiceLength+4, choiceLength+4)); else if(i<colorNum*2/3 && i>=colorNum/3) choiceFrame[i].setBounds(new Rectangle(2*(choosingLength+4)+(i-colorNum/3)*(choiceLength+4)+xSpace, ySpace+(choiceLength+4), choiceLength+4, choiceLength+4)); else choiceFrame[i].setBounds(new Rectangle(2*(choosingLength+4)+(i-colorNum*2/3)*(choiceLength+4)+xSpace, ySpace+2*(choiceLength+4), choiceLength+4, choiceLength+4)); choiceFrame[i].setBorder(BorderFactory.createEtchedBorder(BevelBorder.RAISED)); } Graphics2D graphic = bufferedImg2.createGraphics(); graphic.setPaint(Color.white); graphic.fill( new Rectangle2D.Double( 0, 0, choosingLength, choosingLength ) ); repaint(); this.add(choosingButton1); this.add(choosingButton2); choosingButton1.setLocation(10,15); choosingButton1.setSize(60,85); choosingButton1.setVerticalTextPosition(AbstractButton.TOP); choosingButton1.setHorizontalTextPosition(AbstractButton.CENTER); choosingButton1.addActionListener(this); choosingButton2.setLocation(73,15); choosingButton2.setSize(60,85); choosingButton2.setVerticalTextPosition(AbstractButton.TOP); choosingButton2.setHorizontalTextPosition(AbstractButton.CENTER); choosingButton2.addActionListener(this); buttonGroup.add(choosingButton1); buttonGroup.add(choosingButton2); this.add(editColor); editColor.setLocation(325,15); editColor.setSize(67,85); editColor.setVerticalTextPosition(AbstractButton.TOP); editColor.setHorizontalTextPosition(AbstractButton.CENTER); editColor.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == editColor){ if(choosingButton1.isSelected()){ graphic = bufferedImg.createGraphics(); color1 = drawingColor = JColorChooser.showDialog( this, "Choose the color you like for Color1.", (Color)color1 ); graphic.setPaint(color1); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); repaint(); } else if(choosingButton2.isSelected()){ graphic = bufferedImg2.createGraphics(); color2 = drawingColor = JColorChooser.showDialog( this, "Choose the color you like for Color2.", (Color)color2 ); graphic.setPaint(color2); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); repaint(); } } else if(e.getSource() == choosingButton1) drawingColor = color1; else if(e.getSource() == choosingButton2) drawingColor = color2; } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { int column1Choosed, column2Choosed, column3Choosed; if(e.getY() > ySpace && e.getY() < ySpace+(choiceLength+4)){ column1Choosed = (e.getX()-xSpace-2*(choosingLength+4))/(choiceLength+4); if(column1Choosed < colorNum/3){ if(choosingButton1.isSelected()){ graphic = bufferedImg.createGraphics(); graphic.setPaint(new Color(colorColumn1[0][column1Choosed],colorColumn1[1][column1Choosed],colorColumn1[2][column1Choosed])); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); color1 = drawingColor = new Color(colorColumn1[0][column1Choosed],colorColumn1[1][column1Choosed],colorColumn1[2][column1Choosed]); repaint(); } else{ graphic = bufferedImg2.createGraphics(); graphic.setPaint(new Color(colorColumn1[0][column1Choosed],colorColumn1[1][column1Choosed],colorColumn1[2][column1Choosed])); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); color2 = drawingColor = new Color(colorColumn1[0][column1Choosed],colorColumn1[1][column1Choosed],colorColumn1[2][column1Choosed]); repaint(); } } } else if(e.getY() > ySpace+(choiceLength+4) && e.getY() < ySpace+2*(choiceLength+4)){ column2Choosed = (e.getX()-xSpace-2*(choosingLength+4))/(choiceLength+4); if(column2Choosed < colorNum/3){ if(choosingButton1.isSelected()){ graphic = bufferedImg.createGraphics(); graphic.setPaint(new Color(colorColumn2[0][column2Choosed],colorColumn2[1][column2Choosed],colorColumn2[2][column2Choosed])); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); color1 = drawingColor = new Color(colorColumn2[0][column2Choosed],colorColumn2[1][column2Choosed],colorColumn2[2][column2Choosed]); repaint(); } else{ graphic = bufferedImg2.createGraphics(); graphic.setPaint(new Color(colorColumn2[0][column2Choosed],colorColumn2[1][column2Choosed],colorColumn2[2][column2Choosed])); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); color2 = drawingColor = new Color(colorColumn2[0][column2Choosed],colorColumn2[1][column2Choosed],colorColumn2[2][column2Choosed]); repaint(); } } } else if(e.getY() > ySpace+2*(choiceLength+4) && e.getY() < ySpace+3*(choiceLength+4)){ column3Choosed = (e.getX()-xSpace-2*(choosingLength+4))/(choiceLength+4); if(column3Choosed < colorNum/3){ if(choosingButton1.isSelected()){ graphic = bufferedImg.createGraphics(); graphic.setPaint(new Color(colorColumn3[0][column3Choosed],colorColumn3[1][column3Choosed],colorColumn3[2][column3Choosed])); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); color1 = drawingColor = new Color(colorColumn3[0][column3Choosed],colorColumn3[1][column3Choosed],colorColumn3[2][column3Choosed]); repaint(); } else{ graphic = bufferedImg2.createGraphics(); graphic.setPaint(new Color(colorColumn3[0][column3Choosed],colorColumn3[1][column3Choosed],colorColumn3[2][column3Choosed])); graphic.fill( new Rectangle( 0, 0, choosingLength, choosingLength ) ); color2 = drawingColor = new Color(colorColumn3[0][column3Choosed],colorColumn3[1][column3Choosed],colorColumn3[2][column3Choosed]); repaint(); } } } } @Override public void mouseReleased(MouseEvent e) {} }
42.776256
167
0.713706
36d50ed9519b1b900f315ca5de86dcbb4642387a
745
package jp.sf.amateras.stepcounter; import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; public class EclipseFileEncodingDetector implements FileEncodingDetector { @Override public String getEncoding(File file) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IPath location = Path.fromOSString(file.getAbsolutePath()); IFile resource = workspace.getRoot().getFileForLocation(location); if (resource != null) { try { return resource.getCharset(); } catch (Exception ex) { ex.printStackTrace(); } } return null; } }
24.032258
74
0.759732
a799fd1fadad78fe74d33356b491ff9d0a264840
5,081
package com.masanta.ratan.leetcode.study.plan.algorithms.one; public class ReverseBits { /* * Problem statement * Reverse bits of a given 32 bits unsigned integer. * Note: * Note that in some languages, such as Java, there is no unsigned integer type. * In this case, both input and output will be given as a signed integer type. * They should not affect your implementation, as the integer's internal binary representation is the same, whether * it is signed or unsigned. * In Java, the compiler represents the signed integers using 2's complement notation. * Therefore, in Example 2 above, the input represents the signed integer -3 and the output * represents the signed integer -1073741825. * * */ /* * Solution explanation: * * We first initialize result to 0. We then iterate from * 0 to 31 (an integer has 32 bits). In each iteration: We first shift result to * the left by 1 bit. Then, if the last digit of input n is 1, we add 1 to * result. To find the last digit of n, we just do: (n & 1) Example, if n=5 * (101), n&1 = 101 & 001 = 001 = 1; however, if n = 2 (10), n&1 = 10 & 01 = 00 * = 0). * * Finally, we update n by shifting it to the right by 1 (n >>= 1). This is * because the last digit is already taken care of, so we need to drop it by * shifting n to the right by 1. * * At the end of the iteration, we return result. * * Example, if input n = 13 (represented in binary as * 0000_0000_0000_0000_0000_0000_0000_1101, the "_" is for readability), calling * reverseBits(13) should return: 1011_0000_0000_0000_0000_0000_0000_0000 * * Here is how our algorithm would work for input n = 13: * * Initially, result = 0 = 0000_0000_0000_0000_0000_0000_0000_0000, n = 13 = * 0000_0000_0000_0000_0000_0000_0000_1101 * * Starting for loop: i = 0: result = result << 1 = * 0000_0000_0000_0000_0000_0000_0000_0000. n&1 = * 0000_0000_0000_0000_0000_0000_0000_1101 & * 0000_0000_0000_0000_0000_0000_0000_0001 = * 0000_0000_0000_0000_0000_0000_0000_0001 = 1 therefore result = result + 1 = * 0000_0000_0000_0000_0000_0000_0000_0000 + * 0000_0000_0000_0000_0000_0000_0000_0001 = * 0000_0000_0000_0000_0000_0000_0000_0001 = 1 * * Next, we right shift n by 1 (n >>= 1) (i.e. we drop the least significant * bit) to get: n = 0000_0000_0000_0000_0000_0000_0000_0110. We then go to the * next iteration. * * i = 1: result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_0010; n&1 = * 0000_0000_0000_0000_0000_0000_0000_0110 & * 0000_0000_0000_0000_0000_0000_0000_0001 = * 0000_0000_0000_0000_0000_0000_0000_0000 = 0; therefore we don't increment * result. We right shift n by 1 (n >>= 1) to get: n = * 0000_0000_0000_0000_0000_0000_0000_0011. We then go to the next iteration. * * i = 2: result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_0100. n&1 = * 0000_0000_0000_0000_0000_0000_0000_0011 & * 0000_0000_0000_0000_0000_0000_0000_0001 = * 0000_0000_0000_0000_0000_0000_0000_0001 = 1 therefore result = result + 1 = * 0000_0000_0000_0000_0000_0000_0000_0100 + * 0000_0000_0000_0000_0000_0000_0000_0001 = result = * 0000_0000_0000_0000_0000_0000_0000_0101 We right shift n by 1 to get: n = * 0000_0000_0000_0000_0000_0000_0000_0001. We then go to the next iteration. * * i = 3: result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_1010. n&1 = * 0000_0000_0000_0000_0000_0000_0000_0001 & * 0000_0000_0000_0000_0000_0000_0000_0001 = * 0000_0000_0000_0000_0000_0000_0000_0001 = 1 therefore result = result + 1 = = * 0000_0000_0000_0000_0000_0000_0000_1011 We right shift n by 1 to get: n = * 0000_0000_0000_0000_0000_0000_0000_0000 = 0. * * Now, from here to the end of the iteration, n is 0, so (n&1) will always be 0 * and and n >>=1 will not change n. The only change will be for result <<=1, * i.e. shifting result to the left by 1 digit. Since there we have i=4 to i = * 31 iterations left, this will result in padding 28 0's to the right of * result. i.e at the end, we get result = * 1011_0000_0000_0000_0000_0000_0000_0000 * * This is exactly what we expected to get */ public static void main(String[] args) { System.out.println(reverseBits(43261596)); } public static final int MAX_INT_LENGTH = 31; public static final int HALF_INT_LENGTH = 16; public static int reverseBits(int n) { for (short i = 0; i < HALF_INT_LENGTH; i++) { /* left bit */ /*vs*/ /* right bit */ if (((n & (1 << i)) == 0) != ((n & (1 << MAX_INT_LENGTH - i)) == 0)) { /* bits switch */ n = n ^ ((1 << i) ^ (1 << MAX_INT_LENGTH - i)); } } return n; } public static int reverseBitsSolExplained(int n) { if (n == 0) return 0; int result = 0; for (int i = 0; i < 32; i++) { result <<= 1; if ((n & 1) == 1) result++; n >>= 1; } return result; } }
40.325397
118
0.670931
dde3aa5a7715573816f58ce08d56015e4d8e179f
368
package gwt.react.mobx.todo.client.components; import gwt.react.client.proptypes.BaseProps; import gwt.react.mobx.todo.client.state.AppState; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; @JsType(isNative=true, namespace = JsPackage.GLOBAL, name="Object") public class AppStateProps extends BaseProps { public AppState appState; }
30.666667
67
0.8125
83d5f285577530e249cf12ae4cf5195c894762b6
2,242
package com.mapofzones.cleaner.processor; import com.mapofzones.cleaner.data.constants.DateConstants; import com.mapofzones.cleaner.data.entities.ActiveAddress; import com.mapofzones.cleaner.data.entities.TransactionStatistics; import com.mapofzones.cleaner.data.entities.TransferStatistics; import com.mapofzones.cleaner.data.repositories.ActiveAddressRepository; import com.mapofzones.cleaner.data.repositories.TransactionStatisticsRepository; import com.mapofzones.cleaner.data.repositories.TransferStatisticsRepository; import org.springframework.stereotype.Service; import java.sql.Timestamp; import java.util.List; @Service public class Processor { private final ActiveAddressRepository activeAddressRepository; private final TransactionStatisticsRepository transactionStatisticsRepository; private final TransferStatisticsRepository transferStatisticsRepository; public Processor(ActiveAddressRepository activeAddressRepository, TransactionStatisticsRepository transactionStatisticsRepository, TransferStatisticsRepository transferStatisticsRepository) { this.activeAddressRepository = activeAddressRepository; this.transactionStatisticsRepository = transactionStatisticsRepository; this.transferStatisticsRepository = transferStatisticsRepository; } public void doScript() { System.out.println("Starting..."); System.out.println("ready to cleanup database"); Timestamp twoMonthAgo = new Timestamp(System.currentTimeMillis() - DateConstants.TWO_MONTH); List<ActiveAddress> activeAddresses = activeAddressRepository.deleteByHourBefore(twoMonthAgo); System.out.println("active addresses: " + activeAddresses); List<TransactionStatistics> transactionStatistics = transactionStatisticsRepository.deleteByHourBefore(twoMonthAgo); System.out.println("transaction statistics: " + transactionStatistics); List<TransferStatistics> transferStatistics = transferStatisticsRepository.deleteByHourBefore(twoMonthAgo); System.out.println("transfer statistics: " + transferStatistics); System.out.println("Finished!"); System.out.println("---------------"); } }
50.954545
124
0.787244
4107b5b31e94fba290cc91fa79ba4019880c53be
725
package com.klinksoftware.neurallife.item; import com.klinksoftware.neurallife.LifeCanvas; import com.klinksoftware.neurallife.simulation.Board; import com.klinksoftware.neurallife.simulation.Configuration; import java.awt.Color; import java.util.Random; public class ItemRobot extends Item { public ItemRobot(Configuration config, Random random, LifeCanvas lifeCanvas, Board board) { super(config, random, lifeCanvas, board, "robot", new Color(0.2f, 0.2f, 0.8f)); pnt = board.getCenterPoint(); sightAngle = random.nextInt(360); sightSweep = config.robot.sightSweep; sightDistance = config.robot.sightDistance; } @Override public void runStep(int step) { } }
29
95
0.728276
42988a0f42e7c645bd592cf95860fe9083e5348e
38,971
package com.tinymooc.handler.team.controller; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.tinymooc.authority.annotation.CheckAuthority; import com.tinymooc.common.domain.*; import com.tinymooc.handler.label.service.LabelService; import com.tinymooc.handler.team.service.TeamService; import com.tinymooc.util.UUIDGenerator; import net.sf.json.JSONObject; import org.apache.commons.codec.binary.Base64; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class TeamController { @Autowired private TeamService teamService; @Autowired private LabelService labelService; private String labels; private String previousLabels; @RequestMapping("teamPage.htm") public ModelAndView teamPage(HttpServletRequest req, HttpServletResponse res) { String message = req.getParameter("message"); // FIXME System.out.println("============message========="+message); User user = (User) req.getSession().getAttribute("user"); // 1 我的店铺 - 我管理的店铺 DetachedCriteria detachedCriteria1 = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("user", user)) .add(Restrictions.eq("userPosition", "组长")); // 先建立team的引用 DetachedCriteria criteria1 = detachedCriteria1.createCriteria("team") .add(Restrictions.eq("teamState", "批准")); // 2 我的店铺 - 我加入的店铺 DetachedCriteria detachedCriteria2 = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("user", user)) .add(Restrictions.eq("userPosition", "组员")); DetachedCriteria criteria2 = detachedCriteria2.createCriteria("team") .add(Restrictions.eq("teamState", "批准")); // 3 查询活跃店铺(店铺建设度降序) DetachedCriteria detachedCriteria3 = DetachedCriteria.forClass(Team.class) .add(Restrictions.eq("teamState", "批准")) .addOrder(Order.desc("construction")); //查询数据字典 DetachedCriteria detachedCriteria4 = DetachedCriteria.forClass(DataDic.class) .add(Restrictions.eq("dicKey", "专业分类")); //查询热门话题 DetachedCriteria detachedCriteria5 = DetachedCriteria.forClass(Discuss.class) .addOrder(Order.desc("publishDate")) .addOrder(Order.desc("scanNum")); List<UserTeam> userTeam1 = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, criteria1); List<UserTeam> userTeam2 = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, criteria2); List<Team> hotTeams = (List<Team>) teamService.queryAllOfCondition(Team.class, detachedCriteria3); List<DataDic> dictionaries = (List<DataDic>) teamService.queryAllOfCondition(DataDic.class, detachedCriteria4); List<Discuss> discussList = (List<Discuss>) teamService.queryAllOfCondition(Discuss.class, detachedCriteria5); System.out.println(dictionaries.get(0).getDicValue()); req.setAttribute("userTeam1", userTeam1); req.setAttribute("userTeam2", userTeam2); req.setAttribute("hotTeams", hotTeams); req.setAttribute("dictionaries", dictionaries); req.setAttribute(" discussList", discussList); return new ModelAndView("/team/team", "message", message); } @RequestMapping("teamHomePage.htm") public ModelAndView teamHomePage(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); // FIXME System.out.println("==============teamId" + teamId + "==============="); User user = (User) req.getSession().getAttribute("user"); if (user == null) { return new ModelAndView("redirect:login.htm"); } Team team = teamService.findById(Team.class, teamId); DetachedCriteria detachedCriteria1 = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("userState", "批准")) .addOrder(Order.desc("approveDate")); DetachedCriteria detachedCriteria2 = DetachedCriteria.forClass(Discuss.class) .add(Restrictions.eq("team", team)) .addOrder(Order.desc("top")) .addOrder(Order.desc("publishDate")); List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria1); List<Discuss> discusses = (List<Discuss>) teamService.queryAllOfCondition(Discuss.class, detachedCriteria2); UserTeam userTeam1 = new UserTeam(); UserTeam userTeam2 = new UserTeam(); for (int i = 0; i < userTeams.size(); i++) { if (userTeams.get(i).getUser().getUserId().equals(user.getUserId())) { // 与当前用户关联的UserTeam userTeam1 = userTeams.get(i); } if (userTeams.get(i).getUserPosition().equals("组长")) { // 组长的UserTeam userTeam2 = userTeams.get(i); } } int discussNum = discusses.size(); int memberNum = userTeams.size(); // 获取店铺成员等级及其称号 DetachedCriteria detachedCriteria3 = DetachedCriteria.forClass(Level.class) .add(Restrictions.eq("type", "店铺用户")) .addOrder(Order.asc("lvCondition")); List<Level> teamUserLevels = (List<Level>) teamService.queryAllOfCondition(Level.class, detachedCriteria3); // FIXME for (Level l: teamUserLevels) System.out.println("==========测试店铺成员========="+l.getTitle()); // 获取店铺等级及其称号 DetachedCriteria detachedCriteria4 = DetachedCriteria.forClass(Level.class) .add(Restrictions.eq("type", "店铺")) .addOrder(Order.asc("lvCondition")); List<Level> teamLevels = (List<Level>) teamService.queryAllOfCondition(Level.class, detachedCriteria4); // 获取店铺标签 DetachedCriteria detachedCriteria5 = DetachedCriteria.forClass(LabelObject.class) .add(Restrictions.eq("objectId", team.getTeamId())); List<LabelObject> labelObjects = (List<LabelObject>) teamService.queryAllOfCondition(LabelObject.class, detachedCriteria5); // 组内成员等级 Level level1 = new Level(); // 店铺等级 Level level2 = new Level(); for (int j = 0; j < teamUserLevels.size(); j++) { if (j == teamUserLevels.size() - 1) { level1 = teamUserLevels.get(j); break; } if (userTeam1.getContribution() != null) { if (userTeam1.getContribution() < teamUserLevels.get(j).getLvCondition()) { level1 = teamUserLevels.get(j - 1); break; } } } for (int k = 0; k < teamLevels.size(); k++) { if (k == teamLevels.size() - 1) { level2 = teamLevels.get(k); break; } if (team.getConstruction() < teamLevels.get(k).getLvCondition()) { level2 = teamLevels.get(k - 1); break; } } req.setAttribute("userTeams", userTeams); req.setAttribute("userTeam1", userTeam1); req.setAttribute("userTeam2", userTeam2); req.setAttribute("discussNum", discussNum); req.setAttribute("memberNum", memberNum); req.setAttribute("discusses", discusses); req.setAttribute("level1", level1); req.setAttribute("level2", level2); req.setAttribute("labelList", labelObjects); return new ModelAndView("/team/teamHome"); } @RequestMapping("createGuidePage.htm") public ModelAndView createGuidePage(HttpServletRequest req, HttpServletResponse res) { return new ModelAndView("/team/createGuide"); } @RequestMapping("createTeamPage.htm") public ModelAndView createTeamPage(HttpServletRequest req, HttpServletResponse res) { DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DataDic.class) .add(Restrictions.eq("dicKey", "专业分类")); List<DataDic> majorType = (List<DataDic>) teamService.queryAllOfCondition(DataDic.class, detachedCriteria); return new ModelAndView("/team/createPublicTeam", "majorType", majorType); } @CheckAuthority(name = "创建店铺") @RequestMapping("createTeam.htm") public ModelAndView createTeam(HttpServletRequest req, HttpServletResponse res) { String teamName = ServletRequestUtils.getStringParameter(req, "teamName", ""); String teamIntro = ServletRequestUtils.getStringParameter(req, "teamIntro", ""); String teamType = ServletRequestUtils.getStringParameter(req, "teamType", ""); User user = (User) req.getSession().getAttribute("user"); Team team = new Team(); team.setTeamId(UUIDGenerator.randomUUID()); team.setTeamName(teamName); team.setTeamIntro(teamIntro); team.setType(teamType); team.setConstruction(0); team.setTeamState("申请中"); team.setHeadImage(new HeadImage("70328611d330411ca1d438ba70a10ccc")); team.setApplyDate(new Date()); teamService.save(team); UserTeam userTeam = new UserTeam(); userTeam.setUserTeamId(UUIDGenerator.randomUUID()); userTeam.setApplyDate(new Date()); userTeam.setApproveDate(new Date()); userTeam.setUser(user); userTeam.setUserPosition("组长"); userTeam.setContribution(0); userTeam.setTeam(team); userTeam.setUserState("批准"); teamService.save(userTeam); String message = "创建成功,请等待批准"; return new ModelAndView("redirect:teamPage.htm", "message", message); } @RequestMapping("takePartInTeam.htm") public ModelAndView takePartInTeam(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); User user = (User) req.getSession().getAttribute("user"); Team team = teamService.findById(Team.class, teamId); UserTeam userTeam = new UserTeam(); userTeam.setUserTeamId(UUIDGenerator.randomUUID()); userTeam.setApplyDate(new Date()); userTeam.setUser(user); userTeam.setUserState("申请中"); userTeam.setTeam(team); teamService.save(userTeam); return new ModelAndView("redirect:teamHomePage.htm?teamId=" + teamId); } @RequestMapping("membersAdminPage.htm") public ModelAndView membersAdminPage(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); User user = (User) req.getSession().getAttribute("user"); Team team = teamService.findById(Team.class, teamId); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("userState", "批准")) .addOrder(Order.desc("approveDate")); // 批准的UserTeam List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria); // 申请中的UserTeam DetachedCriteria detachedCriteria2 = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("userState", "申请中")) .addOrder(Order.desc("applyDate")); List<UserTeam> userTeams2 = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria2); // 个人UserTeam UserTeam userTeam1 = new UserTeam(); // 组长UserTeam2 UserTeam userTeam2 = new UserTeam(); for (int i = 0; i < userTeams.size(); i++) { if (userTeams.get(i).getUser().getUserId().equals(user.getUserId())) { userTeam1 = userTeams.get(i); } if (userTeams.get(i).getUserPosition().equals("组长")) { userTeam2 = userTeams.get(i); } } // 获取店铺成员等级及其称号 DetachedCriteria detachedCriteria3 = DetachedCriteria.forClass(Level.class) .add(Restrictions.eq("type", "店铺用户")) .addOrder(Order.asc("lvCondition")); List<Level> teamUserLevels = (List<Level>) teamService.queryAllOfCondition(Level.class, detachedCriteria3); // 组内成员等级 Level level1 = new Level(); // 店铺等级 Level level2 = new Level(); for (int j = 0; j < teamUserLevels.size(); j++) { if (j == teamUserLevels.size() - 1) { level1 = teamUserLevels.get(j); break; } if (userTeam1.getContribution() != null) { if (userTeam1.getContribution() < teamUserLevels.get(j).getLvCondition()) { level1 = teamUserLevels.get(j - 1); break; } } } // 获取店铺等级及其称号 DetachedCriteria detachedCriteria4 = DetachedCriteria.forClass(Level.class) .add(Restrictions.eq("type", "店铺")) .addOrder(Order.asc("lvCondition")); List<Level> teamLevels = (List<Level>) teamService.queryAllOfCondition(Level.class, detachedCriteria4); for (int k = 0; k < teamLevels.size(); k++) { if (k == teamLevels.size() - 1) { level2 = teamLevels.get(k); break; } if (team.getConstruction() < teamLevels.get(k).getLvCondition()) { level2 = teamLevels.get(k - 1); break; } } int memberNum = userTeams.size(); req.setAttribute("userTeams", userTeams); req.setAttribute("userTeams2", userTeams2); req.setAttribute("memberNum", memberNum); req.setAttribute("userTeam1", userTeam1); req.setAttribute("userTeam2", userTeam2); req.setAttribute("level1", level1); req.setAttribute("level2", level2); return new ModelAndView("/team/membersAdmin"); } @RequestMapping("kickOutTeam.htm") public ModelAndView kickOutTeam(HttpServletRequest req, HttpServletResponse res) { String userTeamId = ServletRequestUtils.getStringParameter(req, "userTeamId", ""); UserTeam userTeam = teamService.findById(UserTeam.class, userTeamId); String teamId = userTeam.getTeam().getTeamId(); teamService.delete(userTeam); return new ModelAndView("redirect:membersAdminPage.htm?teamId=" + teamId); } @RequestMapping("banTeamUser.htm") public ModelAndView banTeamUser(HttpServletRequest req, HttpServletResponse res) { String userTeamId = ServletRequestUtils.getStringParameter(req, "userTeamId", ""); UserTeam userTeam = teamService.findById(UserTeam.class, userTeamId); String teamId = userTeam.getTeam().getTeamId(); userTeam.setUserState("封禁"); teamService.update(userTeam); return new ModelAndView("redirect:membersAdminPage.htm?teamId=" + teamId); } @RequestMapping("addApplyUser.htm") public ModelAndView addApplyUser(HttpServletRequest req, HttpServletResponse res) { String userTeamId = ServletRequestUtils.getStringParameter(req, "userTeamId", ""); UserTeam userTeam = teamService.findById(UserTeam.class, userTeamId); String teamId = userTeam.getTeam().getTeamId(); userTeam.setUserState("批准"); userTeam.setApproveDate(new Date()); userTeam.setContribution(0); userTeam.setUserPosition("组员"); teamService.update(userTeam); return new ModelAndView("redirect:membersAdminPage.htm?teamId=" + teamId); } @RequestMapping("manageTeam.htm") public ModelAndView manageTeam(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); User user = (User) req.getSession().getAttribute("user"); Team team = teamService.findById(Team.class, teamId); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("userState", "批准")) .addOrder(Order.desc("approveDate")); List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria); labels = labelService.getTenHotLabels(); previousLabels = labelService.getObjectLabels(team.getTeamId(), "team"); UserTeam userTeam = new UserTeam(); UserTeam userTeam2 = new UserTeam(); for (int i = 0; i < userTeams.size(); i++) { if (userTeams.get(i).getUser().getUserId().equals(user.getUserId())) { userTeam = userTeams.get(i); } if (userTeams.get(i).getUserPosition().equals("组长")) { userTeam2 = userTeams.get(i); } } int memberNum = userTeams.size(); req.setAttribute("userTeams", userTeams); req.setAttribute("memberNum", memberNum); req.setAttribute("userTeam", userTeam); req.setAttribute("userTeam2", userTeam2); req.setAttribute("labels", labels); req.setAttribute("previousLabels", previousLabels); return new ModelAndView("/team/admin"); } @RequestMapping("updateTeamInfo.htm") public ModelAndView updateTeamInfo(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); String teamName = ServletRequestUtils.getStringParameter(req, "teamName", ""); String teamIntro = ServletRequestUtils.getStringParameter(req, "teamIntro", ""); String labels = ServletRequestUtils.getStringParameter(req, "teamTag", ""); labelService.saveObjectLabels(labels, teamId, "team"); Team team = teamService.findById(Team.class, teamId); team.setTeamName(teamName); team.setTeamIntro(teamIntro); teamService.update(team); return new ModelAndView("redirect:manageTeam.htm?teamId=" + teamId); } @RequestMapping("discussPage.htm") public ModelAndView discussPage(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); User user = (User) req.getSession().getAttribute("user"); Team team = teamService.findById(Team.class, teamId); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("userState", "批准")) .addOrder(Order.desc("approveDate")); List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria); UserTeam userTeam = new UserTeam(); UserTeam userTeam2 = new UserTeam(); for (int i = 0; i < userTeams.size(); i++) { if (userTeams.get(i).getUser().getUserId().equals(user.getUserId())) { userTeam = userTeams.get(i); } if (userTeams.get(i).getUserPosition().equals("组长")) { userTeam2 = userTeams.get(i); } } DetachedCriteria criteria = DetachedCriteria.forClass(Discuss.class) .add(Restrictions.eq("team", team)) .addOrder(Order.desc("top")) .addOrder(Order.desc("publishDate")); List<Discuss> discusses = (List<Discuss>) teamService.queryAllOfCondition(Discuss.class, criteria); int memberNum = userTeams.size(); int discussNum = team.getDiscusses().size(); req.setAttribute("userTeams", userTeams); req.setAttribute("memberNum", memberNum); req.setAttribute("userTeam", userTeam); req.setAttribute("userTeam2", userTeam2); req.setAttribute("discussNum", discussNum); req.setAttribute("discusses", discusses); return new ModelAndView("/team/discuss"); } @RequestMapping("createDiscussPage.htm") public ModelAndView createDiscussPage(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); Team team = teamService.findById(Team.class, teamId); req.setAttribute("team", team); return new ModelAndView("/team/createDiscuss"); } @CheckAuthority(name = "发表话题") @RequestMapping("createDiscuss.htm") public ModelAndView createDiscuss(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); String topic = ServletRequestUtils.getStringParameter(req, "topic", ""); String content = ServletRequestUtils.getStringParameter(req, "content", ""); User user = (User) req.getSession().getAttribute("user"); Discuss discuss = new Discuss(); discuss.setDiscussId(UUIDGenerator.randomUUID()); discuss.setPublishDate(new Date()); discuss.setTeam(teamService.findById(Team.class, teamId)); discuss.setUser(user); discuss.setTopic(topic); discuss.setTop(0); discuss.setScanNum(0); teamService.save(discuss); Resource resource = new Resource(); resource.setResourceId(UUIDGenerator.randomUUID()); resource.setResourceObject(discuss.getDiscussId()); teamService.save(resource); ImageText imageText = new ImageText(); imageText.setResourceId(resource.getResourceId()); imageText.setContent(content); imageText.setResource(resource); teamService.save(imageText); return new ModelAndView("redirect:discussPage.htm?teamId=" + teamId); } @RequestMapping("discussDetailPage.htm") public ModelAndView discussDetailPage(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); //String userId=ServletRequestUtils.getStringParameter(req, "userId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); User user = discuss.getUser(); User user2 = (User) req.getSession().getAttribute("user"); DetachedCriteria criteria = DetachedCriteria.forClass(Attention.class) .add(Restrictions.eq("userByUserId", user2)) .add(Restrictions.eq("userByAttentionedUserId", user)); DetachedCriteria criteria2 = DetachedCriteria.forClass(Discuss.class) .addOrder(Order.desc("publishDate")) .createCriteria("team") .add(Restrictions.eq("teamId", discuss.getTeam().getTeamId())); DetachedCriteria criteria3 = DetachedCriteria.forClass(Resource.class) .add(Restrictions.eq("resourceObject", discuss.getDiscussId())); DetachedCriteria criteria4 = DetachedCriteria.forClass(UserCourse.class) .add(Restrictions.eq("userPosition", "创建者")) .createCriteria("user") .add(Restrictions.eq("userId", user.getUserId())); DetachedCriteria criteria5 = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("userPosition", "组长")) .createCriteria("team") .add(Restrictions.eq("teamId", discuss.getTeam().getTeamId())); // DetachedCriteria criteria6 = DetachedCriteria.forClass(Favorite.class) // .add(Restrictions.eq("user", user2)) // .add(Restrictions.eq("objectId", discuss.getDiscussId())); DetachedCriteria criteria7 = DetachedCriteria.forClass(Comment.class) .add(Restrictions.eq("commentObject", discussId)) .add(Restrictions.isNull("comment")) .addOrder(Order.asc("commentDate")); DetachedCriteria criteria8 = DetachedCriteria.forClass(Comment.class) .add(Restrictions.eq("commentObject", discussId)) .add(Restrictions.isNotNull("comment")) .addOrder(Order.asc("commentDate")); DetachedCriteria criteria9 = DetachedCriteria.forClass(Attention.class) .add(Restrictions.eq("userByUserId", user)); List<Attention> attentions = (List<Attention>) teamService.queryAllOfCondition(Attention.class, criteria); List<Discuss> discusses = (List<Discuss>) teamService.queryAllOfCondition(Discuss.class, criteria2); List<Resource> resources = (List<Resource>) teamService.queryAllOfCondition(Resource.class, criteria3); List<UserCourse> userCourses = (List<UserCourse>) teamService.queryAllOfCondition(UserCourse.class, criteria4); List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, criteria5); // List<Favorite> favorites = (List<Favorite>) teamService.queryAllOfCondition(Favorite.class, criteria6); List<Comment> comments = (List<Comment>) teamService.queryAllOfCondition(Comment.class, criteria7); List<Comment> comments2 = (List<Comment>) teamService.queryAllOfCondition(Comment.class, criteria8); List<Attention> attentions2 = (List<Attention>) teamService.queryAllOfCondition(Attention.class, criteria9); Resource resource = resources.get(0); UserTeam userTeam = userTeams.get(0); int courseNum = userCourses.size(); int fansNum = attentions2.size(); int isAttention = 0; if (! attentions.isEmpty()) { isAttention = 1; } int commentNum = comments.size() + comments2.size(); discuss.setScanNum(discuss.getScanNum() + 1); teamService.update(discuss); req.setAttribute("discuss", discuss); req.setAttribute("fansNum", fansNum); req.setAttribute("isAttention", isAttention); req.setAttribute("discusses", discusses); req.setAttribute("resource", resource); req.setAttribute("courseNum", courseNum); req.setAttribute("userTeam", userTeam); // req.setAttribute("flag", flag); req.setAttribute("comments", comments); req.setAttribute("comments2", comments2); req.setAttribute("commentNum", commentNum); return new ModelAndView("/team/discussDetail"); } @RequestMapping("makeEssence.htm") public ModelAndView makeEssence(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); discuss.setEssence("精华"); teamService.update(discuss); return new ModelAndView("redirect:discussDetailPage.htm?discussId=" + discussId); } @RequestMapping("cancelEssence.htm") public ModelAndView cancelEssence(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); discuss.setEssence(""); teamService.update(discuss); return new ModelAndView("redirect:discussDetailPage.htm?discussId=" + discussId); } @RequestMapping("makeTop.htm") public ModelAndView makeTop(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); discuss.setTop(1); teamService.update(discuss); return new ModelAndView("redirect:discussDetailPage.htm?discussId=" + discussId); } @RequestMapping("cancelTop.htm") public ModelAndView cancelTop(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); discuss.setTop(0); teamService.update(discuss); return new ModelAndView("redirect:discussDetailPage.htm?discussId=" + discussId); } @CheckAuthority(name = "删除话题") @RequestMapping("deleteDiscuss.htm") public ModelAndView deleteDiscuss(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); teamService.delete(discuss); //删除评论 return new ModelAndView("redirect:discussDetailPage.htm?discussId=" + discussId); } @RequestMapping("addInform.htm") public ModelAndView addInform(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); req.setAttribute("discussId", discussId); return new ModelAndView("/inform/addinform"); } @RequestMapping("informDiscuss.htm") public ModelAndView informDiscuss(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); String informreason = ServletRequestUtils.getStringParameter(req, "informreason", ""); User user = (User) req.getSession().getAttribute("user"); Inform inform = new Inform(); inform.setInformId(UUIDGenerator.randomUUID()); inform.setInformDate(new Date()); inform.setInformObject(discussId); inform.setUser(user); inform.setInformReason(informreason); inform.setInformType("话题"); inform.setInformState("未处理"); teamService.save(inform); return new ModelAndView("/common/outSuccess"); } @RequestMapping("editDiscussPage.htm") public ModelAndView editDiscussPage(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); DetachedCriteria criteria = DetachedCriteria.forClass(ImageText.class) .createCriteria("resource") .add(Restrictions.eq("resourceObject", discussId)); List<ImageText> texts = (List<ImageText>) teamService.queryAllOfCondition(ImageText.class, criteria); ImageText text = texts.get(0); req.setAttribute("discuss", discuss); req.setAttribute("text", text); return new ModelAndView("/team/editDiscuss"); } @RequestMapping("updateDiscuss.htm") public ModelAndView updateDiscuss(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); String topic = ServletRequestUtils.getStringParameter(req, "topic", ""); String content = ServletRequestUtils.getStringParameter(req, "content", ""); Discuss discuss = teamService.findById(Discuss.class, discussId); discuss.setTopic(topic); teamService.update(discuss); DetachedCriteria criteria = DetachedCriteria.forClass(ImageText.class) .createCriteria("resource") .add(Restrictions.eq("resourceObject", discussId)); List<ImageText> texts = (List<ImageText>) teamService.queryAllOfCondition(ImageText.class, criteria); ImageText text = texts.get(0); text.setContent(content); teamService.update(text); return new ModelAndView("/common/outSuccess"); } @CheckAuthority(name = "回复话题") @RequestMapping("createContent.htm") public ModelAndView createContent(HttpServletRequest req, HttpServletResponse res) { String discussId = ServletRequestUtils.getStringParameter(req, "discussId", ""); String content = ServletRequestUtils.getStringParameter(req, "content", ""); String parentId = ServletRequestUtils.getStringParameter(req, "parentId", ""); User user = (User) req.getSession().getAttribute("user"); Comment comment = new Comment(); comment.setCommentId(UUIDGenerator.randomUUID()); comment.setCommentDate(new Date()); comment.setCommentContent(content); comment.setCommentObject(discussId); comment.setUser(user); comment.setType("话题"); if (!parentId.equals(null)) { comment.setComment(teamService.findById(Comment.class, parentId)); } teamService.save(comment); return new ModelAndView("redirect:discussDetailPage.htm?discussId=" + discussId); } @RequestMapping("constructTeam.htm") public ModelAndView constructTeam(HttpServletRequest req, HttpServletResponse res) { String teamId = ServletRequestUtils.getStringParameter(req, "teamId", ""); String gold = ServletRequestUtils.getStringParameter(req, "gold", ""); User user = (User) req.getSession().getAttribute("user"); Team team = teamService.findById(Team.class, teamId); team.setConstruction(team.getConstruction() + Integer.parseInt(gold)); teamService.update(team); DetachedCriteria criteria = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("user", user)); List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, criteria); UserTeam userTeam = userTeams.get(0); userTeam.setContribution(userTeam.getContribution() + Integer.parseInt(gold)); teamService.update(userTeam); user.setGold(user.getGold() - Integer.parseInt(gold)); teamService.update(user); return new ModelAndView("redirect:teamHomePage.htm?teamId=" + teamId); } @RequestMapping("goTeamPicture.htm") public ModelAndView goteampicture(HttpServletRequest request, HttpServletResponse response) throws Exception { //teamId String teamId = request.getParameter("teamId"); Team team = teamService.findById(Team.class, teamId); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserTeam.class) .add(Restrictions.eq("team", team)) .add(Restrictions.eq("userState", "批准")) .addOrder(Order.desc("approveDate")); List<UserTeam> userTeams = (List<UserTeam>) teamService.queryAllOfCondition(UserTeam.class, detachedCriteria); int memberNum = userTeams.size(); Team teamforpicture = new Team(); teamforpicture = (Team) teamService.getCurrentSession().createCriteria(Team.class).add(Restrictions.eq("teamId", teamId)).uniqueResult(); HttpSession hs = request.getSession(); hs.setAttribute("teamforpicture", teamforpicture); // hs.setMaxInactiveInterval(100); request.setAttribute("memberNum" , memberNum); return new ModelAndView("/team/picture"); } @RequestMapping("teamPicture.htm") public void teamPicture(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession hs = request.getSession(); Team team0 = (Team) hs.getAttribute("teamforpicture"); Team team = (Team) teamService.getCurrentSession().createCriteria(Team.class).add(Restrictions.eq("teamId", team0.getTeamId())).uniqueResult(); System.out.println(team.getTeamId()); //存两份一份供用户读取,如下 //设置基本路径 String uploadPath = request.getSession().getServletContext().getRealPath("/") + ""; String PathToService = uploadPath.split(".metadata")[0] + "/Supper_Microlecture/src/main/webapp/pic/imagehead/"; System.out.println("uploadPath" + uploadPath); System.out.println("uploadPath*********************" + uploadPath); File upPath = new File(PathToService); if (!upPath.exists()) upPath.mkdirs(); //创建小头像 String jsn = request.getParameter("dataAll"); System.out.println("+++++++jsn:" + jsn.substring(0, 50)); JSONObject jsonObject = JSONObject.fromObject(jsn); String img1 = ((String) jsonObject.get("data1")).substring(22); img1 = img1.replaceAll("_", "+"); System.out.println("+++++++img1:" + img1.substring(0, 30)); //byte[] b1=img1.getBytes(); Base64 base64 = new Base64(); byte[] b1 = base64.decode(img1); for (int i = 0; i < b1.length; ++i) { if (b1[i] < 0) {// 调整异常数据 b1[i] += 256; } } String uploadPath1 = "/pic/imagehead/" + team.getTeamId() + "3.jpg"; System.out.println(uploadPath + uploadPath1); File folder1 = new File(uploadPath + uploadPath1); //检查文件存在与否 if (!folder1.exists()) folder1.createNewFile(); File folder1S = new File(PathToService + team.getTeamId() + "3.jpg"); if (!folder1S.exists()) folder1S.createNewFile(); // 创建文件输出流对象 OutputStream d1 = new FileOutputStream(folder1); // 写入输出流 d1.write(b1); d1.flush(); // 关闭输出流 d1.close(); OutputStream d1S = new FileOutputStream(folder1S); d1S.write(b1); d1S.flush(); // 关闭输出流 d1S.close(); System.out.println("唯一店铺头像已保存到" + uploadPath + uploadPath1); //存头像数据 if (folder1.length() >= 0) { HeadImage hi = new HeadImage(); if (team.getHeadImage() == null) { hi.setImageId(UUIDGenerator.randomUUID()); hi.setImageSmall(uploadPath1); } else { hi = (HeadImage) teamService.getCurrentSession().createCriteria(HeadImage.class).add(Restrictions.eq("imageId", team.getHeadImage().getImageId())).uniqueResult(); hi.setImageSmall(uploadPath1); } teamService.saveOrUpdate(hi); team.setHeadImage(hi); teamService.update(team); hs.setAttribute("teamforpicture", team); } //返回后台数据 PrintWriter pw = response.getWriter(); String math = "?" + Math.random(); uploadPath1 = "<c:url value=\"" + uploadPath1 + "\"/>"; String data = uploadPath1; System.out.println(data); pw.println(data); //hs.removeAttribute("teamId"); } }
46.783914
178
0.650561
bb0faa15bec2657061bd5c331026ba78bf89f121
1,951
package space.polarfish.musicmeta.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import space.polarfish.musicmeta.data.model.Genre; import space.polarfish.musicmeta.data.model.MusicVideoMetadata; import space.polarfish.musicmeta.data.service.MusicVideoMetadataService; import space.polarfish.musicmeta.data.validation.groups.OnCreate; import javax.validation.Valid; import javax.validation.groups.Default; import java.util.List; @RestController @RequestMapping(path = "/api/v1/music-video-metadata", consumes = "application/json; charset=UTF-8", produces = "application/json; charset=UTF-8") public class MusicVideoMetadataController { @Autowired private MusicVideoMetadataService musicVideoMetadataService; @PostMapping public MusicVideoMetadata create(@Validated({Default.class, OnCreate.class}) @Valid @RequestBody MusicVideoMetadata meta) { return musicVideoMetadataService.create(meta); } @GetMapping("/{id}") public MusicVideoMetadata read(@PathVariable("id") Long id) { return musicVideoMetadataService.read(id); } @PutMapping("/{id}") public MusicVideoMetadata update(@PathVariable("id") Long id, @Valid @RequestBody MusicVideoMetadata entity) { return musicVideoMetadataService.update(id, entity); } @DeleteMapping("/{id}") public void delete(@PathVariable("id") Long id) { musicVideoMetadataService.delete(id); } @GetMapping public List<MusicVideoMetadata> list(@RequestParam(value = "genre", required = false) String genre, @RequestParam(value = "subgenre", required = false) String subgenre) { return musicVideoMetadataService.list(genre == null ? null : Genre.fromString(genre), subgenre); } }
37.519231
127
0.721681
8f570918296f0c5aa7a96962ba28caa5e31c4c76
824
package vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class OriginalRequest { private String source; private Data data; private String version; public String getSource () { return source; } public void setSource (String source) { this.source = source; } public Data getData () { return data; } public void setData (Data data) { this.data = data; } public String getVersion () { return version; } public void setVersion (String version) { this.version = version; } @Override public String toString() { return "ClassPojo [source = "+source+", data = "+data+", version = "+version+"]"; } }
16.816327
89
0.592233
ec8f1a4b6a3ebcfcffa877cd71705232f95b2bd3
426
package me.codpoe.gankio.main.gank.item; import me.drakeet.multitype.Item; /** * Created by Codpoe on 2016/11/14. */ public class GankImgSubItem extends GankSubItem implements Item { public String mImgUrl; public GankImgSubItem(String id, String title, String who, String type, String publishAt, String url, String imgUrl) { super(id, title, who, type, publishAt, url); mImgUrl = imgUrl; } }
25.058824
122
0.704225
1c19936d8baaa454e9c070d9088bd11a09138441
1,211
package projects.nyinyihtunlwin.news.events; import android.content.Context; import java.util.List; import projects.nyinyihtunlwin.news.data.vo.NewsVO; /** * Created by Dell on 12/2/2017. */ public class RestApiEvents { public static class EmptyResponseEvent { } public static class ErrorInvokingAPIEvent { private String errorMsg; public ErrorInvokingAPIEvent(String errorMsg) { this.errorMsg = errorMsg; } public String getErrorMsg() { return errorMsg; } } public static class NewsDataLoadedEvent { private int loadedPageIndex; private List<NewsVO> loadedNews; private Context context; public NewsDataLoadedEvent(int loadedPageIndex, List<NewsVO> loadedNews, Context context) { this.loadedPageIndex = loadedPageIndex; this.loadedNews = loadedNews; this.context = context; } public int getLoadedPageIndex() { return loadedPageIndex; } public List<NewsVO> getLoadedNews() { return loadedNews; } public Context getContext() { return context; } } }
22.425926
99
0.625103
3b7110668123ee44dbdc1efe8acc6e2f79f0fc70
2,807
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.hanbell.wco.comm; /** * * @author kevindong */ public class MiniProgramSession { private String openId; private String sessionKey; private String unionId; private boolean authorized; private String employeeId; private String employeeName; private String defaultDeptId; private String defaultDeptName; public MiniProgramSession() { } /** * @return the openId */ public String getOpenId() { return openId; } /** * @param openId the openId to set */ public void setOpenId(String openId) { this.openId = openId; } /** * @return the sessionKey */ public String getSessionKey() { return sessionKey; } /** * @param sessionKey the sessionKey to set */ public void setSessionKey(String sessionKey) { this.sessionKey = sessionKey; } /** * @return the unionId */ public String getUnionId() { return unionId; } /** * @param unionId the unionId to set */ public void setUnionId(String unionId) { this.unionId = unionId; } /** * @return the authorized */ public boolean isAuthorized() { return authorized; } /** * @param authorized the authorized to set */ public void setAuthorized(boolean authorized) { this.authorized = authorized; } /** * @return the employeeId */ public String getEmployeeId() { return employeeId; } /** * @param employeeId the employeeId to set */ public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } /** * @return the employeeName */ public String getEmployeeName() { return employeeName; } /** * @param employeeName the employeeName to set */ public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } /** * @return the defaultDeptId */ public String getDefaultDeptId() { return defaultDeptId; } /** * @param defaultDeptId the defaultDeptId to set */ public void setDefaultDeptId(String defaultDeptId) { this.defaultDeptId = defaultDeptId; } /** * @return the defaultDeptName */ public String getDefaultDeptName() { return defaultDeptName; } /** * @param defaultDeptName the defaultDeptName to set */ public void setDefaultDeptName(String defaultDeptName) { this.defaultDeptName = defaultDeptName; } }
20.05
79
0.602779
6c7635769be02956e552cfcd6c90e50db636a12c
1,740
/** * Project Name: weixin-boot * Package Name: com.guhanjie.misc * File Name: TestThreadPoolTaskExecutor.java * Create Date: 2016年10月3日 上午10:59:16 * Copyright (c) 2008-2016, guhanjie All Rights Reserved. */ package com.guhanjie.misc; import java.util.Date; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.TaskScheduler; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Class Name: TestThreadPoolTaskExecutor<br/> * Description: [description] * @time 2016年10月3日 上午10:59:16 * @author guhanjie * @version 1.0.0 * @since JDK 1.6 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = {"classpath:/context/db-mysql.xml", "classpath:/context/application-context.xml"}) public class TestTaskScheduler { @Resource(name="paySearchScheduler") private TaskScheduler taskScheduler; @Test public void test() { Date now = new Date(); System.out.println("=============="+now); taskScheduler.schedule(new Runnable() { @Override public void run() { System.out.println("=================="+new Date()); } }, new Date(now.getTime()+5000)); try { Thread.sleep(20000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
31.071429
113
0.638506