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
f692f4fbe7021d68c9116e72988a312a70ab0370
812
package jpa; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class ProgrammaJpa { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lezione8"); EntityManager em = emf.createEntityManager(); Studente s = new Studente(); s.setNome("Mario"); s.setCognome("Rossi"); s.setMatricola(123); s.setEmail("[email protected]"); s.setIndirizzo("Milano"); s.setDataNascita(new Date()); Corso c = new Corso(); c.setCodice(2); c.setNome("ITS"); s.getIscrizioni().add(c); c.getStudenti().add(s); em.getTransaction().begin(); em.persist(s); em.getTransaction().commit(); } }
21.945946
81
0.673645
4fffa8819822aff59a71e30f1478c86539dcce59
22,393
/* * Copyright (C) 2016 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 art; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.CountDownLatch; public class Test913 { public static void run() throws Exception { doTest(); // Use a countdown latch for synchronization, as join() will introduce more roots. final CountDownLatch cdl1 = new CountDownLatch(1); // Run the follow-references tests on a dedicated thread so we know the specific Thread type. Thread t = new Thread() { @Override public void run() { try { Test913.runFollowReferences(); } catch (Exception e) { throw new RuntimeException(e); } cdl1.countDown(); } }; t.start(); cdl1.await(); doExtensionTests(); } public static void runFollowReferences() throws Exception { new TestConfig().doFollowReferencesTest(); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); new TestConfig(null, 0, 1, -1).doFollowReferencesTest(); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); new TestConfig(null, 0, Integer.MAX_VALUE, 1).doFollowReferencesTest(); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); doStringTest(); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); doPrimitiveArrayTest(); doPrimitiveFieldTest(); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); // Test klass filter. System.out.println("--- klass ---"); new TestConfig(A.class, 0).doFollowReferencesTest(); // Test heap filter. System.out.println("--- heap_filter ---"); System.out.println("---- tagged objects"); new TestConfig(null, 0x4).doFollowReferencesTest(); System.out.println("---- untagged objects"); new TestConfig(null, 0x8).doFollowReferencesTest(); System.out.println("---- tagged classes"); new TestConfig(null, 0x10).doFollowReferencesTest(); System.out.println("---- untagged classes"); new TestConfig(null, 0x20).doFollowReferencesTest(); } public static void doTest() throws Exception { setupGcCallback(); enableGcTracking(true); runGc(); enableGcTracking(false); } public static void doStringTest() throws Exception { final String str = new String("HelloWorld"); final String str2 = new String(""); Object o = new Object() { String s = str; String s2 = str2; }; setTag(str, 1); setTag(str2, 2); System.out.println(Arrays.toString(followReferencesString(o))); System.out.println(getTag(str)); System.out.println(getTag(str2)); } public static void doPrimitiveArrayTest() throws Exception { final boolean[] zArray = new boolean[] { false, true }; setTag(zArray, 1); final byte[] bArray = new byte[] { 1, 2, 3 }; setTag(bArray, 2); final char[] cArray = new char[] { 'A', 'Z' }; setTag(cArray, 3); final short[] sArray = new short[] { 1, 2, 3 }; setTag(sArray, 4); final int[] iArray = new int[] { 1, 2, 3 }; setTag(iArray, 5); final float[] fArray = new float[] { 0.0f, 1.0f }; setTag(fArray, 6); final long[] lArray = new long[] { 1, 2, 3 }; setTag(lArray, 7); final double[] dArray = new double[] { 0.0, 1.0 }; setTag(dArray, 8); Object o = new Object() { Object z = zArray; Object b = bArray; Object c = cArray; Object s = sArray; Object i = iArray; Object f = fArray; Object l = lArray; Object d = dArray; }; System.out.println(followReferencesPrimitiveArray(o)); System.out.print(getTag(zArray)); System.out.print(getTag(bArray)); System.out.print(getTag(cArray)); System.out.print(getTag(sArray)); System.out.print(getTag(iArray)); System.out.print(getTag(fArray)); System.out.print(getTag(lArray)); System.out.println(getTag(dArray)); } public static void doPrimitiveFieldTest() throws Exception { // Force GCs to clean up dirt. Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); doTestPrimitiveFieldsClasses(); doTestPrimitiveFieldsIntegral(); // Force GCs to clean up dirt. Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); doTestPrimitiveFieldsFloat(); // Force GCs to clean up dirt. Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); } private static void doTestPrimitiveFieldsClasses() { setTag(IntObject.class, 10000); System.out.println(followReferencesPrimitiveFields(IntObject.class)); System.out.println(getTag(IntObject.class)); setTag(IntObject.class, 0); setTag(FloatObject.class, 10000); System.out.println(followReferencesPrimitiveFields(FloatObject.class)); System.out.println(getTag(FloatObject.class)); setTag(FloatObject.class, 0); boolean correctHeapValue = false; setTag(Inf1.class, 10000); String heapTrace = followReferencesPrimitiveFields(Inf1.class); if (!checkInitialized(Inf1.class)) { correctHeapValue = heapTrace.equals("10000@0 (static, int, index=0) 0000000000000000"); } else { correctHeapValue = heapTrace.equals("10000@0 (static, int, index=0) 0000000000000001"); } if (!correctHeapValue) System.out.println("Heap Trace for Inf1 is not as expected:\n" + heapTrace); System.out.println(getTag(Inf1.class)); setTag(Inf1.class, 0); setTag(Inf2.class, 10000); heapTrace = followReferencesPrimitiveFields(Inf2.class); if (!checkInitialized(Inf2.class)) { correctHeapValue = heapTrace.equals("10000@0 (static, int, index=1) 0000000000000000"); } else { correctHeapValue = heapTrace.equals("10000@0 (static, int, index=1) 0000000000000001"); } if (!correctHeapValue) System.out.println("Heap Trace for Inf2 is not as expected:\n" + heapTrace); System.out.println(getTag(Inf2.class)); setTag(Inf2.class, 0); } private static void doTestPrimitiveFieldsIntegral() { IntObject intObject = new IntObject(); setTag(intObject, 10000); System.out.println(followReferencesPrimitiveFields(intObject)); System.out.println(getTag(intObject)); } private static void doTestPrimitiveFieldsFloat() { FloatObject floatObject = new FloatObject(); setTag(floatObject, 10000); System.out.println(followReferencesPrimitiveFields(floatObject)); System.out.println(getTag(floatObject)); } static ArrayList<Object> extensionTestHolder; private static void doExtensionTests() { checkForExtensionApis(); extensionTestHolder = new ArrayList<>(); System.out.println(); try { getHeapName(-1); System.out.println("Expected failure for -1"); } catch (Exception e) { } System.out.println(getHeapName(0)); System.out.println(getHeapName(1)); System.out.println(getHeapName(2)); System.out.println(getHeapName(3)); try { getHeapName(4); System.out.println("Expected failure for -1"); } catch (Exception e) { } System.out.println(); setTag(Object.class, 100000); int objectClassHeapId = getObjectHeapId(100000); int objClassExpectedHeapId = hasImage() ? 1 : 3; if (objectClassHeapId != objClassExpectedHeapId) { throw new RuntimeException("Expected object class in heap " + objClassExpectedHeapId + " but received " + objectClassHeapId); } A a = new A(); extensionTestHolder.add(a); setTag(a, 100001); System.out.println(getObjectHeapId(100001)); checkGetObjectHeapIdInCallback(100000, objClassExpectedHeapId); checkGetObjectHeapIdInCallback(100001, 3); long baseTag = 30000000; setTag(Object.class, baseTag + objClassExpectedHeapId); setTag(Class.class, baseTag + objClassExpectedHeapId); Object o = new Object(); extensionTestHolder.add(o); setTag(o, baseTag + 3); iterateThroughHeapExt(); extensionTestHolder = null; } private static void runGc() { clearStats(); forceGarbageCollection(); printStats(); } private static void clearStats() { getGcStarts(); getGcFinishes(); } private static void printStats() { System.out.println("---"); int s = getGcStarts(); int f = getGcFinishes(); System.out.println((s > 0) + " " + (f > 0)); } private static boolean hasImage() { try { int pid = Integer.parseInt(new File("/proc/self").getCanonicalFile().getName()); BufferedReader reader = new BufferedReader(new FileReader("/proc/" + pid + "/maps")); String line; while ((line = reader.readLine()) != null) { if (line.endsWith(".art")) { reader.close(); return true; } } reader.close(); return false; } catch (Exception e) { throw new RuntimeException(e); } } private static class TestConfig { private Class<?> klass = null; private int heapFilter = 0; private int stopAfter = Integer.MAX_VALUE; private int followSet = -1; public TestConfig() { } public TestConfig(Class<?> klass, int heapFilter) { this.klass = klass; this.heapFilter = heapFilter; } public TestConfig(Class<?> klass, int heapFilter, int stopAfter, int followSet) { this.klass = klass; this.heapFilter = heapFilter; this.stopAfter = stopAfter; this.followSet = followSet; } public void doFollowReferencesTest() throws Exception { // Force GCs to clean up dirt. Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); setTag(Thread.currentThread(), 3000); { ArrayList<Object> tmpStorage = new ArrayList<>(); doFollowReferencesTestNonRoot(tmpStorage); tmpStorage = null; } // Force GCs to clean up dirt. Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); doFollowReferencesTestRoot(); // Force GCs to clean up dirt. Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); } private void doFollowReferencesTestNonRoot(ArrayList<Object> tmpStorage) { Verifier v = new Verifier(); tagClasses(v); A a = createTree(v); tmpStorage.add(a); v.add("0@0", "1@1000"); // tmpStorage[0] --(array-element)--> a. doFollowReferencesTestImpl(null, stopAfter, followSet, null, v, null); doFollowReferencesTestImpl(a.foo2, stopAfter, followSet, null, v, "3@1001"); tmpStorage.clear(); } private void doFollowReferencesTestRoot() { Verifier v = new Verifier(); tagClasses(v); A a = createTree(v); doFollowReferencesTestImpl(null, stopAfter, followSet, a, v, null); doFollowReferencesTestImpl(a.foo2, stopAfter, followSet, a, v, "3@1001"); } private void doFollowReferencesTestImpl(A root, int stopAfter, int followSet, Object asRoot, Verifier v, String additionalEnabled) { String[] lines = followReferences(heapFilter, klass, root, stopAfter, followSet, asRoot); v.process(lines, additionalEnabled, heapFilter != 0 || klass != null); } private static void tagClasses(Verifier v) { setTag(A.class, 1000); registerClass(1000, A.class); setTag(B.class, 1001); registerClass(1001, B.class); v.add("1001@0", "1000@0"); // B.class --(superclass)--> A.class. setTag(C.class, 1002); registerClass(1002, C.class); v.add("1002@0", "1001@0"); // C.class --(superclass)--> B.class. v.add("1002@0", "2001@0"); // C.class --(interface)--> I2.class. setTag(I1.class, 2000); registerClass(2000, I1.class); setTag(I2.class, 2001); registerClass(2001, I2.class); v.add("2001@0", "2000@0"); // I2.class --(interface)--> I1.class. } private static A createTree(Verifier v) { A aInst = new A(); setTag(aInst, 1); String aInstStr = "1@1000"; String aClassStr = "1000@0"; v.add(aInstStr, aClassStr); // A -->(class) --> A.class. A a2Inst = new A(); setTag(a2Inst, 2); aInst.foo = a2Inst; String a2InstStr = "2@1000"; v.add(a2InstStr, aClassStr); // A2 -->(class) --> A.class. v.add(aInstStr, a2InstStr); // A -->(field) --> A2. B bInst = new B(); setTag(bInst, 3); aInst.foo2 = bInst; String bInstStr = "3@1001"; String bClassStr = "1001@0"; v.add(bInstStr, bClassStr); // B -->(class) --> B.class. v.add(aInstStr, bInstStr); // A -->(field) --> B. A a3Inst = new A(); setTag(a3Inst, 4); bInst.bar = a3Inst; String a3InstStr = "4@1000"; v.add(a3InstStr, aClassStr); // A3 -->(class) --> A.class. v.add(bInstStr, a3InstStr); // B -->(field) --> A3. C cInst = new C(); setTag(cInst, 5); bInst.bar2 = cInst; String cInstStr = "5@1000"; String cClassStr = "1002@0"; v.add(cInstStr, cClassStr); // C -->(class) --> C.class. v.add(bInstStr, cInstStr); // B -->(field) --> C. A a4Inst = new A(); setTag(a4Inst, 6); cInst.baz = a4Inst; String a4InstStr = "6@1000"; v.add(a4InstStr, aClassStr); // A4 -->(class) --> A.class. v.add(cInstStr, a4InstStr); // C -->(field) --> A4. cInst.baz2 = aInst; v.add(cInstStr, aInstStr); // C -->(field) --> A. A[] aArray = new A[2]; setTag(aArray, 500); aArray[1] = a2Inst; cInst.array = aArray; String aArrayStr = "500@0"; v.add(cInstStr, aArrayStr); v.add(aArrayStr, a2InstStr); return aInst; } } public static class A { public A foo; public A foo2; public A() {} public A(A a, A b) { foo = a; foo2 = b; } } public static class B extends A { public A bar; public A bar2; public B() {} public B(A a, A b) { bar = a; bar2 = b; } } public static interface I1 { public final static int i1Field = 1; } public static interface I2 extends I1 { public final static int i2Field = 2; } public static class C extends B implements I2 { public A baz; public A baz2; public A[] array; public C() {} public C(A a, A b) { baz = a; baz2 = b; } } private static interface Inf1 { public final static int A = 1; } private static interface Inf2 extends Inf1 { public final static int B = 1; } private static class IntObject implements Inf1 { byte b = (byte)1; char c= 'a'; short s = (short)2; int i = 3; long l = 4; Object o = new Object(); static int sI = 5; } private static class FloatObject extends IntObject implements Inf2 { float f = 1.23f; double d = 1.23; Object p = new Object(); static int sI = 6; } public static class Verifier { // Should roots with vreg=-1 be printed? public final static boolean PRINT_ROOTS_WITH_UNKNOWN_VREG = false; public static class Node { public String referrer; public HashSet<String> referrees = new HashSet<>(); public Node(String r) { referrer = r; } public boolean isRoot() { return referrer.startsWith("root@"); } } HashMap<String, Node> nodes = new HashMap<>(); public Verifier() { } public void add(String referrer, String referree) { if (!nodes.containsKey(referrer)) { nodes.put(referrer, new Node(referrer)); } if (referree != null) { nodes.get(referrer).referrees.add(referree); } } public void process(String[] lines, String additionalEnabledReferrer, boolean filtered) { // This method isn't optimal. The loops could be merged. However, it's more readable if // the different parts are separated. ArrayList<String> rootLines = new ArrayList<>(); ArrayList<String> nonRootLines = new ArrayList<>(); // Check for consecutive chunks of referrers. Also ensure roots come first. { String currentHead = null; boolean rootsDone = false; HashSet<String> completedReferrers = new HashSet<>(); for (String l : lines) { String referrer = getReferrer(l); if (isRoot(referrer)) { if (rootsDone) { System.out.println("ERROR: Late root " + l); print(lines); return; } rootLines.add(l); continue; } rootsDone = true; if (currentHead == null) { currentHead = referrer; } else { // Ignore 0@0, as it can happen at any time (as it stands for all other objects). if (!currentHead.equals(referrer) && !referrer.equals("0@0")) { completedReferrers.add(currentHead); currentHead = referrer; if (completedReferrers.contains(referrer)) { System.out.println("Non-contiguous referrer " + l); print(lines); return; } } } nonRootLines.add(l); } } // Sort (root order is not specified) and print the roots. // TODO: What about extra roots? JNI and the interpreter seem to introduce those (though it // isn't clear why a debuggable-AoT test doesn't have the same, at least for locals). // For now, swallow duplicates, and resolve once we have the metadata for the roots. { Collections.sort(rootLines); String lastRoot = null; for (String l : rootLines) { if (lastRoot != null && lastRoot.equals(l)) { continue; } lastRoot = l; if (!PRINT_ROOTS_WITH_UNKNOWN_VREG && l.indexOf("vreg=-1") > 0) { continue; } System.out.println(l); } } if (filtered) { // If we aren't tracking dependencies, just sort the lines and print. // TODO: As the verifier is currently using the output lines to track dependencies, we // cannot verify that output is correct when parts of it are suppressed by filters. // To correctly track this we need to take node information into account, and // actually analyze the graph. Collections.sort(nonRootLines); for (String l : nonRootLines) { System.out.println(l); } System.out.println("---"); return; } // Iterate through the lines, keeping track of which referrers are visited, to ensure the // order is acceptable. HashSet<String> enabled = new HashSet<>(); if (additionalEnabledReferrer != null) { enabled.add(additionalEnabledReferrer); } // Always add "0@0". enabled.add("0@0"); for (String l : lines) { String referrer = getReferrer(l); String referree = getReferree(l); if (isRoot(referrer)) { // For a root src, just enable the referree. enabled.add(referree); } else { // Check that the referrer is enabled (may be visited). if (!enabled.contains(referrer)) { System.out.println("Referrer " + referrer + " not enabled: " + l); print(lines); return; } enabled.add(referree); } } // Now just sort the non-root lines and output them Collections.sort(nonRootLines); for (String l : nonRootLines) { System.out.println(l); } System.out.println("---"); } public static boolean isRoot(String ref) { return ref.startsWith("root@"); } private static String getReferrer(String line) { int i = line.indexOf(" --"); if (i <= 0) { throw new IllegalArgumentException(line); } int j = line.indexOf(' '); if (i != j) { throw new IllegalArgumentException(line); } return line.substring(0, i); } private static String getReferree(String line) { int i = line.indexOf("--> "); if (i <= 0) { throw new IllegalArgumentException(line); } int j = line.indexOf(' ', i + 4); if (j < 0) { throw new IllegalArgumentException(line); } return line.substring(i + 4, j); } private static void print(String[] lines) { for (String l : lines) { System.out.println(l); } } } private static void setTag(Object o, long tag) { Main.setTag(o, tag); } private static long getTag(Object o) { return Main.getTag(o); } private static native boolean checkInitialized(Class<?> klass); private static native void setupGcCallback(); private static native void enableGcTracking(boolean enable); private static native int getGcStarts(); private static native int getGcFinishes(); private static native void forceGarbageCollection(); private static native void checkForExtensionApis(); private static native int getObjectHeapId(long tag); private static native String getHeapName(int heapId); private static native void checkGetObjectHeapIdInCallback(long tag, int heapId); public static native String[] followReferences(int heapFilter, Class<?> klassFilter, Object initialObject, int stopAfter, int followSet, Object jniRef); public static native String[] followReferencesString(Object initialObject); public static native String followReferencesPrimitiveArray(Object initialObject); public static native String followReferencesPrimitiveFields(Object initialObject); private static native void iterateThroughHeapExt(); private static native void registerClass(long tag, Object obj); }
29.387139
97
0.619613
0b669c522c67a254088d5e1be1df0e0642e95f41
1,550
package com.kaesar.interview_zuo.t006; /** * 用栈来求解汉诺塔问题 * 递归 */ public class HanoiProblem1 { public int hanoiProblem1(int num, String left, String mid, String right) { if (num < 1) { return 0; } return process(num, left, mid, right, left, right); } public int process(int num, String left, String mid, String right, String from, String to) { if (num == 1) { if (from.equals(mid) || to.equals(mid)) { System.out.println("Move 1 from " + from + " to " + to); return 1; } else { System.out.println("Move 1 from " + from + " to " + mid); System.out.println("Move 1 from " + mid + " to " + to); return 2; } } if (from.equals(mid) || to.equals(mid)) { String another = (from.equals(left) || to.equals(left)) ? right : left; int part1 = process(num - 1, left, mid, right, from, another); int part2 = 1; System.out.println("Move " + num + " from " + from + " to " + to); int part3 = process(num - 1, left, mid, right, another, to); return part1 + part2 + part3; } else { int part1 = process(num - 1, left, mid, right, from, to); int part2 = 1; System.out.println("Move " + num + " from " + from + " to " + mid); int part3 = process(num - 1, left, mid, right, to, from); int part4 = 1; System.out.println("Move " + num + " from " + mid + " to " + to); int part5 = process(num - 1, left, mid, right, from, to); return part1 + part2 + part3 + part4 + part5; } } }
31.632653
94
0.549032
3b31bd21edd8002da47d831d7fdce44d4c6ef199
2,684
package app.keyconnect.server.controllers; import app.keyconnect.api.client.model.BlockchainAccountTransaction; import app.keyconnect.api.client.model.SubmitTransactionRequest; import app.keyconnect.api.client.model.SubmitTransactionResult; import app.keyconnect.server.factories.BlockchainGatewayFactory; import app.keyconnect.server.gateways.exceptions.UnknownNetworkException; import app.keyconnect.server.services.rate.RateHelper; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class BlockchainTransactionController { private final BlockchainGatewayFactory blockchainGatewayFactory; private final RateHelper rateHelper; public BlockchainTransactionController( BlockchainGatewayFactory blockchainGatewayFactory, RateHelper rateHelper) { this.blockchainGatewayFactory = blockchainGatewayFactory; this.rateHelper = rateHelper; } @GetMapping( path = "/v1/blockchains/{chainId}/transactions/{hash}", produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<BlockchainAccountTransaction> getTransaction( @PathVariable("chainId") String chainId, @PathVariable("hash") String hash, @RequestParam( value = "network", required = false, defaultValue = "mainnet" ) String network, @RequestParam( value = "fiat", required = false ) String fiat ) throws UnknownNetworkException { final BlockchainAccountTransaction transaction = blockchainGatewayFactory.getGateway(chainId) .getTransaction(network, hash); rateHelper.applyFiatValueToTransaction(fiat, transaction); return ResponseEntity.ok( transaction ); } @PostMapping( path = "/v1/blockchains/{chainId}/transactions" ) public ResponseEntity<SubmitTransactionResult> submitTransaction( @PathVariable("chainId") String chainId, @RequestParam(value = "network", required = false, defaultValue = "mainnet") String network, @RequestBody SubmitTransactionRequest submitTransactionRequest ) throws UnknownNetworkException { return ResponseEntity.accepted().body( blockchainGatewayFactory.getGateway(chainId) .submitTransaction(network, submitTransactionRequest) ); } }
37.802817
98
0.770864
f70a5165e051c90c9db8686e5efb3f8bd89257e8
2,608
/* * Licensed to the University of California, Berkeley 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 tachyon.underfs.glusterfs; import org.apache.hadoop.conf.Configuration; import tachyon.Constants; import tachyon.conf.TachyonConf; import tachyon.underfs.hdfs.HdfsUnderFileSystem; /** * A variant of {@link HdfsUnderFileSystem} that instead uses the Gluster FS * <p> * Currently this implementation simply manages the extra configuration setup necessary to connect * to Gluster FS * </p> * */ public class GlusterFSUnderFileSystem extends HdfsUnderFileSystem { /** * Constant for the Gluster FS URI scheme */ public static final String SCHEME = "glusterfs://"; public GlusterFSUnderFileSystem(String fsDefaultName, TachyonConf tachyonConf, Object conf) { super(fsDefaultName, tachyonConf, conf); } @Override public UnderFSType getUnderFSType() { return UnderFSType.GLUSTERFS; } @Override protected void prepareConfiguration(String path, TachyonConf tachyonConf, Configuration config) { if (path.startsWith(SCHEME)) { // Configure for Gluster FS config.set("fs.glusterfs.impl", tachyonConf.get(Constants.UNDERFS_GLUSTERFS_IMPL)); config.set("mapred.system.dir", tachyonConf.get(Constants.UNDERFS_GLUSTERFS_MR_DIR)); config .set("fs.glusterfs.volumes", tachyonConf.get(Constants.UNDERFS_GLUSTERFS_VOLUMES)); config.set( "fs.glusterfs.volume.fuse." + tachyonConf.get(Constants.UNDERFS_GLUSTERFS_VOLUMES), tachyonConf.get(Constants.UNDERFS_GLUSTERFS_MOUNTS)); } else { // If not Gluster FS fall back to default HDFS behaviour // This should only happen if someone creates an instance of this directly rather than via the // registry and factory which enforces the GlusterFS prefix being present. super.prepareConfiguration(path, tachyonConf, config); } } }
37.797101
100
0.745399
d2b585a8bc3323f4b517804b3737ea0331f417c4
27,317
/* * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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 io.ballerina.openapi.generators.client; import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; import io.ballerina.compiler.syntax.tree.BasicLiteralNode; import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; import io.ballerina.compiler.syntax.tree.CheckExpressionNode; import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; import io.ballerina.compiler.syntax.tree.ExpressionNode; import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; import io.ballerina.compiler.syntax.tree.FunctionArgumentNode; import io.ballerina.compiler.syntax.tree.IdentifierToken; import io.ballerina.compiler.syntax.tree.ImplicitNewExpressionNode; import io.ballerina.compiler.syntax.tree.MetadataNode; import io.ballerina.compiler.syntax.tree.Node; import io.ballerina.compiler.syntax.tree.NodeFactory; import io.ballerina.compiler.syntax.tree.NodeList; import io.ballerina.compiler.syntax.tree.ObjectFieldNode; import io.ballerina.compiler.syntax.tree.ParenthesizedArgList; import io.ballerina.compiler.syntax.tree.PositionalArgumentNode; import io.ballerina.compiler.syntax.tree.RecordFieldNode; import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; import io.ballerina.compiler.syntax.tree.RequiredParameterNode; import io.ballerina.compiler.syntax.tree.SeparatedNodeList; import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; import io.ballerina.compiler.syntax.tree.Token; import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; import io.ballerina.openapi.generators.GeneratorConstants; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.security.SecurityScheme; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; import static io.ballerina.compiler.syntax.tree.NodeFactory.createAssignmentStatementNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createBasicLiteralNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createCaptureBindingPatternNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createCheckExpressionNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createDefaultableParameterNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldAccessExpressionNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createImplicitNewExpressionNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createObjectFieldNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalFieldAccessExpressionNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createParenthesizedArgList; import static io.ballerina.compiler.syntax.tree.NodeFactory.createPositionalArgumentNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createSeparatedNodeList; import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createToken; import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypedBindingPatternNode; import static io.ballerina.compiler.syntax.tree.NodeFactory.createVariableDeclarationNode; import static io.ballerina.compiler.syntax.tree.SyntaxKind.CHECK_KEYWORD; import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.DOT_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY; import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_CONFIG; import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_CONFIG_PARAM; import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_CONFIG_RECORD_FIELD; import static io.ballerina.openapi.generators.GeneratorConstants.API_KEY_MAP; import static io.ballerina.openapi.generators.GeneratorConstants.AUTH_CONFIG_FILED_NAME; import static io.ballerina.openapi.generators.GeneratorConstants.AuthConfigTypes; import static io.ballerina.openapi.generators.GeneratorConstants.BASIC; import static io.ballerina.openapi.generators.GeneratorConstants.BEARER; import static io.ballerina.openapi.generators.GeneratorConstants.CLIENT_CRED; import static io.ballerina.openapi.generators.GeneratorConstants.CONFIG_RECORD_ARG; import static io.ballerina.openapi.generators.GeneratorConstants.CONFIG_RECORD_NAME; import static io.ballerina.openapi.generators.GeneratorConstants.HTTP; import static io.ballerina.openapi.generators.GeneratorConstants.OAUTH2; import static io.ballerina.openapi.generators.GeneratorConstants.PASSWORD; import static io.ballerina.openapi.generators.GeneratorConstants.SSL_FIELD_NAME; import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier; /** * This class is used to generate authentication related nodes of the ballerina connector client syntax tree. */ public class BallerinaAuthConfigGenerator { private final List<String> headerApiKeyNameList = new ArrayList<>(); private final List<String> queryApiKeyNameList = new ArrayList<>(); private boolean isAPIKey = false; private boolean isHttpOROAuth = false; private final Set<String> authTypes = new LinkedHashSet<>(); public BallerinaAuthConfigGenerator(boolean isAPIKey, boolean isHttpOROAuth) { this.isAPIKey = isAPIKey; this.isHttpOROAuth = isHttpOROAuth; } public BallerinaAuthConfigGenerator() { } public boolean isHttpOROAuth() { return isHttpOROAuth; } public boolean isAPIKey() { return isAPIKey; } /** * Generate the Config record for the relevant authentication type. * -- ex: Config record for Http and OAuth 2.0 Authentication mechanisms. * <pre> * public type ClientConfig record { * http:CredentialsConfig authConfig; * http:ClientSecureSocket secureSocketConfig?; * }; * </pre> * -- ex: Config record for API Key Authentication mechanism. * <pre> * public type ApiKeysConfig record { * map<string|string[]> apiKeys; * }; * </pre> * * @param openAPI OpenApi object received from swagger open-api parser * @return {@link TypeDefinitionNode} Syntax tree node of config record */ public TypeDefinitionNode getConfigRecord(OpenAPI openAPI) { if (openAPI.getComponents() != null && openAPI.getComponents().getSecuritySchemes() != null) { List<Node> recordFieldList = addItemstoRecordFieldList(openAPI); if (!recordFieldList.isEmpty()) { Token typeName; if (isAPIKey) { typeName = AbstractNodeFactory.createIdentifierToken(API_KEY_CONFIG); } else { typeName = AbstractNodeFactory.createIdentifierToken(CONFIG_RECORD_NAME); } Token visibilityQualifierNode = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.PUBLIC); Token typeKeyWord = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.TYPE); Token recordKeyWord = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.RECORD); Token bodyStartDelimiter = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.OPEN_BRACE); NodeList<Node> fieldNodes = AbstractNodeFactory.createNodeList(recordFieldList); Token bodyEndDelimiter = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.CLOSE_BRACE); RecordTypeDescriptorNode recordTypeDescriptorNode = NodeFactory.createRecordTypeDescriptorNode(recordKeyWord, bodyStartDelimiter, fieldNodes, null, bodyEndDelimiter); Token semicolon = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.SEMICOLON); return NodeFactory.createTypeDefinitionNode(null, visibilityQualifierNode, typeKeyWord, typeName, recordTypeDescriptorNode, semicolon); } } return null; } /** * Generate Class variable for api key map {@code map<string|string[]> apiKeys; }. * * @return {@link List<ObjectFieldNode>} syntax tree object field node list */ public ObjectFieldNode getApiKeyMapClassVariable() { // return ObjectFieldNode if (isAPIKey) { NodeList<Token> qualifierList = createEmptyNodeList(); BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(API_KEY_MAP)); IdentifierToken fieldName = createIdentifierToken(API_KEY_CONFIG_RECORD_FIELD); MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); return createObjectFieldNode(metadataNode, null, qualifierList, typeName, fieldName, null, null, createToken(SEMICOLON_TOKEN)); } return null; } /** * Generate the config parameters of the client class init method. * -- ex: Config param for Http and OAuth 2.0 Authentication mechanisms. * {@code ClientConfig clientConfig } * -- ex: Config param for API Key Authentication mechanism. * {@code ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {} } * -- ex: Config param for API Key Authentication mechanism. * {@code http:ClientConfiguration clientConfig = {} } * * @return {@link List<Node>} syntax tree node list of config parameters */ public List<Node> getConfigParamForClassInit() { List<Node> parameters = new ArrayList<>(); IdentifierToken equalToken = createIdentifierToken(GeneratorConstants.EQUAL); NodeList<AnnotationNode> annotationNodes = createEmptyNodeList(); if (isHttpOROAuth) { BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(CONFIG_RECORD_NAME)); IdentifierToken paramName = createIdentifierToken(CONFIG_RECORD_ARG); RequiredParameterNode authConfig = createRequiredParameterNode(annotationNodes, typeName, paramName); parameters.add(authConfig); } else { if (isAPIKey) { BuiltinSimpleNameReferenceNode apiKeyConfigTypeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(API_KEY_CONFIG)); IdentifierToken apiKeyConfigParamName = createIdentifierToken(API_KEY_CONFIG_PARAM); RequiredParameterNode apiKeyConfigParamNode = createRequiredParameterNode(annotationNodes, apiKeyConfigTypeName, apiKeyConfigParamName); parameters.add(apiKeyConfigParamNode); parameters.add(createToken(COMMA_TOKEN)); } BuiltinSimpleNameReferenceNode httpClientConfigTypeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken("http:ClientConfiguration")); IdentifierToken httpClientConfig = createIdentifierToken(CONFIG_RECORD_ARG); BasicLiteralNode emptyexpression = createBasicLiteralNode(null, createIdentifierToken(" {}")); DefaultableParameterNode defaultHTTPConfig = createDefaultableParameterNode(annotationNodes, httpClientConfigTypeName, httpClientConfig, equalToken, emptyexpression); parameters.add(defaultHTTPConfig); } return parameters; } /** * Generate {@code http:ClientSecureSocket secureSocketConfig } local variable. * * @return {@link VariableDeclarationNode} syntax tree variable declaration node. */ public VariableDeclarationNode getSecureSocketInitNode () { if (isHttpOROAuth) { NodeList<AnnotationNode> annotationNodes = createEmptyNodeList(); TypeDescriptorNode typeName = createOptionalTypeDescriptorNode( createBuiltinSimpleNameReferenceNode(null, createIdentifierToken("http:ClientSecureSocket")), createToken(QUESTION_MARK_TOKEN)); CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( createIdentifierToken(SSL_FIELD_NAME)); TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeName, bindingPattern); ExpressionNode configRecordSSLField = createOptionalFieldAccessExpressionNode( createSimpleNameReferenceNode(createIdentifierToken(CONFIG_RECORD_ARG)), createIdentifierToken("?."), createSimpleNameReferenceNode(createIdentifierToken(SSL_FIELD_NAME))); return createVariableDeclarationNode(annotationNodes, null, typedBindingPatternNode, createToken(EQUAL_TOKEN), configRecordSSLField, createToken(SEMICOLON_TOKEN)); } return null; } /** * Generate http:client initialization node * -- ex: Config record for Http and OAuth 2.0 Authentication mechanisms. * <pre> * http:Client httpEp = check new (serviceUrl, { * auth: clientConfig.authConfig, * secureSocket: secureSocketConfig * }); * </pre> * -- ex: Config record for API Key Authentication mechanism. * <pre> * http:Client httpEp = check new (serviceUrl, clientConfig); * </pre> * * -- ex: Config record when no Security Schema is given * <pre> * http:Client httpEp = check new (serviceUrl, clientConfig); * </pre> * * @return {@link VariableDeclarationNode} Synatx tree node of client initialization */ public VariableDeclarationNode getClientInitializationNode () { NodeList<AnnotationNode> annotationNodes = createEmptyNodeList(); BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken("http:Client")); CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( createIdentifierToken("httpEp")); TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, bindingPattern); //Expression node Token newKeyWord = createIdentifierToken("new"); Token openParenArg = createIdentifierToken("("); List<Node> argumentsList = new ArrayList<>(); PositionalArgumentNode positionalArgumentNode01 = createPositionalArgumentNode(createSimpleNameReferenceNode( createIdentifierToken(GeneratorConstants.SERVICE_URL))); argumentsList.add(positionalArgumentNode01); Token comma1 = createIdentifierToken(","); PositionalArgumentNode positionalArgumentNode02; if (isHttpOROAuth) { // try to create specific node positionalArgumentNode02 = createPositionalArgumentNode(createSimpleNameReferenceNode( createIdentifierToken(String.format("{ auth: %s.%s, secureSocket: %s }", CONFIG_RECORD_ARG, AUTH_CONFIG_FILED_NAME, SSL_FIELD_NAME)))); argumentsList.add(comma1); argumentsList.add(positionalArgumentNode02); } else { positionalArgumentNode02 = createPositionalArgumentNode(createSimpleNameReferenceNode( createIdentifierToken(CONFIG_RECORD_ARG))); argumentsList.add(comma1); argumentsList.add(positionalArgumentNode02); } SeparatedNodeList<FunctionArgumentNode> arguments = createSeparatedNodeList(argumentsList); Token closeParenArg = createToken(CLOSE_PAREN_TOKEN); ParenthesizedArgList parenthesizedArgList = createParenthesizedArgList(openParenArg, arguments, closeParenArg); ImplicitNewExpressionNode expressionNode = createImplicitNewExpressionNode(newKeyWord, parenthesizedArgList); CheckExpressionNode initializer = createCheckExpressionNode(null, createToken(CHECK_KEYWORD), expressionNode); return createVariableDeclarationNode(annotationNodes, null, typedBindingPatternNode, createToken(EQUAL_TOKEN), initializer, createToken(SEMICOLON_TOKEN)); } /** * Generate assignment nodes for api key map assignment {@code self.apiKeys = apiKeyConfig.apiKeys;}. * * @return {@link AssignmentStatementNode} syntax tree assignment statement node. */ public AssignmentStatementNode getApiKeyAssignmentNode() { if (isAPIKey) { FieldAccessExpressionNode varRefApiKey = createFieldAccessExpressionNode( createSimpleNameReferenceNode(createIdentifierToken("self")), createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG_RECORD_FIELD))); SimpleNameReferenceNode expr = createSimpleNameReferenceNode (createIdentifierToken(API_KEY_CONFIG_PARAM + GeneratorConstants.PERIOD + API_KEY_CONFIG_RECORD_FIELD)); return createAssignmentStatementNode(varRefApiKey, createToken(EQUAL_TOKEN), expr, createToken(SEMICOLON_TOKEN)); } return null; } /** * Returns API Key names which need to send in the query string. * * @return {@link List<String>} API key name list */ public List<String> getQueryApiKeyNameList () { return queryApiKeyNameList; } /** * Returns API Key names which need to send as request headers. * * @return {@link List<String>} API key name list */ public List<String> getHeaderApiKeyNameList () { return headerApiKeyNameList; } /** * Return auth type to generate test file. * * @return {@link Set<String>} */ public Set<String> getAuthType () { return authTypes; } /** * Return fields of config record for the given security schema. * -- ex: Record fields for Http and OAuth 2.0 Authentication mechanisms. * <pre> * http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig authConfig; * http:ClientSecureSocket secureSocketConfig?; * </pre> * -- ex: Record fields for API Key Authentication mechanism. * <pre> * map<string> apiKeys; * </pre> * * @return {@link List<Node>} syntax tree node list of record fields */ private List<Node> addItemstoRecordFieldList (OpenAPI openAPI) { List<Node> recordFieldNodes = new ArrayList<>(); Token semicolonToken = AbstractNodeFactory.createIdentifierToken(GeneratorConstants.SEMICOLON); Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents().getSecuritySchemes(); String httpFieldTypeNames = getConfigRecordFieldTypeNames (securitySchemeMap); if (!httpFieldTypeNames.isBlank()) { // add auth config field Token authFieldType = AbstractNodeFactory.createIdentifierToken(httpFieldTypeNames); IdentifierToken authFieldName = AbstractNodeFactory.createIdentifierToken(escapeIdentifier( AUTH_CONFIG_FILED_NAME)); TypeDescriptorNode fieldTypeNode = createBuiltinSimpleNameReferenceNode(null, authFieldType); RecordFieldNode recordFieldNode = NodeFactory.createRecordFieldNode(null, null, fieldTypeNode, authFieldName, null, semicolonToken); recordFieldNodes.add(recordFieldNode); // add socket config IdentifierToken sslFieldNameNode = AbstractNodeFactory.createIdentifierToken(SSL_FIELD_NAME); TypeDescriptorNode sslfieldTypeNode = createBuiltinSimpleNameReferenceNode(null, AbstractNodeFactory.createIdentifierToken("http:ClientSecureSocket")); RecordFieldNode sslRecordFieldNode = NodeFactory.createRecordFieldNode(null, null, sslfieldTypeNode, sslFieldNameNode, createToken(QUESTION_MARK_TOKEN), semicolonToken); recordFieldNodes.add(sslRecordFieldNode); } else if (isAPIKey) { Token apiKeyMap = AbstractNodeFactory.createIdentifierToken(API_KEY_MAP); IdentifierToken apiKeyMapFieldName = AbstractNodeFactory.createIdentifierToken(API_KEY_CONFIG_RECORD_FIELD); TypeDescriptorNode fieldTypeNode = createBuiltinSimpleNameReferenceNode(null, apiKeyMap); RecordFieldNode recordFieldNode = NodeFactory.createRecordFieldNode(null, null, fieldTypeNode, apiKeyMapFieldName, null, semicolonToken); recordFieldNodes.add(recordFieldNode); } return recordFieldNodes; } /** * Travers through the security schemas of the given open api spec. * Store api key names which needs to send in the query string and as a request header separately. * * @param securitySchemeMap Map of security schemas of the given open api spec * @return {@link String} Type name of the authConfig field in ClientConfig record */ private String getConfigRecordFieldTypeNames(Map<String, SecurityScheme> securitySchemeMap) { Set<String> httpFieldTypeNames = new HashSet<>(); for (Map.Entry<String, SecurityScheme> securitySchemeEntry : securitySchemeMap.entrySet()) { SecurityScheme schemaValue = securitySchemeEntry.getValue(); if (schemaValue != null && schemaValue.getType() != null) { String schemaType = schemaValue.getType().name().toLowerCase(Locale.getDefault()); switch (schemaType) { case HTTP: isHttpOROAuth = true; String scheme = schemaValue.getScheme(); if (scheme.equals(BASIC)) { httpFieldTypeNames.add(AuthConfigTypes.BASIC.getValue()); authTypes.add(BASIC); } else if (scheme.equals(BEARER)) { httpFieldTypeNames.add(AuthConfigTypes.BEARER.getValue()); authTypes.add(BEARER); } break; case OAUTH2: isHttpOROAuth = true; if (schemaValue.getFlows().getClientCredentials() != null) { httpFieldTypeNames.add(AuthConfigTypes.CLIENT_CREDENTIAL.getValue()); authTypes.add(CLIENT_CRED); } if (schemaValue.getFlows().getPassword() != null) { httpFieldTypeNames.add(AuthConfigTypes.PASSWORD.getValue()); authTypes.add(PASSWORD); } if (schemaValue.getFlows().getAuthorizationCode() != null) { httpFieldTypeNames.add(AuthConfigTypes.BEARER.getValue()); httpFieldTypeNames.add(AuthConfigTypes.REFRESH_TOKEN.getValue()); authTypes.add(BEARER); } if (schemaValue.getFlows().getImplicit() != null) { httpFieldTypeNames.add(AuthConfigTypes.BEARER.getValue()); authTypes.add(BEARER); } break; case API_KEY: isAPIKey = true; String apiKeyType = schemaValue.getIn().name().toLowerCase(Locale.getDefault()); authTypes.add(API_KEY); switch (apiKeyType) { case "query": queryApiKeyNameList.add(schemaValue.getName()); break; case "header": headerApiKeyNameList.add(schemaValue.getName()); break; default: break; } break; } } } return buildConfigRecordFieldTypes(httpFieldTypeNames).toString(); } /** * This method is used concat the config record authConfig field type. * * @param fieldtypes Type name set from {@link #getConfigRecordFieldTypeNames(Map)} method. * @return {@link String} Pipe concatenated list of type names */ private StringBuilder buildConfigRecordFieldTypes(Set<String> fieldtypes) { StringBuilder httpAuthFieldTypes = new StringBuilder(); if (!fieldtypes.isEmpty()) { for (String fieldType: fieldtypes) { if (httpAuthFieldTypes.length() != 0) { httpAuthFieldTypes.append("|").append(fieldType); } else { httpAuthFieldTypes.append(fieldType); } } } return httpAuthFieldTypes; } }
52.939922
120
0.693341
863306612f8ba5ae1cd8f5b056a0625b76afc8b9
751
package cn.sbx0.zhibei.logic.websocket; import lombok.extern.slf4j.Slf4j; import org.springframework.web.socket.WebSocketSession; import java.util.concurrent.ConcurrentHashMap; @Slf4j public class SocketManager { private static ConcurrentHashMap<String, WebSocketSession> manager = new ConcurrentHashMap<>(); public static void add(String key, WebSocketSession webSocketSession) { log.info("新添加webSocket连接 {} ", key); manager.put(key, webSocketSession); } public static void remove(String key) { log.info("移除webSocket连接 {} ", key); manager.remove(key); } public static WebSocketSession get(String key) { log.info("获取webSocket连接 {}", key); return manager.get(key); } }
26.821429
99
0.697736
59eb64ce41ba117be60b7d2e8014775a6e6e95bf
625
package DBManager; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class BeaconManager { public Connection getConnection(){ try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cas_database", "root", "123qwe"); return conn; } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println(e.toString()); return null; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.toString()); return null; } } }
24.038462
111
0.712
dcba9bcfb85ef90e456a1c90844fd8b65cc9a90e
2,454
/* * Copyright 2021 Sonu Kumar * * 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 * * https://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.github.sonus21.rqueue.spring.boot.tests.integration; import com.github.sonus21.junit.LocalTest; import com.github.sonus21.rqueue.spring.boot.application.Application; import com.github.sonus21.rqueue.spring.boot.tests.SpringBootIntegrationTest; import com.github.sonus21.rqueue.test.common.SpringTestBase; import com.github.sonus21.rqueue.test.dto.Sms; import com.github.sonus21.rqueue.utils.Constants; import com.github.sonus21.rqueue.utils.TimeoutUtils; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; @ContextConfiguration(classes = Application.class) @SpringBootTest @Slf4j @TestPropertySource( properties = { "rqueue.job.durability.in-terminal-state=0", "rqueue.job.enabled=false", "rqueue.retry.per.poll=1", "spring.redis.port=8022", "job.queue.active=false", "notification.queue.active=false", "email.queue.active=false", "sms.queue.concurrency=20-40", "sms.queue.active=true", }) @SpringBootIntegrationTest @LocalTest class ListenerConcurrencyTest extends SpringTestBase { @Test void runConcurrentTest() { int msgCount = 100_000; long executionTime = 10 * Constants.ONE_MILLI; long msgStartAt = System.currentTimeMillis(); enqueue(smsQueue, (i) -> Sms.newInstance(), msgCount, false); long msgEndAt = System.currentTimeMillis(); log.info("Msg enqueue time {}Ms", msgEndAt - msgStartAt); TimeoutUtils.sleep(executionTime); log.info("Enqueued msg count {}", msgCount); log.info("Approx remaining msgs {}", getMessageCount(smsQueue)); log.info("Approx msg consumed {}", msgCount - getMessageCount(smsQueue)); } }
37.753846
102
0.745314
7192f4da363edea0a3dca66cf4f49a8ab431da42
5,288
package info.u_team.u_team_core.util; import java.util.Random; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3d; public class MathUtil { public static final Random RANDOM = new Random(); public static Vector3d rotateVectorAroundYCC(Vector3d vec, double angle) { return rotateVectorCC(vec, new Vector3d(0, 1, 0), angle); } public static Vector3d rotateVectorCC(Vector3d vec, Vector3d axis, double angle) { final double x = vec.getX(); final double y = vec.getY(); final double z = vec.getZ(); final double u = axis.getX(); final double v = axis.getY(); final double w = axis.getZ(); final double rotationX = u * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + x * Math.cos(angle) + (-w * y + v * z) * Math.sin(angle); final double rotationY = v * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + y * Math.cos(angle) + (w * x - u * z) * Math.sin(angle); final double rotationZ = w * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + z * Math.cos(angle) + (-v * x + u * y) * Math.sin(angle); return new Vector3d(rotationX, rotationY, rotationZ); } /** * Returns a pseudo random number in range of min and max (inclusive). Use this {@link #RANDOM} instance * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @return Return a random value between min and max */ public static int randomNumberInRange(int min, int max) { return randomNumberInRange(RANDOM, min, max); } /** * Returns a pseudo random number in range of min and max (inclusive). * * @param random The random instance * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @return Return a random value between min and max */ public static int randomNumberInRange(Random random, int min, int max) { return random.nextInt(max - min + 1) + min; } /** * Returns a pseudo random number in range of min and max (inclusive). Use this {@link #RANDOM} instance * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @return Return a random value between min and max */ public static float randomNumberInRange(float min, float max) { return randomNumberInRange(RANDOM, min, max); } /** * Returns a pseudo random number in range of min and max (inclusive). * * @param random The random instance * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @return Return a random value between min and max */ public static float randomNumberInRange(Random random, float min, float max) { return random.nextFloat() * (max - min) + min; } /** * Returns a pseudo random number in range of min and max (inclusive). Use this {@link #RANDOM} instance * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @return Return a random value between min and max */ public static double randomNumberInRange(double min, double max) { return randomNumberInRange(RANDOM, min, max); } /** * Returns a pseudo random number in range of min and max (inclusive). * * @param random The random instance * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @return Return a random value between min and max */ public static double randomNumberInRange(Random random, double min, double max) { return random.nextDouble() * (max - min) + min; } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static int valueInRange(int min, int max, int value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static long valueInRange(long min, long max, long value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static float valueInRange(float min, float max, float value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static double valueInRange(double min, double max, double value) { return Math.min(max, Math.max(min, value)); } /** * Returns the distance between x1, z1 and x2, z2 * * @param x1 First x coordinate * @param z1 First z coordinate * @param x2 Second x coordinate * @param z2 Second z coordinate * @return The distance between these two coordinates */ public static float getPlaneDistance(int x1, int z1, int x2, int z2) { final int xDiff = x2 - x1; final int zDiff = z2 - z1; return MathHelper.sqrt(xDiff * xDiff + zDiff * zDiff); } }
32.243902
138
0.678896
7f85a9539fa1c4d537e8587149121059eaea8166
473
package org.wfrobotics.reuse.commands.config; import edu.wpi.first.wpilibj.command.InstantCommand; /** Selects an Auto Mode parameter */ public class AutoConfig extends InstantCommand { protected Runnable selectNext; // Functional to force constructor call public AutoConfig(Runnable selectNextCallback) { selectNext = selectNextCallback; setRunWhenDisabled(true); } public void initialize() { selectNext.run(); } }
22.52381
75
0.710359
74a731b0ddc9e827a4ab42ac40efee66304145a7
931
package com.batch.android.tracker; /** * Define the running mode of the Tracker module * */ public enum TrackerMode { /** * Tracker is OFF (no Sqlite & webservice) */ OFF(0), /** * Tracker is only storing event in DB, not sending */ DB_ONLY(1), /** * Tracker is up & running */ ON(2); // ----------------------------------------> private int value; TrackerMode(int value) { this.value = value; } public int getValue() { return value; } // -----------------------------------------> /** * Mode from value * * @param value * @return mode if found, null otherwise */ public static TrackerMode fromValue(int value) { for (TrackerMode mode : values()) { if (mode.getValue() == value) { return mode; } } return null; } }
16.333333
55
0.453276
18ec1e26764a4efb3f60cfea14c76e92f753f7ef
386
package com.mwj.echarts.impl; import com.mwj.echarts.interf.ChartData; import java.util.ArrayList; /** * @author Meng Wei Jin * @description * [ * {value:335, name:'直接访问'}, * {value:310, name:'邮件营销'}, * {value:234, name:'联盟广告'}, * {value:135, name:'视频广告'}, * {value:1548, name:'搜索引擎'} * ] **/ public class PieData<T> extends ArrayList<T> implements ChartData { }
19.3
67
0.632124
6a15b9c28df4283fc4f4c4a9e0bd4653749925e8
329
package net.md_5.bungee; public interface VersionInfo { public static String SOFTWARE = "WaterDog"; public static String VERSION = "1.0.0"; public static String JENKINS_BUILD_ID = "unknown"; public static boolean IS_DEVELOPMENT_BUILD = false; public static String AUTHORS = "YesDogOSS Team, Bungee Team"; }
29.909091
65
0.732523
46fc907d2c3a550623b0bbc72987ae2ac4787b56
342
package org.apache.goat.chapter100.E.E066; import org.apache.common.MyBaseDataTest; import org.junit.jupiter.api.Test; class App extends MyBaseDataTest { public static final String XMLPATH = "org/apache/goat/chapter100/E/E066/mybatis-config.xml"; @Test void deleteById1() throws Exception { setUpByReader(XMLPATH); } }
16.285714
94
0.745614
c85a474a7fb7daaf65506f9733a6bc1210e0aed7
1,390
package com.example.android.popular_movies_app.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.android.popular_movies_app.db.MovieContracts.*; /** * @author harshita.k */ public class MovieDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 6; public static final String DATABASE_NAME = "popularmovie.db"; public MovieDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { final String CREATE_TABLE_MOVIE = "CREATE TABLE " + MOVIES_TABLE.TABLE_NAME + "(" + MOVIES_TABLE._ID + " INTEGER PRIMARY KEY," + MOVIES_TABLE.COLUMN_TITLE + " TEXT NOT NULL," + MOVIES_TABLE.COLUMN_OVERVIEW + " TEXT NOT NULL," + MOVIES_TABLE.COLUMN_POSTER_IMAGE + " TEXT NOT NULL," + MOVIES_TABLE.COLUMN_RELEASE_DATE + " TEXT NOT NULL," + MOVIES_TABLE.COLUMN_VOTE_AVERAGE + " REAL TEXT NOT NULL" + ")"; db.execSQL(CREATE_TABLE_MOVIE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + MOVIES_TABLE.TABLE_NAME); onCreate(db); } }
33.095238
91
0.670504
a2504ff890201db4699a9ec09f9c5470726fe86f
1,375
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.productruntime; import java.util.List; import java.util.HashMap; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; import java.io.IOException; import java.lang.ClassNotFoundException; import com.mozu.api.contracts.productruntime.SearchSuggestion; /** * A group of product search terms to suggest to a customer based on defined queries. */ @JsonIgnoreProperties(ignoreUnknown = true) public class SearchSuggestionGroup implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * The user supplied name that appears in . You can use this field for identification purposes. */ protected String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } /** * List of related SearchSuggestions */ protected List<SearchSuggestion> suggestions; public List<SearchSuggestion> getSuggestions() { return this.suggestions; } public void setSuggestions(List<SearchSuggestion> suggestions) { this.suggestions = suggestions; } }
25.943396
97
0.731636
43c21f4a4cac3f7c7198c107c6526d778bd5c4e1
16,343
package net.mcft.copy.backpacks.misc.util; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import java.util.stream.Collector.Characteristics; import com.google.common.collect.Iterables; import net.minecraft.item.ItemStack; import net.minecraft.nbt.*; import net.minecraftforge.common.util.INBTSerializable; /** Contains NBT related methods for manipulating NBT tags and item stacks. */ public final class NbtUtils { private NbtUtils() { } // TODO: Update to use enum instead and make methods "safer" by checking the type before casting. public static final class NbtType { private NbtType() { } public static final int END = 0; public static final int BYTE = 1; public static final int SHORT = 2; public static final int INT = 3; public static final int LONG = 4; public static final int FLOAT = 5; public static final int DOUBLE = 6; public static final int BYTE_ARRAY = 7; public static final int STRING = 8; public static final int LIST = 9; public static final int COMPOUND = 10; public static final int INT_ARRAY = 11; } public static final String TAG_INDEX = "index"; public static final String TAG_STACK = "stack"; // Utility ItemStack / NBT manipulation methods /** Gets an NBT tag of the specified item stack, or null if it doesn't exist. * Example: <pre>{@code StackUtils.get(stack, "display", "color") }</pre> */ public static NBTBase get(ItemStack stack, String... tags) { return get(stack.getTagCompound(), tags); } /** Gets a child NBT tag of the specified compound tag, or null if it doesn't exist. * Example: <pre>{@code StackUtils.get(compound, "display", "color") }</pre> */ public static NBTBase get(NBTTagCompound compound, String... tags) { if (compound == null) return null; String tag = null; for (int i = 0; i < tags.length; i++) { tag = tags[i]; if (!compound.hasKey(tag)) return null; if (i == tags.length - 1) break; compound = compound.getCompoundTag(tag); } return compound.getTag(tag); } /** Gets a value from the specified item stack's compound tag, or the default if it doesn't exist. * Example: <pre>{@code StackUtils.get(stack, -1, "display", "color") }</pre> */ public static <T> T get(ItemStack stack, T defaultValue, String... tags) { return get(stack.getTagCompound(), defaultValue, tags); } /** Gets a value from the specified compound tag, or the default if it doesn't exist. * Example: <pre>{@code StackUtils.get(compound, -1, "display", "color") }</pre> */ public static <T> T get(NBTTagCompound compound, T defaultValue, String... tags) { NBTBase tag = get(compound, tags); return ((tag != null) ? getTagValue(tag) : defaultValue); } /** Returns if the specified item stack's compound tag has a certain NBT tag. * Example: <pre>{@code StackUtils.has(stack, "display", "color") }</pre> */ public static boolean has(ItemStack stack, String... tags) { return has(stack.getTagCompound(), tags); } /** Returns if the specified compound tag has a certain child NBT tag. * Example: <pre>{@code StackUtils.has(compound, "display", "color") }</pre> */ public static boolean has(NBTTagCompound compound, String... tags) { return (get(compound, tags) != null); } /** Adds or replaces a tag on the specified item stack's compound tag, creating it and any parent compound tags if necessary. * Example: <pre>{@code StackUtils.set(stack, new NBTTagInt(0xFF0000), "display", "color") }</pre> */ public static void set(ItemStack stack, NBTBase nbtTag, String... tags) { if (stack.isEmpty()) throw new IllegalArgumentException("stack is empty"); NBTTagCompound compound = stack.getTagCompound(); if (compound == null) stack.setTagCompound(compound = new NBTTagCompound()); set(compound, nbtTag, tags); } /** Adds or replaces a tag on the specified compound tag, creating any parent compound tags if necessary. * Example: <pre>{@code StackUtils.set(compound, new NBTTagInt(0xFF0000), "display", "color") }</pre> */ public static void set(NBTTagCompound compound, NBTBase nbtTag, String... tags) { if (compound == null) throw new IllegalArgumentException("compound is null"); String tag = null; for (int i = 0; i < tags.length; i++) { tag = tags[i]; if (i == tags.length - 1) break; if (!compound.hasKey(tag)) { NBTTagCompound child = new NBTTagCompound(); compound.setTag(tag, child); compound = child; } else compound = compound.getCompoundTag(tag); } compound.setTag(tag, nbtTag); } /** Adds or replaces a value on the specified item stack's compound tag, creating it and any parent compound tags if necessary. * Example: <pre>{@code StackUtils.set(stack, 0xFF0000, "display", "color") }</pre> */ public static <T> void set(ItemStack stack, T value, String... tags) { set(stack, createTag(value), tags); } /** Adds or replaces a value on the specified compound tag, creating any parent compound tags if necessary. * Example: <pre>{@code StackUtils.set(compound, 0xFF0000, "display", "color") }</pre> */ public static <T> void set(NBTTagCompound compound, T value, String... tags) { set(compound, createTag(value), tags); } /** Removes a certain NBT tag from the specified item stack's compound tag. * Example: <pre>{@code StackUtils.remove(stack, "display", "color") }</pre> */ public static void remove(ItemStack stack, String... tags) { if (tags.length == 0) throw new IllegalArgumentException( "tags should have at least one element"); if (!stack.hasTagCompound()) return; NBTTagCompound compound = stack.getTagCompound(); remove(compound, tags); // If compound is empty, remove it from the stack. if (compound.hasNoTags()) stack.setTagCompound(null); } /** Removes a certain NBT tag from the specified compound tag. * Example: <pre>{@code StackUtils.remove(compound, "display", "color") }</pre> */ public static void remove(NBTTagCompound compound, String... tags) { if (tags.length == 0) throw new IllegalArgumentException( "tags should have at least one element"); if (compound == null) return; if (tags.length > 1) { NBTBase tag = compound.getTag(tags[0]); if (!(tag instanceof NBTTagCompound)) return; NBTTagCompound subCompound = (NBTTagCompound)tag; remove(subCompound, (String[])Arrays.copyOfRange(tags, 1, tags.length)); // If subCompound is empty, remove it from the parent compound. if (!subCompound.hasNoTags()) return; } compound.removeTag(tags[0]); } // Compound / List creation /** Creates an NBT compound from the name-value pairs in the parameters. * Doesn't add any null values to the resulting compound tag. * Example: <pre>{@code NbtUtils.createCompound("id", 1, "name", "copygirl") }</pre> */ public static NBTTagCompound createCompound(Object... nameValuePairs) { return addToCompound(new NBTTagCompound(), nameValuePairs); } /** Adds entries to an ItemStack's NBT data from the name-value pairs in the parameters. * Doesn't add any null values to the ItemStack's compound tag. * Example: <pre>{@code NbtUtils.createCompound("id", 1, "name", "copygirl") }</pre> */ public static NBTTagCompound add(ItemStack stack, Object... nameValuePairs) { if (stack.isEmpty()) throw new IllegalArgumentException("stack is empty"); if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); return addToCompound(stack.getTagCompound(), nameValuePairs); } /** Adds entries to an NBT compound from the name-value pairs in the parameters. * Doesn't add any null values to the specified compound tag. * Example: <pre>{@code NbtUtils.addToCompound(compound, "id", 1, "name", "copygirl") }</pre> */ public static NBTTagCompound addToCompound(NBTTagCompound compound, Object... nameValuePairs) { if (compound == null) throw new IllegalArgumentException("compound is null"); for (int i = 0; i < nameValuePairs.length; i += 2) { String name = (String)nameValuePairs[i]; Object value = nameValuePairs[i + 1]; if (value == null) continue; compound.setTag(name, createTag(value)); } return compound; } /** Creates an NBT list with the values, all of the single type. * Doesn't add any null values to the resulting list tag. */ public static NBTTagList createList(Object... values) { return addToList(new NBTTagList(), values); } /** Adds values to an NBT list. Doesn't add any null values to the specified list tag. */ public static NBTTagList addToList(NBTTagList list, Object... values) { if (list == null) throw new IllegalArgumentException("list is null"); for (Object value : values) { if (value == null) continue; list.appendTag(createTag(value)); } return list; } // Reading / writing ItemStacks /** Writes an item stack to an NBT compound. */ public static NBTTagCompound writeItem(ItemStack item) { return writeItem(item, true); } /** Writes an item stack to an NBT compound. */ public static NBTTagCompound writeItem(ItemStack item, boolean writeNullAsEmptyCompound) { return (!item.isEmpty()) ? item.writeToNBT(new NBTTagCompound()) : (writeNullAsEmptyCompound ? new NBTTagCompound() : null); } /** Reads an item stack from an NBT compound. */ public static ItemStack readItem(NBTTagCompound compound) { return ((compound != null) && !compound.hasNoTags()) ? new ItemStack(compound) : ItemStack.EMPTY; } /** Writes an item stack array to an NBT list. */ public static NBTTagList writeItems(ItemStack[] items) { NBTTagList list = new NBTTagList(); for (int i = 0; i < items.length; i++) if (items[i] != null) list.appendTag(createCompound( TAG_INDEX, (short)i, TAG_STACK, writeItem(items[i]))); return list; } /** Reads items from an NBT list to an item stack array. */ public static ItemStack[] readItems(NBTTagList list, ItemStack[] items) { return readItems(list, items, null); } /** Reads items from an NBT list to an item stack array. * Any items falling outside the range of the items array * will get added to the invalid list if that's non-null. */ public static ItemStack[] readItems(NBTTagList list, ItemStack[] items, List<ItemStack> invalid) { for (int i = 0; i < list.tagCount(); i++) { NBTTagCompound compound = list.getCompoundTagAt(i); int index = compound.getShort(TAG_INDEX); ItemStack stack = readItem(compound.getCompoundTag(TAG_STACK)); if ((index >= 0) || (index < items.length)) items[index] = stack; else if (invalid != null) invalid.add(stack); } return items; } // Other utility functions /** Returns the primitive value of a tag, casted to the return type. */ @SuppressWarnings("unchecked") public static <T> T getTagValue(NBTBase tag) { if (tag == null) throw new IllegalArgumentException("tag is null"); if (tag instanceof NBTTagByte) return (T)(Object)((NBTTagByte)tag).getByte(); if (tag instanceof NBTTagShort) return (T)(Object)((NBTTagShort)tag).getShort(); if (tag instanceof NBTTagInt) return (T)(Object)((NBTTagInt)tag).getInt(); if (tag instanceof NBTTagLong) return (T)(Object)((NBTTagLong)tag).getLong(); if (tag instanceof NBTTagFloat) return (T)(Object)((NBTTagFloat)tag).getFloat(); if (tag instanceof NBTTagDouble) return (T)(Object)((NBTTagDouble)tag).getDouble(); if (tag instanceof NBTTagString) return (T)(Object)((NBTTagString)tag).getString(); if (tag instanceof NBTTagByteArray) return (T)((NBTTagByteArray)tag).getByteArray(); if (tag instanceof NBTTagIntArray) return (T)((NBTTagIntArray)tag).getIntArray(); throw new IllegalArgumentException(NBTBase.NBT_TYPES[tag.getId()] + " isn't a primitive NBT tag"); } /** Creates and returns a primitive NBT tag from a value. * If the value already is an NBT tag, it is returned instead. */ public static NBTBase createTag(Object value) { if (value == null) throw new IllegalArgumentException("value is null"); if (value instanceof NBTBase) return (NBTBase)value; if (value instanceof INBTSerializable) return ((INBTSerializable<?>)value).serializeNBT(); if (value instanceof Collection) return ((Collection<?>)value).stream() .map(NbtUtils::createTag).collect(toList()); if (value instanceof Byte) return new NBTTagByte((Byte)value); if (value instanceof Short) return new NBTTagShort((Short)value); if (value instanceof Integer) return new NBTTagInt((Integer)value); if (value instanceof Long) return new NBTTagLong((Long)value); if (value instanceof Float) return new NBTTagFloat((Float)value); if (value instanceof Double) return new NBTTagDouble((Double)value); if (value instanceof String) return new NBTTagString((String)value); if (value instanceof byte[]) return new NBTTagByteArray((byte[])value); if (value instanceof int[]) return new NBTTagIntArray((int[])value); throw new IllegalArgumentException("Can't create an NBT tag of value: " + value); } /** Returns the specified NBT serializable value * instance deserialized from the specified NBT tag. */ public static <N extends NBTBase, T extends INBTSerializable<N>> T getTagValue(N tag, T value) { if (tag == null) throw new IllegalArgumentException("tag is null"); if (value == null) throw new IllegalArgumentException("value is null"); value.deserializeNBT(tag); return value; } /** Returns a list of NBT serializable values instantiated * using the value supplier from the specified NBT list. */ @SuppressWarnings("unchecked") public static <N extends NBTBase, T extends INBTSerializable<N>> List<T> getTagList( NBTTagList list, Supplier<T> valueSupplier) { return stream(list) .map(tag -> getTagValue((N)tag, valueSupplier.get())) .collect(Collectors.toList()); } // Iterable / Stream related functions /** Returns an iterable of NBT tags in the specified NBT list. */ @SuppressWarnings("unchecked") public static <T extends NBTBase> Iterable<T> iterate(NBTTagList list) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private int _index = 0; @Override public boolean hasNext() { return (_index < list.tagCount()); } @Override public T next() { return (T)list.get(_index++); } }; } }; } /** Returns an iterable of entries in the specified NBT compound. */ public static Iterable<CompoundEntry> iterate(NBTTagCompound compound) { return Iterables.transform(compound.getKeySet(), key -> new CompoundEntry(key, compound.getTag(key))); } /** Returns a stream of NBT tags in the specified NBT list. */ public static <T extends NBTBase> Stream<T> stream(NBTTagList list) { return StreamSupport.stream(NbtUtils.<T>iterate(list).spliterator(), false); } /** Returns a stream of entries in the specified NBT compound. */ public static Stream<CompoundEntry> stream(NBTTagCompound compound) { return StreamSupport.stream(NbtUtils.iterate(compound).spliterator(), false); } /** Returns a collector that accumulates the the input elements into a new NBT list. */ public static <T> Collector<T, NBTTagList, NBTTagList> toList() { return Collector.of(NBTTagList::new, (list, element) -> list.appendTag(createTag(element)), (left, right) -> { for (NBTBase tag : iterate(right)) left.appendTag(tag); return left; }, Characteristics.IDENTITY_FINISH); } /** Returns a collector that accumulates the the input NBT tags into a new NBT list. */ public static <T> Collector<T, NBTTagCompound, NBTTagCompound> toCompound( Function<T, String> keyMapper, Function<T, NBTBase> tagMapper) { return Collector.of(NBTTagCompound::new, (compound, element) -> compound.setTag(keyMapper.apply(element), tagMapper.apply(element)), (left, right) -> { for (String key : right.getKeySet()) left.setTag(key, right.getTag(key)); return left; }, Characteristics.IDENTITY_FINISH); } public static class CompoundEntry { public final String key; public final NBTBase tag; public CompoundEntry(String key, NBTBase tag) { this.key = key; this.tag = tag; } } }
42.012853
128
0.70544
d084e703df9bea867ed01fc71bbcc9e6300e3695
5,017
package com.jamworkspro.jamworksxg2; import android.content.Context; import android.text.InputType; import android.util.AttributeSet; import android.view.View; public class JMEdit extends android.support.v7.widget.AppCompatEditText { JMKeyboardView m_JMKeyboardView; public int m_iCursorBegin; public int m_iCursorEnd; public String m_strLeft; public String m_strRight; public String m_strNewCharacter; JMEdit m_this; //Constructors public JMEdit(Context context, AttributeSet attrs) { super(context, attrs); setText(" "); int len = getText().length(); setSelection(0, len); setRawInputType(InputType.TYPE_NULL); setTextIsSelectable(false); setBackgroundColor(0xff00ff00); setCursorVisible(false); m_JMKeyboardView = null; m_this = this; setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(m_JMKeyboardView == null)return; m_JMKeyboardView.SetEditText(m_this); if(hasFocus) m_JMKeyboardView.showKeyboard(); else m_JMKeyboardView.hideKeyboard(); } }); } public JMEdit(Context context) { super(context); } public void SetKeyboardView(JMKeyboardView e) { m_JMKeyboardView = e; } //Edit Function private void AddCharacter() { String strNewText = m_strLeft + m_strNewCharacter + m_strRight; { m_iCursorBegin++; m_iCursorEnd++; setText(strNewText); setSelection(m_iCursorBegin, m_iCursorEnd); } } private void DeleteCharacter() { if(m_strRight.length() > 1) { String modStringRight = m_strRight.substring(1, m_strRight.length()); String strNewString = m_strLeft + modStringRight; setText(strNewString); setSelection(m_iCursorBegin, m_iCursorEnd); } } private void CAPS() { if(m_JMKeyboardView == null) return; boolean bShifted = m_JMKeyboardView.isShifted(); m_JMKeyboardView.setShifted(!bShifted); m_JMKeyboardView.m_CapsLockOn = !bShifted; if(m_JMKeyboardView.m_CapsLockOn) m_JMKeyboardView.m_keyCapsLocks.label = "CAPS"; else m_JMKeyboardView.m_keyCapsLocks.label = "caps"; } private void Home() { if(m_iCursorBegin > 0) { int st = 0; int en = 1; m_iCursorBegin = st; m_iCursorEnd = en; setSelection(m_iCursorBegin, m_iCursorEnd); } } private void End() { { int len = getText().length(); int st = len - 1; int en = len; m_iCursorBegin = st; m_iCursorEnd = en; setSelection(m_iCursorBegin, m_iCursorEnd); } } private void LeftArrow() { if(m_iCursorBegin > 0) { int st = getSelectionStart(); int en = getSelectionEnd(); m_iCursorBegin = st - 1; m_iCursorEnd = en - 1; setSelection(m_iCursorBegin, m_iCursorEnd); } } private void RightArrow() { if(m_iCursorEnd < getText().length()) { int st = getSelectionStart(); int en = getSelectionEnd(); m_iCursorBegin = st + 1; m_iCursorEnd = en + 1; setSelection(m_iCursorBegin, m_iCursorEnd); } } private void Clear() { setText(" "); m_iCursorBegin = 0; m_iCursorEnd = 1; setSelection(m_iCursorBegin, m_iCursorEnd); } public void onNewCharacter(int primaryCode) { //store the new character m_strNewCharacter = Character.toString((char)primaryCode); //note the contents of the original string String strCurrentText = getText().toString(); //note the cursor position. a zero length cursor indicates nothing selected m_iCursorBegin = getSelectionStart(); m_iCursorEnd = getSelectionEnd(); //Split the current string m_strLeft = strCurrentText.substring(0, m_iCursorBegin);//include the selection on the right m_strRight = strCurrentText.substring(m_iCursorBegin, strCurrentText.length()); if(primaryCode >= 32 && primaryCode <= 126)//process a printable character { if(m_JMKeyboardView.m_CapsLockOn && primaryCode >= 97 && primaryCode <= 122) m_strNewCharacter = Character.toString((char)(primaryCode-32)); AddCharacter(); } if(primaryCode == 127)//delete DeleteCharacter(); if(primaryCode == -1)//Home Home(); if(primaryCode == -2)//left arrow LeftArrow(); if(primaryCode == -3)//right arrow RightArrow(); if(primaryCode == -4)//end End(); if(primaryCode == -5)//backspace { int[] i={0}; onNewCharacter(-2); onNewCharacter(127); } if(primaryCode == -6)//clear Clear(); if(primaryCode == -7)//caps lock CAPS(); } }
24.354369
97
0.614112
d1257c99a8267c376b618d38f003f6c494f771aa
7,861
//package File; import java.util.*; import java.io.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class StayHome { static ArrayList<Character> input; static ArrayList<Integer> X; static ArrayList<Integer> A; static int M,N,S,W,T,z, size; static int[] vir; static int[] visited; static char[] path; public static void main(String[] args) { try { File f=new File(args[0]); FileReader fr=new FileReader(f); //Creation of File Reader object BufferedReader br=new BufferedReader(fr); //Creation of BufferedReader object int c = 0; input = new ArrayList<Character>(); X = new ArrayList<Integer>(); A = new ArrayList<Integer>(); while ((c = br.read()) != -1) { char character = (char) c; input.add(character); } br.close(); size = input.size(); for(int i =0; i<size; i++){ if(input.get(i)=='\n'){ M=i; break; } } N=0; vir = new int[size]; path = new char[size]; visited = new int[size]; for(int i =0; i<size; i++){ vir[i]=0; path[i]='N'; visited[i]=0; if(input.get(i)=='S') S=i; if(input.get(i)=='X') X.add(i); if(input.get(i)=='W') W=i; if(input.get(i)=='A') A.add(i); if(input.get(i)=='T') T=i; if(input.get(i)=='\n') N++; } N=N; move_virus(W,0); int n=1; ArrayList<Integer> listd = new ArrayList<Integer>(); listd.add(S); while(!listd.isEmpty()){ ArrayList<Integer> listdtemp = listd; listd = new ArrayList<Integer>(); int[] L = new int[4]; char[] D = {'D', 'L', 'R', 'U'}; for(int kk = 0; kk < listdtemp.size(); kk++) { int x = listdtemp.get(kk); L[0] = move_down(x); L[1] = move_left(x); L[2] = move_right(x); L[3] = move_up(x); for(int i = 0; i<4; i++) { if(L[i] != -1) { if(visited[L[i]] == 0 && n<vir[L[i]]) { visited[L[i]] = n; visited[S]=-1; path[L[i]] = D[i]; listd.add(L[i]); } } } } n += 1; } if(visited[T] == 0) System.out.println("IMPOSSIBLE"); else{ System.out.println(visited[T]); String way = ""; int x = T; while(x != S) { way = path[x] + way; if(path[x] == 'D') x = x - M-1; else if(path[x] == 'L') x = x + 1; else if(path[x] == 'R') x = x - 1; else if(path[x] == 'U') x = x + M+1; } System.out.println(way); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } static int move_up(int x){ if (x-(M+1)>=0) if((x-(M+1)>=0) && (input.get(x)!='X') && (input.get(x)!='\n') && (input.get(x-M-1)!='X') && (input.get(x-M-1)!='W') ) return x-(M+1); else return -1; else return -1; } static int move_down(int x){ if (x+(M+1)<=(size-1)) if((input.get(x)!='X') && (input.get(x)!='\n') && (input.get(x+M+1)!='X') && (input.get(x+M+1)!='W') ) return x+(M+1); else return -1; else return -1; } static int move_right(int x){ if((x%(M+1)!= M-1)) if((input.get(x+1)!='\n') && (input.get(x+1)!='X') && (input.get(x)!='X') && (input.get(x+1)!='W') ) return x+1; else return -1; else return -1; } static int move_left(int x){ if ((x % (M+1))!=0) if( (input.get(x)!='X') && (input.get(x-1)!='X') && (input.get(x-1)!='\n') && (input.get(x-1)!='W') ) return x-1; else return -1; else return -1; } static void move_virus(int x, int y){ if(vir[x]==0 || y<=vir[x] ){ vir[x]=y; if (move_down(x)!= -1){ if (input.get(x+M+1)!='A'){ z=y+2; move_virus(x+M+1, z); } else{ if(vir[x+M+1]==0){ z=y+2; vir[x+M+1]=z; for (int i=0; i<A.size(); i++){ if (A.get(i)!=(x+M+1)) vir[A.get(i)]= z+5; } for (int i=0; i<A.size(); i++) move_virus(A.get(i),vir[A.get(i)] ); } } } if(move_left(x)!=-1){ if(input.get(x-1)!='A'){ z=y+2; move_virus(x-1, z); } else{ if(vir[x-1]==0){ z=y+2; vir[x-1]=z; for (int i=0; i<A.size(); i++){ if (A.get(i)!=(x-1)) vir[A.get(i)]= z+5; } for (int i=0; i<A.size(); i++) move_virus(A.get(i),vir[A.get(i)] ); } } } if(move_right(x)!=-1){ if(input.get(x+1)!='A'){ z=y+2; move_virus(x+1,z); } else{ if(vir[x+1]==0){ z=y+2; vir[x+1]=z; for (int i=0; i<A.size(); i++){ if (A.get(i)!=(x+1)) vir[A.get(i)]= z+5; } for (int i=0; i<A.size(); i++) move_virus(A.get(i),vir[A.get(i)] ); } } } if (move_up(x)!= -1){ if (input.get(x-(M+1))!='A'){ z=y+2; move_virus(x-M-1, z); } else{ if(vir[x-M-1]==0){ z=y+2; vir[x-M-1]=z; for (int i=0; i<A.size(); i++){ if (A.get(i)!=(x-M-1)) vir[A.get(i)]= z+5; } for (int i=0; i<A.size(); i++) move_virus(A.get(i),vir[A.get(i)] ); } } } } } }
32.085714
136
0.301107
b6c21302b0aefeaa7f751f1d8c86b26643ef8299
1,440
//Package name --- import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; import java.util.List; public class ViewPagerAdapter extends PagerAdapter { LayoutInflater layoutInflater; Context context; List<Integer> pages; public ViewPagerAdapter(Context context, List<Integer> pages){ this.context = context; this.pages = pages; layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return pages.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == ((RelativeLayout) object); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { View itemView = layoutInflater.inflate(pages.get(position), container, false); container.addView(itemView); return itemView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((RelativeLayout)object); } }
23.606557
101
0.681944
5d3d4e311bfc124fe69f0cf802aed5033406c3eb
644
package com.kaixin.core.sql2o.quirks.parameterparsing.impl; /** * Created by lars on 22.09.2014. */ public class ForwardSlashCommentParser extends AbstractCommentParser { private boolean commentAlmostEnded; @Override protected void init() { commentAlmostEnded = false; } @Override public boolean canParse(char c, String sql, int idx) { return sql.length() > idx + 1 && c == '/' && sql.charAt(idx + 1) == '*'; } @Override public boolean isEndComment(char c) { if (commentAlmostEnded && c == '/') return true; commentAlmostEnded = c == '*'; return false; } }
23.851852
80
0.619565
ddbcdd224014d3a5ecbbb439cb5a0ff053a5e2c3
8,431
package info.geometrixx.webviewapp; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.apache.cordova.Config; import org.apache.cordova.ConfigXmlParser; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaInterfaceImpl; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaPreferences; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebViewImpl; import org.apache.cordova.PluginEntry; import org.apache.cordova.engine.SystemWebView; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * This is the Home section fragment that implements {@link CordovaInterface} and uses a layout that contains * a {@link CordovaWebView}. * */ public class HomeFragment extends Fragment implements CordovaInterface { // Plugin to call when activity result is received protected CordovaPlugin activityResultCallback = null; protected boolean activityResultKeepRunning; // Keep app running when pause is received. (default = true) // If true, then the JavaScript and native code continue to run in the background // when another application (activity) is started. protected boolean keepRunning = true; //Instance of the actual Cordova WebView CordovaWebView aemView; protected CordovaPreferences preferences; protected ArrayList<PluginEntry> pluginEntries; protected CordovaInterfaceImpl cordovaInterface; private final ExecutorService threadPool = Executors.newCachedThreadPool(); /** * Returns a new instance of this fragment for the given section * number. */ public static HomeFragment newInstance() { HomeFragment fragment = new HomeFragment(); return fragment; } @Override /** * Initialize the {@link CordovaWebView} and load its start URL. * * The fragment inflator needs to be cloned first to use an instance of {@link CordovaContext} instead. This * alternate context object implements the {@link CordovaInterface} as well and acts as a proxy between the activity * and fragment for the {@link CordovaWebView}. The actual {@link CordovaWebView} is defined in the home_view_frag.xml layout * and has an id of <b>aemWebView</b>. */ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LayoutInflater localInflater = inflater.cloneInContext(new CordovaContext(getActivity(), this)); View rootView = localInflater.inflate(R.layout.home_view_frag, container, false); cordovaInterface = new CordovaInterfaceImpl(getActivity()); if(savedInstanceState != null) { cordovaInterface.restoreInstanceState(savedInstanceState); } ConfigXmlParser parser = new ConfigXmlParser(); parser.parse(getActivity()); preferences = parser.getPreferences(); preferences.setPreferencesBundle(getActivity().getIntent().getExtras()); pluginEntries = parser.getPluginEntries(); aemView = new CordovaWebViewImpl(CordovaWebViewImpl.createEngine(getActivity(), preferences)); RelativeLayout.LayoutParams wvlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); wvlp.addRule(RelativeLayout.BELOW,R.id.webviewLayout); aemView.getView().setLayoutParams(wvlp); if (!aemView.isInitialized()) { aemView.init(cordovaInterface, pluginEntries, preferences); } cordovaInterface.onCordovaInit(aemView.getPluginManager()); aemView.loadUrlIntoView(parser.getLaunchUrl(), true); ((LinearLayout)rootView).addView(aemView.getView()); return rootView; } // // Cordova // /** * Called when a message is sent to plugin. * * @param id * The message id * @param data * The message data * @return Object or null */ public Object onMessage(String id, Object data) { return null; } // Cordova Interface Events @Override public ExecutorService getThreadPool() { return threadPool; } @Override public void requestPermission(CordovaPlugin plugin, int requestCode, String permission) { } @Override public void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) { } @Override public boolean hasPermission(String permission) { return false; } @Override public void setActivityResultCallback(CordovaPlugin plugin) { this.activityResultCallback = plugin; } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method is called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); CordovaPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } /** * A {@link ContextWrapper} that also implements {@link CordovaInterface} and acts as a proxy between the base * activity context and the fragment that contains a {@link CordovaWebView}. * */ private class CordovaContext extends ContextWrapper implements CordovaInterface { CordovaInterface cordova; public CordovaContext(Context base, CordovaInterface cordova) { super(base); this.cordova = cordova; } public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) { cordova.startActivityForResult(command, intent, requestCode); } public void setActivityResultCallback(CordovaPlugin plugin) { cordova.setActivityResultCallback(plugin); } public Activity getActivity() { return cordova.getActivity(); } public Object onMessage(String id, Object data) { return cordova.onMessage(id, data); } public ExecutorService getThreadPool() { return cordova.getThreadPool(); } @Override public void requestPermission(CordovaPlugin plugin, int requestCode, String permission) { } @Override public void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) { } @Override public boolean hasPermission(String permission) { return false; } } }
35.57384
136
0.686633
9faa6f49811e4b216346bd13bc71599e1f17fed1
383
package com.algolia.search.models.indexing; import java.io.Serializable; import java.util.List; public class ListIndicesResponse implements Serializable { public List<IndicesResponse> getIndices() { return items; } public ListIndicesResponse setItems(List<IndicesResponse> items) { this.items = items; return this; } private List<IndicesResponse> items; }
20.157895
68
0.754569
c6a77d6a2460a9fe7097049fd14bab6ebc4358e4
936
package com.ibm.research.drl.deepguidelines.pathways.extractor.synthea.parser; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import java.time.Instant; import java.util.Map; import org.junit.Test; import com.ibm.research.drl.deepguidelines.pathways.extractor.synthea.Patient; public class PatientsParserTest { private static final String SYNTHEA_DATA_PATH = ""; @Test public void test() { InputDataParser patientsParser = new SyntheaCsvInputDataParser(Instant.now().toEpochMilli()); Map<String, Patient> patientsMap = patientsParser.getPatients(SYNTHEA_DATA_PATH); assertThat(patientsMap, notNullValue()); assertThat(patientsMap.size(), equalTo(55421)); for (Patient patient : patientsMap.values()) { assertThat(patient.getMarital(), notNullValue()); } } }
31.2
101
0.735043
26467c7c674bc94a95c97b101741630e4472f662
14,601
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.gui.sequence; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.io.Serializable; import java.util.HashSet; import java.util.List; import java.util.Set; import org.biojava.bio.BioError; import org.biojava.bio.seq.FeatureFilter; import org.biojava.bio.seq.FeatureHolder; import org.biojava.utils.AbstractChangeable; import org.biojava.utils.ChangeEvent; import org.biojava.utils.ChangeForwarder; import org.biojava.utils.ChangeListener; import org.biojava.utils.ChangeSupport; import org.biojava.utils.ChangeType; import org.biojava.utils.ChangeVetoException; import org.biojava.utils.Changeable; import org.biojava.utils.cache.CacheMap; import org.biojava.utils.cache.FixedSizeMap; /** * <p><code>PairwiseFilteringRenderer</code> wraps a * <code>PairwiseSequenceRenderer</code> and filters the * <code>PairwiseRenderContext</code>s passed to it. The renderer * receives a new <code>PairwiseRenderContext</code> which has had * both of its <code>FeatureHolder</code>s filtered with the * <code>FeatureFilter</code>.<p> * * <p>Instances of this class cache up to 5 of the derived * <code>PairwiseRenderContext</code>s. Therefore cycling through up * to 5 different <code>FeatureFilter</code>s will only be hitting the * cache rather than recalculating everthing. Should the * <code>FeatureHolder</code>s themselves change, the cache will be * flushed. As only the features overlapping the context's range are * filtered, changing the range will also result in re-filtering.</p> * * @author Keith James * @author Matthew Pocock * @since 1.2 */ public class PairwiseFilteringRenderer extends AbstractChangeable implements PairwiseSequenceRenderer, Serializable { /** * Constant <code>FILTER</code> indicating a change to the * renderer's filter. */ public static final ChangeType FILTER = new ChangeType("The filter has changed", "org.biojava.bio.gui.sequence.PairwiseFilteringRenderer", "FILTER", SequenceRenderContext.LAYOUT); /** * Constant <code>RECURSE</code> indicating a change to the * renderer's filter recursion flag. */ public static final ChangeType RECURSE = new ChangeType("The recurse flag has changed", "org.biojava.bio.gui.sequence.PairwiseFilteringRenderer", "RECURSE", SequenceRenderContext.LAYOUT); /** * Constant <code>RENDERER</code> indicating a change to the * renderer. */ public static final ChangeType RENDERER = new ChangeType("The renderer has changed", "org.biojava.bio.gui.sequence.PairwiseFilteringRenderer", "RENDERER", SequenceRenderContext.REPAINT); /** * <code>filter</code> is the filter applied to both * <code>FeatureHolder</code>s. */ protected FeatureFilter filter; /** * <code>recurse</code> indicates whether the filter should * recurse through any subfeatures. */ protected boolean recurse; // Cache of previously created subcontexts private CacheMap subContextCache = new FixedSizeMap(5); // Set of listeners to cache keys private Set cacheFlushers = new HashSet(); // Delegate renderer private PairwiseSequenceRenderer renderer; private transient ChangeForwarder rendererForwarder; /** * Creates a new <code>PairwiseFilteringRenderer</code> which uses * a filter which accepts all features. * * @param renderer a <code>PairwiseSequenceRenderer</code>. */ public PairwiseFilteringRenderer(PairwiseSequenceRenderer renderer) { this(renderer, FeatureFilter.all, false); } /** * Creates a new <code>PairwiseFilteringRenderer</code>. * * @param renderer a <code>PairwiseSequenceRenderer</code>. * @param filter a <code>FeatureFilter</code>. * @param recurse a <code>boolean</code>. */ public PairwiseFilteringRenderer(PairwiseSequenceRenderer renderer, FeatureFilter filter, boolean recurse) { try { this.renderer = renderer; setFilter(filter); setRecurse(recurse); } catch (ChangeVetoException cve) { throw new BioError("Assertion failed: should have no listeners", cve); } } protected ChangeSupport getChangeSupport(ChangeType ct) { ChangeSupport cs = super.getChangeSupport(ct); if (rendererForwarder == null) { rendererForwarder = new PairwiseSequenceRenderer.PairwiseRendererForwarder(this, cs); if (renderer instanceof Changeable) { Changeable c = (Changeable) renderer; c.addChangeListener(rendererForwarder, SequenceRenderContext.REPAINT); } } return cs; } /** * <code>getRenderer</code> return the current renderer. * * @return a <code>PairwiseSequenceRenderer</code>. */ public PairwiseSequenceRenderer getRenderer() { return renderer; } /** * <code>setRenderer</code> sets the renderer. * * @param renderer a <code>PairwiseSequenceRenderer</code>. * * @exception ChangeVetoException if the change is vetoed. */ public void setRenderer(PairwiseSequenceRenderer renderer) throws ChangeVetoException { if (hasListeners()) { ChangeEvent ce = new ChangeEvent(this, RENDERER, renderer, this.renderer); ChangeSupport cs = getChangeSupport(RENDERER); synchronized(cs) { cs.firePreChangeEvent(ce); if (this.renderer instanceof Changeable) { Changeable c = (Changeable) this.renderer; c.removeChangeListener(rendererForwarder); } this.renderer = renderer; if (renderer instanceof Changeable) { Changeable c = (Changeable) renderer; c.addChangeListener(rendererForwarder); } cs.firePostChangeEvent(ce); } } else { this.renderer = renderer; } } /** * <code>getFilter</code> returns the current filter. * * @return a <code>FeatureFilter</code>. */ public FeatureFilter getFilter() { return filter; } /** * <code>setFilter</code> sets the filter. * * @param filter a <code>FeatureFilter</code>. * * @exception ChangeVetoException if the change is vetoed. */ public void setFilter(FeatureFilter filter) throws ChangeVetoException { if (hasListeners()) { ChangeSupport cs = getChangeSupport(FILTER); synchronized(cs) { ChangeEvent ce = new ChangeEvent(this, FILTER, this.filter, filter); cs.firePreChangeEvent(ce); this.filter = filter; cs.firePostChangeEvent(ce); } } else { this.filter = filter; } } /** * <code>getRecurse</code> returns the recursion flag of the * filter. * * @return a <code>boolean</code>. */ public boolean getRecurse() { return recurse; } /** * <code>setRecurse</code> sets the recursion flag on the filter. * * @param recurse a <code>boolean</code>. * * @exception ChangeVetoException if the change is vetoed. */ public void setRecurse(boolean recurse) throws ChangeVetoException { if (hasListeners()) { ChangeSupport cs = getChangeSupport(RECURSE); synchronized(cs) { ChangeEvent ce = new ChangeEvent(this, RECURSE, new Boolean(recurse), new Boolean(this.recurse)); cs.firePreChangeEvent(ce); this.recurse = recurse; cs.firePostChangeEvent(ce); } } else { this.recurse = recurse; } } public void paint(Graphics2D g2, PairwiseRenderContext context) { renderer.paint(g2, getSubContext(context)); } public SequenceViewerEvent processMouseEvent(PairwiseRenderContext context, MouseEvent me, List path) { path.add(this); return renderer.processMouseEvent(getSubContext(context), me, path); } /** * <code>getSubContext</code> creates a new context which has * <code>FeatureHolder</code>s filtered using the current filter. * * @param context a <code>PairwiseRenderContext</code>. * * @return a <code>PairwiseRenderContext</code>. */ protected PairwiseRenderContext getSubContext(PairwiseRenderContext context) { // Filter the sequence features FeatureFilter ff = new FeatureFilter.And(filter, new FeatureFilter.OverlapsLocation(context.getRange())); // Filter the secondary sequence features FeatureFilter ffSec = new FeatureFilter.And(filter, new FeatureFilter.OverlapsLocation(context.getSecondaryRange())); // Create a cache key FilteredSubContext cacheKey = new FilteredSubContext(context, ff, ffSec, recurse); // Try the cache for a context first PairwiseRenderContext filtered = (PairwiseRenderContext) subContextCache.get(cacheKey); if (filtered == null) { // None in cache, so make a new one filtered = new SubPairwiseRenderContext(context, // context delegate null, // symbols null, // secondary symbols context.getFeatures().filter(ff, recurse), context.getFeatures().filter(ffSec, recurse), null, // range null); // secondary range // Add to cache subContextCache.put(cacheKey, filtered); // Create a listener for changes in the feature holder CacheFlusher cf = new CacheFlusher(cacheKey); // Add the listener for changes in features ((Changeable) context.getSymbols()) .addChangeListener(cf, FeatureHolder.FEATURES); cacheFlushers.add(cf); } return filtered; } /** * <code>FilteredSubContext</code> is a cache key whose equality * with another such key is determined by context, filter and * recurse values. */ private class FilteredSubContext { private PairwiseRenderContext context; private FeatureFilter filter; private FeatureFilter secondaryFilter; private boolean recurse; public FilteredSubContext(PairwiseRenderContext context, FeatureFilter filter, FeatureFilter secondaryFilter, boolean recurse) { this.context = context; this.filter = filter; this.secondaryFilter = secondaryFilter; this.recurse = recurse; } public boolean equals(Object o) { if (! (o instanceof FilteredSubContext)) { return false; } FilteredSubContext that = (FilteredSubContext) o; return context.equals(that.context) && filter.equals(that.filter) && secondaryFilter.equals(that.secondaryFilter) && (recurse == that.recurse); } public int hashCode() { return context.hashCode() ^ filter.hashCode(); } } /** * <code>CacheFlusher</code> is a listener for changes to the * original context's feature holders. A change forces removal of * its associated cache key from the cache. */ private class CacheFlusher implements ChangeListener { private FilteredSubContext fsc; public CacheFlusher(FilteredSubContext fsc) { this.fsc = fsc; } public void preChange(ChangeEvent ce) { } public void postChange(ChangeEvent ce) { subContextCache.remove(fsc); cacheFlushers.remove(this); if (hasListeners()) { ChangeSupport cs = getChangeSupport(SequenceRenderContext.LAYOUT); synchronized(cs) { ChangeEvent ce2 = new ChangeEvent(PairwiseFilteringRenderer.this, SequenceRenderContext.LAYOUT); cs.firePostChangeEvent(ce2); } } } } }
32.591518
99
0.562701
1e08d6be98ce8f78b8dd6aeb48490dabb1919ad4
768
package com.examples.leetcode.array_easy; /** https://leetcode.com/problems/count-largest-group/ */ public class L1399CountLargestGroup { public int countLargestGroup(int n) { int[] counts = new int[37]; for (int i = 1; i <= n; ++i) { int sum = sumOfDigit(i); ++counts[sum]; } int count = 0; int max = 0; for (int i : counts) { if (i > max) { count = 1; max = i; } else if (i == max) { ++count; } } return count; } private int sumOfDigit(int n) { int sum = 0; while (n > 0) { sum += n % 10; n = n / 10; } return sum; } }
22.588235
57
0.419271
60c2e3d2368dedecb429b084561e6ac7faf1321d
14,728
package com.evguard.main; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.NumberPicker; import android.widget.NumberPicker.OnValueChangeListener; import android.widget.TextView; import com.evguard.customview.AppTitleBar; import com.evguard.customview.AppTitleBar.OnTitleActionClickListener; import com.evguard.model.AlamSettings; import com.evguard.model.ICommonWebResponse; import com.evguard.model.WebReq_GetAlarmRemind; import com.evguard.model.WebReq_SetAlarmRemind; import com.evguard.model.WebRes_GetAlarmRemind; import com.evguard.model.WebRes_SetAlamRemind; import com.xinghaicom.evguard.R; public class AC_AlamSetting extends AC_Base { private static final int MESSAGE_GETTING = 0; private static final int MESSAGE_GETTING_OK = 1; private static final int MESSAGE_GETTING_FAILED = 2; private static final int MESSAGE_GETTING_EXCEPTION = 3; private static final int MESSAGE_SETTING = 4; private static final int MESSAGE_SETTING_OK = 5; private static final int MESSAGE_SETTING_FAILED = 6; private static final int MESSAGE_SETTING_EXCEPTION = 7; private AppTitleBar mTitleBar; private TextView tvBatteryLow; private TextView tvDoorUnclosedMin; private ImageButton btHighTemp; private ImageButton btTirePressure; private ImageButton btChargeState; private String mBatteryTemperatureTooHight=""; private String mTirePressure=""; private String mChargeStatu=""; private String mElecTooRow=""; private String mDoorStatu=""; private boolean mIsUserCancle = false; private Dg_Waiting mDownDialog = null; private Bundle bundle; private List<AlamSettings> mAlamSettings; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.ac_alam_setting); findViews(); initViews(); handleListener(); } @Override protected void onResume() { super.onResume(); } private void handleListener() { tvBatteryLow.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { String mElecTooRowTex = tvBatteryLow.getText().toString(); } }); tvBatteryLow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { NumberPicker mPicker = new NumberPicker(AC_AlamSetting.this); mPicker.setMinValue(0); mPicker.setMaxValue(100); mPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { // TODO Auto-generated method stub tvBatteryLow.setText(String.valueOf(newVal) + "%"); mElecTooRow = String.valueOf(newVal); } }); AlertDialog mAlertDialog = new AlertDialog.Builder(AC_AlamSetting.this) .setTitle("请选择电量提醒百分比").setView(mPicker).setPositiveButton("ok",null).create(); mAlertDialog.show(); } }); tvDoorUnclosedMin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { NumberPicker mPicker = new NumberPicker(AC_AlamSetting.this); mPicker.setMinValue(0); mPicker.setMaxValue(60); mPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { // TODO Auto-generated method stub tvDoorUnclosedMin.setText(String.valueOf(newVal) + "分钟"); mDoorStatu = String.valueOf(newVal); } }); AlertDialog mAlertDialog = new AlertDialog.Builder(AC_AlamSetting.this) .setTitle("请选择车门未关提醒分钟数").setView(mPicker).setPositiveButton("ok",null).create(); mAlertDialog.show(); } }); tvDoorUnclosedMin.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { String mDoorStatuTex = tvDoorUnclosedMin.getText().toString(); } }); btHighTemp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.i("llj", "mBatteryTemperatureTooHight--" + mBatteryTemperatureTooHight); if (mBatteryTemperatureTooHight.equals("1")) { mBatteryTemperatureTooHight = "0"; btHighTemp.setImageResource(R.drawable.icon_aa_off); } else if (mBatteryTemperatureTooHight.equals("0")) { mBatteryTemperatureTooHight = "1"; btHighTemp.setImageResource(R.drawable.icon_aa_on); } } }); btTirePressure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mTirePressure.equals("1")) { mTirePressure = "0"; btTirePressure.setImageResource(R.drawable.icon_aa_off); } else if (mTirePressure.equals("0")) { mTirePressure = "1"; btTirePressure.setImageResource(R.drawable.icon_aa_on); } } }); btChargeState.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mChargeStatu.equals("1")) { mChargeStatu = "0"; btChargeState.setImageResource(R.drawable.icon_aa_off); } else if (mChargeStatu.equals("0")) { mChargeStatu = "1"; btChargeState.setImageResource(R.drawable.icon_aa_on); } } }); } private void initViews() { getAlamSettings(); // mAlamSettings = new ArrayList<AlamSettings>(); // AlamSettings mSetting1 = new AlamSettings("ElecTooRow",this.mElecTooRow); // AlamSettings mSetting2 = new AlamSettings("BatteryTemperatureTooHight",this.mBatteryTemperatureTooHight); // AlamSettings mSetting3 = new AlamSettings("DoorStatu",this.mDoorStatu); // AlamSettings mSetting4 = new AlamSettings("TirePressure",this.mTirePressure); // AlamSettings mSetting5 = new AlamSettings("ChargeStatu",this.mChargeStatu); // mAlamSettings.add(mSetting1); // mAlamSettings.add(mSetting2); // mAlamSettings.add(mSetting3); // mAlamSettings.add(mSetting4); // mAlamSettings.add(mSetting5); // mTitleBar.setTitleMode( // AppTitleBar.APPTITLEBARMODE_TXTANDTXTANDTXT, "报警设置", // null); mTitleBar.setTitleMode("取消", null, "报警设置",false, "完成",null); mTitleBar .setOnTitleActionClickListener(new OnTitleActionClickListener() { private EditText etBatteryLow; @Override public void onLeftOperateClick() { AC_AlamSetting.this.finish(); } @Override public void onRightOperateClick() { // mElecTooRow = tvBatteryLow.getText().toString(); // if (mElecTooRow.equals("") || mElecTooRow == null) { // showToast("最低电量不能为空,请重新设置!"); // return; // } // mDoorStatu = tvDoorUnclosedMin.getText().toString(); // if (mDoorStatu.equals("") || mDoorStatu == null) { // showToast("车门未关时间不能为空,请重新设置!"); // return; // } if(mAlamSettings == null) mAlamSettings = new ArrayList<AlamSettings>(); mAlamSettings.clear(); AlamSettings mSetting1 = new AlamSettings("ElecTooRow",mElecTooRow); AlamSettings mSetting2 = new AlamSettings("BatteryTemperatureTooHight",mBatteryTemperatureTooHight); AlamSettings mSetting3 = new AlamSettings("DoorStatu",mDoorStatu); AlamSettings mSetting4 = new AlamSettings("TirePressure",mTirePressure); AlamSettings mSetting5 = new AlamSettings("ChargeStatu",mChargeStatu); mAlamSettings.add(mSetting1); mAlamSettings.add(mSetting2); mAlamSettings.add(mSetting3); mAlamSettings.add(mSetting4); mAlamSettings.add(mSetting5); doSave(mAlamSettings); } @Override public void onTitleClick() { } }); } private void getAlamSettings() { Message waitMsg = mHandler.obtainMessage(MESSAGE_GETTING); mHandler.sendMessage(waitMsg); WebReq_GetAlarmRemind aWebReq_GetAlam = new WebReq_GetAlarmRemind(); ICommonWebResponse<WebRes_GetAlarmRemind> aICommonWebResponse = new ICommonWebResponse<WebRes_GetAlarmRemind>() { @Override public void WebRequestException(String ex) { Message endMsg = mHandler .obtainMessage(MESSAGE_GETTING_EXCEPTION); endMsg.obj = "ex:报警设置信息获取失败,请确认服务器地址设置是否正确,网络连接是否正常."; mHandler.sendMessage(endMsg); } @Override public void WebRequsetFail(String sfalied) { Message endMsg = mHandler.obtainMessage(MESSAGE_GETTING_FAILED); endMsg.obj = "falied:报警设置信息获取失败!" + sfalied; mHandler.sendMessage(endMsg); } @Override public void WebRequstSucess(WebRes_GetAlarmRemind aWebRes) { if (aWebRes.getResult().equals("0")) { // 关闭等待界面 Message endMsg = mHandler.obtainMessage(MESSAGE_GETTING_OK); endMsg.obj = aWebRes.getAlamSettings(); mHandler.sendMessage(endMsg); } else { Message endMsg = mHandler .obtainMessage(MESSAGE_GETTING_FAILED); endMsg.obj = aWebRes.getMessage(); mHandler.sendMessage(endMsg); } } }; WebRequestThreadEx<WebRes_GetAlarmRemind> aWebRequestThreadEx = new WebRequestThreadEx<WebRes_GetAlarmRemind>( aWebReq_GetAlam, aICommonWebResponse, new WebRes_GetAlarmRemind()); new Thread(aWebRequestThreadEx).start(); } private void findViews() { mTitleBar = (AppTitleBar) findViewById(R.id.title_bar); tvBatteryLow = (TextView) findViewById(R.id.tv_battery_low); tvDoorUnclosedMin = (TextView) findViewById(R.id.tv_door_unclose_minutes); btHighTemp = (ImageButton) findViewById(R.id.bt_high_temp); btTirePressure = (ImageButton) findViewById(R.id.bt_tire_pressure); btChargeState = (ImageButton) findViewById(R.id.bt_charge_state); } protected void doSave(List<AlamSettings> alamSettings) { Message waitMsg = mHandler.obtainMessage(MESSAGE_SETTING); mHandler.sendMessage(waitMsg); WebReq_SetAlarmRemind aWebReq_SetAlam = new WebReq_SetAlarmRemind(alamSettings); ICommonWebResponse<WebRes_SetAlamRemind> aICommonWebResponse = new ICommonWebResponse<WebRes_SetAlamRemind>() { @Override public void WebRequestException(String ex) { Message endMsg = mHandler .obtainMessage(MESSAGE_SETTING_EXCEPTION); endMsg.obj = "ex:报警设置信息保存失败,请确认服务器地址设置是否正确,网络连接是否正常."; mHandler.sendMessage(endMsg); } @Override public void WebRequsetFail(String sfalied) { Message endMsg = mHandler.obtainMessage(MESSAGE_SETTING_FAILED); endMsg.obj = "falied:报警设置信息保存失败!" + sfalied; mHandler.sendMessage(endMsg); } @Override public void WebRequstSucess(WebRes_SetAlamRemind aWebRes) { if (aWebRes.getResult().equals("0")) { // 关闭等待界面 Message endMsg = mHandler.obtainMessage(MESSAGE_SETTING_OK); mHandler.sendMessage(endMsg); } else { Message endMsg = mHandler .obtainMessage(MESSAGE_SETTING_FAILED); endMsg.obj = aWebRes.getMessage(); mHandler.sendMessage(endMsg); } } }; WebRequestThreadEx<WebRes_SetAlamRemind> aWebRequestThreadEx = new WebRequestThreadEx<WebRes_SetAlamRemind>( aWebReq_SetAlam, aICommonWebResponse, new WebRes_SetAlamRemind()); new Thread(aWebRequestThreadEx).start(); } @Override protected void handleMsg(Message msg) { switch (msg.what) { case MESSAGE_GETTING: if (mDownDialog != null) { mDownDialog.dismiss(); } if (mDownDialog == null) { mDownDialog = Dg_Waiting.newInstance("报警设置获取", "正在获取报警设置信息,请稍候."); mDownDialog.setCancelable(false); } mDownDialog.show(getSupportFragmentManager(), ""); break; case MESSAGE_GETTING_OK: if (mDownDialog != null) { mDownDialog.dismiss(); mDownDialog = null; } setData((List<AlamSettings>)msg.obj); break; case MESSAGE_GETTING_FAILED: if (mDownDialog != null){ mDownDialog.dismiss(); mDownDialog = null; } showToast((String) msg.obj); break; case MESSAGE_GETTING_EXCEPTION: if (mDownDialog != null) mDownDialog.dismiss(); showToast((String) msg.obj); break; case MESSAGE_SETTING: if (mDownDialog == null) { mDownDialog = Dg_Waiting.newInstance("修改报警设置", "正在修改报警设置,请稍候."); } mDownDialog.show(getSupportFragmentManager(), ""); break; case MESSAGE_SETTING_OK: if (mDownDialog != null) { mDownDialog.dismiss(); } final Dg_Alert mDg_Alert = Dg_Alert.newInstance("修改报警设置", "报警设置修改成功!", "确认"); mDg_Alert.setCancelable(false); mDg_Alert.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(View v) { mDg_Alert.dismiss(); AC_AlamSetting.this.finish(); } }); mDg_Alert.show(getSupportFragmentManager(),""); break; case MESSAGE_SETTING_FAILED: if (mDownDialog != null) mDownDialog.dismiss(); showToast((String) msg.obj); break; case MESSAGE_SETTING_EXCEPTION: if (mDownDialog != null) mDownDialog.dismiss(); showToast((String) msg.obj); break; } } private void setData(List<AlamSettings> alamSettings) { if(alamSettings.size() > 0){ for (AlamSettings settings : alamSettings) { if(settings.getParam().equals("ElecTooRow")){ mElecTooRow = settings.getValue(); Log.i("llj", "mElecTooRow -- " + mElecTooRow); tvBatteryLow.setText(mElecTooRow + "%"); } if(settings.getParam().equals("BatteryTemperatureTooHight")){ if(settings.getValue().equals("0")){ mBatteryTemperatureTooHight = "0"; btHighTemp.setImageResource(R.drawable.icon_aa_off); }else{ mBatteryTemperatureTooHight = "1"; btHighTemp.setImageResource(R.drawable.icon_aa_on); } } if(settings.getParam().equals("DoorStatu")){ mDoorStatu = settings.getValue(); tvDoorUnclosedMin.setText(mDoorStatu + "分钟"); } if(settings.getParam().equals("TirePressure")){ if(settings.getValue().equals("0")){ mTirePressure = "0"; btTirePressure.setImageResource(R.drawable.icon_aa_off); }else{ mTirePressure = "1"; btTirePressure.setImageResource(R.drawable.icon_aa_on); } } if(settings.getParam().equals("ChargeStatu")){ if(settings.getValue().equals("0")){ mChargeStatu = "0"; btChargeState.setImageResource(R.drawable.icon_aa_off); }else{ mChargeStatu = "1"; btChargeState.setImageResource(R.drawable.icon_aa_on); } } } } } @Override protected void onDestroy() { super.onDestroy(); } }
30.87631
115
0.702336
61910b2039c2414b7e06df5f1a4ca180e21ff157
919
package ru.job4j.cash; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; /** * Cash realization via load values from disk. * @author shaplov * @since 01.05.2019 */ public class StoredCash extends BaseCash { @Override protected String loadCash(String key) throws IOException { try (BufferedReader input = new BufferedReader( new InputStreamReader(StoredCash.class.getClassLoader().getResourceAsStream(key), StandardCharsets.UTF_8)) ) { String scanned; StringBuilder sb = new StringBuilder(); while ((scanned = input.readLine()) != null) { sb.append(scanned); sb.append(System.lineSeparator()); } String result = sb.toString(); return result; } } }
28.71875
97
0.616975
862c73e62e9edf4794eac398d96894527a14a676
2,292
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.analytics; import static org.testng.AssertJUnit.assertTrue; import java.util.Collections; import org.json.JSONArray; import org.json.JSONException; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; /** * Tests that {@link AnalyticsNodeJsonWriter} creates the expected JSON. */ public class AnalyticsNodeJsonWriterTest { @Test public void emptyPortfolio() throws JSONException { String json = AnalyticsNodeJsonWriter.getJson(AnalyticsNode.emptyRoot()); assertTrue(JsonTestUtils.equal(new JSONArray("[0,0,[]]"), new JSONArray(json))); } @Test public void flatPortfolio() throws JSONException { /* 0 root 1 |_pos 2 |_pos 3 |_pos */ AnalyticsNode root = new AnalyticsNode(0, 3, Collections.<AnalyticsNode>emptyList()); String json = AnalyticsNodeJsonWriter.getJson(root); assertTrue(JsonTestUtils.equal(new JSONArray("[0,3,[]]"), new JSONArray(json))); } @Test public void portfolioWithSubNodes() throws JSONException { /* 0 root 1 |_child1 2 | |_pos 3 |_child2 4 | |_pos 4 |_pos */ AnalyticsNode child1 = new AnalyticsNode(1, 2, Collections.<AnalyticsNode>emptyList()); AnalyticsNode child2 = new AnalyticsNode(3, 4, Collections.<AnalyticsNode>emptyList()); AnalyticsNode root = new AnalyticsNode(0, 5, ImmutableList.of(child1, child2)); String json = AnalyticsNodeJsonWriter.getJson(root); assertTrue(JsonTestUtils.equal(new JSONArray("[0,5,[[1,2,[]],[3,4,[]]]]"), new JSONArray(json))); } @Test public void nestedPortfolio() throws JSONException { /* 0 root 1 |_child1 2 |_child2 3 |_pos 4 |_pos */ AnalyticsNode child2 = new AnalyticsNode(2, 4, Collections.<AnalyticsNode>emptyList()); AnalyticsNode child1 = new AnalyticsNode(1, 4, ImmutableList.of(child2)); AnalyticsNode root = new AnalyticsNode(0, 4, ImmutableList.of(child1)); String json = AnalyticsNodeJsonWriter.getJson(root); assertTrue(JsonTestUtils.equal(new JSONArray("[0,4,[[1,4,[[2,4,[]]]]]]"), new JSONArray(json))); } }
30.56
101
0.689354
532be06a07962a68e3b9ce59b81546972f991135
12,318
package beans; import model.Intervenant; import beans.util.JsfUtil; import beans.util.PaginationHelper; import session.IntervenantFacade; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import model.Comptebc; @Named("intervenantController") @SessionScoped public class IntervenantController implements Serializable { @PersistenceContext(unitName = "AppFinanciere") private EntityManager em; private List<Intervenant> items = null; private boolean disablCreate = false; private boolean disablUpdate = true; private boolean disablDelete = true; private Intervenant current; @EJB private session.IntervenantFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public IntervenantController() { } public List<Intervenant> getItemes() { try { this.items = new ArrayList<Intervenant>(); Query req = em.createQuery("SELECT o FROM Intervenant o"); List<Intervenant> l = (List<Intervenant>) req.getResultList(); items = l; } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aucun Compte n'est trouvé !", "Information")); } return items; } public List<String> completeText(String id) { List<String> FiltredSP = new ArrayList<String>(); try { List<Intervenant> AllSP = getItemes(); for (Intervenant c : AllSP) { if (c.getCinPpr().startsWith(id)) { FiltredSP.add(c.getCinPpr()); } } } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Echec de convertion !", "Erreure")); } return FiltredSP; } public void subjectSelectionChanged() { if (current instanceof Intervenant && current != null) { try { Query req = em.createQuery("SELECT o FROM Intervenant o WHERE o.cinPpr =?").setParameter(1, current.getCinPpr()); Intervenant c = (Intervenant) req.getSingleResult(); if (c != null && c instanceof Intervenant) { current.setNomComplet(c.getNomComplet()); current.setNomArabe(c.getNomArabe()); current.setTelephone(c.getTelephone()); current.setMail(c.getMail()); disablCreate = true; disablUpdate = false; disablDelete = false; } else { disablCreate = false; disablUpdate = true; disablDelete = true; } } catch (Exception e) { disablCreate = false; disablUpdate = true; disablDelete = true; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Aucun Compte n'est trouvé !", "Information")); } } } public Intervenant getSelected() { if (current == null) { current = new Intervenant(); selectedItemIndex = -1; } return current; } private IntervenantFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } /*public String prepareView() { current = (Intervenant) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; }*/ public String prepareCreate() { current = new Intervenant(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().edit(current); this.items = getItemes(); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("IntervenantCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } /*public String prepareEdit() { current = (Intervenant) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; }*/ public String update() { try { Query req = em.createQuery("SELECT a FROM Intervenant a WHERE a.cinPpr =?").setParameter(1, current.getCinPpr()); Intervenant c=(Intervenant) req.getSingleResult(); current.setCinPpr(c.getCinPpr()); getFacade().edit(current); this.items = getItemes(); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("IntervenantUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } /*public String destroy() { current = (Intervenant) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; }*/ public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } public void performDestroy() { try { Query req = em.createQuery("SELECT a FROM Intervenant a WHERE a.cinPpr =?").setParameter(1, current.getCinPpr()); Intervenant c=(Intervenant) req.getSingleResult(); current.setCinPpr(c.getCinPpr()); getFacade().remove(current); this.items = getItemes(); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("IntervenantDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } /* public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; }*/ private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } public Intervenant getIntervenant(java.lang.String id) { return ejbFacade.find(id); } public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } public List<Intervenant> getItems() { return items; } public void setItems(List<Intervenant> items) { this.items = items; } public Intervenant getCurrent() { return current; } public void setCurrent(Intervenant current) { this.current = current; } public boolean isDisablCreate() { return disablCreate; } public void setDisablCreate(boolean disablCreate) { this.disablCreate = disablCreate; } public boolean isDisablUpdate() { return disablUpdate; } public void setDisablUpdate(boolean disablUpdate) { this.disablUpdate = disablUpdate; } public boolean isDisablDelete() { return disablDelete; } public void setDisablDelete(boolean disablDelete) { this.disablDelete = disablDelete; } public IntervenantFacade getEjbFacade() { return ejbFacade; } public void setEjbFacade(IntervenantFacade ejbFacade) { this.ejbFacade = ejbFacade; } public int getSelectedItemIndex() { return selectedItemIndex; } public void setSelectedItemIndex(int selectedItemIndex) { this.selectedItemIndex = selectedItemIndex; } @FacesConverter(forClass = Intervenant.class) public static class IntervenantControllerConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } IntervenantController controller = (IntervenantController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "intervenantController"); return controller.getIntervenant(getKey(value)); } java.lang.String getKey(String value) { java.lang.String key; key = value; return key; } String getStringKey(java.lang.String value) { StringBuilder sb = new StringBuilder(); sb.append(value); return sb.toString(); } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Intervenant) { Intervenant o = (Intervenant) object; return getStringKey(o.getCinPpr()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Intervenant.class.getName()); } } } }
33.291892
171
0.582806
41c60aba431462cb8f3b57da5541d3c20c2ecb72
809
package yitian.study; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import yitian.study.entity.Person; import java.io.IOException; import java.time.LocalDate; public class XmlSample { public static void main(String[] args) throws IOException { Person p1 = new Person("yitian", "易天", 25, "10000", LocalDate.of(1994, 1, 1)); XmlMapper mapper = new XmlMapper(); mapper.findAndRegisterModules(); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.INDENT_OUTPUT); String text = mapper.writeValueAsString(p1); System.out.println(text); Person p2 = mapper.readValue(text, Person.class); System.out.println(p2); } }
33.708333
86
0.715698
f7667e756325df7e38e723ef29173110bfe60aad
3,544
package com.mgmtp.radio.service.user.favorite; import com.mgmtp.radio.domain.user.FavoriteSong; import com.mgmtp.radio.dto.user.FavoriteSongDTO; import com.mgmtp.radio.mapper.user.FavoriteSongMapper; import com.mgmtp.radio.respository.user.FavoriteSongRepository; import com.mgmtp.radio.service.station.SongService; import com.mgmtp.radio.service.user.FavoriteSongService; import com.mgmtp.radio.service.user.FavoriteSongServiceImpl; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import reactor.core.publisher.Mono; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.when; public class CreateFavoriteSongImplTest { @Mock FavoriteSongRepository favoriteSongRepository; @Mock SongService songService; FavoriteSongMapper favoriteSongMapper = FavoriteSongMapper.INSTANCE; FavoriteSongService favoriteSongService; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); favoriteSongService = new FavoriteSongServiceImpl(favoriteSongRepository, favoriteSongMapper, songService); } @Test public void createSuccess() { //given FavoriteSongDTO favoriteSongDTO = new FavoriteSongDTO(); favoriteSongDTO.setId("001"); favoriteSongDTO.setUserId("001"); favoriteSongDTO.setSongId("001"); FavoriteSong savedFavoriteSong = new FavoriteSong(); savedFavoriteSong.setId(favoriteSongDTO.getId()); savedFavoriteSong.setUserId(favoriteSongDTO.getUserId()); savedFavoriteSong.setSongId(favoriteSongDTO.getSongId()); when(favoriteSongRepository.save(any(FavoriteSong.class))).thenReturn(Mono.just(savedFavoriteSong)); // when Mono<FavoriteSongDTO> result = favoriteSongService.create(favoriteSongDTO.getUserId(), favoriteSongDTO); FavoriteSongDTO expected = result.log().block(); // then assertEquals(favoriteSongDTO.getId(), expected.getId()); assertEquals(favoriteSongDTO.getUserId(), expected.getUserId()); assertEquals(favoriteSongDTO.getSongId(), expected.getSongId()); } @Test public void createFailure() { //given FavoriteSongDTO favoriteSongDTO = new FavoriteSongDTO(); favoriteSongDTO.setId("001"); favoriteSongDTO.setUserId("001"); favoriteSongDTO.setSongId("001"); FavoriteSongDTO failedfavoriteSongDTO = new FavoriteSongDTO(); failedfavoriteSongDTO.setId("002"); failedfavoriteSongDTO.setUserId("002"); failedfavoriteSongDTO.setSongId("002"); FavoriteSong savedFavoriteSong = new FavoriteSong(); savedFavoriteSong.setId(favoriteSongDTO.getId()); savedFavoriteSong.setUserId(favoriteSongDTO.getUserId()); savedFavoriteSong.setSongId(favoriteSongDTO.getSongId()); when(favoriteSongRepository.save(any(FavoriteSong.class))).thenReturn(Mono.just(savedFavoriteSong)); // when Mono<FavoriteSongDTO> result = favoriteSongService.create(favoriteSongDTO.getUserId(), favoriteSongDTO); FavoriteSongDTO expected = result.log().block(); // then assertNotEquals(failedfavoriteSongDTO.getId(), expected.getId()); assertNotEquals(failedfavoriteSongDTO.getUserId(), expected.getUserId()); assertNotEquals(failedfavoriteSongDTO.getSongId(), expected.getSongId()); } }
38.521739
115
0.73702
93e93b8a8b9793ef05b508421b3f4ce4566a06f9
3,223
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.source.resolve.reference; import com.intellij.openapi.paths.GlobalPathReferenceProvider; import com.intellij.openapi.paths.PathReferenceManager; import com.intellij.openapi.util.UserDataCache; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.IssueNavigationConfiguration; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.PsiReferenceProvider; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ProcessingContext; import com.intellij.util.SmartList; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class ArbitraryPlaceUrlReferenceProvider extends PsiReferenceProvider { private static final UserDataCache<CachedValue<PsiReference[]>, PsiElement, Object> ourRefsCache = new UserDataCache<CachedValue<PsiReference[]>, PsiElement, Object>("psielement.url.refs") { private final AtomicReference<GlobalPathReferenceProvider> myReferenceProvider = new AtomicReference<>(); @Override protected CachedValue<PsiReference[]> compute(final PsiElement element, Object p) { return CachedValuesManager.getManager(element.getProject()).createCachedValue(() -> { IssueNavigationConfiguration navigationConfiguration = IssueNavigationConfiguration.getInstance(element.getProject()); if (navigationConfiguration == null) { return CachedValueProvider.Result.create(PsiReference.EMPTY_ARRAY, element); } List<PsiReference> refs = null; GlobalPathReferenceProvider provider = myReferenceProvider.get(); CharSequence commentText = StringUtil.newBombedCharSequence(element.getText(), 500); for (IssueNavigationConfiguration.LinkMatch link : navigationConfiguration.findIssueLinks(commentText)) { if (refs == null) refs = new SmartList<>(); if (provider == null) { provider = (GlobalPathReferenceProvider)PathReferenceManager.getInstance().getGlobalWebPathReferenceProvider(); myReferenceProvider.lazySet(provider); } provider.createUrlReference(element, link.getTargetUrl(), link.getRange(), refs); } PsiReference[] references = refs != null ? refs.toArray(PsiReference.EMPTY_ARRAY) : PsiReference.EMPTY_ARRAY; return new CachedValueProvider.Result<>(references, element, navigationConfiguration); }, false); } }; @Override public PsiReference @NotNull [] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) { if (Registry.is("ide.symbol.url.references")) { return PsiReference.EMPTY_ARRAY; } return ourRefsCache.get(element, null).getValue(); } @Override public boolean acceptsTarget(@NotNull PsiElement target) { return false; } }
49.584615
192
0.754266
5e580349251df5041c1f2ca986631f6d19186d6a
11,886
package com.trovebox.android.common.util; import java.io.InputStream; import java.text.DecimalFormat; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Set; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Environment; import android.text.format.DateUtils; import android.util.Log; import com.actionbarsherlock.internal.ResourcesCompat; import com.trovebox.android.common.BuildConfig; import com.trovebox.android.common.CommonConfigurationUtils; import com.trovebox.android.common.R; public class CommonUtils { /** * This variable is used in the test project to skip some checks */ public static boolean TEST_CASE = false; public static final String TAG = CommonUtils.class.getSimpleName(); /** * Write message to the debug log * * @param TAG * @param message * @param params */ public static void debug(String TAG, String message, Object... params) { try { if (BuildConfig.DEBUG) { if (params == null || params.length == 0) { Log.d(TAG, message); } else { Log.d(TAG, format(message, params)); } } } catch (Exception ex) { error(TAG, ex); } } /** * Format string with params * * @param message * @param params * @return */ public static String format(String message, Object... params) { try { return String.format(Locale.ENGLISH, message, params); } catch (Exception ex) { error(TAG, ex); } return null; } /** * Format the number * * @param number * @return */ public static String format(Number number) { return DecimalFormat.getInstance().format(number); } /** * Format date time accordingly to specified user locale * * @param date * @return */ public static String formatDateTime(Date date) { if (date == null) { return null; } return DateUtils.formatDateTime(CommonConfigurationUtils.getApplicationContext(), date.getTime(), DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME); } /** * Write message to the verbose log * * @param TAG * @param message * @param params */ public static void verbose(String TAG, String message, Object... params) { try { if (BuildConfig.DEBUG) { if (params == null || params.length == 0) { Log.v(TAG, message); } else { Log.v(TAG, format(message, params)); } } } catch (Exception ex) { error(TAG, ex); } } /** * Write message to the error log * * @param TAG * @param message */ public static void error(String TAG, String message) { Log.e(TAG, message); } /** * Write message to the info log * * @param TAG * @param message */ public static void info(String TAG, String message) { Log.i(TAG, message); } /** * Write throwable to the error log and track it * * @param TAG * @param tr */ public static void error(String TAG, Throwable tr) { error(TAG, null, tr); } /** * Write message and throwable to the error log and track it * * @param TAG * @param message * @param tr */ public static void error(String TAG, String message, Throwable tr) { error(TAG, message, tr, true); } /** * Write message to the error log and track it depend on trackThrowable * parameter * * @param TAG * @param message * @param tr * @param trackThrowable - whether to track the throwable via TrackerUtils */ public static void error(String TAG, String message, Throwable tr, boolean trackThrowable) { if (trackThrowable) { TrackerUtils.trackThrowable(tr); } Log.e(TAG, message, tr); } /** * Get serializable object from bundle if it is not null * * @param key * @param bundle * @return */ @SuppressWarnings("unchecked") public static <T> T getSerializableFromBundleIfNotNull(String key, Bundle bundle) { return (T) (bundle == null ? null : bundle.getSerializable(key)); } /** * Get parcelable object from bundle if it is not null * * @param key * @param bundle * @return */ @SuppressWarnings("unchecked") public static <T> T getParcelableFromBundleIfNotNull(String key, Bundle bundle) { return (T) (bundle == null ? null : bundle.getParcelable(key)); } /** * Check the external storage status * * @return */ public static boolean isExternalStorageAvilable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /** * Checks whether the running platform version is 4.x or higher * * @return */ public static boolean isIceCreamSandwichOrHigher() { return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; } /** * Checks whether the running platform version is 4.1 or higher * * @return */ public static boolean isJellyBeanOrHigher() { return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN; } /** * Checks whether the running platform version is 2.2 or higher * * @return */ public static boolean isFroyoOrHigher() { return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; } /** * Get string resource by id * * @param resourceId * @return */ public static String getStringResource(int resourceId) { return CommonConfigurationUtils.getApplicationContext().getString(resourceId); } /** * Get string resource by id with parameters * * @param resourceId * @param args * @return */ public static String getStringResource(int resourceId, Object... args) { return CommonConfigurationUtils.getApplicationContext().getString(resourceId, args); } /** * Get string resource by id * * @param resourceId * @return */ public static String getQuantityStringResource(int resourceId, int quantity) { return CommonConfigurationUtils.getApplicationContext().getResources() .getQuantityString(resourceId, quantity); } /** * Get string resource by id with parameters * * @param resourceId * @param args * @return */ public static String getQuantityStringResource(int resourceId, int quantity, Object... args) { return CommonConfigurationUtils.getApplicationContext().getResources() .getQuantityString(resourceId, quantity, args); } /** * Check whether the device is connected to any network * * @return true if device is connected to any network, otherwise return * false */ public static boolean isOnline() { return isOnline(CommonConfigurationUtils.getApplicationContext()); } /** * Check whether the device is connected to any network * * @param context * @return true if device is connected to any network, otherwise return * false */ public static boolean isOnline(Context context) { boolean result = false; try { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { result = true; } } catch (Exception ex) { error(TAG, "Error", ex); } return result; } /** * Check whether the device is connected to WiFi network and it is active * connection * * @return true if device is connected to WiFi network and it is active, * otherwise return false */ public static boolean isWiFiActive() { boolean result = false; try { ConnectivityManager cm = (ConnectivityManager) CommonConfigurationUtils.getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.isConnectedOrConnecting()) { result = true; } } catch (Exception ex) { error(TAG, "Error", ex); } return result; } public static boolean isTablet(Context context) { return context.getResources().getBoolean(R.bool.isTablet); } /** * Whether actionbar tabs embedded or in split state * * @param context * @return */ public static boolean isActionBarTabsEmbeded(Context context) { return ResourcesCompat.getResources_getBoolean(context, R.bool.abs__action_bar_embed_tabs); } /** * Returns possible external sd card path. Solution taken from here * http://stackoverflow.com/a/13648873/527759 * * @return */ public static Set<String> getExternalMounts() { final Set<String> out = new HashSet<String>(); try { String reg = ".*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*"; StringBuilder sb = new StringBuilder(); try { final Process process = new ProcessBuilder().command("mount") .redirectErrorStream(true).start(); process.waitFor(); final InputStream is = process.getInputStream(); final byte[] buffer = new byte[1024]; while (is.read(buffer) != -1) { sb.append(new String(buffer)); } is.close(); } catch (final Exception e) { e.printStackTrace(); } // parse output final String[] lines = sb.toString().split("\n"); for (String line : lines) { if (!line.toLowerCase(Locale.ENGLISH).contains("asec")) { if (line.matches(reg)) { String[] parts = line.split(" "); for (String part : parts) { if (part.startsWith("/")) if (!part.toLowerCase(Locale.ENGLISH).contains("vold")) { CommonUtils.debug(TAG, "Found path: " + part); out.add(part); } } } } } } catch (Exception ex) { error(TAG, ex); } return out; } }
30.091139
108
0.548629
42b104ce2ed5d4aa480d3e9c65ca991895a92b40
2,727
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import java.util.Set; /** * @author pugh */ public class ComponentPlugin<T> { public ComponentPlugin(Plugin plugin, String id, ClassLoader classLoader, Class<? extends T> componentClass, PropertyBundle properties, boolean enabledByDefault, String description, String details) { this.plugin = plugin; this.id = id; int i = id.lastIndexOf('.'); this.shortId = id.substring(i + 1); this.classLoader = classLoader; this.componentClass = componentClass; this.properties = properties; this.enabledByDefault = enabledByDefault; this.description = description; this.details = details; } protected final Plugin plugin; public String getId() { return id; } public ClassLoader getClassLoader() { return classLoader; } public boolean isEnabledByDefault() { return enabledByDefault; } public PropertyBundle getProperties() { return properties; } public String getDescription() { return description; } public String getDetails() { return details; } @Override public String toString() { return getDescription(); } public Plugin getPlugin() { return plugin; } public boolean isNamed(Set<String> names) { return names.contains(id) || names.contains(shortId); } protected final String id; protected final String shortId; protected final ClassLoader classLoader; protected final PropertyBundle properties; protected final String description; protected final String details; protected final boolean enabledByDefault; public Class<? extends T> getComponentClass() { return componentClass; } final Class<? extends T> componentClass; }
26.475728
77
0.673634
c34e5a9c170831f16a430e7c4e2eaed2604862e9
5,196
package net.jgp.labs.spark.football.lab300; import org.apache.spark.SparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.functions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Finding out the next WorldCup winner. * * @author jgp */ public class NextWinnerApp { private static Logger log = LoggerFactory.getLogger(NextWinnerApp.class); /** * main() is your entry point to the application. This is meant as a joke... * * @param args */ public static void main(String[] args) { NextWinnerApp app = new NextWinnerApp(); app.start(); } /** * The processing code. */ private void start() { // Creates a session on a local master SparkSession spark = SparkSession.builder() .appName("Next winner of the World Cup") .master("local[*]") .getOrCreate(); SparkContext sc = spark.sparkContext(); System.out.println("Running Spark v" + sc.version()); System.out.println("Running in " + sc.deployMode()); // Reads a CSV file with header, called books.csv, stores it in a dataframe Dataset<Row> worldCupRussiaMatchesDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Cup.Russia.Matches.csv"); worldCupRussiaMatchesDf = worldCupRussiaMatchesDf .withColumnRenamed("Home Team", "country1") .withColumnRenamed("Away Team", "country2") .withColumnRenamed("Home Team Goals", "score1") .withColumnRenamed("Away Team Goals", "score2") .withColumn("date", functions.split(worldCupRussiaMatchesDf.col( "Datetime (Brazil)"), ".-.") .getItem(1)) .drop("Datetime (Brazil)"); log.debug("There were {} games in the Soccer World Cup 2018", worldCupRussiaMatchesDf.count()); worldCupRussiaMatchesDf.show(5); Dataset<Row> worldCupRussiaTeamsDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Cup.Russia.Teams.csv"); worldCupRussiaTeamsDf.show(5); Dataset<Row> fixtureDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Fixture.csv"); fixtureDf.show(5); Dataset<Row> playersScoreDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Players_Score.csv"); playersScoreDf.show(5); Dataset<Row> playersStatsDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Players_Stats.csv"); playersStatsDf.show(5); Dataset<Row> playersDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Players.csv"); playersDf.show(5); Dataset<Row> teamsDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/Teams.csv"); teamsDf.show(5); Dataset<Row> worldCupMatchesDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/WorldCupMatches.csv"); worldCupMatchesDf.show(5); Dataset<Row> worldCupPlayersDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/WorldCupPlayers.csv"); worldCupPlayersDf.show(5); Dataset<Row> worldCupsDf = spark.read() .format("csv") .option("header", "true") .option("inferSchema", "true") .load("data/WorldCups.csv"); worldCupsDf.show(5); Dataset<Row> dfReverse = worldCupRussiaMatchesDf.withColumnRenamed( "country1", "x") .withColumnRenamed("country2", "country1") .withColumnRenamed("x", "country2") .withColumnRenamed("score1", "s") .withColumnRenamed("score2", "score1") .withColumnRenamed("s", "score2"); dfReverse.show(5); Dataset<Row> combinedDf = worldCupRussiaMatchesDf.unionByName(dfReverse) .withColumnRenamed("country1", "country") .drop("country2") .withColumnRenamed("score1", "score") .drop("score2"); combinedDf.show(5); log.debug("There were {} interactions in the Soccer World Cup 2018", combinedDf.count()); Dataset<Row> franceScoreDf = combinedDf.filter("country='France'"); franceScoreDf.show(); Dataset<Row> mostPlayedDf = combinedDf.groupBy("country").count(); mostPlayedDf = mostPlayedDf.orderBy(mostPlayedDf.col("count").desc()); mostPlayedDf.show(5); Dataset<Row> goalsDf = combinedDf.groupBy("country").sum("score"); goalsDf = goalsDf.orderBy(goalsDf.col("sum(score)").desc()); goalsDf.show(5); System.out.println("And the winner is..."); try { Thread.sleep(1434); } catch (InterruptedException e) { // oh well, let's ignore it } System.out.println("France"); } }
31.301205
79
0.620477
fc4510390e616ec5ef42b48d7197beb7ac183eb9
1,585
/* * 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 de.ubleipzig.scb.creator.internal; import com.github.jsonldjava.core.JsonLdConsts; import com.github.jsonldjava.core.JsonLdError; import com.github.jsonldjava.core.JsonLdOptions; import com.github.jsonldjava.core.JsonLdProcessor; import com.github.jsonldjava.utils.JsonUtils; import java.io.IOException; import java.io.InputStream; /** * JsonLdUtils. * * @author christopher-johnson */ public class JsonLdUtils { /** * JsonLdUtils. */ public JsonLdUtils() { } /** * unmarshallToNQuads. * * @param is InputStream * @return Object nquads */ public Object unmarshallToNQuads(final InputStream is) { final JsonLdOptions options = new JsonLdOptions(); options.format = JsonLdConsts.APPLICATION_NQUADS; try { return JsonLdProcessor.toRDF(JsonUtils.fromInputStream(is), options); } catch (JsonLdError | IOException jsonLdError) { jsonLdError.printStackTrace(); } return null; } }
27.807018
81
0.700946
db511539d57ca46586102dfe56823d0581f5bb21
13,173
package it.chiarani.meteotrentinoapp.fragments; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatDelegate; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import it.chiarani.meteotrentinoapp.R; import it.chiarani.meteotrentinoapp.adapters.StationDataRainAdapter; import it.chiarani.meteotrentinoapp.adapters.StationDataTemperatureAdapter; import it.chiarani.meteotrentinoapp.api.MeteoTrentinoStationsAPI; import it.chiarani.meteotrentinoapp.api.MeteoTrentinoStationsModel.Anagrafica; import it.chiarani.meteotrentinoapp.api.MeteoTrentinoStationsModel.DatiOggi; import it.chiarani.meteotrentinoapp.api.MeteoTrentinoStationsModel.Precipitazione; import it.chiarani.meteotrentinoapp.api.MeteoTrentinoStationsModel.TemperaturaAria; import it.chiarani.meteotrentinoapp.api.RetrofitAPI; import it.chiarani.meteotrentinoapp.databinding.FragmentStationDataBinding; import it.chiarani.meteotrentinoapp.utils.CustomDateFormatter; public class StationDataFragment extends Fragment { private FragmentStationDataBinding binding; private final CompositeDisposable mDisposable = new CompositeDisposable(); private RetrofitAPI meteoTrentinoAPI; private DatiOggi mDatiOggi; public StationDataFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_station_data, container, false); View view = binding.getRoot(); binding.fragmentStationDataBack.setOnClickListener( v -> popBackStack(getFragmentManager())); meteoTrentinoAPI = MeteoTrentinoStationsAPI.getInstance(); mDisposable.add(meteoTrentinoAPI.getMeteoTrentinoStationList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(model -> { List<Anagrafica> anagraficaList = model.getAnagrafica(); List<String> convertedAnagrafica = new ArrayList<>(); for(Anagrafica val : anagraficaList) { convertedAnagrafica.add(String.format("%s: %s", val.getCodice(), val.getNomebreve())); } ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, convertedAnagrafica); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); binding.fragmentStationDataSpinner.setAdapter(adapter); binding.fragmentStationDataSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { retriveStationData(model.getAnagrafica().get(position).getCodice()); ((TextView) parentView.getChildAt(0)).setTextColor(Color.parseColor("#A4A4A4")); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); }, throwable -> { // TODO: handle error })); binding.fragmentStationDataRadioGroup.setOnCheckedChangeListener((group, checkedId) -> { if(checkedId == binding.fragmentStationDataRadioTemperatura.getId()) { Collections.reverse(mDatiOggi.getTemperature().temperaturaAria()); StationDataTemperatureAdapter mAdapter = new StationDataTemperatureAdapter(mDatiOggi.getTemperature().temperaturaAria()); binding.fragmentStationDataRv.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); // setTemperatureGraph(mDatiOggi); } else { if(mDatiOggi.getTemperature() != null && mDatiOggi.getTemperature().temperaturaAria() != null) { Collections.reverse(mDatiOggi.getTemperature().temperaturaAria()); StationDataRainAdapter mAdapter = new StationDataRainAdapter(mDatiOggi.getPrecipitazioni().getPrecipitazione()); binding.fragmentStationDataRv.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } // setRainGraph(mDatiOggi); } }); return view; } private void retriveStationData(String code) { mDisposable.add(meteoTrentinoAPI.getMeteoTrentinoStationData(code) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(model -> { mDatiOggi = model; binding.fragmentStationDataRadioTemperatura.setEnabled(true); binding.fragmentStationDataRadioPioggia.setEnabled(true); binding.fragmentStationDataAnimLoad.setVisibility(View.GONE); binding.fragmentStationDataTitleAndamentoPioggia.setVisibility(View.VISIBLE); binding.fragmentStationDataTitleAndamentoTemperatura.setVisibility(View.VISIBLE); binding.fragmentStationDataRv.setVisibility(View.VISIBLE); binding.fragmentStationDataChart.setVisibility(View.VISIBLE); binding.fragmentStationDataChartRain.setVisibility(View.VISIBLE); LinearLayoutManager linearLayoutManagerTags = new LinearLayoutManager(getActivity().getApplicationContext()); linearLayoutManagerTags.setOrientation(RecyclerView.VERTICAL); binding.fragmentStationDataRv.setLayoutManager(linearLayoutManagerTags); setTemperatureGraph(model); setRainGraph(model); Collections.reverse(model.getTemperature().temperaturaAria()); Collections.reverse(model.getPrecipitazioni().getPrecipitazione()); binding.fragmentStationDataLastTemperatureValue.setText(model.getTemperature().temperaturaAria().get(0).getTemperatura() + " °C"); binding.fragmentStationDataLastRainValue.setText(model.getPrecipitazioni().getPrecipitazione().get(0).getPioggia() + " mm"); StationDataTemperatureAdapter mAdapter = new StationDataTemperatureAdapter(model.getTemperature().temperaturaAria()); binding.fragmentStationDataRv.setAdapter(mAdapter); }, throwable -> { binding.fragmentStationDataChartRain.setVisibility(View.GONE); binding.fragmentStationDataTitleAndamentoPioggia.setVisibility(View.GONE); binding.fragmentStationDataTitleAndamentoTemperatura.setVisibility(View.GONE); binding.fragmentStationDataChart.setVisibility(View.GONE); binding.fragmentStationDataLastRainValue.setText("--"); binding.fragmentStationDataLastTemperatureValue.setText("--"); binding.fragmentStationDataRadioTemperatura.setEnabled(false); binding.fragmentStationDataRadioPioggia.setEnabled(false); binding.fragmentStationDataRv.setVisibility(View.GONE); Toast.makeText(getActivity().getApplicationContext(), "Stazione non attiva", Toast.LENGTH_LONG).show(); binding.fragmentStationDataAnimLoad.setVisibility(View.VISIBLE); })); } private void setTemperatureGraph(DatiOggi model) { List<Entry> entries = new ArrayList<>(); for (TemperaturaAria data : model.getTemperature().temperaturaAria()) { // turn your data into Entry objects SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { Date date = (Date)inputFormat.parse(data.getData()); long time = date.getTime(); entries.add(new Entry(time, Float.parseFloat(data.getTemperatura()))); }catch (Exception ex) { } } LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset LineData lineData = new LineData(dataSet); dataSet.setDrawFilled(true); Drawable drawable = ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.bg_fade_blue); dataSet.setFillDrawable(drawable); if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) { binding.fragmentStationDataChart.getAxisLeft().setTextColor(Color.WHITE); binding.fragmentStationDataChart.getAxisRight().setTextColor(Color.WHITE); binding.fragmentStationDataChart.getXAxis().setTextColor(Color.WHITE); binding.fragmentStationDataChart.getLegend().setTextColor(Color.WHITE); } else { binding.fragmentStationDataChart.getAxisLeft().setTextColor(Color.BLACK); binding.fragmentStationDataChart.getAxisRight().setTextColor(Color.BLACK); binding.fragmentStationDataChart.getXAxis().setTextColor(Color.BLACK); binding.fragmentStationDataChart.getLegend().setTextColor(Color.BLACK); } binding.fragmentStationDataChart.getDescription().setText("Temperature"); binding.fragmentStationDataChart.getAxisLeft().setDrawGridLines(false); binding.fragmentStationDataChart.getXAxis().setDrawGridLines(false); binding.fragmentStationDataChart.getLegend().setEnabled(false); binding.fragmentStationDataChart.getXAxis().setValueFormatter(new CustomDateFormatter()); binding.fragmentStationDataChart.getXAxis().setGranularity(2000f); binding.fragmentStationDataChart.getXAxis().setLabelRotationAngle(-45); binding.fragmentStationDataChart.setData(lineData); binding.fragmentStationDataChart.invalidate(); // refresh } private void setRainGraph(DatiOggi model) { List<Entry> entries = new ArrayList<>(); for (Precipitazione data : model.getPrecipitazioni().getPrecipitazione()) { // turn your data into Entry objects SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { Date date = (Date)inputFormat.parse(data.getData()); long time = date.getTime(); entries.add(new Entry(time, Float.parseFloat(data.getPioggia()))); }catch (Exception ex) { } } LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset LineData lineData = new LineData(dataSet); dataSet.setDrawFilled(true); Drawable drawable = ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.bg_fade_blue); dataSet.setFillDrawable(drawable); binding.fragmentStationDataChartRain.getDescription().setText("Piogge"); binding.fragmentStationDataChartRain.getAxisLeft().setDrawGridLines(false); binding.fragmentStationDataChartRain.getXAxis().setDrawGridLines(false); binding.fragmentStationDataChartRain.getLegend().setEnabled(false); binding.fragmentStationDataChartRain.getXAxis().setValueFormatter(new CustomDateFormatter()); binding.fragmentStationDataChartRain.getXAxis().setGranularity(2000f); binding.fragmentStationDataChartRain.getXAxis().setLabelRotationAngle(-45); binding.fragmentStationDataChartRain.setData(lineData); binding.fragmentStationDataChartRain.invalidate(); // refresh } private void popBackStack(FragmentManager manager){ mDisposable.dispose(); FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0); manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); } }
50.665385
168
0.688909
3ef917954615115236b5c7b872fbec3cf51f3740
3,640
package myArrayList; import myArrayList.util.Constants; /** * Data Structure class which replicates the behavior of * Java's ArrayList * @author suresh * */ public class MyArrayList implements Cloneable{ private int[] array = new int[Constants.MIN_ARRAY_SIZE]; private int currentIndex = -1; public MyArrayList() { currentIndex = -1; array = new int[Constants.MIN_ARRAY_SIZE]; } /** *Increase the size of array from 50 to 75(50% increase) */ private void increaseArraySize() { int nextLevelSize = (int)(array.length * Constants.GROWTH_RATE); int[] temp = new int[nextLevelSize]; for (int i = 0; i < array.length; i++) { temp[i] = array[i]; } array = temp; } /** * @void */ private void sort() { for (int i = 0; i <= currentIndex; i++) { for (int j = i + 1; j <= currentIndex; j++) { if (array[i] > array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } } /** * Insert a value into array by maintaining the sorted order of array * @param newValue */ public void insertSorted(int newValue) { checkForSize(); currentIndex += 1; array[currentIndex] = newValue; sort(); } /** * Remove all occurrences of given value from array by maintaining the sorted order * @param value * @return <b>Count</b> of occurrence if value is valid otherwise <b> 0 </b> */ public int removeValue(int value) { int count = 0; if(currentIndex == -1) { return count; } int k = 0; while(k < currentIndex) { for(int i = 0; i <= currentIndex; i++) { if (array[i] == value) { // Shift values after removal for(int j = i; j <= currentIndex; j++) { array[j] = array[j+1]; array[j+1] = 0; } ++count; } } if (count > 0) { //sort(); } ++k; } //Point the current index to the last position after removing values currentIndex -= count; return count; } public int valueAtIndex(int index) { if (index < 0 || index > currentIndex) { System.err.println("Array index out of bound for size = " + size() + " Index is " + index); return -1; } return array[index]; } /** * If the size of array is 50 and need more space and then call increase. */ private void checkForSize() { if (array.length == currentIndex + 1) { increaseArraySize(); } } /** * Find the first index of a value in array * @param value * @return <b>index</b> of value if present otherwise <b>-1</b> */ public int indexOf(int value) { if(currentIndex == -1) { return -1; } for(int i = 0; i <= currentIndex; i++) { if (array[i] == value) { return i; } } return -1; } /** * Returns the size of array list * @return size */ public int size() { return currentIndex+1; } /** * Returns the sum of all the values in array * @return sum */ public int sum() { int sum = 0; for(int i = 0; i <= currentIndex; i++) { sum += array[i]; } return sum; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("["); for(int i = 0; i <= currentIndex; i++) { if (i != 0) { builder.append(","); } builder.append(array[i]); } builder.append("]"); return builder.toString(); } @Override public MyArrayList clone() { MyArrayList arrayList = new MyArrayList(); arrayList.array = this.array.clone(); arrayList.currentIndex = this.currentIndex; return arrayList; } }
18.383838
94
0.571978
f0d282581dc40d21088457ddbe69ba96dfbee8f4
1,299
package com.studiocadet.listeners; import android.util.Log; import com.inneractive.api.ads.InneractiveAdListener; import com.studiocadet.InneractiveExtension; public class BannerListener implements InneractiveAdListener { @Override public void onIaAdClicked() { Log.i(InneractiveExtension.TAG, "Banner ad clicked"); } @Override public void onIaAdExpand() { Log.i(InneractiveExtension.TAG, "Banner ad expanded"); } @Override public void onIaAdExpandClosed() { Log.i(InneractiveExtension.TAG, "Banner ad expand closed"); } @Override public void onIaAdFailed() { Log.i(InneractiveExtension.TAG, "Banner ad failed"); InneractiveExtension.context.onBannerFailed("Inneractive SDK failed to receive a banner"); } @Override public void onIaAdReceived() { Log.i(InneractiveExtension.TAG, "Banner ad received a paid ad"); InneractiveExtension.context.onBannerReceived(true); } @Override public void onIaAdResize() { Log.i(InneractiveExtension.TAG, "Banner ad resized"); } @Override public void onIaAdResizeClosed() { Log.i(InneractiveExtension.TAG, "Banner ad resize closed"); } @Override public void onIaDefaultAdReceived() { Log.i(InneractiveExtension.TAG, "Banner ad received a house ad"); InneractiveExtension.context.onBannerReceived(false); } }
24.055556
92
0.763664
afa28b7520b3f3051c48c4218cf6991e3fcbfbc6
8,156
/* * Copyright (C) 2013 The OmniROM Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.omnirom.torch; import java.util.Timer; import java.util.TimerTask; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.UserHandle; import android.os.Bundle; import android.util.Log; public class TorchService extends Service { private static final String TAG = "TorchService"; private TimerTask mTorchTask; private Timer mTorchTimer; private WrapperTask mStrobeTask; private Timer mStrobeTimer; private Timer mSosTimer; private WrapperTask mSosTask; private Runnable mSosOnRunnable; private Runnable mSosOffRunnable; private int mSosCount; private NotificationManager mNotificationManager; private Notification.Builder mNotificationBuilder; private int mStrobePeriod; private boolean mBright; private boolean mSos; private boolean mStrobe; private Runnable mStrobeRunnable; private Context mContext; public void onCreate() { Log.d(TAG, "onCreate"); String ns = Context.NOTIFICATION_SERVICE; mNotificationManager = (NotificationManager) getSystemService(ns); mContext = getApplicationContext(); mTorchTask = new TimerTask() { public void run() { FlashDevice.getInstance(mContext).setFlashMode(FlashDevice.ON, mBright); } }; mTorchTimer = new Timer(); mStrobeRunnable = new Runnable() { private int mCounter = 4; public void run() { int flashMode = FlashDevice.ON; if (FlashDevice.getInstance(mContext).getFlashMode() == FlashDevice.STROBE) { if (mCounter-- < 1) { FlashDevice.getInstance(mContext).setFlashMode( flashMode, mBright); } } else { FlashDevice.getInstance(mContext).setFlashMode( FlashDevice.STROBE, mBright); mCounter = 4; } } }; mStrobeTask = new WrapperTask(mStrobeRunnable); mStrobeTimer = new Timer(); mSosOnRunnable = new Runnable() { public void run() { FlashDevice.getInstance(mContext).setFlashMode(FlashDevice.ON, mBright); mSosTask = new WrapperTask(mSosOffRunnable); int schedTime = 0; switch (mSosCount) { case 0: case 1: case 2: case 6: case 7: case 8: schedTime = 200; break; case 3: case 4: case 5: schedTime = 600; break; default: return; } if (mSosTimer != null) { mSosTimer.schedule(mSosTask, schedTime); } } }; mSosOffRunnable = new Runnable() { public void run() { FlashDevice.getInstance(mContext).setFlashMode(FlashDevice.OFF, mBright); mSosTask = new WrapperTask(mSosOnRunnable); mSosCount++; if (mSosCount == 9) { mSosCount = 0; } if (mSosTimer != null) { mSosTimer.schedule(mSosTask, mSosCount == 0 ? 2000 : 200); } } }; mSosTask = new WrapperTask(mSosOnRunnable); mSosTimer = new Timer(); } public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand"); if (intent == null) { stopSelf(); return START_NOT_STICKY; } boolean startActivity = intent.getBooleanExtra("activity", false); mBright = intent.getBooleanExtra("bright", false); mStrobe = intent.getBooleanExtra("strobe", false); mSos = intent.getBooleanExtra("sos", false); int strobePeriod = intent.getIntExtra("period", 5); if (strobePeriod == 0) { strobePeriod = 1; } mStrobePeriod = (666 / strobePeriod) / 4; if (mSos) { mBright = true; mStrobe = false; } Log.d(TAG, "onStartCommand mBright = " + mBright + " mStrobe = " + mStrobe + " mStrobePeriod = " + mStrobePeriod + " mSos = " + mSos + " startActivity = " + startActivity); if (mSos) { mSosTimer.schedule(mSosTask, 0); } else if (mStrobe) { mStrobeTimer.schedule(mStrobeTask, 0, mStrobePeriod); } else { mTorchTimer.schedule(mTorchTask, 0, 100); } mNotificationBuilder = new Notification.Builder(this); mNotificationBuilder.setSmallIcon(R.drawable.ic_torch_on); mNotificationBuilder.setTicker(getString(R.string.not_torch_title)); mNotificationBuilder .setContentTitle(getString(R.string.not_torch_title)); Intent fullscreenIntent = new Intent(this, MainActivity.class); fullscreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (startActivity) { mNotificationBuilder.setFullScreenIntent(PendingIntent.getActivity( this, 0, fullscreenIntent, PendingIntent.FLAG_UPDATE_CURRENT), true); } mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, 0, fullscreenIntent, 0)); mNotificationBuilder.setAutoCancel(false); mNotificationBuilder.setOngoing(true); PendingIntent turnOff = PendingIntent.getBroadcast(this, 0, new Intent( TorchSwitch.TOGGLE_FLASHLIGHT), 0); mNotificationBuilder.addAction(R.drawable.ic_torch_off, getString(R.string.not_torch_toggle), turnOff); Notification notification = mNotificationBuilder.build(); mNotificationManager.notify(getString(R.string.app_name).hashCode(), notification); startForeground(getString(R.string.app_name).hashCode(), notification); updateState(true); return START_STICKY; } public void onDestroy() { mNotificationManager.cancelAll(); stopForeground(true); mTorchTimer.cancel(); mTorchTimer = null; mStrobeTimer.cancel(); mStrobeTimer = null; mSosTimer.cancel(); mSosTimer = null; FlashDevice.getInstance(mContext) .setFlashMode(FlashDevice.OFF, mBright); updateState(false); } private void updateState(boolean on) { Intent intent = new Intent(TorchSwitch.TORCH_STATE_CHANGED); intent.putExtra("state", on ? 1 : 0); sendBroadcastAsUser(intent, UserHandle.CURRENT); } public class WrapperTask extends TimerTask { private final Runnable mTarget; public WrapperTask(Runnable target) { mTarget = target; } public void run() { mTarget.run(); } } @Override public IBinder onBind(Intent intent) { return null; } }
33.563786
93
0.587052
4ff97b82a8c77496e57494264d2c15462aaa78ae
1,785
package com.elasticsearch.cloud.monitor.metric.common.monitor.kmon.config; import java.util.Map; import com.google.common.collect.Maps; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_ACCESS_KEY; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_ACCESS_SECRET; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_END_POINT; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_LOG_STORE; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_REPORT_SWITCH; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_SLS_PROJECT; /** * @author xiaoping * @date 2019/12/2 */ public class SlsConfigMapBuilder { private Map<String, String> sinkConfMap = Maps.newHashMap(); public SlsConfigMapBuilder reportEnable(boolean enable) { sinkConfMap.put(CONFIG_REPORT_SWITCH, String.valueOf(enable)); return this; } public SlsConfigMapBuilder endpoint(String endpoint) { sinkConfMap.put(CONFIG_END_POINT, endpoint); return this; } public SlsConfigMapBuilder project(String project) { sinkConfMap.put(CONFIG_SLS_PROJECT, project); return this; } public SlsConfigMapBuilder logstore(String logstore) { sinkConfMap.put(CONFIG_LOG_STORE, logstore); return this; } public SlsConfigMapBuilder accesskey(String accesskey) { sinkConfMap.put(CONFIG_ACCESS_KEY, accesskey); return this; } public SlsConfigMapBuilder accesssecret(String accesssecret) { sinkConfMap.put(CONFIG_ACCESS_SECRET, accesssecret); return this; } public Map<String, String> build() { return sinkConfMap; } }
31.875
91
0.74958
c9f875495d9e8e937b9335d8b59a9d7399276f6b
1,066
package learn.baiduyun.aqs; /** * @Author: liangxuanhao * @Description: 两个线程循环打印1-100的数,一个线程打印偶数,一个线程打印奇数 * @Date: 2019年03月13 09:47 */ public class ForPrint { public static void main(String[] args) { final ForPrint forPrint = new ForPrint(); Thread t1 = new Thread(forPrint::demo1); Thread t2 = new Thread(forPrint::demo2); t1.start(); t2.start(); } public synchronized void demo1() { for (int i = 1; i <= 100; i += 2) { System.out.println(i); this.notify(); try { this.wait(); Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } public synchronized void demo2() { for (int i = 0; i <= 100; i += 2) { System.out.println(i); this.notify(); try { this.wait(); Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } }
24.227273
50
0.471857
dd8b65ae9d3765d6ce984fa3eec3ea553f8a6230
1,281
package com.github.pshirshov.conversion.impl.jasmin; import java.io.PrintWriter; import java.io.StringWriter; import com.github.pshirshov.conversion.Disassembler; import com.github.pshirshov.util.IdeaUtils; import com.intellij.openapi.editor.Document; import com.xenoamess.org.objectweb.asm.v_9_2.ClassReader; public class JasminDisassembler implements Disassembler { public static final JasminDisassembler INSTANCE = new JasminDisassembler(); private JasminDisassembler() { } @Override public String disassemble(byte[] classfile) { final ClassReader classReader = new ClassReader(classfile); final StringWriter writer = new StringWriter(); try (final PrintWriter printWriter = new PrintWriter(writer)) { int flags = ClassReader.EXPAND_FRAMES; classReader.accept(new JasminifierClassAdapter(printWriter), flags); } return writer.toString(); } @Override public int getLineOffset( String assembledByteCodeString, Document document, int lineNumber ) { return IdeaUtils.findSubstringOffset( assembledByteCodeString, document, lineNumber, ".line " ); } }
27.255319
80
0.672912
35ddedbec84531a820243245fe2e0dc69c90a33d
1,224
package io.idfy.identificationV2; import io.idfy.OAuthScope; import io.idfy.identificationV2.models.LanguageDetails; import io.idfy.models.IdfyException; import io.idfy.IdfyConfiguration; import java.io.InputStream; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.*; /** * API tests for LanguagesApi */ public class LanguagesApiTest { // The service name still needs to be set manually List<OAuthScope> scopes = Arrays.asList(OAuthScope.DocumentRead, OAuthScope.DocumentWrite, OAuthScope.DocumentFile); private final IdentificationServiceV2 api = new IdentificationServiceV2("clientId", "clientSecret", scopes); @BeforeAll public static void setUp() { IdfyConfiguration.setBaseUrl("http://localhost:5000"); } /** * List languages * * Returns a list of supported languages. */ @Test public void listLanguagesTest() throws IdfyException, Exception { LanguageDetails[] response = api.listLanguages(); assertNotNull(response); } }
29.142857
120
0.742647
e4da4691994b1d2c016599faf4fb1faaafae44cd
268
/* * Copyright (c) 2020. Self learning and applying project advanced concepts through out. */ package com.spring.patterns.decorator; import java.math.BigDecimal; public abstract class PizzaIngredient extends Pizza { public abstract String getDescription(); }
22.333333
88
0.772388
a5c98f839062b245a9f612408609cf514c10d0b5
6,302
package com.dchip.door.smartdoorsdk.http; import com.dchip.door.smartdoorsdk.Bean.ApiGetAdvertisement; import com.dchip.door.smartdoorsdk.Bean.ApiGetCardListModel; import com.dchip.door.smartdoorsdk.Bean.ApiGetDeviceConfigModel; import com.dchip.door.smartdoorsdk.Bean.ApiGetPropManagement; import com.dchip.door.smartdoorsdk.Bean.AppUpdateModel; import com.dchip.door.smartdoorsdk.Bean.JsonResult; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * The interface Device api. * * @author zhangdeming * date 创建时间 2017/5/11 * description 描述类的功能 */ public interface DeviceApi { /** * 查询服务器上最新版本号 * * @param type 默认为1 * @return call */ @FormUrlEncoded @POST("mine/version") Call<JsonResult<AppUpdateModel>> checkVersion(@Field("type") int type); /** * 上传主控板的MAC码 * * @param mac the mac * @param versionName the version name * @param type the type * @return call */ @FormUrlEncoded @POST("maincontrol/uploadVersionInfo") Call<JsonResult<Object>> uploadAppVersion(@Field("mac") String mac, @Field("versionName") String versionName, @Field("type") int type); /** * 上传主控板的MAC码 和 网络类型 * * @param mac the mac * @param networkType the network type * @param smartType the smartType 1-门锁 2-水表 3-电表 4-车位地磁 5-垃圾桶 6 路灯 7智能家庭 * @return call */ @FormUrlEncoded @POST("maincontrol/upload") Call<JsonResult<Object>> uploadMac(@Field("mac") String mac,@Field("networkType") int networkType,@Field("smartType") int smartType); /** * 上传锁的数据 * * @param mac the mac * @param uid the uid * @return call */ @FormUrlEncoded @POST("lockcontrol/upload") Call<JsonResult<Object>> uploadLock(@Field("mac") String mac, @Field("uid") String uid, @Field("category") int category); /** * 锁板故障上报 * * @param uid the uid * @param type the type * @return call */ @FormUrlEncoded @POST("lockcontrol/reportFault") Call<JsonResult<Object>> reportFault(@Field("uid") String uid, @Field("type") int type); /** * appCrash 上传 * * @param mac the mac * @param errorContent the error content * @return call */ @FormUrlEncoded @POST("errorlog/uploadError") Call<JsonResult<Object>> reportCrash(@Field("mac") String mac, @Field("errorContent") String errorContent); /** * 上传是否写卡成功 * * @param mac the mac * @param status the status * @return call */ @FormUrlEncoded @POST("maincontrol/updateTerminalRecord") Call<JsonResult<Object>> reportWriteCardStatus(@Field("mac") String mac, @Field("status") int status); /** * appCrash 上传 * * @param uid the uid * @param cardId the card id * @param phone the phone * @return the call */ @FormUrlEncoded @POST("access/setOpenByCardRecord") Call<JsonResult<Object>> uploadCardId(@Field("uid") String uid, @Field("cardId") String cardId, @Field("id") String phone); /** * appCrash 上传 * * @param mac the mac * @param flows the flows * @return the call */ @FormUrlEncoded @POST("flow/save") Call<JsonResult<Object>> uploadFlow(@Field("mac") String mac, @Field("flows") String flows); /** * app更新失败上传 * * @param mac the mac * @param failReasion the fail reasion * @return the call */ @FormUrlEncoded @POST("maincontrol/uploadInstallFailReasion") Call<JsonResult<Object>> installFail(@Field("mac") String mac, @Field("failReasion") String failReasion); /** * app更新失败上传 * * @param mac the mac * @return the card list by mac */ @FormUrlEncoded @POST("access/getCardListByMac") Call<JsonResult<ApiGetCardListModel>> getCardListByMac(@Field("mac") String mac); /** * 获取锁的设置 * * @param mac the mac * @return the device config */ @FormUrlEncoded @POST("maincontrol/findMainInfo") Call<JsonResult<ApiGetDeviceConfigModel>> getDeviceConfig(@Field("mac") String mac); /** *业主信息写入终端状态 * * @param mac the mac * @param status the status * @return the call */ @FormUrlEncoded @POST("maincontrol/updateOnwerInfoTerminalRecord") Call<JsonResult<Object>> updateOnwerStatus(@Field("mac") String mac,@Field("status") int status); /** * 物业管理 * * @param mac the mac * @return the call */ @FormUrlEncoded @POST("areaconcat/pageDeviceList") Call<JsonResult<ApiGetPropManagement>> propertyManagement(@Field("mac") String mac); /** * 获取广告 * * @param mac the mac * @param type the type * @return the ad */ @FormUrlEncoded @POST("access/getDchipDeviceBanner") Call<JsonResult<ApiGetAdvertisement>> getAd(@Field("mac") String mac,@Field("style") int type); /** * 下载进度 * * @param mac the mac * @param progress the progress * @param type the type * @return the call */ @FormUrlEncoded @POST("maincontrol/downloadRecord") Call<JsonResult<Object>> uploadDownloadProgress(@Field("mac") String mac,@Field("current_progress") int progress,@Field("type") int type); /** * 上传是否按键开门成功 * * @param uid the uid * @return call */ @FormUrlEncoded @POST("access/setOpenByKeyRecord") Call<JsonResult<Object>> setOpenByKeyRecord(@Field("uid") String uid); /** * 长时间开门,超时异常后,检测到关门时上报。 * * @param uid the uid * @return call */ @FormUrlEncoded @POST("lockcontrol/updateNormallyOpenRecord") Call<JsonResult<Object>> doorTimeOutClose(@Field("uid") String uid); /** * 远程锁死 * * @param mac the mac * @return call */ @FormUrlEncoded @POST("maincontrol/isLock") Call<JsonResult<Integer>> deviceLock(@Field("mac") String mac); // /** // * 开锁成功返回 // * // * @param uid // * @return // */ // @FormUrlEncoded // @POST("lockcontrol/openResult") // Call<JsonResult<Object>> openResult(@Field("uid") String uid); }
25.722449
142
0.617582
74ffd73ad46328bfd52888edf232b072d9805f22
1,892
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.rest.filter; import java.io.IOException; import java.util.Locale; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.dspace.core.I18nUtil; import org.springframework.stereotype.Component; /** * This filter assures that when the dspace instance supports multiple languages * they are noted in the Content-Language Header of the response. Where * appropriate the single endpoint can set the Content-Language header directly * to note that the response is specific for a language * * @author Mykhaylo Boychuk (at 4science.it) */ @Component public class ContentLanguageHeaderResponseFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpServletResponse = (HttpServletResponse) response; Locale[] locales = I18nUtil.getSupportedLocales(); StringBuilder locsStr = new StringBuilder(); for (Locale locale : locales) { if (locsStr.length() > 0) { locsStr.append(","); } locsStr.append(locale.getLanguage()); } httpServletResponse.setHeader("Content-Language", locsStr.toString()); chain.doFilter(request, response); } @Override public void destroy() { } }
32.067797
93
0.727801
2f7afb8d6b2c21bb5297cc9af141922cc5fdee82
1,287
/* * Copyright 2017 Jan Sykora * * 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 io.github.resilience4j.bulkhead.event; /** * A BulkheadEvent which informs that a call has been finished. The event doesn't provide any * information on whether the call's execution was successful or not. */ public class BulkheadOnCallFinishedEvent extends AbstractBulkheadEvent { public BulkheadOnCallFinishedEvent(String bulkheadName) { super(bulkheadName); } @Override public Type getEventType() { return Type.CALL_FINISHED; } @Override public String toString() { return String.format( "%s: Bulkhead '%s' has finished a call.", getCreationTime(), getBulkheadName() ); } }
30.642857
93
0.696193
d8e473190dfe2fe5334d50b05430cde80a32d618
963
package org.jeecg.modules.walladvertisers.mapper; import java.util.List; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.toolkit.Constants; import org.apache.ibatis.annotations.Param; import org.jeecg.modules.walladvertisers.entity.WallAdvertisers; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @Description: wall_advertisers * @Author: jeecg-boot * @Date: 2021-05-25 * @Version: V1.0 */ public interface WallAdvertisersMapper extends BaseMapper<WallAdvertisers> { /** * 查询被逻辑删除的advertiser */ List<WallAdvertisers> selectLogicDeleted(@Param(Constants.WRAPPER) Wrapper<WallAdvertisers> wrapper); /** * 还原被逻辑删除的advertiser */ int revertLogicDeleted(@Param("advertiserIds") String advertiserIds, @Param("entity") WallAdvertisers entity); /** * 彻底删除被逻辑删除的advertiser */ int deleteLogicDeleted(@Param("advertiserIds") String advertiserIds); }
30.09375
114
0.750779
6c75eb39885362c6c79d88c305487dcad8b1287c
5,920
package de.imi.odmtoolbox.library; import de.imi.odmtoolbox.model.ODMCompareType; import de.imi.odmtoolbox.model.ODMComparedItem; import de.imi.odmtoolbox.model.ODMForm; import de.imi.odmtoolbox.model.ODMItem; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; /** * This class represents the data structure including all information for the * comparison. * */ public class ODMCompareTableStructure { HashMap<String, Integer> identicalFormWidth; HashMap<String, Integer> matchingFormWidth; HashMap<String, Integer> transformableFormWidth; HashMap<String, Integer> similarFormWidth; HashMap<String, Integer> comparableFormWidth; public ODMCompareTableStructure(Map<ODMCompareType, TreeSet<ODMComparedItem>> comparedItems) { if (comparedItems.get(ODMCompareType.IDENTICAL) != null && !comparedItems.get(ODMCompareType.IDENTICAL).isEmpty()) { identicalFormWidth = getFormWidths(comparedItems.get(ODMCompareType.IDENTICAL), ODMCompareType.IDENTICAL); } if (comparedItems.get(ODMCompareType.MATCHING) != null && !comparedItems.get(ODMCompareType.MATCHING).isEmpty()) { matchingFormWidth = getFormWidths(comparedItems.get(ODMCompareType.MATCHING), ODMCompareType.MATCHING); } if (comparedItems.get(ODMCompareType.TRANSFORMABLE) != null && !comparedItems.get(ODMCompareType.TRANSFORMABLE).isEmpty()) { transformableFormWidth = getFormWidths(comparedItems.get(ODMCompareType.TRANSFORMABLE), ODMCompareType.TRANSFORMABLE); } if (comparedItems.get(ODMCompareType.SIMILAR) != null && !comparedItems.get(ODMCompareType.SIMILAR).isEmpty()) { similarFormWidth = getFormWidths(comparedItems.get(ODMCompareType.SIMILAR), ODMCompareType.SIMILAR); } if (comparedItems.get(ODMCompareType.COMPARABLE) != null && !comparedItems.get(ODMCompareType.COMPARABLE).isEmpty()) { comparableFormWidth = getFormWidths(comparedItems.get(ODMCompareType.COMPARABLE), ODMCompareType.COMPARABLE); } } /** * Returns the width of the table which presents the comparison data for a * given {@link ODMCompareType} to the user. * * @param comparedItems The set of all * {@link ODMComparedItem ODMComparedItems}. * @param compareType The {@link ODMCompareType} for which the form width * should be returned. * @return The width of the table which presents the comparison data for a * given {@link ODMCompareType}. */ private HashMap<String, Integer> getFormWidths(TreeSet<ODMComparedItem> comparedItems, ODMCompareType compareType) { HashMap<ODMForm, HashSet<Integer>> formItemCount = new HashMap<ODMForm, HashSet<Integer>>(); TreeMap<ODMForm, List<ODMItem>> formItems = new TreeMap<>(); for (ODMComparedItem comparedItem : comparedItems) { switch (compareType) { case IDENTICAL: formItems = comparedItem.getIdenticalFormItems(); break; case MATCHING: formItems = comparedItem.getMatchingFormItems(); break; case TRANSFORMABLE: formItems = comparedItem.getTransformableFormItems(); break; case SIMILAR: formItems = comparedItem.getSimilarFormItems(); break; case COMPARABLE: formItems = comparedItem.getComparableFormItems(); break; } for (Map.Entry<ODMForm, List<ODMItem>> entry : formItems.entrySet()) { if (!formItemCount.containsKey(entry.getKey())) { HashSet<Integer> itemCount = new HashSet<Integer>(); formItemCount.put(entry.getKey(), itemCount); } if (!entry.getValue().isEmpty()) { formItemCount.get(entry.getKey()).add(entry.getValue().size()); } else { formItemCount.get(entry.getKey()).add(1); } } } for (HashSet<Integer> itemCount : formItemCount.values()) { Iterator<Integer> formWidthIterator = itemCount.iterator(); while (formWidthIterator.hasNext()) { Integer currentItemCount = formWidthIterator.next(); Iterator<Integer> formWidthCompareIterator = itemCount.iterator(); while (formWidthCompareIterator.hasNext()) { Integer compareItemCount = formWidthCompareIterator.next(); if (currentItemCount != compareItemCount && compareItemCount % currentItemCount == 0) { formWidthIterator.remove(); break; } } } } HashMap<String, Integer> formWidths = new HashMap<>(); for (Map.Entry<ODMForm, HashSet<Integer>> entry : formItemCount.entrySet()) { Integer formWidth = 1; for (Integer itemCount : entry.getValue()) { formWidth *= itemCount; } formWidths.put(entry.getKey().toString(), formWidth); } return formWidths; } public HashMap<String, Integer> getIdenticalFormWidth() { return identicalFormWidth; } public HashMap<String, Integer> getMatchingFormWidth() { return matchingFormWidth; } public HashMap<String, Integer> getTransformableFormWidth() { return transformableFormWidth; } public HashMap<String, Integer> getSimilarFormWidth() { return similarFormWidth; } public HashMap<String, Integer> getComparableFormWidth() { return comparableFormWidth; } }
43.529412
132
0.637331
3418608c78e30cc3e84e975649ce514d7fe50c43
1,314
package GoogleMaps; import com.google.maps.model.PlacesSearchResult; /** * Created by spyridons on 4/10/2017. */ public class GooglePlacesResultObject { private PlacesSearchResult result; private String url; private double lat; private double lng; public PlacesSearchResult getResult() { return result; } public void setResult(PlacesSearchResult result) { this.result = result; this.lat = result.geometry.location.lat; this.lng = result.geometry.location.lng; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GooglePlacesResultObject that = (GooglePlacesResultObject) o; if (Double.compare(that.lat, lat) != 0) return false; return Double.compare(that.lng, lng) == 0; } @Override public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(lat); result = (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(lng); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
24.333333
69
0.604262
72ff10cfdf600fd3d3e9486faefba249cb5dd7af
310
// Generated automatically from org.json.CookieList for testing purposes package org.json; import org.json.JSONObject; public class CookieList { public CookieList(){} public static JSONObject toJSONObject(String p0){ return null; } public static String toString(JSONObject p0){ return null; } }
23.846154
72
0.758065
d76f5a547b144c819ee7d7efe0db7bc47d44286b
598
package cn.gridlife.bzblibrary.b_viewpager.bean; import android.graphics.Bitmap; /** * Created by BZB on 2017/9/14. */ public class ViewPagerDataBean { int id; String title; Bitmap bitmap; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } }
15.736842
48
0.585284
c07af2f648bfdbb86169d11097824cfd72590a71
475
package kh75.day190801.class_core.entity; public class Car { public static void main(String[] args) { Bus bus = new Bus(20); bus.print(); } private int site = 4; // 座位数 Car() { System.out.println("载客量是" + site + "人"); } public void setSite(int site) { this.site = site; } public void print() { System.out.print("载客量是" + site + "人"); } } class Bus extends Car { Bus(int site) { //隐式调用 super() setSite(site); } }
15.322581
43
0.568421
71a72dc3c8b1adc4916eb28d57159c16984a5c6d
7,583
package mogp; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import java.util.HashMap; import java.util.Collections; /** * StandardMaintence class is a vanilla implementation of the * GPMaintance interface, where fitness used in tournament selection * is the aggregate fitness across test problems * * @author Jonathan Fieldsend * @version 1.1 */ public class StandardMaintenance implements GPMaintenance { Problem problem; Parameters parameters; ArraySolution bestFitnessSolution; MinimisationType type; /** * Constructor initialises with standard minimisation type (aggregate fitness) * * @param problem problem to be optimised * @param parameters algorithm parameters */ StandardMaintenance(Problem problem, Parameters parameters) { this(problem,parameters,MinimisationType.STANDARD); } /** * Constructor of maintenance object * * @param problem problem to be optimised * @param parameters algorithm parameters * @param type of mimisiation (e.g. standard or parsimonious) */ StandardMaintenance(Problem problem, Parameters parameters, MinimisationType type ) { this.problem = problem; this.parameters = parameters; this.type = type; } /** * @InheritDoc */ @Override public ArraySolution tournament(HashMap<Integer, ArraySolution> pop) { ArraySolution solution = getRandomParent(pop); for (int i=1; i<parameters.TOURNAMENT_SIZE; i++){ ArraySolution comparisonSolution = getRandomParent(pop); while (solution == comparisonSolution) comparisonSolution = getRandomParent(pop); if (comparisonSolution.getSumOfTestsFailed() < solution.getSumOfTestsFailed()){ solution = comparisonSolution; } } return solution; } /** * @InheritDoc */ @Override public ArraySolution negativeTournament(HashMap<Integer, ArraySolution> pop) { ArraySolution solution = getRandomParent(pop); while(solution == bestFitnessSolution) { solution = getRandomParent(pop); } for (int i=1; i<parameters.TOURNAMENT_SIZE; i++){ ArraySolution comparisonSolution = getRandomParent(pop); while ((comparisonSolution == solution) || (comparisonSolution == bestFitnessSolution)) comparisonSolution = getRandomParent(pop); if (comparisonSolution.getSumOfTestsFailed() > solution.getSumOfTestsFailed()){ solution = comparisonSolution; } else if (type.equals(MinimisationType.PARSIMONIOUS)) { if (comparisonSolution.getSumOfTestsFailed() == solution.getSumOfTestsFailed()){ if (comparisonSolution.size() > solution.size()) { solution = comparisonSolution; } } } } return solution; } /** * @InheritDoc */ @Override public int negativeTournamentKey(HashMap<Integer, ArraySolution> pop) { int solutionKey = getRandomParentKey(pop); while(pop.get(solutionKey) == bestFitnessSolution) { solutionKey = getRandomParentKey(pop); } for (int i=1; i<parameters.TOURNAMENT_SIZE; i++){ int comparisonSolutionKey = getRandomParentKey(pop); while ((comparisonSolutionKey == solutionKey) || (pop.get(comparisonSolutionKey) == bestFitnessSolution)) comparisonSolutionKey = getRandomParentKey(pop); if (pop.get(comparisonSolutionKey).getSumOfTestsFailed() > pop.get(solutionKey).getSumOfTestsFailed()){ solutionKey = comparisonSolutionKey; } else if (type.equals(MinimisationType.PARSIMONIOUS)) { if (pop.get(comparisonSolutionKey).getSumOfTestsFailed() == pop.get(solutionKey).getSumOfTestsFailed()){ if (pop.get(comparisonSolutionKey).size() > pop.get(solutionKey).size()) { solutionKey = comparisonSolutionKey; } } } } return solutionKey; } /** * @InheritDoc */ @Override public void evaluateFitness(HashMap<Integer, ArraySolution> pop, ArraySolution s) { boolean[] results = new boolean[problem.fitnessCases]; int f = 0; for (int i=0; i<problem.fitnessCases; i++ ){ InputVector.setInput(problem.inputs[i]); if (s.process() != problem.targets[i]){ f++; results[i] = false; } else { results[i] = true; } } // track best seen so far if (bestFitnessSolution==null){ bestFitnessSolution = s; } else if (f < bestFitnessSolution.getSumOfTestsFailed()) { bestFitnessSolution = s; } s.setTestsPassed(results); } /** * Method returns the a random member of the set pop * * @param set to select a random member from * @return random population member */ ArraySolution getRandomParent(HashMap<Integer, ArraySolution> pop){ return pop.get(RandomNumberGenerator.getRandom().nextInt(pop.size())); } /** * Method returns the a random key of the set pop - assumes keys are 0 to size()-1 * * @param set to select a random member from * @return random population member key */ int getRandomParentKey(HashMap<Integer, ArraySolution> pop){ return RandomNumberGenerator.getRandom().nextInt(pop.size()); } /** * @InheritDoc */ @Override public void generateNextSearchPopulation(HashMap<Integer, ArraySolution> pop, HashMap<Integer, ArraySolution> children) { // note, the keys in pop must not overlap with the keys in children HashMap<Integer,ArraySolution> combinedPopulation = new HashMap<>(pop); combinedPopulation.putAll(children); Set<ArraySolution> setOfBestSolutions = new HashSet<>(); setOfBestSolutions.add(bestFitnessSolution); // always take best while (setOfBestSolutions.size() < parameters.POPULATION_SIZE) { setOfBestSolutions.add(tournamentWithParsimony(combinedPopulation)); } // setOfBestSolutions now includes parameters.POPULATION_SIZE solutions to preserve int i=0; // replace the search population for (ArraySolution s : setOfBestSolutions){ pop.put(i,s); i++; } } ArraySolution tournamentWithParsimony(HashMap<Integer, ArraySolution> pop) { ArraySolution solution = getRandomParent(pop); for (int i=1; i<parameters.TOURNAMENT_SIZE; i++){ ArraySolution comparisonSolution = getRandomParent(pop); while (solution == comparisonSolution) comparisonSolution = getRandomParent(pop); if (comparisonSolution.getSumOfTestsFailed() < solution.getSumOfTestsFailed()){ solution = comparisonSolution; } else if (type.equals(MinimisationType.PARSIMONIOUS)) { if (comparisonSolution.getSumOfTestsFailed() == solution.getSumOfTestsFailed()){ if (comparisonSolution.size() < solution.size()) { solution = comparisonSolution; } } } } return solution; } }
36.109524
125
0.620994
5e0b04707848c1071c4c5ebcf2fd0b906656d90c
881
package com.michaelhradek.aurkitu.test.service.payloads; import com.michaelhradek.aurkitu.annotations.FlatBufferFieldOptions; import com.michaelhradek.aurkitu.annotations.FlatBufferTable; import com.michaelhradek.aurkitu.annotations.types.FieldType; import com.michaelhradek.aurkitu.test.dependency.LookupError; import com.michaelhradek.aurkitu.test.dependency.Wallet; import lombok.Data; import java.io.CharArrayReader; import java.util.List; import java.util.Map; @Data @FlatBufferTable public class Response { public static String IGNORED_STATIC_FIELD = "ignoredStaticField"; String userId; String username; @FlatBufferFieldOptions(fieldType = FieldType.ULONG) long createDate; Wallet wallet; List<LookupError> errors; List<Integer> codes; List<String> messages; Map<String, Character> dataMap; Map<String, List<String>> keys; }
28.419355
69
0.788876
3debec81d14ba2a81f11af2a9eb83a8e55b34eb6
10,979
/******************************************************************************* * Copyright (c) 2013-2018 Contributors to the Eclipse Foundation * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, * Version 2.0 which accompanies this distribution and is available at * http://www.apache.org/licenses/LICENSE-2.0.txt ******************************************************************************/ package org.locationtech.geowave.test; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.ArrayList; import org.apache.commons.exec.CommandLine; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.mojo.cassandra.AbstractCassandraMojo; import org.codehaus.mojo.cassandra.StartCassandraClusterMojo; import org.codehaus.mojo.cassandra.StartCassandraMojo; import org.codehaus.mojo.cassandra.StopCassandraClusterMojo; import org.codehaus.mojo.cassandra.StopCassandraMojo; import org.codehaus.plexus.util.FileUtils; import org.locationtech.geowave.core.store.GenericStoreFactory; import org.locationtech.geowave.core.store.StoreFactoryOptions; import org.locationtech.geowave.core.store.api.DataStore; import org.locationtech.geowave.core.store.util.ClasspathUtils; import org.locationtech.geowave.datastore.cassandra.CassandraStoreFactoryFamily; import org.locationtech.geowave.datastore.cassandra.config.CassandraOptions; import org.locationtech.geowave.datastore.cassandra.config.CassandraRequiredOptions; import org.locationtech.geowave.test.annotation.GeoWaveTestStore.GeoWaveStoreType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CassandraStoreTestEnvironment extends StoreTestEnvironment { private final static Logger LOGGER = LoggerFactory.getLogger(CassandraStoreTestEnvironment.class); private static final GenericStoreFactory<DataStore> STORE_FACTORY = new CassandraStoreFactoryFamily() .getDataStoreFactory(); private static CassandraStoreTestEnvironment singletonInstance = null; protected static final File TEMP_DIR = new File( System.getProperty("user.dir") + File.separator + "target", "cassandra_temp"); protected static final String NODE_DIRECTORY_PREFIX = "cassandra"; // for testing purposes, easily toggle between running the cassandra server // as multi-nodes or as standalone private static final boolean CLUSTERED_MODE = false; private static class StartGeoWaveCluster extends StartCassandraClusterMojo { private StartGeoWaveCluster() { super(); startWaitSeconds = 180; rpcAddress = "127.0.0.1"; rpcPort = 9160; jmxPort = 7199; startNativeTransport = true; nativeTransportPort = 9042; listenAddress = "127.0.0.1"; storagePort = 7000; stopPort = 8081; stopKey = "cassandra-maven-plugin"; maxMemory = 512; cassandraDir = new File( TEMP_DIR, NODE_DIRECTORY_PREFIX); logLevel = "ERROR"; project = new MavenProject(); project.setFile(cassandraDir); Field f; try { f = StartCassandraClusterMojo.class.getDeclaredField("clusterSize"); f.setAccessible(true); f.set( this, 4); f = AbstractCassandraMojo.class.getDeclaredField("pluginArtifact"); f.setAccessible(true); final DefaultArtifact a = new DefaultArtifact( "group", "artifact", VersionRange.createFromVersionSpec("version"), null, "type", null, new DefaultArtifactHandler()); a.setFile(cassandraDir); f.set( this, a); f = AbstractCassandraMojo.class.getDeclaredField("pluginDependencies"); f.setAccessible(true); f.set( this, new ArrayList<>()); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InvalidVersionSpecificationException e) { LOGGER.error( "Unable to initialize start cassandra cluster", e); } } @Override protected CommandLine newServiceCommandLine( final File cassandraDir, final String listenAddress, final String rpcAddress, final BigInteger initialToken, final String[] seeds, final boolean jmxRemoteEnabled, final int jmxPort ) throws IOException { return super.newServiceCommandLine( cassandraDir, listenAddress, rpcAddress, BigInteger.valueOf(initialToken.longValue()), seeds, false, jmxPort); } @Override protected void createCassandraJar( final File jarFile, final String mainClass, final File cassandraDir ) throws IOException { ClasspathUtils.setupPathingJarClassPath( jarFile, mainClass, this.getClass(), new File( cassandraDir, "conf").toURI().toURL()); } public void start() { try { super.execute(); } catch (MojoExecutionException | MojoFailureException e) { LOGGER.error( "Unable to start cassandra cluster", e); } } } private static class StopGeoWaveCluster extends StopCassandraClusterMojo { private StopGeoWaveCluster() { super(); rpcPort = 9160; stopPort = 8081; stopKey = "cassandra-maven-plugin"; Field f; try { f = StopCassandraClusterMojo.class.getDeclaredField("clusterSize"); f.setAccessible(true); f.set( this, 4); f = StopCassandraClusterMojo.class.getDeclaredField("rpcAddress"); f.setAccessible(true); f.set( this, "127.0.0.1"); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { LOGGER.error( "Unable to initialize stop cassandra cluster", e); } } public void stop() { try { super.execute(); } catch (MojoExecutionException | MojoFailureException e) { LOGGER.error( "Unable to stop cassandra cluster", e); } } } private static class StartGeoWaveStandalone extends StartCassandraMojo { private StartGeoWaveStandalone() { super(); startWaitSeconds = 180; rpcAddress = "127.0.0.1"; rpcPort = 9160; jmxPort = 7199; startNativeTransport = true; nativeTransportPort = 9042; listenAddress = "127.0.0.1"; storagePort = 7000; stopPort = 8081; stopKey = "cassandra-maven-plugin"; maxMemory = 512; cassandraDir = TEMP_DIR; logLevel = "ERROR"; project = new MavenProject(); project.setFile(cassandraDir); Field f; try { f = AbstractCassandraMojo.class.getDeclaredField("pluginArtifact"); f.setAccessible(true); final DefaultArtifact a = new DefaultArtifact( "group", "artifact", VersionRange.createFromVersionSpec("version"), null, "type", null, new DefaultArtifactHandler()); a.setFile(cassandraDir); f.set( this, a); f = AbstractCassandraMojo.class.getDeclaredField("pluginDependencies"); f.setAccessible(true); f.set( this, new ArrayList<>()); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | InvalidVersionSpecificationException e) { LOGGER.error( "Unable to initialize start cassandra cluster", e); } } @Override protected void createCassandraJar( final File jarFile, final String mainClass, final File cassandraDir ) throws IOException { ClasspathUtils.setupPathingJarClassPath( jarFile, mainClass, this.getClass(), new File( cassandraDir, "conf").toURI().toURL()); } public void start() { try { super.execute(); } catch (MojoExecutionException | MojoFailureException e) { LOGGER.error( "Unable to start cassandra cluster", e); } } } private static class StopGeoWaveStandalone extends StopCassandraMojo { public StopGeoWaveStandalone() { super(); rpcPort = 9160; stopPort = 8081; stopKey = "cassandra-maven-plugin"; Field f; try { f = StopCassandraMojo.class.getDeclaredField("rpcAddress"); f.setAccessible(true); f.set( this, "127.0.0.1"); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { LOGGER.error( "Unable to initialize stop cassandra cluster", e); } } public void stop() { try { super.execute(); } catch (MojoExecutionException | MojoFailureException e) { LOGGER.error( "Unable to stop cassandra cluster", e); } } } public static synchronized CassandraStoreTestEnvironment getInstance() { if (singletonInstance == null) { singletonInstance = new CassandraStoreTestEnvironment(); } return singletonInstance; } private boolean running = false; private CassandraStoreTestEnvironment() {} @Override protected void initOptions( final StoreFactoryOptions options ) { final CassandraRequiredOptions cassandraOpts = (CassandraRequiredOptions) options; cassandraOpts.setContactPoint("127.0.0.1"); ((CassandraOptions) cassandraOpts.getStoreOptions()).setBatchWriteSize(5); } @Override protected GenericStoreFactory<DataStore> getDataStoreFactory() { return STORE_FACTORY; } @Override public void setup() { if (!running) { if (TEMP_DIR.exists()) { cleanTempDir(); } if (!TEMP_DIR.mkdirs()) { LOGGER.warn("Unable to create temporary cassandra directory"); } if (CLUSTERED_MODE) { new StartGeoWaveCluster().start(); } else { new StartGeoWaveStandalone().start(); } running = true; } } @Override public void tearDown() { if (running) { if (CLUSTERED_MODE) { new StopGeoWaveCluster().stop(); } else { new StopGeoWaveStandalone().stop(); } running = false; } try { // it seems sometimes one of the nodes processes is still holding // onto a file, so wait a short time to be able to reliably clean up Thread.sleep(1500); } catch (final InterruptedException e) { LOGGER.warn( "Unable to sleep waiting to delete directory", e); } cleanTempDir(); } private static void cleanTempDir() { try { FileUtils.deleteDirectory(TEMP_DIR); } catch (final IOException e) { LOGGER.warn( "Unable to delete temp cassandra directory", e); } } @Override protected GeoWaveStoreType getStoreType() { return GeoWaveStoreType.CASSANDRA; } @Override public TestEnvironment[] getDependentEnvironments() { return new TestEnvironment[] {}; } }
26.583535
107
0.697696
0382921d418b241b9980900c333b2b175e38b04f
1,406
package exercises.dependencyinjection; import com.commercetools.sunrise.framework.controllers.SunriseContentController; import com.commercetools.sunrise.framework.controllers.WithContent; import com.commercetools.sunrise.framework.template.engine.ContentRenderer; import common.BlankPageContent; import play.mvc.Result; import javax.annotation.Nullable; import javax.inject.Inject; import java.util.concurrent.CompletionStage; /** * Access http://localhost:9000/dependencyinjection */ public final class DependencyInjectionController extends SunriseContentController implements WithContent { private final ClassA classA; private final ClassB classB; @Inject public DependencyInjectionController(final ContentRenderer contentRenderer, final ClassA classA, final ClassB classB) { super(contentRenderer); this.classA = classA; this.classB = classB; } public CompletionStage<Result> show() { final BlankPageContent pageContent = new BlankPageContent(); pageContent.put("instanceIdInClassA", classA.getInstanceId()); pageContent.put("instanceIdInClassB", classB.getInstanceId()); return okResultWithPageContent(pageContent); } @Override public String getTemplateName() { return "exercises/dependency-injection"; } }
33.47619
106
0.721906
6bdbe9a0952ad2e3a83866040367dc45485bda41
2,074
package scratch.kevin.ucerf3; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.opensha.commons.data.CSVFile; import org.opensha.commons.geo.Location; import org.opensha.commons.util.FaultUtils; import org.opensha.refFaultParamDb.vo.FaultSectionPrefData; import org.opensha.sha.faultSurface.FaultSection; import scratch.UCERF3.enumTreeBranches.DeformationModels; import scratch.UCERF3.enumTreeBranches.FaultModels; import scratch.UCERF3.utils.DeformationModelFetcher; import scratch.UCERF3.utils.UCERF3_DataUtils; public class SubSectMidpointFinder { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // int subSectIndex = 2166; FaultModels fm = FaultModels.FM3_2; File file = new File("D:\\Documents\\temp\\fm3_2_subSect_midpts.csv"); CSVFile<String> csv = new CSVFile<String>(true); csv.addLine("Sub Section Index", "Sub Section Name", "Parent Section Name", "Parent Section ID", "Midpoint Lat", "Midpoint Lon"); List<? extends FaultSection> subSects = new DeformationModelFetcher( fm, DeformationModels.GEOLOGIC, UCERF3_DataUtils.DEFAULT_SCRATCH_DATA_DIR, 0.1).getSubSectionList(); for (FaultSection subSect : subSects) { Location midPt = FaultUtils.resampleTrace(subSect.getFaultTrace(), 11).get(5); csv.addLine(subSect.getSectionId()+"", subSect.getName(), subSect.getParentSectionName(), subSect.getParentSectionId()+"",midPt.getLatitude()+"", midPt.getLongitude()+""); } csv.writeToFile(file); // FaultSectionPrefData subSect = subSects.get(subSectIndex); // // System.out.println("Name: "+subSect.getName()); // System.out.println("Parent Name: "+subSect.getParentSectionName()); // System.out.println("Parent ID: "+subSect.getParentSectionId()); // Location midPt = FaultUtils.resampleTrace(subSect.getFaultTrace(), 11).get(5); // // System.out.println("Midpoint: "+midPt.getLatitude()+", "+midPt.getLongitude()); } }
37.035714
99
0.728544
b6caac7df0fb5a3a6b18acea3e5b7d746ded34e1
1,359
package ca.gc.aafc.dina.search.messaging.producer; import ca.gc.aafc.dina.search.common.config.YAMLConfigProperties; import ca.gc.aafc.dina.search.messaging.types.DocumentOperationNotification; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; /** * RabbitMQ based message producer */ @Service @ConditionalOnProperty(prefix = "messaging", name = "isProducer", havingValue = "true") public class RabbitMQMessageProducer implements MessageProducer { private static final String EXCHANGE = "exchange"; private static final String ROUTING_KEY = "routingkey"; private final RabbitTemplate rabbitTemplate; private final String mqExchange; private final String mqRoutingKey; @Autowired public RabbitMQMessageProducer(RabbitTemplate rabbitTemplate, YAMLConfigProperties yamlConfigProps) { this.rabbitTemplate = rabbitTemplate; mqExchange = yamlConfigProps.getRabbitmq().get(EXCHANGE); mqRoutingKey = yamlConfigProps.getRabbitmq().get(ROUTING_KEY); } public void send(DocumentOperationNotification documentOperationNotification) { rabbitTemplate.convertAndSend(mqExchange, mqRoutingKey, documentOperationNotification); } }
36.72973
103
0.816041
cce6a05d7a0ad567548f800999319f6b85b47997
1,771
package io.chengine.pipeline.action; import io.chengine.message.ActionResponse; import java.util.function.Consumer; import java.util.function.Supplier; /** * * @param <T> - a context object for passing data between chain methods */ public interface StageAction<T> extends ActionResponse { // ============================================================================================================== // Static Generators // ============================================================================================================== /** * Creates a {@link FireStageAction} * * @param response - an {@link ActionResponse} supplier * @return {@link FireStageAction} */ static <T> StageAction<T> doAction(Supplier<ActionResponse> response) { return new FireStageAction<>(response); } /** * Creates a {@link CheckStageAction} * * @param check - a {@link StageCheck} supplier * @return {@link CheckStageAction} */ static <T> CheckStageAction<T> checkStage(Supplier<StageCheck<T>> check) { return new CheckStageAction<>(check); } // ============================================================================================================== // Error handling methods // ============================================================================================================== StageAction<T> onErrorTerminate(Consumer<Throwable> error, Supplier<ActionResponse> response); StageAction<T> onErrorTerminate(Consumer<Throwable> error); StageAction<T> onErrorResume(Consumer<Throwable> error, Supplier<ActionResponse> response); StageAction<T> onErrorReturn(Consumer<Throwable> error, Supplier<ActionResponse> response); }
34.72549
117
0.511575
a2efbd38c89d535f31fbfa4927449daaddb69f38
259
package top.yang.mapper; import org.apache.ibatis.annotations.Mapper; /** * @author pride * @description 针对表【sys_user(用户信息表)】的数据库操作Mapper * @createDate 2022-01-10 21:07:29 * @Entity generator.domain.SysUser */@Mapper public interface SysUserMapper { }
14.388889
47
0.749035
3b3bd9b2de98f9bd2715ab38690bf8a2c6e9a016
1,053
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.freebasicacc.services; import java.sql.Connection; import com.freebasicacc.dao.SequenceDAOImpl; /** * * @author benzyaa */ public class SequenceService { private static final SequenceService sequenceService = new SequenceService(); private SequenceService(){ } public static SequenceService getInstance(){ return sequenceService; } public synchronized String nextVal(String sequenceName,Connection connection) throws Exception{ SequenceDAOImpl sequeceDAO = SequenceDAOImpl.getInstance(); String nextVal = sequeceDAO.nextVal(sequenceName, connection); SequenceDAOImpl.deleteInstance(); return nextVal; } public synchronized void reset(String sequenceName,Connection connection) throws Exception{ SequenceDAOImpl sequeceDAO = SequenceDAOImpl.getInstance(); sequeceDAO.reset(sequenceName, connection); SequenceDAOImpl.deleteInstance(); } }
32.90625
99
0.734093
e85bbb29183731f715276ef5ce458c7f94c51572
22,807
package util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import jodd.http.Cookie; /** * 封装了一些采用HttpClient发送HTTP请求的方法 * @see 本工具所采用的是最新的HttpComponents-Client-4.2.1 */ public class HttpClientUtil { private HttpClientUtil(){} private static Log logger = LogFactory.getLog(HttpClientUtil.class); /** * 发送HTTP_GET请求 * @see 该方法会自动关闭连接,释放资源 * @param requestURL 请求地址(含参数) * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码 * @return 远程主机响应正文 */ public static String sendGetRequest(HttpGet httpGet, String decodeCharset,HttpHost proxy){ long responseLength = 0; //响应长度 String responseContent = null; //响应内容 HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例 // HttpGet httpGet = new HttpGet(reqURL); //创建org.apache.http.client.methods.HttpGet try{ org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(30000) .setConnectionRequestTimeout(30000).setConnectTimeout(30000);//设置请求和传输超时时间 if (null != proxy) { requestConfigBuilder.setProxy(proxy); } httpGet.setConfig(requestConfigBuilder.build()); HttpResponse response = httpClient.execute(httpGet); //执行GET请求 HttpEntity entity = response.getEntity(); //获取响应实体 if(null != entity){ responseLength = entity.getContentLength(); responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset); EntityUtils.consume(entity); //Consume response content } // System.out.println("请求地址: " + httpGet.getURI()); // System.out.println("响应状态: " + response.getStatusLine()); // System.out.println("响应长度: " + responseLength); // System.out.println("响应内容: " + responseContent); }catch(ClientProtocolException e){ logger.debug("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e); }catch(ParseException e){ logger.debug(e.getMessage(), e); }catch(IOException e){ logger.debug("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e); }finally{ httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源 } return responseContent; } /** * 发送HTTP_POST请求 * @see 该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法 * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code> * @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要 */ public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder){ return sendPostRequest(reqURL, sendData, isEncoder, null, null); } /** * 发送HTTP_POST请求 * @see 该方法会自动关闭连接,释放资源 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code> * @param reqURL 请求地址 * @param sendData 请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中 * @param isEncoder 请求数据是否需要encodeCharset编码,true为需要 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码 * @return 远程主机响应正文 */ public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){ String responseContent = null; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(reqURL); //httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); try{ if(isEncoder){ List<NameValuePair> formParams = new ArrayList<NameValuePair>(); for(String str : sendData.split("&")){ formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1))); } httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset))); }else{ httpPost.setEntity(new StringEntity(sendData)); } HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (null != entity) { responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset); EntityUtils.consume(entity); } }catch(Exception e){ logger.debug("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e); }finally{ httpClient.getConnectionManager().shutdown(); } return responseContent; } /** * 发送HTTP_POST请求 * @see 该方法会自动关闭连接,释放资源 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code> * @param reqURL 请求地址 * @param sendData 请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中 * @param isEncoder 请求数据是否需要encodeCharset编码,true为需要 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码 * @return 远程主机响应正文 */ public static String sendPostRequest(HttpPost httpPost, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){ return sendPostRequest(httpPost, sendData, isEncoder, encodeCharset, decodeCharset,null,null); } /** * 发送HTTP_POST请求 * @see 该方法会自动关闭连接,释放资源 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code> * @param reqURL 请求地址 * @param sendData 请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中 * @param isEncoder 请求数据是否需要encodeCharset编码,true为需要 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码 * @return 远程主机响应正文 */ public static String sendPostRequest(HttpPost httpPost, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset,HttpHost proxy,List<Cookie> cookies){ String responseContent = null; //HttpClient httpClient = new DefaultHttpClient(); CloseableHttpClient httpClient = HttpClients.createDefault(); // HttpPost httpPost = new HttpPost(reqURL); //httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); try{ org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(30000) .setConnectionRequestTimeout(30000).setConnectTimeout(30000);//设置请求和传输超时时间 if (null != proxy) { requestConfigBuilder.setProxy(proxy); } httpPost.setConfig(requestConfigBuilder.build()); if(isEncoder){ List<NameValuePair> formParams = new ArrayList<NameValuePair>(); for(String str : sendData.split("&")){ formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1))); } httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset))); }else{ httpPost.setEntity(new StringEntity(sendData)); } HttpResponse response = httpClient.execute(httpPost); Header[] headers = response.getHeaders("set-cookie"); if(ArrayUtils.isNotEmpty(headers) && cookies!=null){ for(Header h:headers){ //System.out.println("Cookie Value=============="+h.getValue()); jodd.http.Cookie joddCookie = new jodd.http.Cookie(h.getValue()); //System.out.println("rp=="+joddCookie.getName()+"===="+joddCookie.getValue()); cookies.add(joddCookie); } } HttpEntity entity = response.getEntity(); if (null != entity) { responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset); EntityUtils.consume(entity); } }catch(Exception e){ logger.debug("与[" + httpPost + "]通信过程中发生异常,堆栈信息如下", e); }finally{ httpClient.getConnectionManager().shutdown(); } return responseContent; } /** * 发送HTTP_POST请求 * @see 该方法会自动关闭连接,释放资源 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code> * @param reqURL 请求地址 * @param params 请求参数 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码 * @return 远程主机响应正文 */ public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){ String responseContent = null; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(reqURL); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列 for(Map.Entry<String,String> entry : params.entrySet()){ formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try{ httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (null != entity) { responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset); EntityUtils.consume(entity); } }catch(Exception e){ logger.debug("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e); }finally{ httpClient.getConnectionManager().shutdown(); } return responseContent; } /** * 发送HTTPS_POST请求 * @see 该方法为<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的简化方法 * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code> */ public static String sendPostSSLRequest(String reqURL, Map<String, String> params){ return sendPostSSLRequest(reqURL, params, null, null); } /** * 发送HTTPS_POST请求 * @see 该方法会自动关闭连接,释放资源 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code> * @param reqURL 请求地址 * @param params 请求参数 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码 * @return 远程主机响应正文 */ public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){ String responseContent = ""; HttpClient httpClient = new DefaultHttpClient(); X509TrustManager xtm = new X509TrustManager(){ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() {return null;} }; try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{xtm}, null); SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); HttpPost httpPost = new HttpPost(reqURL); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); for(Map.Entry<String,String> entry : params.entrySet()){ formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (null != entity) { responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset); EntityUtils.consume(entity); } } catch (Exception e) { logger.debug("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e); } finally { httpClient.getConnectionManager().shutdown(); } return responseContent; } /** * 发送HTTP_POST请求 * @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code> * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒 * @param reqURL 请求地址 * @param params 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code> * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code> */ public static String sendPostRequestByJava(String reqURL, Map<String, String> params){ StringBuilder sendData = new StringBuilder(); for(Map.Entry<String, String> entry : params.entrySet()){ sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } if(sendData.length() > 0){ sendData.setLength(sendData.length() - 1); //删除最后一个&符号 } return sendPostRequestByJava(reqURL, sendData.toString()); } /** * 发送HTTP_POST请求 * @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code> * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒 * @param reqURL 请求地址 * @param sendData 发送到远程主机的正文数据 * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code> */ public static String sendPostRequestByJava(String reqURL, String sendData){ HttpURLConnection httpURLConnection = null; OutputStream out = null; //写 InputStream in = null; //读 int httpStatusCode = 0; //远程主机响应的HTTP状态码 try{ URL sendUrl = new URL(reqURL); httpURLConnection = (HttpURLConnection)sendUrl.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); //指示应用程序要将数据写入URL连接,其值默认为false httpURLConnection.setUseCaches(false); httpURLConnection.setConnectTimeout(30000); //30秒连接超时 httpURLConnection.setReadTimeout(30000); //30秒读取超时 out = httpURLConnection.getOutputStream(); out.write(sendData.toString().getBytes()); //清空缓冲区,发送数据 out.flush(); //获取HTTP状态码 httpStatusCode = httpURLConnection.getResponseCode(); in = httpURLConnection.getInputStream(); byte[] byteDatas = new byte[in.available()]; in.read(byteDatas); return new String(byteDatas) + "`" + httpStatusCode; }catch(Exception e){ logger.debug(e.getMessage()); return "Failed`" + httpStatusCode; }finally{ if(out != null){ try{ out.close(); }catch (Exception e){ logger.debug("关闭输出流时发生异常,堆栈信息如下", e); } } if(in != null){ try{ in.close(); }catch(Exception e){ logger.debug("关闭输入流时发生异常,堆栈信息如下", e); } } if(httpURLConnection != null){ httpURLConnection.disconnect(); httpURLConnection = null; } } } /** * https posp请求,可以绕过证书校验 * @param url * @param params * @return */ public static final String sendHttpsRequestByPost(String url, Map<String, String> params) { String responseContent = null; HttpClient httpClient = new DefaultHttpClient(); //创建TrustManager X509TrustManager xtm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return null; } }; //这个好像是HOST验证 X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } public void verify(String arg0, SSLSocket arg1) throws IOException {} public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {} public void verify(String arg0, X509Certificate arg1) throws SSLException {} }; try { //TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext SSLContext ctx = SSLContext.getInstance("TLS"); //使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用 ctx.init(null, new TrustManager[] { xtm }, null); //创建SSLSocketFactory SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); socketFactory.setHostnameVerifier(hostnameVerifier); //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上 httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443)); HttpPost httpPost = new HttpPost(url); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数 for (Map.Entry<String, String> entry : params.entrySet()) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); // 获取响应实体 if (entity != null) { responseContent = EntityUtils.toString(entity, "UTF-8"); } } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 httpClient.getConnectionManager().shutdown(); } return responseContent; } /** * 发送HTTP_POST请求,json格式数据 * @param url * @param body * @return * @throws Exception */ public static String sendPostByJson(String url, String body) throws Exception { CloseableHttpClient httpclient = HttpClients.custom().build(); HttpPost post = null; String resData = null; CloseableHttpResponse result = null; try { post = new HttpPost(url); HttpEntity entity2 = new StringEntity(body, Consts.UTF_8); post.setConfig(RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build()); post.setHeader("Content-Type", "application/json"); post.setEntity(entity2); result = httpclient.execute(post); if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) { resData = EntityUtils.toString(result.getEntity()); } } finally { if (result != null) { result.close(); } if (post != null) { post.releaseConnection(); } httpclient.close(); } return resData; } }
43.524809
177
0.64353
22216b9c3718b6e3607a83289088c2a14fe26b6f
6,540
/* * SOL005 - NS Lifecycle Management Interface * SOL005 - NS Lifecycle Management Interface IMPORTANT: Please note that this file might be not aligned to the current version of the ETSI Group Specification it refers to and has not been approved by the ETSI NFV ISG. In case of discrepancies the published ETSI Group Specification takes precedence. Please report bugs to https://forge.etsi.org/bugzilla/buglist.cgi?component=Nfv-Openapis * * OpenAPI spec version: 1.1.0-impl:etsi.org:ETSI_NFV_OpenAPI:1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package it.nextworks.openapi.msno.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * This type represents the information used to scale an NS instance by one or more scaling steps, with respect to a particular NS scaling aspect. Performing a scaling step means increasing/decreasing the capacity of an NS instance in a discrete manner, i.e. moving from one NS scale level to another. The NS scaling aspects and their corresponding NS scale levels applicable to the NS instance are declared in the NSD. */ @ApiModel(description = "This type represents the information used to scale an NS instance by one or more scaling steps, with respect to a particular NS scaling aspect. Performing a scaling step means increasing/decreasing the capacity of an NS instance in a discrete manner, i.e. moving from one NS scale level to another. The NS scaling aspects and their corresponding NS scale levels applicable to the NS instance are declared in the NSD. ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-11-08T16:52:33.422+01:00") public class ScaleNsByStepsData { /** * The scaling direction. Possible values are: - SCALE_IN - SCALE_OUT. */ @JsonAdapter(ScalingDirectionEnum.Adapter.class) public enum ScalingDirectionEnum { IN("SCALE_IN"), OUT("SCALE_OUT"); private String value; ScalingDirectionEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static ScalingDirectionEnum fromValue(String text) { for (ScalingDirectionEnum b : ScalingDirectionEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<ScalingDirectionEnum> { @Override public void write(final JsonWriter jsonWriter, final ScalingDirectionEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public ScalingDirectionEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return ScalingDirectionEnum.fromValue(String.valueOf(value)); } } } @SerializedName("scalingDirection") private ScalingDirectionEnum scalingDirection = null; @SerializedName("aspectId") private String aspectId = null; @SerializedName("numberOfSteps") private Integer numberOfSteps = null; public ScaleNsByStepsData scalingDirection(ScalingDirectionEnum scalingDirection) { this.scalingDirection = scalingDirection; return this; } /** * The scaling direction. Possible values are: - SCALE_IN - SCALE_OUT. * @return scalingDirection **/ @ApiModelProperty(required = true, value = "The scaling direction. Possible values are: - SCALE_IN - SCALE_OUT. ") public ScalingDirectionEnum getScalingDirection() { return scalingDirection; } public void setScalingDirection(ScalingDirectionEnum scalingDirection) { this.scalingDirection = scalingDirection; } public ScaleNsByStepsData aspectId(String aspectId) { this.aspectId = aspectId; return this; } /** * The aspect of the NS that is requested to be scaled, as declared in the NSD. * @return aspectId **/ @ApiModelProperty(required = true, value = "The aspect of the NS that is requested to be scaled, as declared in the NSD. ") public String getAspectId() { return aspectId; } public void setAspectId(String aspectId) { this.aspectId = aspectId; } public ScaleNsByStepsData numberOfSteps(Integer numberOfSteps) { this.numberOfSteps = numberOfSteps; return this; } /** * The number of scaling steps to be performed. Defaults to 1. * @return numberOfSteps **/ @ApiModelProperty(value = "The number of scaling steps to be performed. Defaults to 1. ") public Integer getNumberOfSteps() { return numberOfSteps; } public void setNumberOfSteps(Integer numberOfSteps) { this.numberOfSteps = numberOfSteps; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScaleNsByStepsData scaleNsByStepsData = (ScaleNsByStepsData) o; return Objects.equals(this.scalingDirection, scaleNsByStepsData.scalingDirection) && Objects.equals(this.aspectId, scaleNsByStepsData.aspectId) && Objects.equals(this.numberOfSteps, scaleNsByStepsData.numberOfSteps); } @Override public int hashCode() { return Objects.hash(scalingDirection, aspectId, numberOfSteps); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ScaleNsByStepsData {\n"); sb.append(" scalingDirection: ").append(toIndentedString(scalingDirection)).append("\n"); sb.append(" aspectId: ").append(toIndentedString(aspectId)).append("\n"); sb.append(" numberOfSteps: ").append(toIndentedString(numberOfSteps)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
34.603175
444
0.720336
49848334bb4776f2e139fe8a584891ad67b53451
502
package com.rainbowcard.client.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; /** * Created by gc on 2017-1-6. */ public class ProvinceEntity { @Expose @SerializedName("province_name") public String name; @Expose @SerializedName("province_pre_car_num") public String provinceNum; @Expose @SerializedName("city_list") public ArrayList<CityModel2> cityList; }
22.818182
51
0.703187
f948516198de71e709de2ef9c2d2e7b08fe11096
1,951
package cn.org.hentai.dns.protocol.entity; import cn.org.hentai.dns.util.ByteUtils; import cn.org.hentai.dns.util.IPUtils; import java.net.Inet6Address; /** * Created by matrixy on 2019/4/23. * 响应消息的资源记录,一般为域名所对应的IP或CNAME等 */ public class ResourceRecord { public String name; public int type; // public int class; // 固定值就不声明了 public int ttl; public int dlen; public long ipv4; // 如果type == TYPE_A,则使用IP作为data,省得转来转去 public Inet6Address ipv6; // 同上 public byte[] data; public ResourceRecord(String name, int type, int ttl, long ipv4) { this.name = name; this.type = type; this.ttl = ttl; this.ipv4 = ipv4; this.dlen = 4; } public ResourceRecord(String name, int type, int ttl, Inet6Address ipv6) { this.name = name; this.type = type; this.ttl = ttl; this.ipv6 = ipv6; this.dlen = 16; } public ResourceRecord(String name, int type, int ttl, byte[] data) { this.name = name; this.type = type; this.ttl = ttl; this.data = data; this.dlen = data.length; } public String getAnswerString() { if (type == Message.TYPE_A) { long a = (ipv4 >> 24) & 0xff, b = (ipv4 >> 16) & 0xff, c = (ipv4 >> 8) & 0xff, d = ipv4 & 0xff; return a + "." + b + "." + c + "." + d; } else if (type == Message.TYPE_AAAA) { return ipv6.toString(); } else { return ByteUtils.toString(data); } } public String toString() { if (type == Message.TYPE_A) return "[" + IPUtils.fromInteger(this.ipv4) + "]"; else if (type == Message.TYPE_AAAA) return "[" + ipv6.toString() + "]"; else return "[" + ByteUtils.toString(data) + "]"; } }
25.337662
86
0.520759
9fde11e404a230a527ad7b71fd40eb5b3b15f0eb
433
package uk.ac.ebi.spot.goci; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class SearchApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SearchApplication.class, args); } }
33.307692
73
0.819861
6bba2ea8bbbea0cab08964d18f0a0753c5441827
7,456
/* * 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.ambari.server.checks; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import org.apache.ambari.server.configuration.Configuration; import org.apache.ambari.server.controller.PrereqCheckRequest; import org.apache.ambari.server.orm.dao.RepositoryVersionDAO; import org.apache.ambari.server.orm.entities.RepositoryVersionEntity; import org.apache.ambari.server.state.Cluster; import org.apache.ambari.server.state.Clusters; import org.apache.ambari.server.state.RepositoryType; import org.apache.ambari.server.state.Service; import org.apache.ambari.server.state.ServiceComponent; import org.apache.ambari.server.state.ServiceComponentHost; import org.apache.ambari.server.state.StackId; import org.apache.ambari.server.state.repository.ClusterVersionSummary; import org.apache.ambari.server.state.repository.VersionDefinitionXml; import org.apache.ambari.server.state.stack.PrereqCheckStatus; import org.apache.ambari.server.state.stack.PrerequisiteCheck; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Provider; /** * Tests {@link HiveMultipleMetastoreCheck} */ @RunWith(MockitoJUnitRunner.class) public class HiveMultipleMetastoreCheckTest { private final Clusters m_clusters = Mockito.mock(Clusters.class); private final HiveMultipleMetastoreCheck m_check = new HiveMultipleMetastoreCheck(); private final RepositoryVersionDAO repositoryVersionDAO = Mockito.mock( RepositoryVersionDAO.class); @Mock private ClusterVersionSummary m_clusterVersionSummary; @Mock private VersionDefinitionXml m_vdfXml; @Mock private RepositoryVersionEntity m_repositoryVersion; final Map<String, Service> m_services = new HashMap<>(); /** * */ @Before public void setup() throws Exception { m_check.clustersProvider = new Provider<Clusters>() { @Override public Clusters get() { return m_clusters; } }; Configuration config = Mockito.mock(Configuration.class); m_check.config = config; Mockito.when(m_repositoryVersion.getVersion()).thenReturn("1.0.0.0-1234"); Mockito.when(m_repositoryVersion.getStackId()).thenReturn(new StackId("HDP", "1.0")); m_services.clear(); Mockito.when(m_repositoryVersion.getType()).thenReturn(RepositoryType.STANDARD); Mockito.when(m_repositoryVersion.getRepositoryXml()).thenReturn(m_vdfXml); Mockito.when(m_vdfXml.getClusterSummary(Mockito.any(Cluster.class))).thenReturn(m_clusterVersionSummary); Mockito.when(m_clusterVersionSummary.getAvailableServiceNames()).thenReturn(m_services.keySet()); } /** * Tests that the check is applicable when hive is installed. * * @throws Exception */ @Test public void testIsApplicable() throws Exception { final Cluster cluster = Mockito.mock(Cluster.class); Mockito.when(cluster.getClusterId()).thenReturn(1L); Mockito.when(m_clusters.getCluster("cluster")).thenReturn(cluster); Mockito.when(cluster.getServices()).thenReturn(m_services); m_services.put("HDFS", Mockito.mock(Service.class)); PrereqCheckRequest request = new PrereqCheckRequest("cluster"); request.setTargetRepositoryVersion(m_repositoryVersion); // HIVE not installed Assert.assertFalse(m_check.isApplicable(request)); // install HIVE m_services.put("HIVE", Mockito.mock(Service.class)); m_check.repositoryVersionDaoProvider = new Provider<RepositoryVersionDAO>() { @Override public RepositoryVersionDAO get() { return repositoryVersionDAO; } }; Mockito.when(repositoryVersionDAO.findByStackNameAndVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(m_repositoryVersion); // HIVE installed Assert.assertTrue(m_check.isApplicable(request)); } /** * Tests that the warning is correctly tripped when there are not enough * metastores. * * @throws Exception */ @Test public void testPerform() throws Exception { final Cluster cluster = Mockito.mock(Cluster.class); Service hive = Mockito.mock(Service.class); ServiceComponent metastore = Mockito.mock(ServiceComponent.class); Mockito.when(cluster.getClusterId()).thenReturn(1L); Mockito.when(m_clusters.getCluster("cluster")).thenReturn(cluster); Mockito.when(cluster.getService("HIVE")).thenReturn(hive); Mockito.when(hive.getServiceComponent("HIVE_METASTORE")).thenReturn(metastore); Map<String, ServiceComponentHost> metastores = new HashMap<>(); Mockito.when(metastore.getServiceComponentHosts()).thenReturn(metastores); PrerequisiteCheck check = new PrerequisiteCheck(null, null); PrereqCheckRequest request = new PrereqCheckRequest("cluster"); request.setTargetRepositoryVersion(m_repositoryVersion); m_check.perform(check, request); Assert.assertEquals(PrereqCheckStatus.WARNING, check.getStatus()); metastores.put("c6401", Mockito.mock(ServiceComponentHost.class)); metastores.put("c6402", Mockito.mock(ServiceComponentHost.class)); check = new PrerequisiteCheck(null, null); m_check.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); } @Test public void testPerformFail() throws Exception{ final Cluster cluster = Mockito.mock(Cluster.class); final LinkedHashSet<String> failedOnExpected = new LinkedHashSet<>(); Service hive = Mockito.mock(Service.class); ServiceComponent metastore = Mockito.mock(ServiceComponent.class); Map<String, ServiceComponentHost> metastores = new HashMap<>(); failedOnExpected.add("HIVE"); Mockito.when(cluster.getClusterId()).thenReturn(1L); Mockito.when(m_clusters.getCluster("cluster")).thenReturn(cluster); Mockito.when(cluster.getService("HIVE")).thenReturn(hive); Mockito.when(hive.getServiceComponent("HIVE_METASTORE")).thenReturn(metastore); Mockito.when(metastore.getServiceComponentHosts()).thenReturn(metastores); PrerequisiteCheck check = new PrerequisiteCheck(null, null); PrereqCheckRequest request = new PrereqCheckRequest("cluster"); request.setTargetRepositoryVersion(m_repositoryVersion); m_check.perform(check, request); Assert.assertEquals(PrereqCheckStatus.WARNING, check.getStatus()); check = new PrerequisiteCheck(null, null); m_check.perform(check, request); Assert.assertEquals(failedOnExpected, check.getFailedOn()); Assert.assertEquals(PrereqCheckStatus.WARNING, check.getStatus()); } }
37.28
109
0.760864
ef532afb346721018eac824ba845b6006c1a3cc4
2,774
/* This file is actually about lambdas, the first step to functional programming. The one important sentence for lambdas is: ***Lambdas work with interfaces that have *only one* abstract method.*** Such interfaces are called "functional interface". Lambdas (anonymous functions) are usually passed around like objects. But in Java this is restricted: Java allows lambdas to be passed only to methods that expect a functional interface as input parameter. In other words: lambdas can replace an object that implements a functional interface. */ import java.util.function.Predicate; public class PrideAndPredicates { public static void main(String[] args) { int[] numbers = {123, 1, 34, 43, 42, 314, 121, 88}; // Loop over numbers and print if they are larger than 100 for (int number : numbers) { printIfLargerThan(number, 100); } // On the one hand, this is general, because we can give the minimum // prinntable bound as a second parameter. On the other hand, // printIfLargerThan() is limited to this one operation. System.out.println(); // Now we are doing the same loop as above, but using lambda with // printIfCheck(). for (int number : numbers) { printIfCheck(number, n -> n > 100); } // We could have implemented an extra checker class that implements // the interface TruthChecker and given instead of the lambda. // This example is very unnecessary! Instead of defining an interface, // a member using this interface, and a lambda; we could just have // used the if (number > 100) in the loop itself!. System.out.println(); // Java has a built-in functional interface "Predicate" so that we // don't have to write such an interface every time we want to check a // boolean value. See printIfPredicate(). The interface Predicate is // defined in "java.util.function" package. for (int number : numbers) { printIfPredicate(number, n -> n > 100); } } // Prints first argument if it's larger than the second one static void printIfLargerThan(int num, int min) { if (num > min) System.out.println(num); } // This method expects an int and an object implementing the interface // TruthChecker, and this interface enforces that this object has a method // called check(). static void printIfCheck(int num, TruthChecker bacon) { if (bacon.check(num)) System.out.println(num); } static void printIfPredicate(int num, Predicate<Integer> pred) { if (pred.test(num)) System.out.println(num); } } interface TruthChecker { boolean check(int num); }
33.829268
78
0.664384
747f2340ee9f43eaa83fc028e98356a2d184ef36
652
package InheritanceTest; public class Accessor { public static AA getWbyA() {return new WW();} public static BB getWbyB() {return new WW();} public static AA getXbyA() {return new XX();} public static BB getXbyB() {return new XX();} public static XX getX() {return new XX();} public static AA getYbyA() {return new YY();} public static BB getYbyB() {return new YY();} public static CC getYbyC() {return new YY();} public static YY getY() {return new YY();} public static AA getZbyA() {return new ZZ();} public static BB getZbyB() {return new ZZ();} public static CC getZbyC() {return new ZZ();} }
38.352941
49
0.642638
619a5c59cbb81395565436b19c396639d6ac530f
2,210
package com.epicodus.weather.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.epicodus.weather.R; import com.epicodus.weather.model.Weather; import com.squareup.picasso.Picasso; import java.util.ArrayList; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by Guest on 3/21/16. */ public class DayAdapter extends RecyclerView.Adapter<DayAdapter.DayViewHolder>{ private ArrayList<Weather> dayWeatherList = new ArrayList<>(); private Context context; public DayAdapter (Context context, ArrayList<Weather> dayWeatherList) { this.context = context; this.dayWeatherList = dayWeatherList; } @Override public DayAdapter.DayViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hour_list_item, parent, false); DayViewHolder viewHolder = new DayViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(DayAdapter.DayViewHolder holder, int position) { holder.bindWeather(dayWeatherList.get(position)); } @Override public int getItemCount() { return dayWeatherList.size(); } public class DayViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.hourTextView) TextView hourTextView; @Bind(R.id.iconImageView) ImageView iconImageView; @Bind(R.id.temperatureTextView) TextView temperatureTextView; public DayViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public void bindWeather (Weather weather) { hourTextView.setText(weather.getDate()); temperatureTextView.setText(weather.getTempMain().toString()); Integer iconId = weather.getImageId(); Picasso .with(context) .load(iconId) .fit() // will explain later .into(iconImageView); } } }
31.571429
109
0.692308
e5e76a1692790c903dc92bf37ef7014448786e52
1,040
package datastructure.exercise.leetcode; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 024 2017/5/24. */ public class GenerizeAbbreviations { public List<String> generateAbbreviations(String word) { List<String> result = new ArrayList<String>(); backtrack(result, word, 0, "", 0); return result; } void backtrack(List result, String word, int position, String current, int count) { if (position == word.length()) { if (count > 0) { current += count; } System.out.println(String.format("%d_%s", count, current)); result.add(current); } else { backtrack(result, word, position + 1, current, count + 1); backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0); } } public static void main(String[] args) { new GenerizeAbbreviations().generateAbbreviations("word"); } }
21.22449
113
0.586538
a6dd0793ee98fd42f04274c2c28bbfa2d8705338
584
package com.meijie.net; import com.meijie.ImClient; import com.meijie.proto.ImRequestProtos; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class ImRpcClientHandler extends SimpleChannelInboundHandler<ImRequestProtos.ImResponse> { private ImClient imClient; public ImRpcClientHandler(ImClient imClient) { this.imClient = imClient; } @Override protected void channelRead0(ChannelHandlerContext ctx, ImRequestProtos.ImResponse msg) throws Exception { imClient.addMessage(msg); } }
27.809524
109
0.782534
e69f8c626033952a8c92b34d46cab9e21cf24a6a
3,259
package com.cloud.api.command.admin.vm; import com.cloud.api.APICommand; import com.cloud.api.APICommandGroup; import com.cloud.api.ApiErrorCode; import com.cloud.api.ResponseObject.ResponseView; import com.cloud.api.ServerApiException; import com.cloud.api.command.user.vm.DeployVMCmd; import com.cloud.api.response.UserVmResponse; import com.cloud.context.CallContext; import com.cloud.legacymodel.exceptions.ConcurrentOperationException; import com.cloud.legacymodel.exceptions.InsufficientCapacityException; import com.cloud.legacymodel.exceptions.InsufficientServerCapacityException; import com.cloud.legacymodel.exceptions.ResourceUnavailableException; import com.cloud.legacymodel.vm.VirtualMachine; import com.cloud.uservm.UserVm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @APICommand(name = "deployVirtualMachine", group = APICommandGroup.VirtualMachineService, description = "Creates and automatically starts a virtual machine based on a service offering, disk " + "offering, and template.", responseObject = UserVmResponse.class, responseView = ResponseView.Full, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DeployVMCmdByAdmin extends DeployVMCmd { public static final Logger s_logger = LoggerFactory.getLogger(DeployVMCmdByAdmin.class.getName()); @Override public void execute() { final UserVm result; if (getStartVm()) { try { CallContext.current().setEventDetails("Vm Id: " + getEntityId()); result = _userVmService.startVirtualMachine(this); } catch (final ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (final ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (final InsufficientCapacityException ex) { final StringBuilder message = new StringBuilder(ex.getMessage()); if (ex instanceof InsufficientServerCapacityException) { if (((InsufficientServerCapacityException) ex).isAffinityApplied()) { message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them"); } } s_logger.info(ex.toString()); s_logger.info(message.toString(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString()); } } else { result = _userVmService.getUserVm(getEntityId()); } if (result != null) { final UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", result).get(0); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to deploy vm"); } } }
49.378788
193
0.695612
42f7342ad1be542f428f8cd62b5442e7b5fa94bd
1,495
package com.ge.verdict.gsn; import java.io.*; import javax.xml.parsers.*; import org.xml.sax.SAXException; /** @author Saswata Paul */ public class App { /** * This main method can be used for independently using the security gsn interface * * @param args * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException { if (args.length != 6) { System.out.println("Argument Error: Invalid number of arguments provided."); } else { String userInput = args[0]; String gsnOutputDir = args[1]; String soteriaOutputDir = args[2]; String modelAadlPath = args[3]; String soteriaOutputLinkPathPrefix = args[4]; String hostSTEMDir = args[5]; boolean securityCaseFlag = true; boolean xmlFlag = false; // calling the security gsn creating interface SecurityGSNInterface interfaceObj = new SecurityGSNInterface(); interfaceObj.runGsnArtifactsGenerator( userInput, gsnOutputDir, soteriaOutputDir, modelAadlPath, securityCaseFlag, xmlFlag, soteriaOutputLinkPathPrefix, hostSTEMDir); } } }
30.510204
88
0.577258
0c2b8617fc18f59cbf0b41e946708a769e144e2d
919
package uk.gov.hmcts.reform.finrem.caseorchestration.model.document; import com.google.common.collect.ImmutableMap; import org.junit.Test; import java.util.Map; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class DocumentGenerationRequestTest { private static final Map<String, Object> VALUES = ImmutableMap.of("K", "V"); private static final String TEMPLATE_NAME = "TEMPLATE"; @Test public void properties() { DocumentGenerationRequest fixture = documentRequest(); assertThat(fixture.getTemplate(), is(TEMPLATE_NAME)); assertThat(fixture.getValues(), is(equalTo(VALUES))); } private DocumentGenerationRequest documentRequest() { return DocumentGenerationRequest.builder() .template(TEMPLATE_NAME) .values(VALUES) .build(); } }
30.633333
80
0.717084
91612b118dc223b228009bcbca7e85d71f5db892
2,841
package com.jakewharton.madge; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import static android.os.Build.VERSION_CODES.HONEYCOMB; public final class MadgeFrameLayout extends FrameLayout { private final MadgeCanvas canvasDelegate; private boolean enabled; public MadgeFrameLayout(Context context) { super(context); canvasDelegate = new MadgeCanvas(context); } public MadgeFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); canvasDelegate = new MadgeCanvas(context); } public MadgeFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); canvasDelegate = new MadgeCanvas(context); } /** Set the color for the pixel grid overlay. */ public void setOverlayColor(int color) { canvasDelegate.setColor(color); } /** The color used by the pixel grid overlay. */ public int getOverlayColor() { return canvasDelegate.getColor(); } /** Set whether the scale ratio will be drawn as text on top of the pixel grid. */ public void setOverlayRatioEnabled(boolean overlayRatioEnabled) { canvasDelegate.setOverlayRatioEnabled(overlayRatioEnabled); invalidate(); // Trigger a re-draw so we see the scale text. } /** Returns true if the scale ratio is drawing on top of the pixel grid. */ public boolean isOverlayRatioEnabled() { return canvasDelegate.isOverlayRatioEnabled(); } /** Set whether the pixel grid overlay is enabled. */ public void setOverlayEnabled(boolean enabled) { if (enabled != this.enabled) { if (Build.VERSION.SDK_INT >= HONEYCOMB) { layerize(enabled); } this.enabled = enabled; if (!enabled) { canvasDelegate.clearCache(); } invalidate(); // Trigger a re-draw so we see the grid. } } /** Returns true if the pixel grid overlay is enabled. */ public boolean isOverlayEnabled() { return enabled; } @TargetApi(HONEYCOMB) private void layerize(boolean enabled) { if (enabled) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } else { setLayerType(View.LAYER_TYPE_NONE, null); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (!enabled) { return super.drawChild(canvas, child, drawingTime); } MadgeCanvas delegate = canvasDelegate; try { delegate.setDelegate(canvas); return super.drawChild(delegate, child, drawingTime); } finally { delegate.clearDelegate(); } } @TargetApi(HONEYCOMB) @Override public boolean isHardwareAccelerated() { return !enabled && super.isHardwareAccelerated(); } }
28.128713
86
0.706793
6392a3927a116d3a401a8b78355e6c163b155a6d
8,999
package com.hnust.wxsell.service.impl; import com.hnust.wxsell.converter.ReplenishMaster2ReplenishDTOConverter; import com.hnust.wxsell.dataobject.ReplenishDetail; import com.hnust.wxsell.dataobject.ReplenishMaster; import com.hnust.wxsell.dto.ProductDTO; import com.hnust.wxsell.dto.ReplenishDTO; import com.hnust.wxsell.enums.OrderStatusEnum; import com.hnust.wxsell.enums.ResultEnum; import com.hnust.wxsell.exception.SellException; import com.hnust.wxsell.repository.ReplenishDetailRepository; import com.hnust.wxsell.repository.ReplenishMasterRepository; import com.hnust.wxsell.service.DispatchService; import com.hnust.wxsell.service.GroupMasterService; import com.hnust.wxsell.service.ProductService; import com.hnust.wxsell.service.ReplenishService; import com.hnust.wxsell.utils.KeyUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; /** * @author ZZH * @date 2018/4/8 0008 21:13 **/ @Service @Slf4j public class ReplenishServiceImpl implements ReplenishService { @Autowired ReplenishDetailRepository replenishDetailRepository; @Autowired ReplenishMasterRepository replenishMasterRepository; @Autowired ProductService productService; @Autowired private DispatchService dispatchService; @Autowired GroupMasterService groupMasterService; @Override @Transactional public ReplenishDTO create(ReplenishDTO replenishDTO) { if (CollectionUtils.isEmpty(replenishDTO.getReplenishDetailList())){ throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY); } String replenishId = KeyUtil.genUniqueKey(); BigDecimal replenishAmount = new BigDecimal(BigInteger.ZERO); //1. 查询商品(数量, 价格) for (ReplenishDetail replenishDetail : replenishDTO.getReplenishDetailList()) { ProductDTO productDTO = productService.findOne(replenishDetail.getProductId()); if (productDTO == null) { throw new SellException(ResultEnum.PRODUCT_NOT_EXIST); } //2. 计算订单总价 replenishAmount = productDTO.getProductPrice() .multiply(new BigDecimal(replenishDetail.getProductQuantity())) .add(replenishAmount); //订单详情入库 replenishDetail.setReplenishId(replenishId); BeanUtils.copyProperties(productDTO, replenishDetail); replenishDetail.setDetailId(KeyUtil.genUniqueKey()); replenishDetailRepository.save(replenishDetail); } //3. 写入订单数据库(orderMaster和orderDetail) ReplenishMaster replenishMaster = new ReplenishMaster(); replenishDTO.setReplenishId(replenishId); BeanUtils.copyProperties(replenishDTO, replenishMaster); replenishMaster.setReplenishAmount(replenishAmount); replenishMaster.setReplenishStatus(OrderStatusEnum.NEW.getCode()); replenishMasterRepository.save(replenishMaster); return replenishDTO; } @Override public ReplenishDTO findOne(String replenishId) { ReplenishMaster replenishMaster = replenishMasterRepository.findOne(replenishId); if (replenishMaster == null) { throw new SellException(ResultEnum.ORDER_NOT_EXIST); } List<ReplenishDetail> replenishDetailList = replenishDetailRepository.findByReplenishId(replenishId); if (CollectionUtils.isEmpty(replenishDetailList)) { throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY); } ReplenishDTO replenishDTO = new ReplenishDTO(); BeanUtils.copyProperties(replenishMaster, replenishDTO); replenishDTO.setReplenishDetailList(replenishDetailList); return replenishDTO; } @Override public Page<ReplenishDTO> findList(String openId, Pageable pageable) { Page<ReplenishMaster> replenishMasterPage = replenishMasterRepository.findByOpenId(openId, pageable); List<ReplenishDTO> replenishDTOList = ReplenishMaster2ReplenishDTOConverter.convert(replenishMasterPage.getContent()); return new PageImpl<ReplenishDTO>(replenishDTOList, pageable, replenishMasterPage. getTotalElements()); } @Override @Transactional public ReplenishDTO cancel(ReplenishDTO replenishDTO) { ReplenishMaster replenishMaster = new ReplenishMaster(); //判断订单状态 if (!replenishDTO.getReplenishStatus().equals(OrderStatusEnum.NEW.getCode())) { log.error("【取消补货订单】订单状态不正确, replenishId={}, replenishStatus={}", replenishDTO.getReplenishId(), replenishDTO.getReplenishStatus()); throw new SellException(ResultEnum.ORDER_STATUS_ERROR); } //修改订单状态 replenishDTO.setReplenishStatus(OrderStatusEnum.CANCEL.getCode()); BeanUtils.copyProperties(replenishDTO, replenishMaster); ReplenishMaster updateResult = replenishMasterRepository.save(replenishMaster); if (updateResult == null) { log.error("【取消补货订单】更新失败, replenishMaster={}", replenishMaster); throw new SellException(ResultEnum.ORDER_UPDATE_FAIL); } return replenishDTO; } @Override @Transactional public ReplenishDTO finish(ReplenishDTO replenishDTO) { //判断订单状态 if (!replenishDTO.getReplenishStatus().equals(OrderStatusEnum.NEW.getCode())) { log.error("【完结补货订单】订单状态不正确, replenishId={}, replenishStatus={}", replenishDTO.getReplenishId(), replenishDTO.getReplenishStatus()); throw new SellException(ResultEnum.ORDER_STATUS_ERROR); } //修改订单状态 replenishDTO.setReplenishStatus(OrderStatusEnum.FINISHED.getCode()); ReplenishMaster replenishMaster = new ReplenishMaster(); BeanUtils.copyProperties(replenishDTO, replenishMaster); ReplenishMaster updateResult = replenishMasterRepository.save(replenishMaster); if (updateResult == null) { log.error("【完结补货订单】更新失败, replenishMaster={}", replenishMaster); throw new SellException(ResultEnum.ORDER_UPDATE_FAIL); } return dispatchService.add(replenishDTO); } @Override public Page<ReplenishDTO> findListBySchoolNo(String schoolNo, Pageable pageable) { Page<ReplenishMaster> replenishMasterPage = replenishMasterRepository.findBySchoolNo(schoolNo,pageable); List<ReplenishDTO> replenishDTOList = ReplenishMaster2ReplenishDTOConverter.convert(replenishMasterPage.getContent()); for(ReplenishDTO replenishDTO : replenishDTOList){ List<ReplenishDetail> replenishDetailList = replenishDetailRepository.findByReplenishId(replenishDTO.getReplenishId()); replenishDTO.setReplenishDetailList(replenishDetailList); } return new PageImpl<>(replenishDTOList, pageable, replenishMasterPage.getTotalElements()); } @Override public Page<ReplenishDTO> findNewReplenish(String schoolNo, Pageable pageable) { Page<ReplenishMaster> replenishMasterPage = replenishMasterRepository. findByReplenishStatusAndSchoolNo( OrderStatusEnum.NEW.getCode(),schoolNo,pageable); List<ReplenishDTO> replenishDTOList = ReplenishMaster2ReplenishDTOConverter.convert(replenishMasterPage.getContent()); return new PageImpl<>(replenishDTOList, pageable, replenishMasterPage.getTotalElements()); } @Override public ReplenishDTO save(ReplenishDTO replenishDTO) { ReplenishMaster replenishMaster = new ReplenishMaster(); BeanUtils.copyProperties(replenishDTO,replenishMaster); replenishMasterRepository.save(replenishMaster); for (ReplenishDetail replenishDetail : replenishDTO.getReplenishDetailList()){ if (replenishDetail!=null) { replenishDetailRepository.save(replenishDetail); } } return replenishDTO; } @Override public void delete(ReplenishDetail replenishDetail) { replenishDetailRepository.delete(replenishDetail.getDetailId()); } @Override public ReplenishMaster save(ReplenishMaster replenishMaster) { return replenishMasterRepository.save(replenishMaster); } @Override public ReplenishDetail save(ReplenishDetail replenishDetail) { return replenishDetailRepository.save(replenishDetail); } }
40.719457
144
0.714302
d25e6bec0d78587371b755df8c21067129ac5f78
5,570
package blog.raubach.utils.task; import blog.raubach.database.Database; import blog.raubach.database.codegen.tables.records.HikestatsRecord; import blog.raubach.utils.*; import com.google.maps.*; import com.google.maps.errors.ApiException; import com.google.maps.model.*; import io.jenetics.jpx.*; import org.jooq.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.sql.*; import java.time.ZonedDateTime; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; import static blog.raubach.database.codegen.tables.Hikestats.*; public class GoogleElevationTask implements Runnable { private Integer postId = null; public GoogleElevationTask() { } public GoogleElevationTask(Integer postId) { this.postId = postId; } @Override public void run() { File mediaFolder = new File(PropertyWatcher.get("media.directory.external")); Logger.getLogger("").info("RUNNING GOOGLE ELEVATION TASK"); GeoApiContext gContext = new GeoApiContext.Builder() .apiKey(PropertyWatcher.get("google.elevation.api.key")) .build(); try (Connection conn = Database.getConnection(true)) { DSLContext context = Database.getContext(conn); SelectConditionStep<HikestatsRecord> step = context.selectFrom(HIKESTATS) .where(HIKESTATS.GPX_PATH.isNotNull()) .and(HIKESTATS.ELEVATION_PROFILE_PATH.isNull().or(HIKESTATS.TIME_DISTANCE_PROFILE_PATH.isNull())); if (this.postId != null) step = step.and(HIKESTATS.POST_ID.eq(postId)); step.forEach(hs -> { Logger.getLogger("").info("RUNNING GOOGLE ELEVATION TASK FOR POST: " + hs.getPostId()); File gpx = new File(mediaFolder, hs.getGpxPath()); if (gpx.exists() && gpx.isFile()) { try { // Read the GPX file GPX data = GPX.read(gpx.getPath()); // Extract all the points List<Point> points = new ArrayList<>(); if (data.getTracks().size() > 0) { points = data.tracks() .flatMap(Track::segments) .flatMap(TrackSegment::points) .collect(Collectors.toList()); } else if (data.getRoutes().size() > 0) { points = data.routes() .flatMap(Route::points) .collect(Collectors.toList()); } if (!CollectionUtils.isEmpty(points)) { // Map them to Google Maps LatLng objects LatLng[] latLngs = points.stream().map(p -> new LatLng(p.getLatitude().doubleValue(), p.getLongitude().doubleValue())).toArray(LatLng[]::new); // Fetch their elevations ElevationResult[] result = ElevationApi.getByPoints(gContext, latLngs).await(); String uuid = gpx.getParentFile().getName(); double totalAscent = 0; // Write the outputs File elevation = new File(gpx.getParentFile(), uuid + "-elevation.tsv"); File timeDistance = new File(gpx.getParentFile(), uuid + "-time-distance.tsv"); try (BufferedWriter ew = new BufferedWriter(new FileWriter(elevation, StandardCharsets.UTF_8)); BufferedWriter tdw = new BufferedWriter(new FileWriter(timeDistance, StandardCharsets.UTF_8))) { ew.write("distance\televation"); ew.newLine(); tdw.write("time\tdistance"); tdw.newLine(); double accu = 0; double tdAccu = 0; int lastTime = -1; long startTime = getTime(points.get(0)); for (int i = 1; i < points.size(); i++) { Point prev = points.get(i - 1); Point curr = points.get(i); double haversine = getHaversine(prev, curr); accu += haversine; tdAccu += haversine; totalAscent += Math.max(0, result[i].elevation - result[i - 1].elevation); ew.write(accu + "\t" + result[i].elevation); ew.newLine(); long time = getTime(curr); int tdSeconds = getTimeDistance(time, startTime); if (tdSeconds > lastTime) { lastTime = tdSeconds; tdw.write(tdSeconds + "\t" + tdAccu); tdw.newLine(); } } } hs.setAscent(totalAscent); hs.setElevationProfilePath(mediaFolder.toPath().relativize(elevation.toPath()).toString()); hs.setTimeDistanceProfilePath(mediaFolder.toPath().relativize(timeDistance.toPath()).toString()); hs.store(); } } catch (IOException | InterruptedException | ApiException e) { e.printStackTrace(); Logger.getLogger("").severe(e.getMessage()); } } }); } catch (SQLException e) { e.printStackTrace(); Logger.getLogger("").severe(e.getMessage()); } } private long getTime(Point point) { ZonedDateTime d = point.getTime().orElse(null); if (d != null) return d.toEpochSecond(); else return 0; } private int getTimeDistance(long one, long two) { return (int) Math.floor(Math.abs(two - one) / 60.0); } private double getHaversine(Point one, Point two) { double r = 6371.0; double dLat = toRadians(two.getLatitude().doubleValue() - one.getLatitude().doubleValue()); double dLng = toRadians(two.getLongitude().doubleValue() - one.getLongitude().doubleValue()); double a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) + Math.cos(toRadians(one.getLatitude().doubleValue())) * Math.cos(toRadians(two.getLatitude().doubleValue())) * Math.sin(dLng / 2.0) * Math.sin(dLng / 2.0); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return r * c; } private double toRadians(double value) { return value * Math.PI / 180.0; } }
29.162304
213
0.639497
759daf4393b6c816bc3455b52f207c18b82a2719
7,353
/* Copyright (c) 2016, BogDan Vatra <[email protected]> Contact: http://www.qt-project.org/legal Commercial License Usage Licensees holding valid commercial Qt licenses may use this file in accordance with the commercial license agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Digia. For licensing terms and conditions see http://qt.digia.com/licensing. For further information use the contact form at http://qt.digia.com/contact-us. BSD License Usage Alternatively, this file may be used under the BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.qtproject.qt5.android.bindings; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.Window; import java.lang.reflect.Field; public class QtActivityLoader extends QtLoader { QtActivity m_activity; QtActivityLoader(QtActivity activity) { super(activity, QtActivity.class); m_activity = activity; } @Override protected void downloadUpgradeMinistro(String msg) { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(m_activity); downloadDialog.setMessage(msg); downloadDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { try { Uri uri = Uri.parse("market://details?id=org.kde.necessitas.ministro"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); m_activity.startActivityForResult(intent, MINISTRO_INSTALL_REQUEST_CODE); } catch (Exception e) { e.printStackTrace(); ministroNotFound(); } } }); downloadDialog.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { m_activity.finish(); } }); downloadDialog.show(); } @Override protected String loaderClassName() { return "org.qtproject.qt5.android.QtActivityDelegate"; } @Override protected Class<?> contextClassName() { return android.app.Activity.class; } @Override protected void finish() { m_activity.finish(); } @Override protected String getTitle() { return (String) m_activity.getTitle(); } @Override protected void runOnUiThread(Runnable run) { m_activity.runOnUiThread(run); } @Override Intent getIntent() { return m_activity.getIntent(); } public void onCreate(Bundle savedInstanceState) { try { m_contextInfo = m_activity.getPackageManager().getActivityInfo(m_activity.getComponentName(), PackageManager.GET_META_DATA); int theme = ((ActivityInfo)m_contextInfo).getThemeResource(); for (Field f : Class.forName("android.R$style").getDeclaredFields()) { if (f.getInt(null) == theme) { QT_ANDROID_THEMES = new String[] {f.getName()}; QT_ANDROID_DEFAULT_THEME = f.getName(); break; } } } catch (Exception e) { e.printStackTrace(); finish(); return; } if (Build.VERSION.SDK_INT < 16) { // fatal error, show the error and quit AlertDialog errorDialog = new AlertDialog.Builder(m_activity).create(); if (m_contextInfo.metaData.containsKey("android.app.unsupported_android_version")) errorDialog.setMessage(m_contextInfo.metaData.getString("android.app.unsupported_android_version")); else errorDialog.setMessage("Unsupported Android version."); errorDialog.setButton(m_activity.getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); errorDialog.show(); return; } try { m_activity.setTheme(Class.forName("android.R$style").getDeclaredField(QT_ANDROID_DEFAULT_THEME).getInt(null)); } catch (Exception e) { e.printStackTrace(); } m_activity.requestWindowFeature(Window.FEATURE_ACTION_BAR); if (QtApplication.m_delegateObject != null && QtApplication.onCreate != null) { QtApplication.invokeDelegateMethod(QtApplication.onCreate, savedInstanceState); return; } m_displayDensity = m_activity.getResources().getDisplayMetrics().densityDpi; ENVIRONMENT_VARIABLES += "\tQT_ANDROID_THEME=" + QT_ANDROID_DEFAULT_THEME + "/\tQT_ANDROID_THEME_DISPLAY_DPI=" + m_displayDensity + "\t"; if (null == m_activity.getLastNonConfigurationInstance()) { if (m_contextInfo.metaData.containsKey("android.app.background_running") && m_contextInfo.metaData.getBoolean("android.app.background_running")) { ENVIRONMENT_VARIABLES += "QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED=0\t"; } else { ENVIRONMENT_VARIABLES += "QT_BLOCK_EVENT_LOOPS_WHEN_SUSPENDED=1\t"; } if (m_contextInfo.metaData.containsKey("android.app.auto_screen_scale_factor") && m_contextInfo.metaData.getBoolean("android.app.auto_screen_scale_factor")) { ENVIRONMENT_VARIABLES += "QT_AUTO_SCREEN_SCALE_FACTOR=1\t"; } startApp(true); } } }
39.320856
136
0.658643
081669e349457381706bfe5a1c1323d331960865
1,248
package fr.bastoup.bperipherals; import fr.bastoup.bperipherals.database.DBFactory; import fr.bastoup.bperipherals.registry.ClientRegistry; import fr.bastoup.bperipherals.registry.SharedRegistry; import fr.bastoup.bperipherals.util.BPeripheralsProperties; import fr.bastoup.bperipherals.util.Config; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Mod(BPeripheralsProperties.MODID) public class BPeripherals { private static final Logger LOGGER = LogManager.getLogger(); private static IEventBus MOD_EVENT_BUS = null; private static DBFactory dbFactory; public BPeripherals() { MOD_EVENT_BUS = FMLJavaModLoadingContext.get().getModEventBus(); MOD_EVENT_BUS.register(SharedRegistry.class); MOD_EVENT_BUS.register(ClientRegistry.class); MOD_EVENT_BUS.register(Config.class); Config.setup(); dbFactory = DBFactory.getInstance(); } public static Logger getLogger() { return LOGGER; } public static DBFactory getDBFactory() { return dbFactory; } }
29.714286
72
0.762019
c94ca009e3fbc60da071f2f4ec44977a80035d16
1,820
package echowand.net; import java.net.InetAddress; /** * IPv4ネットワークのサブネットに存在するノード * @author Yoshiki Makino */ public class InetNode implements Node { private InetSubnet subnet; private InetNodeInfo nodeInfo; /** * InetNodeを生成する。 * 直接生成は行わずにInetSubnetのgetRemoteNodeメソッドの利用を推奨する。 * @param subnet このノードの存在するサブネット * @param address このノードのIPv4アドレス */ public InetNode(InetSubnet subnet, InetAddress address) { this(subnet, new InetNodeInfo(address)); } /** * InetNodeを生成する。 * 直接生成は行わずにInetSubnetのgetRemoteNodeメソッドの利用を推奨する。 * @param subnet このノードの存在するサブネット * @param nodeInfo このノードの情報 */ public InetNode(InetSubnet subnet, InetNodeInfo nodeInfo) { this.subnet = subnet; this.nodeInfo = nodeInfo; } /** * このノードのノード情報を返す。 * @return ノード情報 */ @Override public NodeInfo getNodeInfo() { return nodeInfo; } /** * IPアドレスを返す。 * @return IPv4アドレス */ public InetAddress getAddress() { return nodeInfo.getAddress(); } @Override public boolean isMemberOf(Subnet subnet) { return this.subnet == subnet; } /** * このノードを文字列で表現する * @return ノードの文字列表現 */ @Override public String toString() { return nodeInfo.toString(); } @Override public boolean equals(Object o) { if (! (o instanceof InetNode)) { return false; } InetNode node = (InetNode)o; return (getNodeInfo().equals(node.getNodeInfo()) && subnet.equals(node.subnet)); } @Override public int hashCode() { int hash = 7; hash = 71 * hash + (this.nodeInfo != null ? this.nodeInfo.hashCode() : 0); return hash; } }
22.469136
88
0.591209
62053ff30bd8d3b50d7153c24196c8ec4129fbc9
955
package dev.patika.project01.entity; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import lombok.*; import javax.persistence.*; import java.util.Set; @Data //-> @RequiredArgsConstructor, @Getter, @Setter, @EqualsAndHashCode, @ToString @AllArgsConstructor @NoArgsConstructor @Entity //Spring DATA JPA @Builder @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id") public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String code; private Float creditScore; @ManyToMany(mappedBy = "courseList", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<Student> studentList; @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Instructor instructor; }
29.84375
92
0.773822
5b211f8127258cfeca1198388cf8964e0fa5351b
5,195
package org.cacert.gigi.output.template; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.net.URISyntaxException; import java.net.URL; import java.util.LinkedList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Template implements Outputable { class ParseResult { TemplateBlock block; String endType; public ParseResult(TemplateBlock block, String endType) { this.block = block; this.endType = endType; } public String getEndType() { return endType; } public TemplateBlock getBlock(String reqType) { if (endType == null && reqType == null) { return block; } if (endType == null || reqType == null) { throw new Error("Invalid block type: " + endType); } if (endType.equals(reqType)) { return block; } throw new Error("Invalid block type: " + endType); } } private TemplateBlock data; private long lastLoaded; private File source; private static final Pattern CONTROL_PATTERN = Pattern .compile(" ?([a-z]+)\\(\\$([^)]+)\\) ?\\{ ?"); private static final Pattern ELSE_PATTERN = Pattern .compile(" ?\\} ?else ?\\{ ?"); public Template(URL u) { try { Reader r = new InputStreamReader(u.openStream(), "UTF-8"); try { if (u.getProtocol().equals("file")) { source = new File(u.toURI()); lastLoaded = source.lastModified() + 1000; } } catch (URISyntaxException e) { e.printStackTrace(); } data = parse(r).getBlock(null); r.close(); } catch (IOException e) { throw new Error(e); } } public Template(Reader r) { try { data = parse(r).getBlock(null); r.close(); } catch (IOException e) { throw new Error(e); } } private ParseResult parse(Reader r) throws IOException { LinkedList<String> splitted = new LinkedList<String>(); LinkedList<Outputable> commands = new LinkedList<Outputable>(); StringBuffer buf = new StringBuffer(); String blockType = null; outer: while (true) { while (!endsWith(buf, "<?")) { int ch = r.read(); if (ch == -1) { break outer; } buf.append((char) ch); } buf.delete(buf.length() - 2, buf.length()); splitted.add(buf.toString()); buf.delete(0, buf.length()); while (!endsWith(buf, "?>")) { int ch = r.read(); if (ch == -1) { throw new EOFException(); } buf.append((char) ch); } buf.delete(buf.length() - 2, buf.length()); String com = buf.toString().replace("\n", ""); buf.delete(0, buf.length()); Matcher m = CONTROL_PATTERN.matcher(com); if (m.matches()) { String type = m.group(1); String variable = m.group(2); ParseResult body = parse(r); if (type.equals("if")) { if ("else".equals(body.getEndType())) { commands.add(new IfStatement(variable, body .getBlock("else"), parse(r).getBlock("}"))); } else { commands.add(new IfStatement(variable, body .getBlock("}"))); } } else if (type.equals("foreach")) { commands.add(new ForeachStatement(variable, body .getBlock("}"))); } else { throw new IOException( "Syntax error: unknown control structure: " + type); } continue; } else if ((m = ELSE_PATTERN.matcher(com)).matches()) { blockType = "else"; break; } else if (com.matches(" ?\\} ?")) { blockType = "}"; break; } else { commands.add(parseCommand(com)); } } splitted.add(buf.toString()); return new ParseResult(new TemplateBlock( splitted.toArray(new String[splitted.size()]), commands.toArray(new Outputable[commands.size()])), blockType); } private boolean endsWith(StringBuffer buf, String string) { return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()) .equals(string); } private Outputable parseCommand(String s2) { if (s2.startsWith("=$")) { final String raw = s2.substring(2); return new OutputVariableCommand(raw); } else { System.out.println("Unknown processing instruction: " + s2); } return null; } @Override public void output(PrintWriter out, Map<String, Object> vars) { if (source != null) { if (lastLoaded < source.lastModified()) { try { System.out.println("Reloading template.... " + source); InputStreamReader r = new InputStreamReader( new FileInputStream(source), "UTF-8"); data = parse(r).getBlock(null); r.close(); lastLoaded = source.lastModified() + 1000; } catch (IOException e) { e.printStackTrace(); } } } data.output(out, vars); } protected static void outputVar(PrintWriter out, Map<String, Object> vars, String varname, boolean unescaped) { Object s = vars.get(varname); if (s == null) { System.out.println("Empty variable: " + varname); // NOTE: Modificated from orig! s = ""; } if (s instanceof Outputable) { ((Outputable) s).output(out, vars); } else { out.print(s == null ? "null" : (unescaped ? s.toString() : HTMLEncoder.encodeHTML(s.toString()))); } } }
25.717822
75
0.629259
2814ce51f2012ac8b6c9a68e9ced17445b3f47fe
3,274
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.metadata; import org.eclipse.birt.report.model.api.metadata.PropertyValueException; import org.eclipse.birt.report.model.core.DesignElement; import org.eclipse.birt.report.model.core.Module; /** * Element name property type. Represents the key member of a structure. * */ public class MemberKeyPropertyType extends TextualPropertyType { /** * Display name key. */ private static final String DISPLAY_NAME_KEY = "Property.memberKey"; //$NON-NLS-1$ /** * Constructor. */ public MemberKeyPropertyType( ) { super( DISPLAY_NAME_KEY ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.design.metadata.PropertyType#getTypeCode() */ public int getTypeCode( ) { return MEMBER_KEY_TYPE; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.design.metadata.PropertyType#getXmlName() */ public String getName( ) { return MEMBER_KEY_NAME; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.metadata.PropertyType#validateValue(org * .eclipse.birt.report.model.core.Module, * org.eclipse.birt.report.model.core.DesignElement, * org.eclipse.birt.report.model.metadata.PropertyDefn, java.lang.Object) */ public Object validateValue( Module module, DesignElement element, PropertyDefn defn, Object value ) throws PropertyValueException { assert defn != null; if ( value == null ) { if ( defn.isStructureMember( ) ) throw new PropertyValueException( null, PropertyValueException.DESIGN_EXCEPTION_VALUE_REQUIRED, MEMBER_KEY_TYPE ); return null; } if ( value instanceof String ) { String stringValue = trimString( (String) value, defn .getTrimOption( ) ); if ( stringValue == null ) { if ( defn.isStructureMember( ) ) throw new PropertyValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, MEMBER_KEY_TYPE ); return null; } return stringValue; } throw new PropertyValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, MEMBER_KEY_TYPE ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.metadata.PropertyType#validateXml(org.eclipse * .birt.report.model.core.Module, * org.eclipse.birt.report.model.core.DesignElement, * org.eclipse.birt.report.model.metadata.PropertyDefn, java.lang.Object) */ public Object validateXml( Module module, DesignElement element, PropertyDefn defn, Object value ) throws PropertyValueException { assert value == null || value instanceof String; String tmpValue = (String) value; if ( tmpValue == null ) return null; return trimString( tmpValue, defn.getTrimOption( ) ); } }
25.578125
83
0.679597
539b27448492699d35f6299bd6f5ac5a60a9ff5d
5,788
package pl.edu.mimuw.dbaugmentor.copier; import pl.edu.mimuw.dbaugmentor.config.ApplicationProperties; import pl.edu.mimuw.dbaugmentor.database.*; import java.util.*; import java.util.logging.Logger; public class EntityCopier { private final Database database; private final Set<EntityCopy> copiedEntitiesToOrder = new HashSet<>(); private final ArrayList<Entity> entitiesToInsert = new ArrayList<>(); private final ArrayList<Update> updatesOnCopiedEntities = new ArrayList<>(); private final ApplicationProperties properties; public ArrayList<Update> getUpdatesOnCopiedEntities() { return updatesOnCopiedEntities; } public EntityCopier(Database database, ApplicationProperties properties) { this.database = database; this.properties = properties; } public ArrayList<Entity> getEntitiesToInsert() { return this.entitiesToInsert; } public void copyEntities(Logger logger) throws Exception { if (properties.getMultiplier() < 2) { throw new Exception("Multiplier has to be >= 2"); } Table table = database.getTable(properties.getTableName()); Collection<Entity> entitiesToCopy = table.getEntities(); Collection<Entity> newEntities = new ArrayList<>(); for (int copyNumber = 1; copyNumber < properties.getMultiplier(); copyNumber++) { int toCopy = entitiesToCopy.size(); int copied = 0; for (Entity entityToCopy : entitiesToCopy) { newEntities.add(createEntityCopy(entityToCopy, copyNumber).getEntity()); copied++; logger.info("copied " + copied + " / " + toCopy + " rows from " + table.getName()); } Collection<Entity> tmp = entitiesToCopy; entitiesToCopy = newEntities; newEntities = tmp; newEntities.clear(); } if (properties.isCaching()) { fixUniqueKeyValues(); } if (properties.isCaching() && !properties.isIgnoringFkConstraints()) { orderEntities(); } else { for (EntityCopy entityCopy : copiedEntitiesToOrder) { entitiesToInsert.add(entityCopy.getEntity()); } } } private EntityCopy createEntityCopy(Entity entityToCopy, int copyNumber) throws Exception { EntityCopy newEntity = new EntityCopy(entityToCopy, copyNumber); fixPrimaryKeyValue(newEntity.getEntity()); copiedEntitiesToOrder.add(newEntity); for (IncomingReference incomingReference: entityToCopy.getIncomingReferences()) { Entity childEntityToCopy = incomingReference.getEntity(); EntityCopy newChildEntity; if (!childEntityToCopy.isCopied()) { newChildEntity = createEntityCopy(childEntityToCopy, copyNumber); } else { newChildEntity = childEntityToCopy.getEntityCopy(); } ForeignKeyDefinition fkDefinition = incomingReference.getFkDefinition(); IncomingReference newIncomingReference = new IncomingReference(newChildEntity.getEntity(), fkDefinition); newIncomingReference.setFKValueFromDestinationEntity(newEntity.getEntity()); newEntity.getEntity().addIncomingReference(newIncomingReference); newEntity.addDependent(newChildEntity, fkDefinition); newChildEntity.addDependency(newEntity, fkDefinition); } return newEntity; } private void fixPrimaryKeyValue(Entity entity) throws Exception { entity.fixUniqueKeyValue( entity.getTable().getPrimaryKey(), properties.isGeneratingReadableString(), properties.isCachingUniqueKey()); } private void fixUniqueKeyValues() throws Exception { for (EntityCopy entityCopy : copiedEntitiesToOrder) { for (UniqueKey uniqueKey: entityCopy.getEntity().getTable().getUniqueKeys()) { entityCopy.getEntity().fixUniqueKeyValue( uniqueKey, properties.isGeneratingReadableString(), properties.isCachingUniqueKey()); } } } private void orderEntities() throws Exception { Queue<EntityCopy> nonDependent = new LinkedList<>(); for (EntityCopy entityCopy : copiedEntitiesToOrder) { if (entityCopy.hasNoDependencies()) { nonDependent.add(entityCopy); } } while (!nonDependent.isEmpty()) { EntityCopy entityCopy = nonDependent.remove(); entitiesToInsert.add(entityCopy.getEntity()); copiedEntitiesToOrder.remove(entityCopy); for (InsertDependency dependent : entityCopy.getDependent()) { if (dependent.getEntityCopy().removeDependency(entityCopy)) { if (dependent.getEntityCopy().hasNoDependencies()) { nonDependent.add(dependent.getEntityCopy()); } } } if (nonDependent.isEmpty() && !copiedEntitiesToOrder.isEmpty()) { for (EntityCopy next : copiedEntitiesToOrder) { if (next.allDependenciesNullable()) { updatesOnCopiedEntities.add(next.getUpdateOnNullableFkFields()); next.nullDependencies(); next.clearDependencies(); nonDependent.add(next); } } } } if (!copiedEntitiesToOrder.isEmpty()) { throw new Exception("Unable to order entities, try \"Ignore foreign key constraints \" option."); } } }
42.248175
117
0.618348
27a7b4d09b48695ad6bceb56455f06e9aa1ab9f0
5,288
package com.android.org.bouncycastle.jce.provider; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public class JCEBlockCipher extends WrapCipherSpi implements PBE { // Classes public static class DES extends JCEBlockCipher { // Constructors public DES(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithMD5AndDES extends JCEBlockCipher { // Constructors public PBEWithMD5AndDES(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithMD5AndRC2 extends JCEBlockCipher { // Constructors public PBEWithMD5AndRC2(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHA1AndDES extends JCEBlockCipher { // Constructors public PBEWithSHA1AndDES(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHA1AndRC2 extends JCEBlockCipher { // Constructors public PBEWithSHA1AndRC2(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHAAndDES3Key extends JCEBlockCipher { // Constructors public PBEWithSHAAndDES3Key(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHAAndDES2Key extends JCEBlockCipher { // Constructors public PBEWithSHAAndDES2Key(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHAAnd128BitRC2 extends JCEBlockCipher { // Constructors public PBEWithSHAAnd128BitRC2(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHAAnd40BitRC2 extends JCEBlockCipher { // Constructors public PBEWithSHAAnd40BitRC2(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithSHAAndTwofish extends JCEBlockCipher { // Constructors public PBEWithSHAAndTwofish(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } public static class PBEWithAESCBC extends JCEBlockCipher { // Constructors public PBEWithAESCBC(){ super((com.android.org.bouncycastle.crypto.BlockCipher) null); } } // Constructors protected JCEBlockCipher(com.android.org.bouncycastle.crypto.BlockCipher arg1){ super(); } protected JCEBlockCipher(com.android.org.bouncycastle.crypto.BlockCipher arg1, int arg2){ super(); } protected JCEBlockCipher(com.android.org.bouncycastle.crypto.BufferedBlockCipher arg1, int arg2){ super(); } // Methods protected void engineInit(int arg1, java.security.Key arg2, java.security.spec.AlgorithmParameterSpec arg3, java.security.SecureRandom arg4) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException{ } protected void engineInit(int arg1, java.security.Key arg2, java.security.AlgorithmParameters arg3, java.security.SecureRandom arg4) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException{ } protected void engineInit(int arg1, java.security.Key arg2, java.security.SecureRandom arg3) throws java.security.InvalidKeyException{ } protected int engineGetBlockSize(){ return 0; } protected byte [] engineGetIV(){ return (byte []) null; } protected int engineGetKeySize(java.security.Key arg1){ return 0; } protected int engineGetOutputSize(int arg1){ return 0; } protected java.security.AlgorithmParameters engineGetParameters(){ return (java.security.AlgorithmParameters) null; } protected void engineSetMode(java.lang.String arg1) throws java.security.NoSuchAlgorithmException{ } protected void engineSetPadding(java.lang.String arg1) throws javax.crypto.NoSuchPaddingException{ } protected byte [] engineUpdate(byte [] arg1, int arg2, int arg3){ return (byte []) null; } protected int engineUpdate(byte [] arg1, int arg2, int arg3, byte [] arg4, int arg5) throws javax.crypto.ShortBufferException{ return 0; } protected byte [] engineDoFinal(byte [] arg1, int arg2, int arg3) throws javax.crypto.IllegalBlockSizeException, javax.crypto.BadPaddingException{ return (byte []) null; } protected int engineDoFinal(byte [] arg1, int arg2, int arg3, byte [] arg4, int arg5) throws javax.crypto.IllegalBlockSizeException, javax.crypto.BadPaddingException, javax.crypto.ShortBufferException{ return 0; } }
30.923977
234
0.727685
4db63c440155dec825c847479f190bda5a7da8a1
64
package com.example.lifting; public class WorkoutActivity { }
10.666667
30
0.78125
a48537c0cc99b95494fb6a93946d81294a6f9745
3,347
package com.leboro.service; import com.leboro.service.game.GameService; import com.leboro.service.game.impl.GameServiceImpl; import com.leboro.service.live.LiveService; import com.leboro.service.live.impl.LiveServiceImpl; import com.leboro.service.news.NewsService; import com.leboro.service.news.impl.NewsServiceImpl; import com.leboro.service.standing.StandingService; import com.leboro.service.standing.impl.StandingServiceImpl; import com.leboro.service.statistics.StatisticsService; import com.leboro.service.statistics.impl.StatisticsServiceImpl; import com.leboro.service.teaminfo.TeamInfoService; import com.leboro.service.teaminfo.impl.TeamInfoServiceImpl; import com.leboro.service.volley.NetworkImageLoaderService; import com.leboro.service.volley.impl.VolleyServiceImpl; import com.leboro.util.parser.news.feb.FebNewsParser; import com.leboro.util.parser.news.zonadebasquet.ZonaDeBasquetNewsParser; public class ApplicationServiceProvider { private static StatisticsService statisticsService; private static NetworkImageLoaderService networkImageLoaderService; private static NewsService newsService; private static LiveService liveService; private static GameService gameService; private static StandingService standingService; private static TeamInfoService teamInfoService; // News providers parsers private static FebNewsParser febNewsParser; private static ZonaDeBasquetNewsParser zonaDeBasquetNewsParser; public static NetworkImageLoaderService getNetworkImageLoaderService() { if (networkImageLoaderService == null) { networkImageLoaderService = new VolleyServiceImpl(); } return networkImageLoaderService; } public static StatisticsService getStatisticsService() { if (statisticsService == null) { statisticsService = new StatisticsServiceImpl(); } return statisticsService; } public static NewsService getNewsService() { if (newsService == null) { newsService = new NewsServiceImpl(); } return newsService; } public static LiveService getLiveService() { if (liveService == null) { liveService = new LiveServiceImpl(); } return liveService; } public static GameService getGameService() { if (gameService == null) { gameService = new GameServiceImpl(); } return gameService; } public static StandingService getStandingService() { if (standingService == null) { standingService = new StandingServiceImpl(); } return standingService; } public static TeamInfoService getTeamInfoService() { if (teamInfoService == null) { teamInfoService = new TeamInfoServiceImpl(); } return teamInfoService; } // News providers info public static FebNewsParser getFebNewsParser() { if (febNewsParser == null) { febNewsParser = new FebNewsParser(); } return febNewsParser; } public static ZonaDeBasquetNewsParser getZonaDeBasquetNewsParser() { if (zonaDeBasquetNewsParser == null) { zonaDeBasquetNewsParser = new ZonaDeBasquetNewsParser(); } return zonaDeBasquetNewsParser; } }
28.853448
76
0.713475
0a3f92d502914aab5b2779df6268749a05868945
2,291
package rsb.wrappers.subwrap; import rsb.methods.Menu; import rsb.wrappers.common.Clickable; import java.awt.*; public class RSMenuNode { private int index; private Rectangle area; private String action; private String target; private int type; private int data1; private int data2; private int data3; RSMenuNode(int index, Rectangle area, String action, String target, int type, int data1, int data2, int data3){ this.index = index; this.area = area; this.action = action; this.target = target; this.type = type; this.data1 = data1; this.data2 = data2; this.data3 = data3; } public boolean contains(String... text) { for (String check : text) { if ((this.action + " " + this.target).contains(check)) { return true; } } return false; } public boolean containsTarget(String... text) { for (String check : text) { if ((this.target).equals(check)) { return true; } } return false; } public boolean containsAction(String... text) { for (String check : text) { if ((this.action).equals(check)) { return true; } } return false; } /** * TODO: Properly implement feature * Checks if the RSMenuNode is associated with an option of a clickable entity * @param clickable The clickable object to check * @return <code>True</code> if the RSMenuNode is associated with the clickable */ public boolean correlatesTo(Clickable clickable) { return false; } /* public boolean equals(Object o) { } */ public int getIndex() { return index; } public Rectangle getArea() { return area; } public String getAction() { return Menu.stripFormatting(action); } public String getTarget() { return Menu.stripFormatting(target); } public int getType() { return type; } public int getData1() { return data1; } public int getData2() { return data2; } public int getData3() { return data3; } }
21.212963
115
0.562636
578d88b94549a8842f469b463ed0425516ce768d
536
package util.rocket_league.controllers.ground.dribble.strong; import util.math.vector.Vector3; import java.util.function.Supplier; public class StrongDribbleProfile { public final Supplier<Vector3> offsetFunction; public final Supplier<Double> minimumBoostAmount; StrongDribbleProfile( final Supplier<Vector3> offsetFunction, final Supplier<Double> minimumBoostAmount) { this.offsetFunction = offsetFunction; this.minimumBoostAmount = minimumBoostAmount; } }
29.777778
62
0.723881
974f185f0c8dc90762323ee076a11ae5dfe6f750
3,903
package org.batfish.representation.palo_alto; import java.io.Serializable; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNullableByDefault; import org.batfish.datamodel.IntegerSpace; import org.batfish.datamodel.IpProtocol; import org.batfish.datamodel.SubRange; /** PAN datamodel component containing application-override rule configuration */ @ParametersAreNullableByDefault public final class ApplicationOverrideRule implements Serializable { // Possible protocols for traffic to match an application-override rule public enum Protocol { TCP, UDP, UNSPECIFIED } // Name of the rule @Nonnull private final String _name; // Description of the rule @Nullable private String _description; // Application used for traffic matching this rule @Nullable private String _application; private boolean _disabled; // Zones to match @Nonnull private final SortedSet<String> _from; @Nonnull private final SortedSet<String> _to; // IPs to match @Nonnull private final List<RuleEndpoint> _source; @Nonnull private final List<RuleEndpoint> _destination; private boolean _negateSource; private boolean _negateDestination; // Traffic characteristics to match @Nonnull private Protocol _protocol; @Nonnull private IntegerSpace _port; @Nonnull private final Set<String> _tags; public ApplicationOverrideRule(@Nonnull String name) { _destination = new LinkedList<>(); _negateDestination = false; _source = new LinkedList<>(); _negateSource = false; _disabled = false; _from = new TreeSet<>(); _to = new TreeSet<>(); _tags = new HashSet<>(1); _name = name; _port = IntegerSpace.EMPTY; _protocol = Protocol.UNSPECIFIED; } @Nonnull public String getName() { return _name; } @Nullable public String getDescription() { return _description; } @Nullable public String getApplication() { return _application; } public boolean getDisabled() { return _disabled; } @Nonnull public SortedSet<String> getFrom() { return _from; } @Nonnull public SortedSet<String> getTo() { return _to; } @Nonnull public List<RuleEndpoint> getSource() { return _source; } @Nonnull public List<RuleEndpoint> getDestination() { return _destination; } public boolean getNegateSource() { return _negateSource; } public boolean getNegateDestination() { return _negateDestination; } @Nonnull public Protocol getProtocol() { return _protocol; } @Nullable public IpProtocol getIpProtocol() { switch (_protocol) { case TCP: return IpProtocol.TCP; case UDP: return IpProtocol.UDP; case UNSPECIFIED: default: return null; } } @Nonnull public IntegerSpace getPort() { return _port; } @Nonnull public Set<String> getTags() { return _tags; } public void setDescription(String description) { _description = description; } public void setApplication(String application) { _application = application; } public void setDisabled(boolean disabled) { _disabled = disabled; } public void setNegateSource(boolean negateSource) { _negateSource = negateSource; } public void setNegateDestination(boolean negateDestination) { _negateDestination = negateDestination; } public void setProtocol(@Nonnull Protocol protocol) { _protocol = protocol; } public void addPort(int port) { _port = IntegerSpace.builder().including(_port).including(port).build(); } public void addPorts(@Nonnull SubRange ports) { _port = IntegerSpace.builder().including(_port).including(ports).build(); } }
22.176136
81
0.714835
84ba4406c2d420b5db3b5e55dc782c50533b74d6
70,522
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * 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.eclipse.andmore.internal.editors; import static org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.Collections; import org.eclipse.andmore.AdtUtils; import org.eclipse.andmore.AndmoreAndroidConstants; import org.eclipse.andmore.AndmoreAndroidPlugin; import org.eclipse.andmore.internal.editors.uimodel.UiElementNode; import org.eclipse.andmore.internal.lint.EclipseLintRunner; import org.eclipse.andmore.internal.preferences.AdtPrefs; import org.eclipse.andmore.internal.refactorings.core.RenameResourceXmlTextAction; import org.eclipse.andmore.internal.sdk.AndroidTargetData; import org.eclipse.andmore.internal.sdk.Sdk; import org.eclipse.andmore.internal.sdk.Sdk.ITargetChangeListener; import org.eclipse.andmore.internal.sdk.Sdk.TargetChangeListener; import org.eclipse.andworx.build.AndworxFactory; import org.eclipse.andworx.context.AndroidEnvironment; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IURIEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.editor.IFormPage; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.events.IHyperlinkListener; import org.eclipse.ui.forms.widgets.FormText; import org.eclipse.ui.ide.IDEActionFactory; import org.eclipse.ui.ide.IGotoMarker; import org.eclipse.ui.internal.browser.WorkbenchBrowserSupport; import org.eclipse.ui.part.MultiPageEditorPart; import org.eclipse.ui.part.WorkbenchPart; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.wst.sse.core.StructuredModelManager; import org.eclipse.wst.sse.core.internal.provisional.IModelManager; import org.eclipse.wst.sse.core.internal.provisional.IModelStateListener; import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; import org.eclipse.wst.sse.ui.StructuredTextEditor; import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; import org.eclipse.wst.xml.core.internal.document.NodeContainer; import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; import org.w3c.dom.Document; import org.w3c.dom.Node; import com.android.annotations.Nullable; import com.android.sdklib.IAndroidTarget; /** * Multi-page form editor for Android XML files. * <p/> * It is designed to work with a {@link StructuredTextEditor} that will display an XML file. * <br/> * Derived classes must implement createFormPages to create the forms before the * source editor. This can be a no-op if desired. */ @SuppressWarnings("restriction") // Uses XML model, which has no non-restricted replacement yet public abstract class AndroidXmlEditor extends FormEditor { /** Icon used for the XML source page. */ public static final String ICON_XML_PAGE = "editor_page_source"; //$NON-NLS-1$ /** Preference name for the current page of this file */ private static final String PREF_CURRENT_PAGE = "_current_page"; //$NON-NLS-1$ /** Id string used to create the Android SDK browser */ private static String BROWSER_ID = "android"; //$NON-NLS-1$ /** Page id of the XML source editor, used for switching tabs programmatically */ public final static String TEXT_EDITOR_ID = "editor_part"; //$NON-NLS-1$ /** Width hint for text fields. Helps the grid layout resize properly on smaller screens */ public static final int TEXT_WIDTH_HINT = 50; /** Page index of the text editor (always the last page) */ protected int mTextPageIndex; /** The text editor */ private StructuredTextEditor mTextEditor; /** Listener for the XML model from the StructuredEditor */ private XmlModelStateListener mXmlModelStateListener; /** Listener to update the root node if the target of the file is changed because of a * SDK location change or a project target change */ private TargetChangeListener mTargetListener = null; /** flag set during page creation */ private boolean mIsCreatingPage = false; /** * Flag used to ignore XML model updates. For example, the flag is set during * formatting. A format operation should completely preserve the semantics of the XML * so the document listeners can use this flag to skip updating the model when edits * are observed during a formatting operation */ private boolean mIgnoreXmlUpdate; /** * Flag indicating we're inside {@link #wrapEditXmlModel(Runnable)}. * This is a counter, which allows us to nest the edit XML calls. * There is no pending operation when the counter is at zero. */ private int mIsEditXmlModelPending; /** * Usually null, but during an editing operation, represents the highest * node which should be formatted when the editing operation is complete. */ private UiElementNode mFormatNode; /** * Whether {@link #mFormatNode} should be formatted recursively, or just * the node itself (its arguments) */ private boolean mFormatChildren; /** * Creates a form editor. * <p/> * Some derived classes will want to use {@link #addDefaultTargetListener()} * to setup the default listener to monitor SDK target changes. This * is no longer the default. */ public AndroidXmlEditor() { super(); } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { super.init(site, input); } /** * Setups a default {@link ITargetChangeListener} that will call * {@link #initUiRootNode(boolean)} when the SDK or the target changes. */ public void addDefaultTargetListener() { if (mTargetListener == null) { mTargetListener = new TargetChangeListener() { @Override public IProject getProject() { return AndroidXmlEditor.this.getProject(); } @Override public void reload() { commitPages(false /* onSave */); // recreate the ui root node always initUiRootNode(true /*force*/); } }; AndmoreAndroidPlugin.getDefault().addTargetListener(mTargetListener); } } // ---- Abstract Methods ---- /** * Returns the root node of the UI element hierarchy manipulated by the current * UI node editor. */ abstract public UiElementNode getUiRootNode(); /** * Creates the various form pages. * <p/> * Derived classes must implement this to add their own specific tabs. */ abstract protected void createFormPages(); /** * Called by the base class {@link AndroidXmlEditor} once all pages (custom form pages * as well as text editor page) have been created. This give a chance to deriving * classes to adjust behavior once the text page has been created. */ protected void postCreatePages() { // Nothing in the base class. } /** * Creates the initial UI Root Node, including the known mandatory elements. * @param force if true, a new UiManifestNode is recreated even if it already exists. */ abstract protected void initUiRootNode(boolean force); /** * Subclasses should override this method to process the new XML Model, which XML * root node is given. * * The base implementation is empty. * * @param xml_doc The XML document, if available, or null if none exists. */ abstract protected void xmlModelChanged(Document xml_doc); /** * Controls whether XML models are ignored or not. * * @param ignore when true, ignore all subsequent XML model updates, when false start * processing XML model updates again */ public void setIgnoreXmlUpdate(boolean ignore) { mIgnoreXmlUpdate = ignore; } /** * Returns whether XML model events are ignored or not. This is the case * when we are deliberately modifying the document in a way which does not * change the semantics (such as formatting), or when we have already * directly updated the model ourselves. * * @return true if XML events should be ignored */ public boolean getIgnoreXmlUpdate() { return mIgnoreXmlUpdate; } // ---- Base Class Overrides, Interfaces Implemented ---- @SuppressWarnings("unchecked") @Override public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { Object result = super.getAdapter(adapter); if (result != null && adapter.equals(IGotoMarker.class) ) { final IGotoMarker gotoMarker = (IGotoMarker) result; return new IGotoMarker() { @Override public void gotoMarker(IMarker marker) { gotoMarker.gotoMarker(marker); try { // Lint markers should always jump to XML text if (marker.getType().equals(AndmoreAndroidConstants.MARKER_LINT)) { IEditorPart editor = AdtUtils.getActiveEditor(); if (editor instanceof AndroidXmlEditor) { AndroidXmlEditor xmlEditor = (AndroidXmlEditor) editor; xmlEditor.setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID); } } } catch (CoreException e) { AndmoreAndroidPlugin.log(e, null); } } }; } if (result == null && adapter == IContentOutlinePage.class) { return getStructuredTextEditor().getAdapter(adapter); } return result; } /** * Creates the pages of the multi-page editor. */ @Override protected void addPages() { createAndroidPages(); selectDefaultPage(null /* defaultPageId */); } /** * Creates the page for the Android Editors */ public void createAndroidPages() { mIsCreatingPage = true; createFormPages(); createTextEditor(); updateActionBindings(); postCreatePages(); mIsCreatingPage = false; } /** * Returns whether the editor is currently creating its pages. */ public boolean isCreatingPages() { return mIsCreatingPage; } /** * {@inheritDoc} * <p/> * If the page is an instance of {@link IPageImageProvider}, the image returned by * by {@link IPageImageProvider#getPageImage()} will be set on the page's tab. */ @Override public int addPage(IFormPage page) throws PartInitException { int index = super.addPage(page); if (page instanceof IPageImageProvider) { setPageImage(index, ((IPageImageProvider) page).getPageImage()); } return index; } /** * {@inheritDoc} * <p/> * If the editor is an instance of {@link IPageImageProvider}, the image returned by * by {@link IPageImageProvider#getPageImage()} will be set on the page's tab. */ @Override public int addPage(IEditorPart editor, IEditorInput input) throws PartInitException { int index = super.addPage(editor, input); if (editor instanceof IPageImageProvider) { setPageImage(index, ((IPageImageProvider) editor).getPageImage()); } return index; } /** * Creates undo redo (etc) actions for the editor site (so that it works for any page of this * multi-page editor) by re-using the actions defined by the {@link StructuredTextEditor} * (aka the XML text editor.) */ protected void updateActionBindings() { IActionBars bars = getEditorSite().getActionBars(); if (bars != null) { IAction action = mTextEditor.getAction(ActionFactory.UNDO.getId()); bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), action); action = mTextEditor.getAction(ActionFactory.REDO.getId()); bars.setGlobalActionHandler(ActionFactory.REDO.getId(), action); bars.setGlobalActionHandler(ActionFactory.DELETE.getId(), mTextEditor.getAction(ActionFactory.DELETE.getId())); bars.setGlobalActionHandler(ActionFactory.CUT.getId(), mTextEditor.getAction(ActionFactory.CUT.getId())); bars.setGlobalActionHandler(ActionFactory.COPY.getId(), mTextEditor.getAction(ActionFactory.COPY.getId())); bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), mTextEditor.getAction(ActionFactory.PASTE.getId())); bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), mTextEditor.getAction(ActionFactory.SELECT_ALL.getId())); bars.setGlobalActionHandler(ActionFactory.FIND.getId(), mTextEditor.getAction(ActionFactory.FIND.getId())); bars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), mTextEditor.getAction(IDEActionFactory.BOOKMARK.getId())); bars.updateActionBars(); } } /** * Clears the action bindings for the editor site. */ protected void clearActionBindings(boolean includeUndoRedo) { IActionBars bars = getEditorSite().getActionBars(); if (bars != null) { // For some reason, undo/redo doesn't seem to work in the form editor. // This appears to be the case for pure Eclipse form editors too, e.g. see // https://bugs.eclipse.org/bugs/show_bug.cgi?id=68423 // However, as a workaround we can use the *text* editor's underlying undo // to revert operations being done in the UI, and the form automatically updates. // Therefore, to work around this, we simply leave the text editor bindings // in place if {@code includeUndoRedo} is not set if (includeUndoRedo) { bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), null); bars.setGlobalActionHandler(ActionFactory.REDO.getId(), null); } bars.setGlobalActionHandler(ActionFactory.DELETE.getId(), null); bars.setGlobalActionHandler(ActionFactory.CUT.getId(), null); bars.setGlobalActionHandler(ActionFactory.COPY.getId(), null); bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), null); bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null); bars.setGlobalActionHandler(ActionFactory.FIND.getId(), null); bars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), null); bars.updateActionBars(); } } /** * Selects the default active page. * @param defaultPageId the id of the page to show. If <code>null</code> the editor attempts to * find the default page in the properties of the {@link IResource} object being edited. */ public void selectDefaultPage(String defaultPageId) { if (defaultPageId == null) { IFile file = getInputFile(); if (file != null) { QualifiedName qname = new QualifiedName(AndmoreAndroidConstants.ANDMORE_ID, getClass().getSimpleName() + PREF_CURRENT_PAGE); String pageId; try { pageId = file.getPersistentProperty(qname); if (pageId != null) { defaultPageId = pageId; } } catch (CoreException e) { // ignored } } } AdtPrefs adtPrefs = AndmoreAndroidPlugin.getDefault().getAdtPrefs(); if (defaultPageId != null) { try { setActivePage(Integer.parseInt(defaultPageId)); } catch (Exception e) { // We can get NumberFormatException from parseInt but also // AssertionError from setActivePage when the index is out of bounds. // Generally speaking we just want to ignore any exception and fall back on the // first page rather than crash the editor load. Logging the error is enough. AndmoreAndroidPlugin.log(e, "Selecting page '%s' in AndroidXmlEditor failed", defaultPageId); } } else if (adtPrefs.isXmlEditorPreferred(getPersistenceCategory())) { setActivePage(mTextPageIndex); } } /** The layout editor */ public static final int CATEGORY_LAYOUT = 1 << 0; /** The manifest editor */ public static final int CATEGORY_MANIFEST = 1 << 1; /** Any other XML editor */ public static final int CATEGORY_OTHER = 1 << 2; /** * Returns the persistence category to use for this editor; this should be * one of the {@code CATEGORY_} constants such as {@link #CATEGORY_MANIFEST}, * {@link #CATEGORY_LAYOUT}, {@link #CATEGORY_OTHER}, ... * <p> * The persistence category is used to group editors together when it comes * to certain types of persistence metadata. For example, whether this type * of file was most recently edited graphically or with an XML text editor. * We'll open new files in the same text or graphical mode as the last time * the user edited a file of the same persistence category. * <p> * Before we added the persistence category, we had a single boolean flag * recording whether the XML files were most recently edited graphically or * not. However, this meant that users can't for example prefer to edit * Manifest files graphically and string files via XML. By splitting the * editors up into categories, we can track the mode at a finer granularity, * and still allow similar editors such as those used for animations and * colors to be treated the same way. * * @return the persistence category constant */ protected int getPersistenceCategory() { return CATEGORY_OTHER; } /** * Removes all the pages from the editor. */ protected void removePages() { int count = getPageCount(); for (int i = count - 1 ; i >= 0 ; i--) { removePage(i); } } /** * Overrides the parent's setActivePage to be able to switch to the xml editor. * * If the special pageId TEXT_EDITOR_ID is given, switches to the mTextPageIndex page. * This is needed because the editor doesn't actually derive from IFormPage and thus * doesn't have the get-by-page-id method. In this case, the method returns null since * IEditorPart does not implement IFormPage. */ @Override public IFormPage setActivePage(String pageId) { if (pageId.equals(TEXT_EDITOR_ID)) { super.setActivePage(mTextPageIndex); return null; } else { return super.setActivePage(pageId); } } /** * Notifies this multi-page editor that the page with the given id has been * activated. This method is called when the user selects a different tab. * * @see MultiPageEditorPart#pageChange(int) */ @Override protected void pageChange(int newPageIndex) { super.pageChange(newPageIndex); // Do not record page changes during creation of pages if (mIsCreatingPage) { return; } IFile file = getInputFile(); if (file != null) { QualifiedName qname = new QualifiedName(AndmoreAndroidConstants.ANDMORE_ID, getClass().getSimpleName() + PREF_CURRENT_PAGE); try { file.setPersistentProperty(qname, Integer.toString(newPageIndex)); } catch (CoreException e) { // ignore } } boolean isTextPage = newPageIndex == mTextPageIndex; AdtPrefs adtPrefs = AndmoreAndroidPlugin.getDefault().getAdtPrefs(); adtPrefs.setXmlEditorPreferred(getPersistenceCategory(), isTextPage); } /** * Returns true if the active page is the editor page * * @return true if the active page is the editor page */ public boolean isEditorPageActive() { return getActivePage() == mTextPageIndex; } /** * Returns the {@link IFile} matching the editor's input or null. */ @Nullable public IFile getInputFile() { IEditorInput input = getEditorInput(); if (input instanceof IFileEditorInput) { return ((IFileEditorInput) input).getFile(); } return null; } /** * Removes attached listeners. * * @see WorkbenchPart */ @Override public void dispose() { IStructuredModel xml_model = getModelForRead(); if (xml_model != null) { try { if (mXmlModelStateListener != null) { xml_model.removeModelStateListener(mXmlModelStateListener); } } finally { xml_model.releaseFromRead(); } } if (mTargetListener != null) { AndmoreAndroidPlugin.getDefault().removeTargetListener(mTargetListener); mTargetListener = null; } if (pages != null) // Workaround for NPE super.dispose(); else { if (getToolkit() != null) { getToolkit().dispose(); } } } /** * Commit all dirty pages then saves the contents of the text editor. * <p/> * This works by committing all data to the XML model and then * asking the Structured XML Editor to save the XML. * * @see IEditorPart */ @Override public void doSave(IProgressMonitor monitor) { commitPages(true /* onSave */); AdtPrefs adtPrefs = AndmoreAndroidPlugin.getDefault().getAdtPrefs(); if (adtPrefs.isFormatOnSave()) { IAction action = mTextEditor.getAction(ACTION_NAME_FORMAT_DOCUMENT); if (action != null) { try { mIgnoreXmlUpdate = true; action.run(); } finally { mIgnoreXmlUpdate = false; } } } // The actual "save" operation is done by the Structured XML Editor getEditor(mTextPageIndex).doSave(monitor); // Check for errors on save, if enabled if (adtPrefs.isLintOnSave()) { runLint(); } } /** * Tells the editor to start a Lint check. * It's up to the caller to check whether this should be done depending on preferences. * <p/> * The default implementation is to call {@link #startLintJob()}. * * @return The Job started by {@link EclipseLintRunner} or null if no job was started. */ protected Job runLint() { return startLintJob(); } /** * Utility method that creates a Job to run Lint on the current document. * Does not wait for the job to finish - just returns immediately. * * @return a new job, or null * @see EclipseLintRunner#startLint(java.util.List, IResource, IDocument, * boolean, boolean) */ @Nullable public Job startLintJob() { IFile file = getInputFile(); if (file != null) { return EclipseLintRunner.startLint(Collections.singletonList(file), file, getStructuredDocument(), false /*fatalOnly*/, false /*show*/); } return null; } /* (non-Javadoc) * Saves the contents of this editor to another object. * <p> * Subclasses must override this method to implement the open-save-close lifecycle * for an editor. For greater details, see <code>IEditorPart</code> * </p> * * @see IEditorPart */ @Override public void doSaveAs() { commitPages(true /* onSave */); IEditorPart editor = getEditor(mTextPageIndex); editor.doSaveAs(); setPageText(mTextPageIndex, editor.getTitle()); setInput(editor.getEditorInput()); } /** * Commits all dirty pages in the editor. This method should * be called as a first step of a 'save' operation. * <p/> * This is the same implementation as in {@link FormEditor} * except it fixes two bugs: a cast to IFormPage is done * from page.get(i) <em>before</em> being tested with instanceof. * Another bug is that the last page might be a null pointer. * <p/> * The incorrect casting makes the original implementation crash due * to our {@link StructuredTextEditor} not being an {@link IFormPage} * so we have to override and duplicate to fix it. * * @param onSave <code>true</code> if commit is performed as part * of the 'save' operation, <code>false</code> otherwise. * @since 3.3 */ @Override public void commitPages(boolean onSave) { if (pages != null) { for (int i = 0; i < pages.size(); i++) { Object page = pages.get(i); if (page != null && page instanceof IFormPage) { IFormPage form_page = (IFormPage) page; IManagedForm managed_form = form_page.getManagedForm(); if (managed_form != null && managed_form.isDirty()) { managed_form.commit(onSave); } } } } } /* (non-Javadoc) * Returns whether the "save as" operation is supported by this editor. * <p> * Subclasses must override this method to implement the open-save-close lifecycle * for an editor. For greater details, see <code>IEditorPart</code> * </p> * * @see IEditorPart */ @Override public boolean isSaveAsAllowed() { return false; } /** * Returns the page index of the text editor (always the last page) * @return the page index of the text editor (always the last page) */ public int getTextPageIndex() { return mTextPageIndex; } // ---- Local methods ---- /** * Helper method that creates a new hyper-link Listener. * Used by derived classes which need active links in {@link FormText}. * <p/> * This link listener handles two kinds of URLs: * <ul> * <li> Links starting with "http" are simply sent to a local browser. * <li> Links starting with "file:/" are simply sent to a local browser. * <li> Links starting with "page:" are expected to be an editor page id to switch to. * <li> Other links are ignored. * </ul> * * @return A new hyper-link listener for FormText to use. */ public final IHyperlinkListener createHyperlinkListener() { return new HyperlinkAdapter() { /** * Switch to the page corresponding to the link that has just been clicked. * For this purpose, the HREF of the &lt;a&gt; tags above is the page ID to switch to. */ @Override public void linkActivated(HyperlinkEvent e) { super.linkActivated(e); String link = e.data.toString(); if (link.startsWith("http") || //$NON-NLS-1$ link.startsWith("file:/")) { //$NON-NLS-1$ openLinkInBrowser(link); } else if (link.startsWith("page:")) { //$NON-NLS-1$ // Switch to an internal page setActivePage(link.substring(5 /* strlen("page:") */)); } } }; } /** * Open the http link into a browser * * @param link The URL to open in a browser */ private void openLinkInBrowser(String link) { try { IWorkbenchBrowserSupport wbs = WorkbenchBrowserSupport.getInstance(); wbs.createBrowser(BROWSER_ID).openURL(new URL(link)); } catch (PartInitException e1) { // pass } catch (MalformedURLException e1) { // pass } } /** * Creates the XML source editor. * <p/> * Memorizes the index page of the source editor (it's always the last page, but the number * of pages before can change.) * <br/> * Retrieves the underlying XML model from the StructuredEditor and attaches a listener to it. * Finally triggers modelChanged() on the model listener -- derived classes can use this * to initialize the model the first time. * <p/> * Called only once <em>after</em> createFormPages. */ private void createTextEditor() { try { mTextEditor = new StructuredTextEditor() { @Override protected void createActions() { super.createActions(); Action action = new RenameResourceXmlTextAction(mTextEditor); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.RENAME_ELEMENT); setAction(IJavaEditorActionDefinitionIds.RENAME_ELEMENT, action); } }; int index = addPage(mTextEditor, getEditorInput()); mTextPageIndex = index; setPageText(index, mTextEditor.getTitle()); setPageImage(index, IconFactory.getInstance().getIcon(ICON_XML_PAGE)); if (!(mTextEditor.getTextViewer().getDocument() instanceof IStructuredDocument)) { Status status = new Status(IStatus.ERROR, AndmoreAndroidConstants.ANDMORE_ID, "Error opening the Android XML editor. Is the document an XML file?"); throw new RuntimeException("Android XML Editor Error", new CoreException(status)); } IStructuredModel xml_model = getModelForRead(); if (xml_model != null) { try { mXmlModelStateListener = new XmlModelStateListener(); xml_model.addModelStateListener(mXmlModelStateListener); mXmlModelStateListener.modelChanged(xml_model); } catch (Exception e) { AndmoreAndroidPlugin.log(e, "Error while loading editor"); //$NON-NLS-1$ } finally { xml_model.releaseFromRead(); } } } catch (PartInitException e) { ErrorDialog.openError(getSite().getShell(), "Android XML Editor Error", null, e.getStatus()); } } /** * Returns the ISourceViewer associated with the Structured Text editor. */ public final ISourceViewer getStructuredSourceViewer() { if (mTextEditor != null) { // We can't access mDelegate.getSourceViewer() because it is protected, // however getTextViewer simply returns the SourceViewer casted, so we // can use it instead. return mTextEditor.getTextViewer(); } return null; } /** * Return the {@link StructuredTextEditor} associated with this XML editor * * @return the associated {@link StructuredTextEditor} */ public StructuredTextEditor getStructuredTextEditor() { return mTextEditor; } /** * Returns the {@link IStructuredDocument} used by the StructuredTextEditor (aka Source * Editor) or null if not available. */ public IStructuredDocument getStructuredDocument() { if (mTextEditor != null && mTextEditor.getTextViewer() != null) { return (IStructuredDocument) mTextEditor.getTextViewer().getDocument(); } return null; } /** * Returns a version of the model that has been shared for read. * <p/> * Callers <em>must</em> call model.releaseFromRead() when done, typically * in a try..finally clause. * * Portability note: this uses getModelManager which is part of wst.sse.core; however * the interface returned is part of wst.sse.core.internal.provisional so we can * expect it to change in a distant future if they start cleaning their codebase, * however unlikely that is. * * @return The model for the XML document or null if cannot be obtained from the editor */ public IStructuredModel getModelForRead() { IStructuredDocument document = getStructuredDocument(); if (document != null) { IModelManager mm = StructuredModelManager.getModelManager(); if (mm != null) { // TODO simplify this by not using the internal IStructuredDocument. // Instead we can now use mm.getModelForRead(getFile()). // However we must first check that SSE for Eclipse 3.3 or 3.4 has this // method. IIRC 3.3 didn't have it. return mm.getModelForRead(document); } } return null; } /** * Returns a version of the model that has been shared for edit. * <p/> * Callers <em>must</em> call model.releaseFromEdit() when done, typically * in a try..finally clause. * <p/> * Because of this, it is mandatory to use the wrapper * {@link #wrapEditXmlModel(Runnable)} which executes a runnable into a * properly configured model and then performs whatever cleanup is necessary. * * @return The model for the XML document or null if cannot be obtained from the editor */ private IStructuredModel getModelForEdit() { IStructuredDocument document = getStructuredDocument(); if (document != null) { IModelManager mm = StructuredModelManager.getModelManager(); if (mm != null) { // TODO simplify this by not using the internal IStructuredDocument. // Instead we can now use mm.getModelForRead(getFile()). // However we must first check that SSE for Eclipse 3.3 or 3.4 has this // method. IIRC 3.3 didn't have it. return mm.getModelForEdit(document); } } return null; } /** * Helper class to perform edits on the XML model whilst making sure the * model has been prepared to be changed. * <p/> * It first gets a model for edition using {@link #getModelForEdit()}, * then calls {@link IStructuredModel#aboutToChangeModel()}, * then performs the requested action * and finally calls {@link IStructuredModel#changedModel()} * and {@link IStructuredModel#releaseFromEdit()}. * <p/> * The method is synchronous. As soon as the {@link IStructuredModel#changedModel()} method * is called, XML model listeners will be triggered. * <p/> * Calls can be nested: only the first outer call will actually start and close the edit * session. * <p/> * This method is <em>not synchronized</em> and is not thread safe. * Callers must be using it from the the main UI thread. * * @param editAction Something that will change the XML. */ public final void wrapEditXmlModel(Runnable editAction) { wrapEditXmlModel(editAction, null); } /** * Perform any editor-specific hooks after applying an edit. When edits are * nested, the hooks will only run after the final top level edit has been * performed. * <p> * Note that the edit hooks are performed outside of the edit lock so * the hooks should not perform edits on the model without acquiring * a lock first. */ public void runEditHooks() { if (!mIgnoreXmlUpdate) { AdtPrefs adtPrefs = AndmoreAndroidPlugin.getDefault().getAdtPrefs(); // Check for errors, if enabled if (adtPrefs.isLintOnSave()) { runLint(); } } } /** * Executor which performs the given action under an edit lock (and optionally as a * single undo event). * * @param editAction the action to be executed * @param undoLabel if non null, the edit action will be run as a single undo event * and the label used as the name of the undoable action */ private final void wrapEditXmlModel(final Runnable editAction, final String undoLabel) { Display display = mTextEditor.getSite().getShell().getDisplay(); if (display.getThread() != Thread.currentThread()) { display.syncExec(new Runnable() { @Override public void run() { if (!mTextEditor.getTextViewer().getControl().isDisposed()) { wrapEditXmlModel(editAction, undoLabel); } } }); return; } IStructuredModel model = null; int undoReverseCount = 0; try { if (mIsEditXmlModelPending == 0) { try { model = getModelForEdit(); if (undoLabel != null) { // Run this action as an undoable unit. // We have to do it more than once, because in some scenarios // Eclipse WTP decides to cancel the current undo command on its // own -- see http://code.google.com/p/android/issues/detail?id=15901 // for one such call chain. By nesting these calls several times // we've incrementing the command count such that a couple of // cancellations are ignored. Interfering with this mechanism may // sound dangerous, but it appears that this undo-termination is // done for UI reasons to anticipate what the user wants, and we know // that in *our* scenarios we want the entire unit run as a single // unit. Here's what the documentation for // IStructuredTextUndoManager#forceEndOfPendingCommand says // "Normally, the undo manager can figure out the best // times when to end a pending command and begin a new // one ... to the structure of a structured // document. There are times, however, when clients may // wish to override those algorithms and end one earlier // than normal. The one known case is for multi-page // editors. If a user is on one page, and type '123' as // attribute value, then click around to other parts of // page, or different pages, then return to '123|' and // type 456, then "undo" they typically expect the undo // to just undo what they just typed, the 456, not the // whole attribute value." for (int i = 0; i < 4; i++) { model.beginRecording(this, undoLabel); undoReverseCount++; } } model.aboutToChangeModel(); } catch (Throwable t) { // This is never supposed to happen unless we suddenly don't have a model. // If it does, we don't want to even try to modify anyway. AndmoreAndroidPlugin.log(t, "XML Editor failed to get model to edit"); //$NON-NLS-1$ return; } } mIsEditXmlModelPending++; editAction.run(); } finally { mIsEditXmlModelPending--; if (model != null) { try { boolean oldIgnore = mIgnoreXmlUpdate; try { mIgnoreXmlUpdate = true; AdtPrefs adtPrefs = AndmoreAndroidPlugin.getDefault().getAdtPrefs(); if (adtPrefs.getFormatGuiXml() && mFormatNode != null) { if (mFormatNode == getUiRootNode()) { reformatDocument(); } else { Node node = mFormatNode.getXmlNode(); if (node instanceof IndexedRegion) { IndexedRegion region = (IndexedRegion) node; int begin = region.getStartOffset(); int end = region.getEndOffset(); if (!mFormatChildren) { // This will format just the attribute list end = begin + 1; } if (mFormatChildren && node == node.getOwnerDocument().getDocumentElement()) { reformatDocument(); } else { reformatRegion(begin, end); } } } mFormatNode = null; mFormatChildren = false; } // Notify the model we're done modifying it. This must *always* be executed. model.changedModel(); // Clean up the undo unit. This is done more than once as explained // above for beginRecording. for (int i = 0; i < undoReverseCount; i++) { model.endRecording(this); } } finally { mIgnoreXmlUpdate = oldIgnore; } } catch (Exception e) { AndmoreAndroidPlugin.log(e, "Failed to clean up undo unit"); } model.releaseFromEdit(); if (mIsEditXmlModelPending < 0) { AndmoreAndroidPlugin.log(IStatus.ERROR, "wrapEditXmlModel finished with invalid nested counter==%1$d", //$NON-NLS-1$ mIsEditXmlModelPending); mIsEditXmlModelPending = 0; } runEditHooks(); // Notify listeners IStructuredModel readModel = getModelForRead(); if (readModel != null) { try { mXmlModelStateListener.modelChanged(readModel); } catch (Exception e) { AndmoreAndroidPlugin.log(e, "Error while notifying changes"); //$NON-NLS-1$ } finally { readModel.releaseFromRead(); } } } } } /** * Does this editor participate in the "format GUI editor changes" option? * * @return true if this editor supports automatically formatting XML * affected by GUI changes */ public boolean supportsFormatOnGuiEdit() { return false; } /** * Mark the given node as needing to be formatted when the current edits are * done, provided the user has turned that option on (see * {@link AdtPrefs#getFormatGuiXml()}). * * @param node the node to be scheduled for formatting * @param attributesOnly if true, only update the attributes list of the * node, otherwise update the node recursively (e.g. all children * too) */ public void scheduleNodeReformat(UiElementNode node, boolean attributesOnly) { if (!supportsFormatOnGuiEdit()) { return; } if (node == mFormatNode) { if (!attributesOnly) { mFormatChildren = true; } } else if (mFormatNode == null) { mFormatNode = node; mFormatChildren = !attributesOnly; } else { if (mFormatNode.isAncestorOf(node)) { mFormatChildren = true; } else if (node.isAncestorOf(mFormatNode)) { mFormatNode = node; mFormatChildren = true; } else { // Two independent nodes; format their closest common ancestor. // Later we could consider having a small number of independent nodes // and formatting those, and only switching to formatting the common ancestor // when the number of individual nodes gets large. mFormatChildren = true; mFormatNode = UiElementNode.getCommonAncestor(mFormatNode, node); } } } /** * Creates an "undo recording" session by calling the undoableAction runnable * under an undo session. * <p/> * This also automatically starts an edit XML session, as if * {@link #wrapEditXmlModel(Runnable)} had been called. * <p> * You can nest several calls to {@link #wrapUndoEditXmlModel(String, Runnable)}, only one * recording session will be created. * * @param label The label for the undo operation. Can be null. Ideally we should really try * to put something meaningful if possible. * @param undoableAction the action to be run as a single undoable unit */ public void wrapUndoEditXmlModel(String label, Runnable undoableAction) { assert label != null : "All undoable actions should have a label"; wrapEditXmlModel(undoableAction, label == null ? "" : label); //$NON-NLS-1$ } /** * Returns true when the runnable of {@link #wrapEditXmlModel(Runnable)} is currently * being executed. This means it is safe to actually edit the XML model. * * @return true if the XML model is already locked for edits */ public boolean isEditXmlModelPending() { return mIsEditXmlModelPending > 0; } /** * Returns the XML {@link Document} or null if we can't get it */ public final Document getXmlDocument(IStructuredModel model) { if (model == null) { AndmoreAndroidPlugin.log(IStatus.WARNING, "Android Editor: No XML model for root node."); //$NON-NLS-1$ return null; } if (model instanceof IDOMModel) { IDOMModel dom_model = (IDOMModel) model; return dom_model.getDocument(); } return null; } /** * Returns the {@link IProject} for the edited file. */ @Nullable public IProject getProject() { IFile file = getInputFile(); if (file != null) { return file.getProject(); } return null; } /** * Returns the {@link AndroidTargetData} for the edited file. */ @Nullable public AndroidTargetData getTargetData() { IProject project = getProject(); if (project != null) { Sdk currentSdk = Sdk.getCurrent(); if (currentSdk != null) { return currentSdk.getTargetData(project); } } IEditorInput input = getEditorInput(); if (input instanceof IURIEditorInput) { IURIEditorInput urlInput = (IURIEditorInput) input; AndroidEnvironment env = AndworxFactory.instance().getAndroidEnvironment(); if (env.isValid() && (urlInput != null)){ try { // NPE encountered during testing, so check for null added String path = null; URI uri = urlInput.getURI(); if (uri != null) { File file = AdtUtils.getFile(uri.toURL()); if (file != null) path = file.getPath(); } if (path != null) { for (IAndroidTarget target : env.getAndroidTargets()) { if (path.startsWith(target.getLocation())) { return Sdk.getCurrent().getTargetData(target); } } } } catch (MalformedURLException e) { // File might be in some other weird random location we can't // handle: Just ignore these } } } return null; } /** * Shows the editor range corresponding to the given XML node. This will * front the editor and select the text range. * * @param xmlNode The DOM node to be shown. The DOM node should be an XML * node from the existing XML model used by the structured XML * editor; it will not do attribute matching to find a * "corresponding" element in the document from some foreign DOM * tree. * @return True if the node was shown. */ public boolean show(Node xmlNode) { if (xmlNode instanceof IndexedRegion) { IndexedRegion region = (IndexedRegion)xmlNode; IEditorPart textPage = getEditor(mTextPageIndex); if (textPage instanceof StructuredTextEditor) { StructuredTextEditor editor = (StructuredTextEditor) textPage; setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID); // Note - we cannot use region.getLength() because that seems to // always return 0. int regionLength = region.getEndOffset() - region.getStartOffset(); editor.selectAndReveal(region.getStartOffset(), regionLength); return true; } } return false; } /** * Selects and reveals the given range in the text editor * * @param start the beginning offset * @param length the length of the region to show * @param frontTab if true, front the tab, otherwise just make the selection but don't * change the active tab */ public void show(int start, int length, boolean frontTab) { IEditorPart textPage = getEditor(mTextPageIndex); if (textPage instanceof StructuredTextEditor) { StructuredTextEditor editor = (StructuredTextEditor) textPage; if (frontTab) { setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID); } editor.selectAndReveal(start, length); if (frontTab) { editor.setFocus(); } } } /** * Returns true if this editor has more than one page (usually a graphical view and an * editor) * * @return true if this editor has multiple pages */ public boolean hasMultiplePages() { return getPageCount() > 1; } /** * Get the XML text directly from the editor. * * @param xmlNode The node whose XML text we want to obtain. * @return The XML representation of the {@link Node}, or null if there was an error. */ public String getXmlText(Node xmlNode) { String data = null; IStructuredModel model = getModelForRead(); try { IStructuredDocument document = getStructuredDocument(); if (xmlNode instanceof NodeContainer) { // The easy way to get the source of an SSE XML node. data = ((NodeContainer) xmlNode).getSource(); } else if (xmlNode instanceof IndexedRegion && document != null) { // Try harder. IndexedRegion region = (IndexedRegion) xmlNode; int start = region.getStartOffset(); int end = region.getEndOffset(); if (end > start) { data = document.get(start, end - start); } } } catch (BadLocationException e) { // the region offset was invalid. ignore. } finally { model.releaseFromRead(); } return data; } /** * Formats the text around the given caret range, using the current Eclipse * XML formatter settings. * * @param begin The starting offset of the range to be reformatted. * @param end The ending offset of the range to be reformatted. */ public void reformatRegion(int begin, int end) { ISourceViewer textViewer = getStructuredSourceViewer(); // Clamp text range to valid offsets. IDocument document = textViewer.getDocument(); int documentLength = document.getLength(); end = Math.min(end, documentLength); begin = Math.min(begin, end); AdtPrefs adtPrefs = AndmoreAndroidPlugin.getDefault().getAdtPrefs(); if (!adtPrefs.getUseCustomXmlFormatter()) { // Workarounds which only apply to the builtin Eclipse formatter: // // It turns out the XML formatter does *NOT* format things correctly if you // select just a region of text. You *MUST* also include the leading whitespace // on the line, or it will dedent all the content to column 0. Therefore, // we must figure out the offset of the start of the line that contains the // beginning of the tag. try { IRegion lineInformation = document.getLineInformationOfOffset(begin); if (lineInformation != null) { int lineBegin = lineInformation.getOffset(); if (lineBegin != begin) { begin = lineBegin; } else if (begin > 0) { // Trick #2: It turns out that, if an XML element starts in column 0, // then the XML formatter will NOT indent it (even if its parent is // indented). If you on the other hand include the end of the previous // line (the newline), THEN the formatter also correctly inserts the // element. Therefore, we adjust the beginning range to include the // previous line (if we are not already in column 0 of the first line) // in the case where the element starts the line. begin--; } } } catch (BadLocationException e) { // This cannot happen because we already clamped the offsets AndmoreAndroidPlugin.log(e, e.toString()); } } if (textViewer instanceof StructuredTextViewer) { StructuredTextViewer structuredTextViewer = (StructuredTextViewer) textViewer; int operation = ISourceViewer.FORMAT; boolean canFormat = structuredTextViewer.canDoOperation(operation); if (canFormat) { StyledText textWidget = textViewer.getTextWidget(); textWidget.setSelection(begin, end); boolean oldIgnore = mIgnoreXmlUpdate; try { // Formatting does not affect the XML model so ignore notifications // about model edits from this mIgnoreXmlUpdate = true; structuredTextViewer.doOperation(operation); } finally { mIgnoreXmlUpdate = oldIgnore; } textWidget.setSelection(0, 0); } } } /** * Invokes content assist in this editor at the given offset * * @param offset the offset to invoke content assist at, or -1 to leave * caret alone */ public void invokeContentAssist(int offset) { ISourceViewer textViewer = getStructuredSourceViewer(); if (textViewer instanceof StructuredTextViewer) { StructuredTextViewer structuredTextViewer = (StructuredTextViewer) textViewer; int operation = ISourceViewer.CONTENTASSIST_PROPOSALS; boolean allowed = structuredTextViewer.canDoOperation(operation); if (allowed) { if (offset != -1) { StyledText textWidget = textViewer.getTextWidget(); // Clamp text range to valid offsets. IDocument document = textViewer.getDocument(); int documentLength = document.getLength(); offset = Math.max(0, Math.min(offset, documentLength)); textWidget.setSelection(offset, offset); } structuredTextViewer.doOperation(operation); } } } /** * Formats the XML region corresponding to the given node. * * @param node The node to be formatted. */ public void reformatNode(Node node) { if (mIsCreatingPage) { return; } if (node instanceof IndexedRegion) { IndexedRegion region = (IndexedRegion) node; int begin = region.getStartOffset(); int end = region.getEndOffset(); reformatRegion(begin, end); } } /** * Formats the XML document according to the user's XML formatting settings. */ public void reformatDocument() { ISourceViewer textViewer = getStructuredSourceViewer(); if (textViewer instanceof StructuredTextViewer) { StructuredTextViewer structuredTextViewer = (StructuredTextViewer) textViewer; int operation = StructuredTextViewer.FORMAT_DOCUMENT; boolean canFormat = structuredTextViewer.canDoOperation(operation); if (canFormat) { boolean oldIgnore = mIgnoreXmlUpdate; try { // Formatting does not affect the XML model so ignore notifications // about model edits from this mIgnoreXmlUpdate = true; structuredTextViewer.doOperation(operation); } finally { mIgnoreXmlUpdate = oldIgnore; } } } } /** * Returns the indentation String of the given node. * * @param xmlNode The node whose indentation we want. * @return The indent-string of the given node, or "" if the indentation for some reason could * not be computed. */ public String getIndent(Node xmlNode) { return getIndent(getStructuredDocument(), xmlNode); } /** * Returns the indentation String of the given node. * * @param document The Eclipse document containing the XML * @param xmlNode The node whose indentation we want. * @return The indent-string of the given node, or "" if the indentation for some reason could * not be computed. */ public static String getIndent(IDocument document, Node xmlNode) { if (xmlNode instanceof IndexedRegion) { IndexedRegion region = (IndexedRegion)xmlNode; int startOffset = region.getStartOffset(); return getIndentAtOffset(document, startOffset); } return ""; //$NON-NLS-1$ } /** * Returns the indentation String at the line containing the given offset * * @param document the document containing the offset * @param offset The offset of a character on a line whose indentation we seek * @return The indent-string of the given node, or "" if the indentation for some * reason could not be computed. */ public static String getIndentAtOffset(IDocument document, int offset) { try { IRegion lineInformation = document.getLineInformationOfOffset(offset); if (lineInformation != null) { int lineBegin = lineInformation.getOffset(); if (lineBegin != offset) { String prefix = document.get(lineBegin, offset - lineBegin); // It's possible that the tag whose indentation we seek is not // at the beginning of the line. In that case we'll just return // the indentation of the line itself. for (int i = 0; i < prefix.length(); i++) { if (!Character.isWhitespace(prefix.charAt(i))) { return prefix.substring(0, i); } } return prefix; } } } catch (BadLocationException e) { AndmoreAndroidPlugin.log(e, "Could not obtain indentation"); //$NON-NLS-1$ } return ""; //$NON-NLS-1$ } /** * Returns the active {@link AndroidXmlEditor}, provided it matches the given source * viewer * * @param viewer the source viewer to ensure the active editor is associated with * @return the active editor provided it matches the given source viewer or null. */ public static AndroidXmlEditor fromTextViewer(ITextViewer viewer) { IWorkbenchWindow wwin = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (wwin != null) { // Try the active editor first. IWorkbenchPage page = wwin.getActivePage(); if (page != null) { IEditorPart editor = page.getActiveEditor(); if (editor instanceof AndroidXmlEditor) { ISourceViewer ssviewer = ((AndroidXmlEditor) editor).getStructuredSourceViewer(); if (ssviewer == viewer) { return (AndroidXmlEditor) editor; } } } // If that didn't work, try all the editors for (IWorkbenchPage page2 : wwin.getPages()) { if (page2 != null) { for (IEditorReference editorRef : page2.getEditorReferences()) { IEditorPart editor = editorRef.getEditor(false /*restore*/); if (editor instanceof AndroidXmlEditor) { ISourceViewer ssviewer = ((AndroidXmlEditor) editor).getStructuredSourceViewer(); if (ssviewer == viewer) { return (AndroidXmlEditor) editor; } } } } } } return null; } /** Called when this editor is activated */ public void activated() { if (getActivePage() == mTextPageIndex) { updateActionBindings(); } } /** Called when this editor is deactivated */ public void deactivated() { } /** * Listen to changes in the underlying XML model in the structured editor. */ private class XmlModelStateListener implements IModelStateListener { /** * A model is about to be changed. This typically is initiated by one * client of the model, to signal a large change and/or a change to the * model's ID or base Location. A typical use might be if a client might * want to suspend processing until all changes have been made. * <p/> * This AndroidXmlEditor implementation of IModelChangedListener is empty. */ @Override public void modelAboutToBeChanged(IStructuredModel model) { // pass } /** * Signals that the changes foretold by modelAboutToBeChanged have been * made. A typical use might be to refresh, or to resume processing that * was suspended as a result of modelAboutToBeChanged. * <p/> * This AndroidXmlEditor implementation calls the xmlModelChanged callback. */ @Override public void modelChanged(IStructuredModel model) { if (mIgnoreXmlUpdate) { return; } xmlModelChanged(getXmlDocument(model)); } /** * Notifies that a model's dirty state has changed, and passes that state * in isDirty. A model becomes dirty when any change is made, and becomes * not-dirty when the model is saved. * <p/> * This AndroidXmlEditor implementation of IModelChangedListener is empty. */ @Override public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) { // pass } /** * A modelDeleted means the underlying resource has been deleted. The * model itself is not removed from model management until all have * released it. Note: baseLocation is not (necessarily) changed in this * event, but may not be accurate. * <p/> * This AndroidXmlEditor implementation of IModelChangedListener is empty. */ @Override public void modelResourceDeleted(IStructuredModel model) { // pass } /** * A model has been renamed or copied (as in saveAs..). In the renamed * case, the two parameters are the same instance, and only contain the * new info for id and base location. * <p/> * This AndroidXmlEditor implementation of IModelChangedListener is empty. */ @Override public void modelResourceMoved(IStructuredModel oldModel, IStructuredModel newModel) { // pass } /** * This AndroidXmlEditor implementation of IModelChangedListener is empty. */ @Override public void modelAboutToBeReinitialized(IStructuredModel structuredModel) { // pass } /** * This AndroidXmlEditor implementation of IModelChangedListener is empty. */ @Override public void modelReinitialized(IStructuredModel structuredModel) { // pass } } }
40.834974
119
0.57877
83f15aa7e9d1222d01afba287a1e2fde340e6b65
904
package cn.easyproject.easyee.ssh.sys.service; import java.util.List; import java.util.Map; import cn.easyproject.easyee.ssh.sys.entity.SysOperationPermission; /** * * @author easyproject.cn * @version 1.0 * */ public interface SysOperationPermissionService{ public void add(SysOperationPermission sysOperationPermission); public void delete(String[] ids); public void deleteByMenuPermissionId(int menuPermissionId); public void delete(SysOperationPermission sysOperationPermission); public void update(SysOperationPermission sysOperationPermission); public SysOperationPermission get(int id); @SuppressWarnings("rawtypes") public List<Map> list(Integer menuId); /** * 查询角色的所有操作权限ID * @param roleId * @return */ public List<String> getIdsByRoleId(Integer roleId); /** * 获得权限动作和名称备注的映射,包括Menu和Operation权限 * @return */ public Map<String,String> getAllOpreationNames(); }
25.828571
67
0.776549
c006ffdf8bf323decf02bf4036920131160bf649
16,037
package top.yokey.shopwt.activity.main; import android.text.TextUtils; import android.view.View; import android.widget.RelativeLayout; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.LinearLayoutCompat; import org.json.JSONException; import org.json.JSONObject; import org.xutils.view.annotation.ContentView; import org.xutils.view.annotation.ViewInject; import top.yokey.base.base.BaseCountTime; import top.yokey.base.base.BaseHttpListener; import top.yokey.base.base.BaseShared; import top.yokey.base.base.BaseToast; import top.yokey.base.base.MemberHttpClient; import top.yokey.base.bean.BaseBean; import top.yokey.base.bean.MemberAssetBean; import top.yokey.base.bean.MemberBean; import top.yokey.base.event.MessageCountEvent; import top.yokey.base.model.MemberAccountModel; import top.yokey.base.model.MemberChatModel; import top.yokey.base.model.MemberIndexModel; import top.yokey.base.util.JsonUtil; import top.yokey.shopwt.R; import top.yokey.shopwt.activity.base.LoginActivity; import top.yokey.shopwt.activity.mine.AddressActivity; import top.yokey.shopwt.activity.mine.CenterActivity; import top.yokey.shopwt.activity.mine.DistributionActivity; import top.yokey.shopwt.activity.mine.FeedbackActivity; import top.yokey.shopwt.activity.mine.FootprintActivity; import top.yokey.shopwt.activity.mine.InviteActivity; import top.yokey.shopwt.activity.mine.PointsActivity; import top.yokey.shopwt.activity.mine.PreDepositActivity; import top.yokey.shopwt.activity.mine.PropertyActivity; import top.yokey.shopwt.activity.mine.RechargeCardActivity; import top.yokey.shopwt.activity.mine.RedPacketActivity; import top.yokey.shopwt.activity.mine.SettingActivity; import top.yokey.shopwt.activity.mine.SignActivity; import top.yokey.shopwt.activity.mine.VoucherActivity; import top.yokey.shopwt.activity.points.ExchangeActivity; import top.yokey.shopwt.activity.refund.RefundActivity; import top.yokey.shopwt.activity.seller.SellerActivity; import top.yokey.shopwt.base.BaseApplication; import top.yokey.shopwt.base.BaseBusClient; import top.yokey.shopwt.base.BaseConstant; import top.yokey.shopwt.base.BaseFragment; import top.yokey.shopwt.base.BaseImageLoader; /** * @author MapleStory * @ qq 1002285057 * @ project https://gitee.com/MapStory/Shopwt-Android */ @ContentView(R.layout.fragment_main_mine) public class MineFragment extends BaseFragment { @ViewInject(R.id.mineLinearLayout) private LinearLayoutCompat mineLinearLayout; @ViewInject(R.id.avatarImageView) private AppCompatImageView avatarImageView; @ViewInject(R.id.nicknameTextView) private AppCompatTextView nicknameTextView; @ViewInject(R.id.goodsTextView) private AppCompatTextView goodsTextView; @ViewInject(R.id.storeTextView) private AppCompatTextView storeTextView; @ViewInject(R.id.footprintTextView) private AppCompatTextView footprintTextView; @ViewInject(R.id.signTextView) private AppCompatTextView signTextView; @ViewInject(R.id.orderRelativeLayout) private RelativeLayout orderRelativeLayout; @ViewInject(R.id.waitPaymentRelativeLayout) private RelativeLayout waitPaymentRelativeLayout; @ViewInject(R.id.waitReceiptRelativeLayout) private RelativeLayout waitReceiptRelativeLayout; @ViewInject(R.id.waitTakesRelativeLayout) private RelativeLayout waitTakesRelativeLayout; @ViewInject(R.id.waitEvaluateRelativeLayout) private RelativeLayout waitEvaluateRelativeLayout; @ViewInject(R.id.waitReturnRelativeLayout) private RelativeLayout waitReturnRelativeLayout; @ViewInject(R.id.waitPaymentDotTextView) private AppCompatTextView waitPaymentDotTextView; @ViewInject(R.id.waitReceiptDotTextView) private AppCompatTextView waitReceiptDotTextView; @ViewInject(R.id.waitTakesDotTextView) private AppCompatTextView waitTakesDotTextView; @ViewInject(R.id.waitEvaluateDotTextView) private AppCompatTextView waitEvaluateDotTextView; @ViewInject(R.id.waitReturnDotTextView) private AppCompatTextView waitReturnDotTextView; @ViewInject(R.id.propertyRelativeLayout) private RelativeLayout propertyRelativeLayout; @ViewInject(R.id.preDepositTextView) private AppCompatTextView preDepositTextView; @ViewInject(R.id.rechargeCardTextView) private AppCompatTextView rechargeCardTextView; @ViewInject(R.id.voucherTextView) private AppCompatTextView voucherTextView; @ViewInject(R.id.redPacketTextView) private AppCompatTextView redPacketTextView; @ViewInject(R.id.pointsTextView) private AppCompatTextView pointsTextView; @ViewInject(R.id.inviteTextView) private AppCompatTextView inviteTextView; @ViewInject(R.id.distributionTextView) private AppCompatTextView distributionTextView; @ViewInject(R.id.addressTextView) private AppCompatTextView addressTextView; @ViewInject(R.id.sellerTextView) private AppCompatTextView sellerTextView; @ViewInject(R.id.exchangeTextView) private AppCompatTextView exchangeTextView; @ViewInject(R.id.feedbackTextView) private AppCompatTextView feedbackTextView; @ViewInject(R.id.settingTextView) private AppCompatTextView settingTextView; @Override public void initData() { if (BaseApplication.get().isLogin()) { getData(); getMessageCount(); } } @Override public void initEven() { mineLinearLayout.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), CenterActivity.class)); goodsTextView.setOnClickListener(view -> BaseApplication.get().startFavorites(getActivity(), 0)); storeTextView.setOnClickListener(view -> BaseApplication.get().startFavorites(getActivity(), 1)); footprintTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), FootprintActivity.class)); signTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), SignActivity.class)); orderRelativeLayout.setOnClickListener(view -> BaseApplication.get().startOrder(getActivity(), 0)); waitPaymentRelativeLayout.setOnClickListener(view -> BaseApplication.get().startOrder(getActivity(), 1)); waitReceiptRelativeLayout.setOnClickListener(view -> BaseApplication.get().startOrder(getActivity(), 2)); waitTakesRelativeLayout.setOnClickListener(view -> BaseApplication.get().startOrder(getActivity(), 3)); waitEvaluateRelativeLayout.setOnClickListener(view -> BaseApplication.get().startOrder(getActivity(), 4)); waitReturnRelativeLayout.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), RefundActivity.class)); propertyRelativeLayout.setOnClickListener(view -> { if (!BaseApplication.get().isLogin()) { BaseApplication.get().start(getActivity(), LoginActivity.class); return; } if (BaseApplication.get().getMemberAssetBean() == null) { return; } BaseApplication.get().start(getActivity(), PropertyActivity.class); }); preDepositTextView.setOnClickListener(view -> { if (!BaseApplication.get().isLogin()) { BaseApplication.get().start(getActivity(), LoginActivity.class); return; } if (BaseApplication.get().getMemberAssetBean() == null) { return; } BaseApplication.get().start(getActivity(), PreDepositActivity.class); }); rechargeCardTextView.setOnClickListener(view -> { if (!BaseApplication.get().isLogin()) { BaseApplication.get().start(getActivity(), LoginActivity.class); return; } if (BaseApplication.get().getMemberAssetBean() == null) { return; } BaseApplication.get().start(getActivity(), RechargeCardActivity.class); }); voucherTextView.setOnClickListener(view -> { if (!BaseApplication.get().isLogin()) { BaseApplication.get().start(getActivity(), LoginActivity.class); return; } if (BaseApplication.get().getMemberAssetBean() == null) { return; } BaseApplication.get().start(getActivity(), VoucherActivity.class); }); redPacketTextView.setOnClickListener(view -> { if (!BaseApplication.get().isLogin()) { BaseApplication.get().start(getActivity(), LoginActivity.class); return; } if (BaseApplication.get().getMemberAssetBean() == null) { return; } BaseApplication.get().start(getActivity(), RedPacketActivity.class); }); pointsTextView.setOnClickListener(view -> { if (!BaseApplication.get().isLogin()) { BaseApplication.get().start(getActivity(), LoginActivity.class); return; } if (BaseApplication.get().getMemberAssetBean() == null) { return; } BaseApplication.get().start(getActivity(), PointsActivity.class); }); inviteTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), InviteActivity.class)); distributionTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), DistributionActivity.class)); addressTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), AddressActivity.class)); sellerTextView.setOnClickListener(view -> BaseApplication.get().startCheckSellerLogin(getActivity(), SellerActivity.class)); exchangeTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), ExchangeActivity.class)); feedbackTextView.setOnClickListener(view -> BaseApplication.get().startCheckLogin(getActivity(), FeedbackActivity.class)); settingTextView.setOnClickListener(view -> BaseApplication.get().start(getActivity(), SettingActivity.class)); } @Override public void onResume() { super.onResume(); if (BaseApplication.get().isLogin()) { getData(); } else { nicknameTextView.setText("请登录"); } } //自定义方法 private void getData() { MemberIndexModel.get().index(new BaseHttpListener() { @Override public void onSuccess(BaseBean baseBean) { String data = JsonUtil.getDatasString(baseBean.getDatas(), "member_info"); BaseApplication.get().setMemberBean(JsonUtil.json2Bean(data, MemberBean.class)); BaseImageLoader.get().displayCircle(BaseApplication.get().getMemberBean().getAvatar(), avatarImageView); nicknameTextView.setText(BaseApplication.get().getMemberBean().getUserName()); goodsTextView.setText("商品"); if (!TextUtils.isEmpty(BaseApplication.get().getMemberBean().getFavoritesGoods())) { goodsTextView.append(":" + BaseApplication.get().getMemberBean().getFavoritesGoods()); } storeTextView.setText("店铺"); if (!TextUtils.isEmpty(BaseApplication.get().getMemberBean().getFavoritesStore())) { storeTextView.append(":" + BaseApplication.get().getMemberBean().getFavoritesStore()); } waitPaymentDotTextView.setVisibility(BaseApplication.get().getMemberBean().getOrderNopayCount().equals("0") ? View.GONE : View.VISIBLE); waitReceiptDotTextView.setVisibility(BaseApplication.get().getMemberBean().getOrderNoreceiptCount().equals("0") ? View.GONE : View.VISIBLE); waitTakesDotTextView.setVisibility(BaseApplication.get().getMemberBean().getOrderNotakesCount().equals("0") ? View.GONE : View.VISIBLE); waitEvaluateDotTextView.setVisibility(BaseApplication.get().getMemberBean().getOrderNoevalCount().equals("0") ? View.GONE : View.VISIBLE); waitReturnDotTextView.setVisibility(BaseApplication.get().getMemberBean().getReturnX().equals("0") ? View.GONE : View.VISIBLE); getMobileInfo(); } @Override public void onFailure(String reason) { if (reason.equals("请登录")) { MemberHttpClient.get().updateKey(""); BaseToast.get().show(reason); BaseShared.get().putString(BaseConstant.SHARED_KEY, ""); BaseApplication.get().start(getActivity(), LoginActivity.class); } else { new BaseCountTime(BaseConstant.TIME_COUNT, BaseConstant.TIME_TICK) { @Override public void onFinish() { super.onFinish(); getData(); } }.start(); } } }); } private void getMobileInfo() { MemberAccountModel.get().getMobileInfo(new BaseHttpListener() { @Override public void onSuccess(BaseBean baseBean) { try { JSONObject jsonObject = new JSONObject(baseBean.getDatas()); BaseApplication.get().getMemberBean().setMobielState(jsonObject.getBoolean("state")); BaseApplication.get().getMemberBean().setUserMobile(jsonObject.getString("mobile")); getMemberAsset(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(String reason) { new BaseCountTime(BaseConstant.TIME_COUNT, BaseConstant.TIME_TICK) { @Override public void onFinish() { super.onFinish(); getMobileInfo(); } }.start(); } }); } private void getMemberAsset() { MemberIndexModel.get().myAsset(new BaseHttpListener() { @Override public void onSuccess(BaseBean baseBean) { BaseApplication.get().setMemberAssetBean(JsonUtil.json2Bean(baseBean.getDatas(), MemberAssetBean.class)); } @Override public void onFailure(String reason) { new BaseCountTime(BaseConstant.TIME_MESSAGE, BaseConstant.TIME_TICK) { @Override public void onFinish() { super.onFinish(); getMemberAsset(); } }.start(); } }); } private void getMessageCount() { MemberChatModel.get().getMsgCount(new BaseHttpListener() { @Override public void onSuccess(BaseBean baseBean) { if (!baseBean.getDatas().equals("0")) { BaseBusClient.get().post(new MessageCountEvent(true)); } new BaseCountTime(BaseConstant.TIME_COUNT, BaseConstant.TIME_TICK) { @Override public void onFinish() { super.onFinish(); getMessageCount(); } }.start(); } @Override public void onFailure(String reason) { new BaseCountTime(BaseConstant.TIME_COUNT, BaseConstant.TIME_TICK) { @Override public void onFinish() { super.onFinish(); getMessageCount(); } }.start(); } }); } }
41.332474
156
0.655609
9f6472c40a90c2d5f8a85748f8be08e9c2829cd0
1,661
package examples; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.Message; import io.vertx.ext.sync.HandlerReceiverAdaptor; import static io.vertx.ext.sync.Sync.*; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class Examples { public void syncResultExample(Vertx vertx) { EventBus eb = vertx.eventBus(); // Send a message and get the reply synchronously Message<String> reply = awaitResult(h -> eb.request("someaddress", "ping", h)); System.out.println("Received reply " + reply.body()); } public void syncEventExample(Vertx vertx) { // Set up a timer to fire long tid = awaitEvent(h -> vertx.setTimer(1000, h)); System.out.println("Timer has now fired"); } public void streamExample(Vertx vertx) { EventBus eb = vertx.eventBus(); HandlerReceiverAdaptor<Message<String>> adaptor = streamAdaptor(); eb.<String>consumer("some-address").handler(adaptor); // Receive 10 messages from the consumer: for (int i = 0; i < 10; i++) { Message<String> received1 = adaptor.receive(); System.out.println("got message: " + received1.body()); } } public void fiberHandlerExample(Vertx vertx) { EventBus eb = vertx.eventBus(); vertx.createHttpServer().requestHandler(fiberHandler(req -> { // Send a message to address and wait for a reply Message<String> reply = awaitResult(h -> eb.request("some-address", "blah", h)); System.out.println("Got reply: " + reply.body()); // Now end the response req.response().end("blah"); })).listen(8080, "localhost"); } }
22.753425
86
0.660446
854f85b64e173761ff3dddd0ca604116983bf52b
1,567
/* * $Id$ * * 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.struts2.interceptor; import org.apache.struts2.dispatcher.HttpParameters; /** * <p> * This interface gives actions an alternative way of receiving input parameters. The parameters will * contain all input parameters as implementation of {@link org.apache.struts2.dispatcher.Parameter}. * Actions that need this should simply implement it. * </p> * * <p> * One common use for this is to have the action propagate parameters to internally instantiated data * objects. * </p> */ public interface HttpParametersAware { /** * Sets the HTTP parameters in the implementing class. * * @param parameters an instance of {@link HttpParameters}. */ void setParameters(HttpParameters parameters); }
32.645833
101
0.736439