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
48a4b9f9132abd20200e89319c322fb942b10b90
5,528
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.11.17 at 11:49:24 AM EET // package ee.ria.dhx.server.types.ee.riik.xrd.dhl.producers.producer.dhl; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for receiveDocumentsV4RequestType complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="receiveDocumentsV4RequestType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="arv" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/&gt; * &lt;element name="allyksuse_lyhinimetus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="ametikoha_lyhinimetus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="kaust" type="{http://www.riik.ee/schemas/dhl-meta-automatic}dhlDokTaisnimiType" minOccurs="0"/&gt; * &lt;element name="edastus_id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="fragment_nr" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/&gt; * &lt;element name="fragmendi_suurus_baitides" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "receiveDocumentsV4RequestType", propOrder = { "arv", "allyksuseLyhinimetus", "ametikohaLyhinimetus", "kaust", "edastusId", "fragmentNr", "fragmendiSuurusBaitides" }) public class ReceiveDocumentsV4RequestType { protected BigInteger arv; @XmlElement(name = "allyksuse_lyhinimetus") protected String allyksuseLyhinimetus; @XmlElement(name = "ametikoha_lyhinimetus") protected String ametikohaLyhinimetus; protected String kaust; @XmlElement(name = "edastus_id") protected String edastusId; @XmlElement(name = "fragment_nr") protected BigInteger fragmentNr; @XmlElement(name = "fragmendi_suurus_baitides") protected Long fragmendiSuurusBaitides; /** * Gets the value of the arv property. * * @return possible object is {@link BigInteger } * */ public BigInteger getArv() { return arv; } /** * Sets the value of the arv property. * * @param value allowed object is {@link BigInteger } * */ public void setArv(BigInteger value) { this.arv = value; } /** * Gets the value of the allyksuseLyhinimetus property. * * @return possible object is {@link String } * */ public String getAllyksuseLyhinimetus() { return allyksuseLyhinimetus; } /** * Sets the value of the allyksuseLyhinimetus property. * * @param value allowed object is {@link String } * */ public void setAllyksuseLyhinimetus(String value) { this.allyksuseLyhinimetus = value; } /** * Gets the value of the ametikohaLyhinimetus property. * * @return possible object is {@link String } * */ public String getAmetikohaLyhinimetus() { return ametikohaLyhinimetus; } /** * Sets the value of the ametikohaLyhinimetus property. * * @param value allowed object is {@link String } * */ public void setAmetikohaLyhinimetus(String value) { this.ametikohaLyhinimetus = value; } /** * Gets the value of the kaust property. * * @return possible object is {@link String } * */ public String getKaust() { return kaust; } /** * Sets the value of the kaust property. * * @param value allowed object is {@link String } * */ public void setKaust(String value) { this.kaust = value; } /** * Gets the value of the edastusId property. * * @return possible object is {@link String } * */ public String getEdastusId() { return edastusId; } /** * Sets the value of the edastusId property. * * @param value allowed object is {@link String } * */ public void setEdastusId(String value) { this.edastusId = value; } /** * Gets the value of the fragmentNr property. * * @return possible object is {@link BigInteger } * */ public BigInteger getFragmentNr() { return fragmentNr; } /** * Sets the value of the fragmentNr property. * * @param value allowed object is {@link BigInteger } * */ public void setFragmentNr(BigInteger value) { this.fragmentNr = value; } /** * Gets the value of the fragmendiSuurusBaitides property. * * @return possible object is {@link Long } * */ public Long getFragmendiSuurusBaitides() { return fragmendiSuurusBaitides; } /** * Sets the value of the fragmendiSuurusBaitides property. * * @param value allowed object is {@link Long } * */ public void setFragmendiSuurusBaitides(Long value) { this.fragmendiSuurusBaitides = value; } }
25.953052
127
0.665159
98129b18778c89b5ab7723342c941a3247a86997
617
package de.uniks.networkparser.test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.junit.Test; import de.uniks.networkparser.parser.JavaParser; import de.uniks.networkparser.parser.SymTabEntry; public class JavaParserTest { @Test public void testJavaParser() throws IOException{ byte[] fullContext = Files.readAllBytes(new File("src/main/java/de/uniks/networkparser/parser/JavaParser.java").toPath()); String context = new String(fullContext); JavaParser parser = new JavaParser(); SymTabEntry parse = parser.parse(context); System.out.println(parse); } }
25.708333
124
0.774716
778f9bca1b6aa1fde3b80e8d753092e906503912
30,712
package com.immersion.hapticmediasdk; import android.content.Context; import android.os.Handler; import android.os.SystemClock; import com.immersion.aws.analytics.AnalyticsDataCollector; import com.immersion.aws.analytics.DefaultAnalyticsCollectors; import com.immersion.aws.analytics.ImmrAnalytics; import com.immersion.aws.pm.PolicyManager; import com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus; import com.immersion.hapticmediasdk.controllers.MediaController; import com.immersion.hapticmediasdk.utils.Log; import com.immersion.hapticmediasdk.utils.RuntimeInfo; import rrrrrr.crrccc; public class MediaTaskManager implements Runnable { private static final String b042DЭЭ042DЭ042D = "MediaTaskManager"; public static int b044Aъ044Aъъъ = 2; public static int b044Aъъ044Aъъ = 0; public static int bъ044Aъъъъ = 42; public static int bъъ044Aъъъ = 1; private volatile SDKStatus b042D042D042D042DЭ042D; private PolicyManager b042D042D042DЭ042D042D; private final Object b042D042DЭ042DЭ042D; private Context b042D042DЭЭ042D042D; private long b042DЭ042D042DЭ042D; private ImmrAnalytics b042DЭ042DЭ042D042D; private String b042DЭЭЭ042D042D; private Handler bЭ042D042D042DЭ042D; private crrccc bЭ042D042DЭ042D042D; private final Object bЭ042DЭ042DЭ042D; private boolean bЭ042DЭЭ042D042D; private long bЭЭ042D042DЭ042D; private RuntimeInfo bЭЭ042DЭ042D042D; private MediaController bЭЭЭЭ042D042D; /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public MediaTaskManager(android.os.Handler r3, android.content.Context r4, com.immersion.hapticmediasdk.utils.RuntimeInfo r5, com.immersion.aws.pm.PolicyManager r6) { /* r2 = this; r0 = bъ044Aъъъъ; r1 = bъъ044Aъъъ; r0 = r0 + r1; r1 = bъ044Aъъъъ; r0 = r0 * r1; r1 = b044Aъ044Aъъъ; r0 = r0 % r1; r1 = b044A044Aъъъъ(); if (r0 == r1) goto L_0x001d; L_0x0011: r0 = bъ044A044Aъъъ(); bъ044Aъъъъ = r0; r0 = bъ044A044Aъъъ(); bъъ044Aъъъ = r0; L_0x001d: r2.<init>(); r0 = new java.lang.Object; r0.<init>(); r2.bЭ042DЭ042DЭ042D = r0; r0 = new java.lang.Object; r0.<init>(); r2.b042D042DЭ042DЭ042D = r0; r0 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.NOT_INITIALIZED; r2.b042D042D042D042DЭ042D = r0; r2.bЭ042D042D042DЭ042D = r3; r2.b042D042DЭЭ042D042D = r4; r2.bЭЭ042DЭ042D042D = r5; L_0x0038: r0 = 1; switch(r0) { case 0: goto L_0x0038; case 1: goto L_0x0041; default: goto L_0x003c; }; L_0x003c: r0 = 0; switch(r0) { case 0: goto L_0x0041; case 1: goto L_0x0038; default: goto L_0x0040; }; L_0x0040: goto L_0x003c; L_0x0041: r0 = r2.b042D042DЭЭ042D042D; r0 = com.immersion.aws.analytics.ImmrAnalytics.getInstance(r0); r2.b042DЭ042DЭ042D042D = r0; r0 = rrrrrr.crrccc.NOT_SENT; r2.bЭ042D042DЭ042D042D = r0; r2.b042D042D042DЭ042D042D = r6; return; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.<init>(android.os.Handler, android.content.Context, com.immersion.hapticmediasdk.utils.RuntimeInfo, com.immersion.aws.pm.PolicyManager):void"); } private int b0449044904490449щщ() { try { int onPause = this.bЭЭЭЭ042D042D.onPause(); if (onPause == 0) { this.b042D042D042D042DЭ042D = SDKStatus.PAUSED_DUE_TO_BUFFERING; int i = bъ044Aъъъъ; switch ((i * (b044A044Aъ044Aъъ() + i)) % b044Aъ044Aъъъ) { case 0: break; default: bъ044Aъъъъ = 10; b044Aъъ044Aъъ = bъ044A044Aъъъ(); break; } } return onPause; } catch (Exception e) { throw e; } } private int b044904490449щщщ() { try { this.bЭ042D042D042DЭ042D.removeCallbacks(this); if (!(this.bЭЭЭЭ042D042D == null || b04490449щ0449щщ() == 0)) { Log.e(b042DЭЭ042DЭ042D, "Could not dispose haptics, reset anyway."); } int i = bъ044Aъъъъ; switch ((i * (bъъ044Aъъъ + i)) % b044Aъ044Aъъъ) { case 0: break; default: bъ044Aъъъъ = bъ044A044Aъъъ(); bъъ044Aъъъ = 69; break; } try { this.b042DЭЭЭ042D042D = null; this.bЭЭ042D042DЭ042D = 0; this.b042D042D042D042DЭ042D = SDKStatus.NOT_INITIALIZED; return 0; } catch (Exception e) { throw e; } } catch (Exception e2) { throw e2; } } private int b04490449щ0449щщ() { int bщ0449щ0449щщ = bщ0449щ0449щщ(); if (bщ0449щ0449щщ == 0) { this.bЭЭЭЭ042D042D.onDestroy(this.bЭ042D042D042DЭ042D); this.bЭЭЭЭ042D042D = null; } return bщ0449щ0449щщ; } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ private int b0449щ04490449щщ() { /* r5 = this; r0 = 0; r1 = r5.bЭ042D042D042DЭ042D; r1.removeCallbacks(r5); r1 = r5.bЭ042D042D042DЭ042D; r2 = 1500; // 0x5dc float:2.102E-42 double:7.41E-321; L_0x000a: switch(r0) { case 0: goto L_0x0012; case 1: goto L_0x000a; default: goto L_0x000d; }; L_0x000d: r4 = 1; switch(r4) { case 0: goto L_0x000a; case 1: goto L_0x0012; default: goto L_0x0011; }; L_0x0011: goto L_0x000d; L_0x0012: r1 = r1.postDelayed(r5, r2); if (r1 == 0) goto L_0x002f; L_0x0018: r1 = bъ044Aъъъъ; r2 = bъъ044Aъъъ; r2 = r2 + r1; r1 = r1 * r2; r2 = b044Aъ044Aъъъ; r1 = r1 % r2; switch(r1) { case 0: goto L_0x002e; default: goto L_0x0024; }; L_0x0024: r1 = 44; bъ044Aъъъъ = r1; r1 = bъ044A044Aъъъ(); b044Aъъ044Aъъ = r1; L_0x002e: return r0; L_0x002f: r0 = -1; goto L_0x002e; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.b0449щ04490449щщ():int"); } private int b0449щщ0449щщ() { try { this.bЭ042D042D042DЭ042D.removeCallbacks(this); int onPrepared = this.bЭЭЭЭ042D042D.onPrepared(); if (onPrepared == 0) { try { this.b042D042D042D042DЭ042D = SDKStatus.PLAYING; this.bЭ042D042D042DЭ042D.postDelayed(this, 1500); int bъ044A044Aъъъ = bъ044A044Aъъъ(); switch ((bъ044A044Aъъъ * (bъъ044Aъъъ + bъ044A044Aъъъ)) % b044Aъ044Aъъъ) { case 0: break; default: bъ044Aъъъъ = bъ044A044Aъъъ(); b044Aъъ044Aъъ = bъ044A044Aъъъ(); break; } this.bЭ042D042DЭ042D042D = crrccc.NOT_SENT; } catch (Exception e) { throw e; } } return onPrepared; } catch (Exception e2) { throw e2; } } private void b0449щщщ0449щ() { if (this.b042D042DЭЭ042D042D.checkCallingOrSelfPermission("android.permission.INTERNET") == 0) { for (AnalyticsDataCollector analyticsDataCollector : new DefaultAnalyticsCollectors().getDefaultAnalytics(this.b042D042DЭЭ042D042D)) { ImmrAnalytics immrAnalytics = this.b042DЭ042DЭ042D042D; if (((bъ044Aъъъъ + bъъ044Aъъъ) * bъ044Aъъъъ) % b044Aъ044Aъъъ != b044Aъъ044Aъъ) { bъ044Aъъъъ = bъ044A044Aъъъ(); b044Aъъ044Aъъ = 2; } immrAnalytics.addAnalyticsDataCollector(analyticsDataCollector); } this.b042DЭ042DЭ042D042D.sendAnalytics(); } } public static int b044A044Aъ044Aъъ() { return 1; } public static int b044A044Aъъъъ() { return 0; } private int bщ044904490449щщ() { int onPause = this.bЭЭЭЭ042D042D.onPause(); if (onPause == 0) { this.b042D042D042D042DЭ042D = SDKStatus.PAUSED_DUE_TO_TIMEOUT; if (((bъ044Aъъъъ + bъъ044Aъъъ) * bъ044Aъъъъ) % b044Aъ044Aъъъ != b044Aъъ044Aъъ) { bъ044Aъъъъ = 59; b044Aъъ044Aъъ = 79; } } return onPause; } private int bщ0449щ0449щщ() { try { this.bЭ042D042D042DЭ042D.removeCallbacks(this); this.bЭЭ042D042DЭ042D = 0; int stopHapticPlayback = this.bЭЭЭЭ042D042D.stopHapticPlayback(); if (stopHapticPlayback == 0) { this.b042D042D042D042DЭ042D = SDKStatus.STOPPED; crrccc rrrrrr_crrccc = this.bЭ042D042DЭ042D042D; crrccc rrrrrr_crrccc2 = crrccc.SENT; if (((bъ044Aъъъъ + bъъ044Aъъъ) * bъ044Aъъъъ) % b044Aъ044Aъъъ != b044A044Aъъъъ()) { bъ044Aъъъъ = 55; b044Aъъ044Aъъ = bъ044A044Aъъъ(); } if (rrrrrr_crrccc != rrrrrr_crrccc2) { try { b0449щщщ0449щ(); this.bЭ042D042DЭ042D042D = crrccc.SENT; } catch (Exception e) { throw e; } } } return stopHapticPlayback; } catch (Exception e2) { throw e2; } } private int bщщ04490449щщ() { try { this.bЭ042D042D042DЭ042D.removeCallbacks(this); try { int onPause = this.bЭЭЭЭ042D042D.onPause(); if (onPause == 0) { this.b042D042D042D042DЭ042D = SDKStatus.PAUSED; } int i = bъ044Aъъъъ; switch ((i * (bъъ044Aъъъ + i)) % b044Aъ044Aъъъ) { case 0: break; default: bъ044Aъъъъ = bъ044A044Aъъъ(); b044Aъъ044Aъъ = 54; break; } return onPause; } catch (Exception e) { throw e; } } catch (Exception e2) { throw e2; } } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ private int bщщщ0449щщ(com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus r9) { /* r8 = this; r7 = 0; r0 = -1; r1 = r8.bЭ042D042D042DЭ042D; r1.removeCallbacks(r8); r8.b042D042D042D042DЭ042D = r9; L_0x0009: r1 = new int[r0]; Catch:{ Exception -> 0x000c } goto L_0x0009; L_0x000c: r0 = move-exception; r0 = bъ044A044Aъъъ(); bъ044Aъъъъ = r0; r0 = r8.b042DЭЭЭ042D042D; if (r0 == 0) goto L_0x0048; L_0x0017: r0 = new com.immersion.hapticmediasdk.controllers.MediaController; r1 = r8.bЭ042D042D042DЭ042D; r1 = r1.getLooper(); r0.<init>(r1, r8); r8.bЭЭЭЭ042D042D = r0; r0 = r8.bЭЭЭЭ042D042D; r3 = r0.getControlHandler(); r0 = new com.immersion.hapticmediasdk.controllers.HapticPlaybackThread; r1 = r8.b042D042DЭЭ042D042D; r2 = r8.b042DЭЭЭ042D042D; L_0x0030: switch(r7) { case 0: goto L_0x0038; case 1: goto L_0x0030; default: goto L_0x0033; }; L_0x0033: r4 = 1; switch(r4) { case 0: goto L_0x0030; case 1: goto L_0x0038; default: goto L_0x0037; }; L_0x0037: goto L_0x0033; L_0x0038: r4 = r8.bЭ042DЭЭ042D042D; r5 = r8.bЭЭ042DЭ042D042D; r6 = r8.b042D042D042DЭ042D042D; r0.<init>(r1, r2, r3, r4, r5, r6); r1 = r8.bЭЭЭЭ042D042D; r1.initHapticPlayback(r0); r0 = r7; L_0x0047: return r0; L_0x0048: r0 = -4; goto L_0x0047; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.bщщщ0449щщ(com.immersion.hapticmediasdk.HapticContentSDK$SDKStatus):int"); } private int bщщщщ0449щ() { try { int b0449щщ0449щщ = b0449щщ0449щщ(); if (((bъ044Aъъъъ + bъъ044Aъъъ) * bъ044Aъъъъ) % b044Aъ044Aъъъ != b044Aъъ044Aъъ) { bъ044Aъъъъ = bъ044A044Aъъъ(); b044Aъъ044Aъъ = 26; } if (b0449щщ0449щщ == 0) { try { b0449щщ0449щщ = b0449щ04490449щщ(); } catch (Exception e) { throw e; } } return b0449щщ0449щщ; } catch (Exception e2) { throw e2; } } public static int bъ044A044Aъъъ() { return 33; } public static int bъ044Aъ044Aъъ() { return 2; } public int SeekTo(int i) { setMediaTimestamp((long) i); this.bЭЭЭЭ042D042D.seekTo(i); if (getSDKStatus() != SDKStatus.PLAYING) { return 0; } if (((bъ044Aъъъъ + bъъ044Aъъъ) * bъ044Aъъъъ) % bъ044Aъ044Aъъ() != b044Aъъ044Aъъ) { bъ044Aъъъъ = 94; b044Aъъ044Aъъ = 7; } return this.bЭЭЭЭ042D042D.prepareHapticPlayback(); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public long getMediaReferenceTime() { /* r4 = this; r0 = 1; r1 = r4.b042D042DЭ042DЭ042D; L_0x0003: switch(r0) { case 0: goto L_0x0003; case 1: goto L_0x000a; default: goto L_0x0006; }; L_0x0006: switch(r0) { case 0: goto L_0x0003; case 1: goto L_0x000a; default: goto L_0x0009; }; L_0x0009: goto L_0x0006; L_0x000a: monitor-enter(r1); r2 = r4.b042DЭ042D042DЭ042D; Catch:{ all -> 0x000f } monitor-exit(r1); Catch:{ all -> 0x000f } return r2; L_0x000f: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x000f } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.getMediaReferenceTime():long"); } public long getMediaTimestamp() { long j; synchronized (this.b042D042DЭ042DЭ042D) { j = this.bЭЭ042D042DЭ042D; } return j; } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus getSDKStatus() { /* r2 = this; r1 = r2.bЭ042DЭ042DЭ042D; monitor-enter(r1); r0 = r2.b042D042D042D042DЭ042D; Catch:{ all -> 0x0010 } monitor-exit(r1); Catch:{ all -> 0x0010 } L_0x0006: r1 = 0; switch(r1) { case 0: goto L_0x000f; case 1: goto L_0x0006; default: goto L_0x000a; }; Catch:{ all -> 0x0010 } L_0x000a: r1 = 1; switch(r1) { case 0: goto L_0x0006; case 1: goto L_0x000f; default: goto L_0x000e; }; Catch:{ all -> 0x0010 } L_0x000e: goto L_0x000a; L_0x000f: return r0; L_0x0010: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0010 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.getSDKStatus():com.immersion.hapticmediasdk.HapticContentSDK$SDKStatus"); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void run() { /* r2 = this; r0 = 0; java.lang.System.currentTimeMillis(); L_0x0004: switch(r0) { case 0: goto L_0x000b; case 1: goto L_0x0004; default: goto L_0x0007; }; L_0x0007: switch(r0) { case 0: goto L_0x000b; case 1: goto L_0x0004; default: goto L_0x000a; }; L_0x000a: goto L_0x0007; L_0x000b: r0 = bъ044Aъъъъ; r1 = b044A044Aъ044Aъъ(); r1 = r1 + r0; r0 = r0 * r1; r1 = bъ044Aъ044Aъъ(); r0 = r0 % r1; switch(r0) { case 0: goto L_0x0024; default: goto L_0x001b; }; L_0x001b: r0 = 2; bъ044Aъъъъ = r0; r0 = bъ044A044Aъъъ(); b044Aъъ044Aъъ = r0; L_0x0024: r0 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED_DUE_TO_TIMEOUT; r2.transitToState(r0); return; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.run():void"); } public void setHapticsUrl(String str, boolean z) { synchronized (this.bЭ042DЭ042DЭ042D) { this.b042DЭЭЭ042D042D = str; this.bЭ042DЭЭ042D042D = z; } } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void setMediaReferenceTime() { /* r4 = this; r1 = r4.b042D042DЭ042DЭ042D; monitor-enter(r1); r0 = r4.b042D042D042D042DЭ042D; Catch:{ all -> 0x001f } L_0x0005: r2 = 1; switch(r2) { case 0: goto L_0x0005; case 1: goto L_0x000e; default: goto L_0x0009; }; Catch:{ all -> 0x001f } L_0x0009: r2 = 0; switch(r2) { case 0: goto L_0x000e; case 1: goto L_0x0005; default: goto L_0x000d; }; Catch:{ all -> 0x001f } L_0x000d: goto L_0x0009; L_0x000e: r2 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001f } if (r0 != r2) goto L_0x0017; L_0x0012: r0 = r4.bЭЭЭЭ042D042D; Catch:{ all -> 0x001f } r0.waitHapticStopped(); Catch:{ all -> 0x001f } L_0x0017: r2 = android.os.SystemClock.uptimeMillis(); Catch:{ all -> 0x001f } r4.b042DЭ042D042DЭ042D = r2; Catch:{ all -> 0x001f } monitor-exit(r1); Catch:{ all -> 0x001f } return; L_0x001f: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x001f } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.setMediaReferenceTime():void"); } public void setMediaTimestamp(long j) { synchronized (this.b042D042DЭ042DЭ042D) { if (this.b042D042D042D042DЭ042D == SDKStatus.STOPPED) { this.bЭЭЭЭ042D042D.waitHapticStopped(); } this.b042DЭ042D042DЭ042D = SystemClock.uptimeMillis(); this.bЭЭ042D042DЭ042D = j; } } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public int transitToState(com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus r7) { /* r6 = this; r1 = 0; r0 = -1; r2 = r6.bЭ042DЭ042DЭ042D; monitor-enter(r2); r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.NOT_INITIALIZED; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x000f; L_0x0009: r0 = r6.b044904490449щщщ(); Catch:{ all -> 0x001e } monitor-exit(r2); Catch:{ all -> 0x001e } L_0x000e: return r0; L_0x000f: r3 = rrrrrr.crcrcr.b041B041BЛ041B041B041B; Catch:{ all -> 0x001e } r4 = r6.b042D042D042D042DЭ042D; Catch:{ all -> 0x001e } r4 = r4.ordinal(); Catch:{ all -> 0x001e } r3 = r3[r4]; Catch:{ all -> 0x001e } switch(r3) { case 1: goto L_0x0049; case 2: goto L_0x0052; case 3: goto L_0x0104; case 4: goto L_0x0064; case 5: goto L_0x011c; case 6: goto L_0x013b; case 7: goto L_0x0142; default: goto L_0x001c; }; Catch:{ all -> 0x001e } L_0x001c: monitor-exit(r2); Catch:{ all -> 0x001e } goto L_0x000e; L_0x001e: r0 = move-exception; monitor-exit(r2); Catch:{ all -> 0x001e } throw r0; L_0x0021: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x001c; L_0x0025: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r1; Catch:{ all -> 0x001e } goto L_0x001c; L_0x002e: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PLAYING; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x003f; L_0x0032: r0 = r6.bЭЭЭЭ042D042D; Catch:{ all -> 0x001e } r4 = r6.bЭЭ042D042DЭ042D; Catch:{ all -> 0x001e } r1 = (int) r4; Catch:{ all -> 0x001e } r0.setRequestBufferPosition(r1); Catch:{ all -> 0x001e } r0 = r6.bщщщщ0449щ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x003f: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x00fa; L_0x0043: r0 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r0; Catch:{ all -> 0x001e } r0 = r1; goto L_0x001c; L_0x0049: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.INITIALIZED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x001c; L_0x004d: r0 = r6.bщщщ0449щщ(r7); Catch:{ all -> 0x001e } goto L_0x001c; L_0x0052: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PLAYING; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x005b; L_0x0056: r0 = r6.bщщщщ0449щ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x005b: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x0075; L_0x005f: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x0064: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PLAYING; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x00b6; L_0x0068: r0 = r6.bЭЭЭЭ042D042D; Catch:{ all -> 0x001e } r4 = r6.bЭЭ042D042DЭ042D; Catch:{ all -> 0x001e } r1 = (int) r4; Catch:{ all -> 0x001e } r0.setRequestBufferPosition(r1); Catch:{ all -> 0x001e } r0 = r6.bщщщщ0449щ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x0075: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x001c; L_0x0079: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r1; Catch:{ all -> 0x001e } goto L_0x001c; L_0x0082: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x008b; L_0x0086: r0 = r6.bщщ04490449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x008b: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED_DUE_TO_TIMEOUT; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x009b; L_0x008f: r0 = "MediaTaskManager"; r1 = "Haptic playback is paused due to update time-out. Call update() to resume playback"; com.immersion.hapticmediasdk.utils.Log.w(r0, r1); Catch:{ all -> 0x001e } r0 = r6.bщ044904490449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x009b: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED_DUE_TO_BUFFERING; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x00ac; L_0x009f: r0 = r6.b0449044904490449щщ(); Catch:{ all -> 0x001e } r1 = "MediaTaskManager"; r3 = "Haptic playback is paused due to slow data buffering..."; com.immersion.hapticmediasdk.utils.Log.w(r1, r3); Catch:{ all -> 0x001e } goto L_0x001c; L_0x00ac: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x00ec; L_0x00b0: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x00b6: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x00da; L_0x00ba: r0 = r1; goto L_0x001c; L_0x00bd: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PLAYING; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x00cf; L_0x00c1: r0 = r6.bЭЭЭЭ042D042D; Catch:{ all -> 0x001e } r4 = r6.bЭЭ042D042DЭ042D; Catch:{ all -> 0x001e } r1 = (int) r4; Catch:{ all -> 0x001e } r0.setRequestBufferPosition(r1); Catch:{ all -> 0x001e } r0 = r6.bщщщщ0449щ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x00cf: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x0123; L_0x00d3: r0 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r0; Catch:{ all -> 0x001e } r0 = r1; goto L_0x001c; L_0x00da: switch(r1) { case 0: goto L_0x00e2; case 1: goto L_0x00da; default: goto L_0x00dd; }; Catch:{ all -> 0x001e } L_0x00dd: r3 = 1; switch(r3) { case 0: goto L_0x00da; case 1: goto L_0x00e2; default: goto L_0x00e1; }; Catch:{ all -> 0x001e } L_0x00e1: goto L_0x00dd; L_0x00e2: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x0021; L_0x00e6: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x00ec: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x001c; L_0x00f0: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r1; Catch:{ all -> 0x001e } goto L_0x001c; L_0x00fa: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x010e; L_0x00fe: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x0104: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PLAYING; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x0082; L_0x0108: r0 = r6.b0449щ04490449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x010e: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x001c; L_0x0112: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r1; Catch:{ all -> 0x001e } goto L_0x001c; L_0x011c: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED_DUE_TO_TIMEOUT; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x00bd; L_0x0120: r0 = r1; goto L_0x001c; L_0x0123: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x012d; L_0x0127: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x012d: r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } if (r7 != r1) goto L_0x001c; L_0x0131: r0 = r6.bщ0449щ0449щщ(); Catch:{ all -> 0x001e } r1 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED_DUE_TO_ERROR; Catch:{ all -> 0x001e } r6.b042D042D042D042DЭ042D = r1; Catch:{ all -> 0x001e } goto L_0x001c; L_0x013b: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PAUSED_DUE_TO_BUFFERING; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x002e; L_0x013f: r0 = r1; goto L_0x001c; L_0x0142: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.PLAYING; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x014c; L_0x0146: r0 = r6.bщщщщ0449щ(); Catch:{ all -> 0x001e } goto L_0x001c; L_0x014c: r3 = com.immersion.hapticmediasdk.HapticContentSDK.SDKStatus.STOPPED; Catch:{ all -> 0x001e } if (r7 != r3) goto L_0x001c; L_0x0150: r0 = r1; goto L_0x001c; */ throw new UnsupportedOperationException("Method not decompiled: com.immersion.hapticmediasdk.MediaTaskManager.transitToState(com.immersion.hapticmediasdk.HapticContentSDK$SDKStatus):int"); } }
35.962529
261
0.570917
7f32a19560da01705458f16dc7c75f908ede781e
5,423
/** * VMware Continuent Tungsten Replicator * Copyright (C) 2015 VMware, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Initial developer(s): Robert Hodges * Contributor(s): */ package com.continuent.tungsten.replicator.datasource; import org.apache.log4j.Logger; import com.continuent.tungsten.common.file.FileIO; import com.continuent.tungsten.common.file.FilePath; import com.continuent.tungsten.common.file.JavaFileIO; import com.continuent.tungsten.replicator.ReplicatorException; /** * Implements a data source that stores data on a file system. */ public class FileDataSource extends AbstractDataSource implements UniversalDataSource { private static Logger logger = Logger.getLogger(FileDataSource.class); // Properties of this data source. private String directory; // Catalog tables. FileCommitSeqno commitSeqno; // File IO-related variables. FilePath rootDir; FilePath serviceDir; JavaFileIO javaFileIO; /** Create new instance. */ public FileDataSource() { } public String getDirectory() { return directory; } public void setDirectory(String directory) { this.directory = directory; } /** * {@inheritDoc} * * @see com.continuent.tungsten.replicator.datasource.CatalogEntity#configure() */ public void configure() throws ReplicatorException, InterruptedException { super.configure(); // Configure file paths. rootDir = new FilePath(directory); serviceDir = new FilePath(rootDir, serviceName); // Create a new Java file IO instance. javaFileIO = new JavaFileIO(); // Configure tables. commitSeqno = new FileCommitSeqno(javaFileIO); commitSeqno.setServiceName(serviceName); commitSeqno.setChannels(channels); commitSeqno.setServiceDir(serviceDir); } /** * Prepare all data source tables for use. */ @Override public void prepare() throws ReplicatorException, InterruptedException { // Ensure the service directory is ready for use. FileIO fileIO = new JavaFileIO(); if (!fileIO.exists(serviceDir)) { logger.info("Service directory does not exist, creating: " + serviceDir.toString()); fileIO.mkdirs(serviceDir); } // Ensure everything exists now. if (!fileIO.readable(serviceDir)) { throw new ReplicatorException( "Service directory does not exist or is not readable: " + serviceDir.toString()); } else if (!fileIO.writable(serviceDir)) { throw new ReplicatorException("Service directory is not writable: " + serviceDir.toString()); } // Prepare all tables. commitSeqno.prepare(); } /** * {@inheritDoc} */ public void reduce() throws ReplicatorException, InterruptedException { // Reduce tasks. if (commitSeqno != null) { commitSeqno.reduceTasks(); } } /** * Release all data source tables. */ @Override public void release() throws ReplicatorException, InterruptedException { // Release tables. if (commitSeqno != null) { commitSeqno.reduceTasks(); commitSeqno.release(); commitSeqno = null; } } /** * Ensure all tables are ready for use, creating them if necessary. */ @Override public void initialize() throws ReplicatorException, InterruptedException { logger.info("Initializing data source files: service=" + serviceName + " directory=" + directory); commitSeqno.initialize(); } @Override public boolean clear() throws ReplicatorException, InterruptedException { commitSeqno.clear(); return true; } /** * {@inheritDoc} * * @see com.continuent.tungsten.replicator.datasource.UniversalDataSource#getCommitSeqno() */ @Override public CommitSeqno getCommitSeqno() { return commitSeqno; } /** * {@inheritDoc} * * @see com.continuent.tungsten.replicator.datasource.UniversalDataSource#getConnection() */ public UniversalConnection getConnection() throws ReplicatorException { return new FileConnection(csv); } /** * {@inheritDoc} * * @see com.continuent.tungsten.replicator.datasource.UniversalDataSource#releaseConnection(com.continuent.tungsten.replicator.datasource.UniversalConnection) */ public void releaseConnection(UniversalConnection conn) { conn.close(); } }
27.810256
162
0.630463
ba0050e79cf7dcb643d2ddc794f9279ad464a921
2,687
package seedu.address.logic.command.delete; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.ParserUtil.ACTIVITY_INDEX; import java.util.List; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.command.CommandResult; import seedu.address.logic.command.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.activity.Activity; import seedu.address.model.commons.TravelPlanObject; /** * Deletes an activity in a travel plan or wishlist identified using the index from the travel plan or wishlist. */ public class DeleteActivityCommand extends DeleteCommand { public static final String COMMAND_WORD = "activity"; public static final String MESSAGE_EXAMPLE = "Example: " + DeleteCommand.COMMAND_WORD + COMMAND_SEPARATOR + COMMAND_WORD + " 1"; public static final String MESSAGE_USAGE = "Delete an activity by its index in the displayed activity list using the format:\n" + DeleteCommand.COMMAND_WORD + COMMAND_SEPARATOR + COMMAND_WORD + " INDEX\n" + MESSAGE_EXAMPLE; public static final String MESSAGE_DELETE_ACTIVITY_SUCCESS = "Deleted Activity:\n%1$s"; private final Index targetIndex; /** * Constructor for DeleteActivityCommand. * @param targetIndex index to be deleted. */ public DeleteActivityCommand(Index targetIndex) { super(targetIndex); this.targetIndex = targetIndex; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); boolean isTravelPlan = model.isDirectoryTypeTravelPlan(); List<Activity> activityList; if (isTravelPlan) { activityList = model.getFilteredActivityList(); } else { activityList = model.getFilteredWishlist(); } if (targetIndex.getZeroBased() >= activityList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_ACTIVITY_DISPLAYED_INDEX); } TravelPlanObject activityToDelete = activityList.get(targetIndex.getZeroBased()); model.deleteTravelPlanObject(activityToDelete); return new CommandResult(String.format(MESSAGE_DELETE_ACTIVITY_SUCCESS, activityToDelete), ACTIVITY_INDEX); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DeleteActivityCommand // instanceof handles nulls && targetIndex.equals(((DeleteActivityCommand) other).targetIndex)); // state check } }
36.808219
115
0.718273
c4f7fa26f80fcda1aa0a2411fdea7506a7ca86ab
149
package com.liuenci.dao; import com.liuenci.pojo.Dept1; import java.util.List; public interface DeptMapper1 { List<Dept1> selectAllDept(); }
13.545455
32
0.744966
886084222c21ba784c02d91717825c3ad7bf9194
3,988
package org.openur.module.service.security; import java.util.Set; import javax.inject.Inject; import org.apache.commons.lang3.Validate; import org.openur.module.domain.security.authorization.IAuthorizableTechUser; import org.openur.module.domain.security.authorization.IPermission; import org.openur.module.domain.userstructure.orgunit.IOrganizationalUnit; import org.openur.module.domain.userstructure.person.IPerson; import org.openur.module.service.securitydomain.ISecurityDomainServices; import org.openur.module.service.userstructure.IOrgUnitServices; import org.openur.module.service.userstructure.IUserServices; import org.openur.module.util.exception.EntityNotFoundException; public class AuthorizationServicesImpl implements IAuthorizationServices { @Inject private IUserServices userServices; @Inject private IOrgUnitServices orgUnitServices; @Inject private ISecurityDomainServices securityDomainServices; private boolean internalHasPermission(IPerson person, IOrganizationalUnit orgUnit, IPermission permission) { boolean hasPerm = false; IOrganizationalUnit ouTmp = orgUnit; while (!hasPerm && ouTmp != null) { hasPerm = ouTmp.hasPermission(person, permission); ouTmp = ouTmp.getSuperOrgUnit(); } return hasPerm; } private boolean lookupDomainObjectsAndCheckIfUserHasPermission(String userId, String permissionText, String applicationName, IOrganizationalUnit orgUnit) throws EntityNotFoundException { Validate.notEmpty(userId, "user-id must not be empty!"); Validate.notEmpty(permissionText, "permission-text must not be empty!"); Validate.notEmpty(applicationName, "application-name must not be empty!"); IPermission permission = securityDomainServices.findPermission(permissionText, applicationName); if (permission == null) { throw new EntityNotFoundException(String.format("No permission found with permission-text '%s' and application-name '%s'!", permissionText, applicationName)); } if (orgUnit != null) { IPerson person = userServices.findPersonById(userId); if (person == null) { throw new EntityNotFoundException(String.format("No person found for ID '%s'!", userId)); } return internalHasPermission(person, orgUnit, permission); } else { IAuthorizableTechUser techUser = userServices.findTechnicalUserById(userId); if (techUser == null) { throw new EntityNotFoundException(String.format("No technical-user found for techUserId '%s'!", userId)); } return techUser.hasPermission(permission); } } @Override public Boolean hasPermission(String personId, String orgUnitId, String permissionText, String applicationName) throws EntityNotFoundException { Validate.notEmpty(orgUnitId, "org-unit-id must not be empty!"); IOrganizationalUnit orgUnit = orgUnitServices.findOrgUnitById(orgUnitId, Boolean.TRUE); if (orgUnit == null) { throw new EntityNotFoundException(String.format("No org-unit found for orgUnitId '%s'!", orgUnitId)); } return lookupDomainObjectsAndCheckIfUserHasPermission(personId, permissionText, applicationName, orgUnit); } @Override public Boolean hasPermission(String personId, String permissionText, String applicationName) throws EntityNotFoundException { Set<IOrganizationalUnit> rootOus = orgUnitServices.obtainRootOrgUnits(); Validate.validState(!rootOus.isEmpty(), "There must be at least one root organizational-unit within the system!"); // take first root-ou, for system-wide permissions are placed (redundantly) // in ALL root-ou's: IOrganizationalUnit orgUnit = rootOus.stream().findFirst().get(); return lookupDomainObjectsAndCheckIfUserHasPermission(personId, permissionText, applicationName, orgUnit); } @Override public Boolean hasPermissionTechUser(String techUserId, String permissionText, String applicationName) throws EntityNotFoundException { return lookupDomainObjectsAndCheckIfUserHasPermission(techUserId, permissionText, applicationName, null); } }
34.08547
164
0.790371
d0cb910f2b7a3759f38ca267bec39e327974d830
2,680
package ua.knu.csc.entity; import java.util.*; // directed graph (or digraph) public class Digraph { private final Map<Vertex, List<Vertex>> adjacencyList = new HashMap<>(); private final Map<Vertex, Integer> indegree = new HashMap<>(); // checks if the specified vertex is in the graph private void validateVertex(Vertex vertex) { if (!adjacencyList.containsKey(vertex)) { throw new NoSuchElementException("The specified vertex " + vertex + " is not in the graph."); } } public void addVertex(Vertex vertex) { if (vertex == null) { throw new NullPointerException("The specified vertex is null."); } adjacencyList.putIfAbsent(vertex, new LinkedList<>()); indegree.putIfAbsent(vertex, 0); } public void removeVertex(Vertex vertex) { validateVertex(vertex); adjacencyList.get(vertex).forEach(to -> indegree.put(to, indegree.get(to) - 1)); adjacencyList.values().forEach(list -> list.remove(vertex)); adjacencyList.remove(vertex); indegree.remove(vertex); } public void addEdge(Vertex from, Vertex to) { validateVertex(from); validateVertex(to); adjacencyList.get(from).add(to); indegree.put(to, indegree.get(to) + 1); } public void removeEdge(Vertex from, Vertex to) { validateVertex(from); validateVertex(to); adjacencyList.get(from).remove(to); indegree.put(to, indegree.get(to) - 1); } // Returns the vertices adjacent from the specified vertex in this digraph. public Iterable<Vertex> getVerticesAdjacentFrom(Vertex vertex) { validateVertex(vertex); return adjacencyList.get(vertex); } // The indegree of a vertex is the number of edges pointing to it. public int getIndegree(Vertex vertex) { validateVertex(vertex); return indegree.get(vertex); } // The outdegree of a vertex is the number of edges pointing from it. public int getOutdegree(Vertex vertex) { validateVertex(vertex); return adjacencyList.get(vertex).size(); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<Vertex, List<Vertex>> entry : adjacencyList.entrySet()) { stringBuilder.append(entry.getKey()).append(": "); for (Vertex vertex : entry.getValue()) { stringBuilder.append("[").append(vertex).append("] "); } stringBuilder.append(System.getProperty("line.separator")); } return stringBuilder.toString(); } }
29.777778
105
0.631716
389e2d3ecb803ef26cd0b35c028057e6fb9f4722
9,165
package at.porscheinformatik.antimapper; import static at.porscheinformatik.antimapper.TestUtils.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; import java.util.Collections; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.junit.Assert; import org.junit.Test; public class MergeMapIntoTreeSetTest extends AbstractMapperTest { @Test public void testNullMapIntoNullTreeSet() { Map<Integer, String> dtos = null; SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, nullValue()); } @Test public void testNullMapIntoNullTreeSetOrEmpty() { Map<Integer, String> dtos = null; SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS, Hint.OR_EMPTY).intoTreeSet(entities, CHAR_ARRAY_COMPARATOR); assertThat(describeResult(result), result, is(Collections.emptySortedSet())); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testNullMapIntoEmptyTreeSet() { Map<Integer, String> dtos = null; SortedSet<char[]> entities = TestUtils.toSortedSet(CHAR_ARRAY_COMPARATOR); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, is(Collections.emptySet())); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testNullMapIntoTreeSet() { Map<Integer, String> dtos = null; SortedSet<char[]> entities = toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, null, "a".toCharArray()); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection( toList(is("!a".toCharArray()), is("!b".toCharArray()), is("!c1".toCharArray()), is("!c2".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testMapIntoNullTreeSet() { Map<Integer, String> dtos = toMap(1, "A", 2, "C2", 3, "C1", 4, null, 5, "A"); SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities, CHAR_ARRAY_COMPARATOR); assertThat(describeResult(result), result, matchesCollection(toList(is("A".toCharArray()), is("C2".toCharArray()), is("C1".toCharArray())))); assertThat(((TreeSet<char[]>) result).comparator(), is(CHAR_ARRAY_COMPARATOR)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testEmptyMapIntoNullTreeSet() { Map<Integer, String> dtos = Collections.emptyMap(); SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities, CHAR_ARRAY_COMPARATOR); assertThat(describeResult(result), result, is(Collections.emptySet())); assertThat(((TreeSet<char[]>) result).comparator(), is(CHAR_ARRAY_COMPARATOR)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testEmptyMapIntoEmptyTreeSet() { Map<Integer, String> dtos = Collections.emptyMap(); SortedSet<char[]> entities = new TreeSet<>(CHAR_ARRAY_COMPARATOR); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, is(Collections.emptySet())); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testEmptyMapIntoTreeSet() { Map<Integer, String> dtos = Collections.emptyMap(); SortedSet<char[]> entities = toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, null, "a".toCharArray()); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection( toList(is("!a".toCharArray()), is("!b".toCharArray()), is("!c1".toCharArray()), is("!c2".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testMapIntoEmptyTreeSet() { Map<Integer, String> dtos = toMap(1, "A", 2, "C2", 3, "C1", 4, null, 5, "A"); SortedSet<char[]> entities = new TreeSet<>(CHAR_ARRAY_COMPARATOR); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection(toList(is("A".toCharArray()), is("C2".toCharArray()), is("C1".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testMapIntoTreeSet() { Map<Integer, String> dtos = toMap(1, "A", 2, "C2", 3, "C1", 4, null, 5, "A"); SortedSet<char[]> entities = toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, null, "a".toCharArray()); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection( toList(is("A".toCharArray()), is("C2".toCharArray()), is("!b".toCharArray()), is("C1".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testMapIntoTreeSetKeepNullAndUnmodifiable() { Map<Integer, String> dtos = toMap(1, "A", 2, "C2", 3, "C1", 4, null, 5, "A"); SortedSet<char[]> entities = Collections .unmodifiableSortedSet(toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, "a".toCharArray())); SortedSet<char[]> result = this.mergeAll(dtos, Hint.KEEP_NULL, Hint.UNMODIFIABLE, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection(toList(is("A".toCharArray()), is("C2".toCharArray()), is("!b".toCharArray()), is("C1".toCharArray()), nullValue()))); try { result.add("Z".toCharArray()); fail(); } catch (UnsupportedOperationException e) { // expected } } @Override public boolean isUniqueKeyMatching(String dto, char[] entity, Object... hints) { // make sure, there is a key Assert.assertTrue(Hints.containsHint(hints, Integer.class)); return super.isUniqueKeyMatching(dto, entity, hints); } }
41.849315
119
0.654446
6c20a32019e526c226af5ccafd8e518d3551da6f
305
package com.exerciseday6; import java.util.*; public class Exercise_3 { public static void main(String[] args) { // TODO Auto-generated method stub List<Integer> rev = new ArrayList<>(); for(int i = 1; i<=10; i++) { rev.add(i); } Collections.reverse(rev); System.out.println(rev); } }
17.941176
41
0.652459
55272d732b9cd85dc64e6d3ec5e8e43505b706aa
4,709
package org.basex.http.restxq; import static org.junit.Assert.*; import java.io.*; import org.basex.core.*; import org.basex.util.http.*; import org.junit.*; /** * This test contains RESTXQ methods. * * @author BaseX Team 2005-16, BSD License * @author Christian Gruen */ public final class RestXqMethodTest extends RestXqTest { /** * Retrieve path with typed variable. * @throws Exception exception */ @Test public void post() throws Exception { // text String f = "declare %R:POST('{$x}') %R:path('') function m:f($x) {$x};"; post(f, "12", "12", MediaType.TEXT_PLAIN); post(f, "<x>A</x>", "<x>A</x>", MediaType.APPLICATION_XML); // json f = "declare %R:POST('{$x}') %R:path('') function m:f($x) {$x/json/*};"; post(f, "<A>B</A>", "{ \"A\":\"B\" }", MediaType.APPLICATION_JSON); // csv f = "declare %R:POST('{$x}') %R:path('') function m:f($x) {$x/csv/*/*};"; post(f, "<entry>A</entry>", "A", MediaType.TEXT_CSV); // binary f = "declare %R:POST('{$x}') %R:path('') function m:f($x) {$x};"; post(f, "AAA", "AAA", MediaType.APPLICATION_OCTET_STREAM); post(f, "AAA", "AAA", new MediaType("whatever/type")); } /** * Custom method. * @throws Exception exception */ @Test public void method() throws Exception { // standard HTTP method without body get("declare %R:method('GET') %R:path('') function m:f() {'x'};", "", "x"); // standard HTTP method specified twice getE("declare %R:method('GET') %R:GET %R:path('') function m:f() {'x'};", ""); // standard HTTP method without body, body provided in request getE("declare %R:method('GET', '{$b}') %R:path('') function m:f($b) {$b};", ""); // standard HTTP method with body, body provided in request post("declare %R:method('POST', '{$b}') %R:path('') function m:f($b) {$b};", "12", "12", MediaType.TEXT_PLAIN); // ignore case get("declare %R:method('get') %R:path('') function m:f() {'x'};", "", "x"); getE("declare %R:method('get') declare %R:method('GET') %R:path('') " + "function m:f() {'x'};", ""); // custom HTTP method without body install("declare %R:method('RETRIEVE') %R:path('') function m:f() {'x'};"); // java.net.HttpUrlConnection does not support custom HTTP methods // assertEquals("x", request("", "RETRIEVE")); // custom HTTP method with body install("declare %R:method('RETRIEVE', '{$b}') %R:path('') function m:f($b) {$b};"); // java.net.HttpUrlConnection does not support custom HTTP methods // assertEquals("12", request("", "RETRIEVE", "12", MediaType.TEXT_PLAIN)); // custom HTTP method specified twice final String q = "declare %R:method('RETRIEVE') %R:method('RETRIEVE') %R:path('') " + "function m:f() {'x'};"; install(q); try { // java.net.HttpUrlConnection does not support custom HTTP methods request("", "RETRIEVE"); fail("Error expected: " + q); } catch (final BaseXException ignored) { } } /** * {@code %HEAD} method. * @throws Exception exception */ @Test public void head() throws Exception { // correct return type headR("declare %R:HEAD %R:path('') function m:f() { <R:response/> };"); headR("declare %R:HEAD %R:path('') function m:f() as element(R:response) { <R:response/> };"); // wrong type headE("declare %R:HEAD %R:path('') function m:f() { () };"); headE("declare %R:HEAD %R:path('') function m:f() { <response/> };"); headE("declare %R:HEAD %R:path('') function m:f() as element(R:response)* {()};"); } /** * Executes the specified POST request and tests the result. * * @param function function to test * @param exp expected result * @param request request body * @param type media type * @throws IOException I/O exception */ private static void post(final String function, final String exp, final String request, final MediaType type) throws IOException { install(function); assertEquals(exp, post("", request, type)); } /** * Executes the specified HEAD request and tests the result. * * @param function function to test * @throws IOException I/O exception */ private static void headR(final String function) throws IOException { install(function); assertEquals("", head("")); } /** * Executes the specified HEAD request and tests for an error. * * @param function function to test * @throws IOException I/O exception */ private static void headE(final String function) throws IOException { install(function); try { head(""); fail("Error expected: " + ""); } catch(final BaseXException ignored) { } } }
34.123188
98
0.599703
62f2cc4910ca04c84229eb2d142e1617ab1246cc
244
package com.open9527.router.inter; import com.open9527.annotation.router.RouteMeta; import java.util.Map; /** * @author open_9527 * Create at 2021/3/1 **/ public interface IRouteGroup { void loadInto(Map<String, RouteMeta> atlas); }
16.266667
48
0.729508
c1cacb4280b12ae79f4679aad5e68e04f4e2016e
28,747
package com.massivecraft.massivecore.util; import com.massivecraft.massivecore.cmd.CmdMassiveCore; import com.massivecraft.massivecore.collections.MassiveList; import com.massivecraft.massivecore.command.MassiveCommand; import com.massivecraft.massivecore.mson.Mson; import com.massivecraft.massivecore.mson.MsonEvent; import com.massivecraft.massivecore.predicate.PredicateStartsWithIgnoreCase; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.massivecraft.massivecore.mson.Mson.mson; public class Txt { // -------------------------------------------- // // STATIC // -------------------------------------------- // public static final int PAGEHEIGHT_PLAYER = 9; public static final int PAGEHEIGHT_CONSOLE = 50; public static final Map<String, String> parseReplacements; public static final Pattern parsePattern; public static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s+"); public static final Pattern PATTERN_NEWLINE = Pattern.compile("\\r?\\n"); public static final Pattern PATTERN_NUMBER = Pattern.compile("[0-9]+"); private static final Pattern PATTERN_UPPERCASE_ZEROWIDTH = Pattern.compile("(?=[A-Z])"); // NOTE: Use camelsplit instead for Java 6/7 compatibility. public static final long millisPerSecond = 1000; public static final long millisPerMinute = 60 * millisPerSecond; public static final long millisPerHour = 60 * millisPerMinute; public static final long millisPerDay = 24 * millisPerHour; public static final long millisPerWeek = 7 * millisPerDay; public static final long millisPerMonth = 31 * millisPerDay; public static final long millisPerYear = 365 * millisPerDay; public static final Set<String> vowel = MUtil.set( "A", "E", "I", "O", "U", "Y", "Å", "Ä", "Ö", "Æ", "Ø", "a", "e", "i", "o", "u", "y", "å", "ä", "ö", "æ", "ø" ); public static final Map<String, Long> unitMillis = MUtil.map( "years", millisPerYear, "months", millisPerMonth, "weeks", millisPerWeek, "days", millisPerDay, "hours", millisPerHour, "minutes", millisPerMinute, "seconds", millisPerSecond ); static { // Create the parse replacements map parseReplacements = new HashMap<>(); // Color by name parseReplacements.put("<empty>", ""); parseReplacements.put("<black>", "\u00A70"); parseReplacements.put("<navy>", "\u00A71"); parseReplacements.put("<green>", "\u00A72"); parseReplacements.put("<teal>", "\u00A73"); parseReplacements.put("<red>", "\u00A74"); parseReplacements.put("<purple>", "\u00A75"); parseReplacements.put("<gold>", "\u00A76"); parseReplacements.put("<orange>", "\u00A76"); parseReplacements.put("<silver>", "\u00A77"); parseReplacements.put("<gray>", "\u00A78"); parseReplacements.put("<grey>", "\u00A78"); parseReplacements.put("<blue>", "\u00A79"); parseReplacements.put("<lime>", "\u00A7a"); parseReplacements.put("<aqua>", "\u00A7b"); parseReplacements.put("<rose>", "\u00A7c"); parseReplacements.put("<pink>", "\u00A7d"); parseReplacements.put("<yellow>", "\u00A7e"); parseReplacements.put("<white>", "\u00A7f"); parseReplacements.put("<magic>", "\u00A7k"); parseReplacements.put("<bold>", "\u00A7l"); parseReplacements.put("<strong>", "\u00A7l"); parseReplacements.put("<strike>", "\u00A7m"); parseReplacements.put("<strikethrough>", "\u00A7m"); parseReplacements.put("<under>", "\u00A7n"); parseReplacements.put("<underline>", "\u00A7n"); parseReplacements.put("<italic>", "\u00A7o"); parseReplacements.put("<em>", "\u00A7o"); parseReplacements.put("<reset>", "\u00A7r"); // Color by semantic functionality parseReplacements.put("<l>", "\u00A72"); parseReplacements.put("<logo>", "\u00A72"); parseReplacements.put("<a>", "\u00A76"); parseReplacements.put("<art>", "\u00A76"); parseReplacements.put("<n>", "\u00A77"); parseReplacements.put("<notice>", "\u00A77"); parseReplacements.put("<i>", "\u00A7e"); parseReplacements.put("<info>", "\u00A7e"); parseReplacements.put("<g>", "\u00A7a"); parseReplacements.put("<good>", "\u00A7a"); parseReplacements.put("<b>", "\u00A7c"); parseReplacements.put("<bad>", "\u00A7c"); parseReplacements.put("<k>", "\u00A7b"); parseReplacements.put("<key>", "\u00A7b"); parseReplacements.put("<v>", "\u00A7d"); parseReplacements.put("<value>", "\u00A7d"); parseReplacements.put("<h>", "\u00A7d"); parseReplacements.put("<highlight>", "\u00A7d"); parseReplacements.put("<c>", "\u00A7b"); parseReplacements.put("<command>", "\u00A7b"); parseReplacements.put("<p>", "\u00A73"); parseReplacements.put("<parameter>", "\u00A73"); parseReplacements.put("&&", "&"); parseReplacements.put("§§", "§"); // Color by number/char for (int i = 48; i <= 122; i++) { char c = (char)i; parseReplacements.put("§"+c, "\u00A7"+c); parseReplacements.put("&"+c, "\u00A7"+c); if (i == 57) i = 96; } // Build the parse pattern and compile it StringBuilder patternStringBuilder = new StringBuilder(); for (String find : parseReplacements.keySet()) { patternStringBuilder.append('('); patternStringBuilder.append(Pattern.quote(find)); patternStringBuilder.append(")|"); } String patternString = patternStringBuilder.toString(); patternString = patternString.substring(0, patternString.length()-1); // Remove the last | parsePattern = Pattern.compile(patternString); } // -------------------------------------------- // // CONSTRUCTOR (FORBIDDEN) // -------------------------------------------- // private Txt() { } // -------------------------------------------- // // PARSE // -------------------------------------------- // public static String parse(String string) { if (string == null) throw new NullPointerException("string"); StringBuffer ret = new StringBuffer(); Matcher matcher = parsePattern.matcher(string); while (matcher.find()) { matcher.appendReplacement(ret, parseReplacements.get(matcher.group(0))); } matcher.appendTail(ret); return ret.toString(); } public static String parse(String string, Object... args) { return String.format(parse(string), args); } public static ArrayList<String> parse(Collection<String> strings) { ArrayList<String> ret = new ArrayList<>(strings.size()); for (String string : strings) { ret.add(parse(string)); } return ret; } // -------------------------------------------- // // SPLIT AT LINEBREAKS // -------------------------------------------- // public static ArrayList<String> wrap(final String string) { if (string == null) throw new NullPointerException("string"); return new ArrayList<>(Arrays.asList(PATTERN_NEWLINE.split(string))); } public static ArrayList<String> wrap(final Collection<String> strings) { ArrayList<String> ret = new ArrayList<>(); for (String string : strings) { ret.addAll(wrap(string)); } return ret; } // -------------------------------------------- // // Parse and Wrap combo // -------------------------------------------- // public static ArrayList<String> parseWrap(final String string) { return wrap(parse(string)); } public static ArrayList<String> parseWrap(final Collection<String> strings) { return wrap(parse(strings)); } // -------------------------------------------- // // Standard utils like UCFirst, implode and repeat. // -------------------------------------------- // public static List<String> camelsplit(String string) { List<String> ret = Arrays.asList(PATTERN_UPPERCASE_ZEROWIDTH.split(string)); // In version before Java 8 zero width matches in the beginning created a leading empty string. // We manually look for it and removes it to be compatible with Java 6 and 7. if (ret.get(0).isEmpty()) ret = ret.subList(1, ret.size()); return ret; } public static String upperCaseFirst(String string) { if (string == null) throw new NullPointerException("string"); if (string.length() == 0) return string; return string.substring(0, 1).toUpperCase() + string.substring(1); } public static String lowerCaseFirst(String string) { if (string == null) throw new NullPointerException("string"); if (string.length() == 0) return string; return string.substring(0, 1).toLowerCase() + string.substring(1); } public static String repeat(String string, int times) { // Create Ret StringBuilder ret = new StringBuilder(times); // Fill Ret for (int i = 0; i < times; i++) { ret.append(string); } // Return Ret return ret.toString(); } public static String implode(final Object[] list, final String glue, final String format) { StringBuilder ret = new StringBuilder(); for (int i=0; i<list.length; i++) { Object item = list[i]; String str = (item == null ? "NULL" : item.toString()); if (i!=0) { ret.append(glue); } if (format != null) { ret.append(String.format(format, str)); } else { ret.append(str); } } return ret.toString(); } public static String implode(final Object[] list, final String glue) { return implode(list, glue, null); } public static String implode(final Collection<?> coll, final String glue, final String format) { return implode(coll.toArray(new Object[0]), glue, format); } public static String implode(final Collection<?> coll, final String glue) { return implode(coll, glue, null); } public static String implodeCommaAndDot(final Collection<?> objects, final String format, final String comma, final String and, final String dot) { if (objects.size() == 0) return ""; if (objects.size() == 1) { return implode(objects, comma, format); } List<Object> ourObjects = new ArrayList<>(objects); String lastItem = ourObjects.get(ourObjects.size()-1).toString(); String nextToLastItem = ourObjects.get(ourObjects.size()-2).toString(); if (format != null) { lastItem = String.format(format, lastItem); nextToLastItem = String.format(format, nextToLastItem); } String merge = nextToLastItem+and+lastItem; ourObjects.set(ourObjects.size()-2, merge); ourObjects.remove(ourObjects.size()-1); return implode(ourObjects, comma, format)+dot; } public static String implodeCommaAndDot(final Collection<?> objects, final String comma, final String and, final String dot) { return implodeCommaAndDot(objects, null, comma, and, dot); } public static String implodeCommaAnd(final Collection<?> objects, final String comma, final String and) { return implodeCommaAndDot(objects, comma, and, ""); } public static String implodeCommaAndDot(final Collection<?> objects, final String color) { return implodeCommaAndDot(objects, color+", ", color+" and ", color+"."); } public static String implodeCommaAnd(final Collection<?> objects, final String color) { return implodeCommaAndDot(objects, color+", ", color+" and ", ""); } public static String implodeCommaAndDot(final Collection<?> objects) { return implodeCommaAndDot(objects, ""); } public static String implodeCommaAnd(final Collection<?> objects) { return implodeCommaAnd(objects, ""); } public static Integer indexOfFirstDigit(final String str) { Integer ret = null; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); boolean isDigit = (c >= '0' && c <= '9'); if (isDigit) { ret = i; break; } } return ret; } public static String removeLeadingCommandDust(String string) { return string.replaceAll("^[/\\s]+", ""); } public static Entry<String, String> divideOnFirstSpace(String string) { String[] parts = string.split("\\s+", 2); String first = parts[0]; String second = null; if (parts.length > 1) { second = parts[1]; } return new SimpleEntry<>(first, second); } public static boolean isVowel(String str) { if (str == null) throw new NullPointerException("str"); if (str.length() == 0) return false; return vowel.contains(str.substring(0, 1)); } public static String aan(String noun) { return isVowel(noun) ? "an" : "a"; } // -------------------------------------------- // // START COLORS // -------------------------------------------- // // This method never returns null public static final String START_COLORS_REGEX = "^((?:§.)+).*$"; public static final Pattern START_COLORS_PATTERN = Pattern.compile(START_COLORS_REGEX); public static String getStartColors(String string) { Matcher matcher = START_COLORS_PATTERN.matcher(string); if (!matcher.find()) return ""; return matcher.group(1); } // -------------------------------------------- // // Material name tools // -------------------------------------------- // protected static Pattern PATTERN_ENUM_SPLIT = Pattern.compile("[\\s_]+"); public static String getNicedEnumString(String str, String glue) { List<String> parts = new ArrayList<>(); for (String part : PATTERN_ENUM_SPLIT.split(str.toLowerCase())) { parts.add(upperCaseFirst(part)); } return implode(parts, glue); } public static String getNicedEnumString(String str) { return getNicedEnumString(str, ""); } public static <T extends Enum<T>> String getNicedEnum(T enumObject, String glue) { return getNicedEnumString(enumObject.name(), glue); } public static <T extends Enum<T>> String getNicedEnum(T enumObject) { return getNicedEnumString(enumObject.name()); } public static String getMaterialName(Material material) { return getNicedEnum(material, " "); } public static String getItemName(ItemStack itemStack) { if (InventoryUtil.isNothing(itemStack)) return Txt.parse("<silver><em>Nothing"); ChatColor color = (itemStack.getEnchantments().size() > 0) ? ChatColor.AQUA : ChatColor.WHITE; if (itemStack.hasItemMeta()) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasDisplayName()) { return color.toString() + ChatColor.ITALIC.toString() + itemMeta.getDisplayName(); } } return color + Txt.getMaterialName(itemStack.getType()); } public static Mson createItemMson(ItemStack item) { String name = Txt.getItemName(item); String colors = Txt.getStartColors(name); name = colors + "[" + ChatColor.stripColor(name) + "]"; Mson ret = Mson.fromParsedMessage(name); if (InventoryUtil.isSomething(item)) ret = ret.item(item); return ret; } // -------------------------------------------- // // Paging and chrome-tools like titleize // -------------------------------------------- // private final static String titleizeLine = repeat("_", 52); private final static int titleizeBalance = -1; public static Mson titleize(Object obj) { Mson title = mson(obj); if (title.getColor() == null) title = title.color(ChatColor.DARK_GREEN); Mson center = mson( mson(".[ ").color(ChatColor.GOLD), title, mson(" ].").color(ChatColor.GOLD) ); int centerlen = center.length(); int pivot = titleizeLine.length() / 2; int eatLeft = (centerlen / 2) - titleizeBalance; int eatRight = (centerlen - eatLeft) + titleizeBalance; if (eatLeft < pivot) return mson( mson(titleizeLine.substring(0, pivot - eatLeft)).color(ChatColor.GOLD), center, mson(titleizeLine.substring(pivot + eatRight)).color(ChatColor.GOLD) ); else return center; } public static Mson getMessageEmpty() { return mson("Sorry, no pages available.").color(ChatColor.YELLOW); } public static Mson getMessageInvalid(int size) { if (size == 0) { return getMessageEmpty(); } else if (size == 1) { return mson("Invalid, there is only one page.").color(ChatColor.RED); } else { return Mson.format("Invalid, page must be between 1 and %d.", size).color(ChatColor.RED); } } public static Mson titleizeMson(Object obj, int pagecount, int pageHumanBased, MassiveCommand command, List<String> args) { if (command == null) { return titleize(mson( obj, Mson.SPACE, mson(pageHumanBased + "/" + pagecount).color(ChatColor.GOLD) )); } // Math Mson title = mson(obj, Mson.SPACE, "[<]", String.valueOf(pageHumanBased), "/", String.valueOf(pagecount), "[>]"); int centerlen = ".[ ".length() + title.length() + " ].".length(); int pivot = titleizeLine.length() / 2; int eatLeft = (centerlen / 2) - titleizeBalance; int eatRight = (centerlen - eatLeft) + titleizeBalance; // Mson Mson centerMson = mson( mson(".[ ").color(ChatColor.GOLD), mson(obj, Mson.SPACE).color(ChatColor.DARK_GREEN), getFlipSection(pagecount, pageHumanBased, args, command), mson(" ].").color(ChatColor.GOLD) ); if (eatLeft < pivot) { Mson ret = mson( mson(titleizeLine.substring(0, pivot - eatLeft)).color(ChatColor.GOLD), centerMson, mson(titleizeLine.substring(pivot + eatRight)).color(ChatColor.GOLD) ); return ret; } else { return centerMson; } } public static List<Mson> getPage(List<?> lines, int pageHumanBased, Object title) { return getPage(lines, pageHumanBased, title, null, null, null); } public static List<Mson> getPage(List<?> lines, int pageHumanBased, Object title, CommandSender sender) { return getPage(lines, pageHumanBased, title, sender, null, null); } public static List<Mson> getPage(List<?> lines, int pageHumanBased, Object title, MassiveCommand command) { return getPage(lines, pageHumanBased, title, command, command.getArgs()); } public static List<Mson> getPage(List<?> lines, int pageHumanBased, Object title, MassiveCommand command, List<String> args) { return getPage(lines, pageHumanBased, title, command.sender, command, args); } public static List<Mson> getPage(List<?> lines, int pageHumanBased, Object title, CommandSender sender, MassiveCommand command, List<String> args) { return getPage(lines, pageHumanBased, title, (sender == null || sender instanceof Player) ? Txt.PAGEHEIGHT_PLAYER : Txt.PAGEHEIGHT_CONSOLE, command, args); } @SuppressWarnings("unchecked") public static List<Mson> getPage(List<?> lines, int pageHumanBased, Object title, int pageheight, MassiveCommand command, List<String> args) { // Create Ret List<Mson> ret = new MassiveList<>(); int pageZeroBased = pageHumanBased - 1; int pagecount = (int)Math.ceil(((double)lines.size()) / pageheight); // Add Title Mson msonTitle = Txt.titleizeMson(title, pagecount, pageHumanBased, command, args); ret.add(msonTitle); // Check empty and invalid if (pagecount == 0) { ret.add(getMessageEmpty()); return ret; } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { ret.add(getMessageInvalid(pagecount)); return ret; } // Get Lines int from = pageZeroBased * pageheight; int to = from + pageheight; if (to > lines.size()) { to = lines.size(); } // Check object type and add lines Object first = lines.get(0); if (first instanceof String) { for (String line : (List<String>) lines.subList(from, to)) { ret.add(Mson.fromParsedMessage(line)); } } else if (first instanceof Mson) { ret.addAll((List<Mson>) lines.subList(from, to)); } else { throw new IllegalArgumentException("The lines must be either String or Mson."); } // Return Ret return ret; } private static Mson getFlipSection(int pagecount, int pageHumanBased, List<String> args, MassiveCommand command) { // Construct Mson Mson start = mson(String.valueOf(pageHumanBased)).color(ChatColor.GOLD); Mson backward = mson("[<] ").color(ChatColor.GRAY); Mson forward = mson(" [>]").color(ChatColor.GRAY); Mson end = mson(String.valueOf(pagecount)).color(ChatColor.GOLD); // Set flip page backward commands if (pageHumanBased > 1) { start = setFlipPageCommand(start, pageHumanBased, 1, args, command); backward = setFlipPageCommand(backward, pageHumanBased, pageHumanBased - 1, args, command).color(ChatColor.AQUA); } // Set flip page forward commands if (pagecount > pageHumanBased) { forward = setFlipPageCommand(forward, pageHumanBased, pageHumanBased + 1, args, command).color(ChatColor.AQUA); end = setFlipPageCommand(end, pageHumanBased, pagecount, args, command); } Mson flipMson = mson( backward, start, mson("/").color(ChatColor.GOLD), end, forward ); return flipMson; } private static Mson setFlipPageCommand(Mson mson, int pageHumanBased, int destinationPage, List<String> args, MassiveCommand command) { // Create the command line String number = String.valueOf(destinationPage); String oldNumber = String.valueOf(pageHumanBased); String commandLine; if (args != null && args.contains(oldNumber)) { List<String> arguments = new ArrayList<>(args); arguments.set(arguments.indexOf(oldNumber), number); commandLine = command.getCommandLine(arguments); } else { commandLine = command.getCommandLine(number); } // Render the corresponding tooltip String tooltip = MsonEvent.command(commandLine).createTooltip(); // Make command line clicking commandLine = CmdMassiveCore.get().cmdMassiveCoreClick.getCommandLine(commandLine); // Apply command mson = mson.command(commandLine); // Set tooltip to hide the clicking clutter mson = mson.tooltip(tooltip); // Return return mson; } // -------------------------------------------- // // Describing Time // -------------------------------------------- // public static String getTimeDeltaDescriptionRelNow(long millis) { String ret = ""; double millisLeft = (double) Math.abs(millis); List<String> unitCountParts = new ArrayList<>(); for (Entry<String, Long> entry : unitMillis.entrySet()) { if (unitCountParts.size() == 3 ) break; String unitName = entry.getKey(); long unitSize = entry.getValue(); long unitCount = (long) Math.floor(millisLeft / unitSize); if (unitCount < 1) continue; millisLeft -= unitSize*unitCount; unitCountParts.add(unitCount+" "+unitName); } if (unitCountParts.size() == 0) return "just now"; ret += implodeCommaAnd(unitCountParts); ret += " "; if (millis <= 0) { ret += "ago"; } else { ret += "from now"; } return ret; } // -------------------------------------------- // // FORMATTING CANDY // -------------------------------------------- // public static String parenthesize(String string) { return Txt.parse("<silver>(%s<silver>)", string); } // -------------------------------------------- // // "SMART" QUOTES // -------------------------------------------- // // The quite stupid "Smart quotes" design idea means replacing normal characters with mutated UTF-8 alternatives. // The normal characters look good in Minecraft. // The UFT-8 "smart" alternatives look quite bad. // http://www.fileformat.info/info/unicode/block/general_punctuation/list.htm public static String removeSmartQuotes(String string) { if (string == null) throw new NullPointerException("string"); // LEFT SINGLE QUOTATION MARK string = string.replace("\u2018", "'"); // RIGHT SINGLE QUOTATION MARK string = string.replace("\u2019", "'"); // LEFT DOUBLE QUOTATION MARK string = string.replace("\u201C", "\""); // RIGHT DOUBLE QUOTATION MARK string = string.replace("\u201D", "\""); // ONE DOT LEADER string = string.replace("\u2024", "."); // TWO DOT LEADER string = string.replace("\u2025", ".."); // HORIZONTAL ELLIPSIS string = string.replace("\u2026", "..."); return string; } // -------------------------------------------- // // String comparison // -------------------------------------------- // public static String getBestCIStart(Collection<String> candidates, String start) { String ret = null; int best = 0; start = start.toLowerCase(); int minlength = start.length(); for (String candidate : candidates) { if (candidate.length() < minlength) continue; if ( ! candidate.toLowerCase().startsWith(start)) continue; // The closer to zero the better int lendiff = candidate.length() - minlength; if (lendiff == 0) { return candidate; } if (lendiff < best || best == 0) { best = lendiff; ret = candidate; } } return ret; } // -------------------------------------------- // // FILTER // -------------------------------------------- // public static <T> List<T> getFiltered(Iterable<T> elements, Predicate<T> predicate) { // Create Ret List<T> ret = new ArrayList<>(); // Fill Ret for (T element : elements) { if ( ! predicate.test(element)) continue; ret.add(element); } // Return Ret return ret; } public static <T> List<T> getFiltered(T[] elements, Predicate<T> predicate) { return getFiltered(Arrays.asList(elements), predicate); } public static List<String> getStartsWithIgnoreCase(Iterable<String> elements, String prefix) { return getFiltered(elements, PredicateStartsWithIgnoreCase.get(prefix)); } public static List<String> getStartsWithIgnoreCase(String[] elements, String prefix) { return getStartsWithIgnoreCase(Arrays.asList(elements), prefix); } // -------------------------------------------- // // Tokenization // -------------------------------------------- // public static List<String> tokenizeArguments(String str) { List<String> ret = new ArrayList<>(); StringBuilder token = null; boolean escaping = false; boolean citing = false; for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (token == null) { token = new StringBuilder(); } if (escaping) { escaping = false; token.append(c); } else if (c == '\\') { escaping = true; } else if (c == '"') { if (citing || token.length() > 0) { ret.add(token.toString()); token = null; } citing = !citing; } else if (citing == false && c == ' ') { if (token.length() > 0) { ret.add(token.toString()); token = null; } } else { token.append(c); } } if (token != null) { ret.add(token.toString()); } return ret; } // -------------------------------------------- // // PREPONDFIX // -------------------------------------------- // // This weird algorithm takes: // - A prefix // - A centerpiece single string or a list of strings. // - A suffix // If the centerpiece is a single String it just concatenates prefix + centerpiece + suffix. // If the centerpiece is multiple Strings it concatenates prefix + suffix and then appends the centerpice at the end. // This algorithm is used in the editor system. public static List<String> prepondfix(String prefix, List<String> strings, String suffix) { // Create List<String> ret = new MassiveList<>(); // Fill List<String> parts = new MassiveList<>(); if (prefix != null) parts.add(prefix); if (strings.size() == 1) parts.add(strings.get(0)); if (suffix != null) parts.add(suffix); ret.add(Txt.implode(parts, " ")); if (strings.size() != 1) { ret.addAll(strings); } // Return return ret; } public static String prepondfix(String prefix, String string, String suffix) { List<String> strings = Arrays.asList(PATTERN_NEWLINE.split(string)); List<String> ret = prepondfix(prefix, strings, suffix); return implode(ret, "\n"); } }
29.393661
158
0.61836
2193043d5b8928531891c0c6b7ee72e6030e0fdf
15,517
package com.linkedin.dagli.object; import com.linkedin.dagli.function.FunctionResult1; import com.linkedin.dagli.producer.Producer; import com.linkedin.dagli.transformer.PreparedTransformer1; import com.linkedin.dagli.util.array.ArraysEx; /** * Methods that create transformers for common conversions. * * Unless otherwise noted, conversions follow the convention that null always converts to null. */ public abstract class Convert { private Convert() { } /** * Conversion transformers from {@link java.lang.Object}s to something else. */ public static abstract class Object { private Object() { } /** * Casts the values provided by the given input to the specified class. A {@link ClassCastException} will be thrown * during DAG execution if the input cannot be cast to the specified type. * * @param input the {@link Producer} supplying input values to cast * @param targetClass the class to which the input values should be cast * @param <T> the type of the class to which to cast * @return a (prepared) transformer that will convert its input values to the target class */ public static <T> PreparedTransformer1<java.lang.Object, T> toClass(Producer<?> input, Class<? extends T> targetClass) { return new Cast<T>(targetClass).withInput(input); } /** * Casts the values provided by the given input to the specified class. If the input cannot be cast to the * specified type, the result will be null. * * @param input the {@link Producer} supplying input values to cast * @param targetClass the class to which the input values should be cast * @param <T> the type of the class to which to cast * @return a (prepared) transformer that will convert its input values to the target class */ public static <T> PreparedTransformer1<java.lang.Object, T> toClassOrNull( Producer<?> input, Class<? extends T> targetClass) { return new Cast<T>(targetClass).withNullIfUncastable().withInput(input); } } /** * Conversion transformers from numbers to something else. */ public static abstract class Number { private Number() { } /** * Converts a Number type (e.g. Integer, Long, Float...) to a Double. * * Depending on the concrete type of {@link Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the Numbers to be converted. * @param <T> the subtype of Number to be converted * @return a transformer that converts its inputs to the desired Number subtype. */ public static <T extends java.lang.Number> PreparedTransformer1<T, Double> toDouble(Producer<T> input) { return new FunctionResult1<T, Double>().withFunction(T::doubleValue).withNullResultOnNullInput().withInput(input); } /** * Converts a Number type (e.g. Integer, Long, Float...) to a Float. * * Depending on the concrete type of {@link Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the Numbers to be converted. * @param <T> the subtype of Number to be converted * @return a transformer that converts its inputs to the desired Number subtype. */ public static <T extends java.lang.Number> PreparedTransformer1<T, Float> toFloat(Producer<T> input) { return new FunctionResult1<T, Float>().withFunction(T::floatValue).withNullResultOnNullInput().withInput(input); } /** * Converts a Number type (e.g. Integer, Long, Float...) to a Long. * * Depending on the concrete type of {@link Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the Numbers to be converted. * @param <T> the subtype of Number to be converted * @return a transformer that converts its inputs to the desired Number subtype. */ public static <T extends java.lang.Number> PreparedTransformer1<T, Long> toLong(Producer<T> input) { return new FunctionResult1<T, Long>().withFunction(T::longValue).withNullResultOnNullInput().withInput(input); } /** * Converts a Number type (e.g. Integer, Long, Float...) to an Integer. * * Depending on the concrete type of {@link Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the Numbers to be converted. * @param <T> the subtype of Number to be converted * @return a transformer that converts its inputs to the desired Number subtype. */ public static <T extends java.lang.Number> PreparedTransformer1<T, Integer> toInteger(Producer<T> input) { return new FunctionResult1<T, Integer>().withFunction(T::intValue).withNullResultOnNullInput().withInput(input); } /** * Converts a Number type (e.g. Integer, Long, Float...) to a Short. * * Depending on the concrete type of {@link Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the Numbers to be converted. * @param <T> the subtype of Number to be converted * @return a transformer that converts its inputs to the desired Number subtype. */ public static <T extends java.lang.Number> PreparedTransformer1<T, Short> toShort(Producer<T> input) { return new FunctionResult1<T, Short>().withFunction(T::shortValue).withNullResultOnNullInput().withInput(input); } /** * Converts a Number type (e.g. Integer, Long, Float...) to a Byte. * * Depending on the concrete type of {@link Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the Numbers to be converted * @param <T> the subtype of Number to be converted * @return a transformer that converts its inputs to the desired Number subtype */ public static <T extends java.lang.Number> PreparedTransformer1<T, Byte> toByte(Producer<T> input) { return new FunctionResult1<T, Byte>().withFunction(T::byteValue).withNullResultOnNullInput().withInput(input); } } /** * Conversion transformers from {@link Iterable}s of {@link java.lang.Number}s to something else. */ public static abstract class Numbers { private Numbers() { } /** * Converts an {@link Iterable} of {@link java.lang.Number}s to an array of doubles. * * Depending on the concrete type of {@link java.lang.Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the {@link java.lang.Number}s to be converted * @return a transformer that converts the provided input to an array of doubles */ public static PreparedTransformer1<Iterable<? extends java.lang.Number>, double[]> toDoubleArray( Producer<? extends Iterable<? extends java.lang.Number>> input) { return new FunctionResult1<Iterable<? extends java.lang.Number>, double[]>().withFunction(ArraysEx::toDoublesLossy) .withNullResultOnNullInput() .withInput(input); } /** * Converts an {@link Iterable} of {@link java.lang.Number}s to an array of floats. * * Depending on the concrete type of {@link java.lang.Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the {@link java.lang.Number}s to be converted * @param <T> the subtype of {@link java.lang.Number} to be converted * @return a transformer that converts the provided input to an array of floats */ public static <T extends java.lang.Number> PreparedTransformer1<Iterable<T>, float[]> toFloatArray( Producer<? extends Iterable<T>> input) { return new FunctionResult1<Iterable<T>, float[]>().withFunction(ArraysEx::toFloatsLossy) .withNullResultOnNullInput() .withInput(input); } /** * Converts an {@link Iterable} of {@link java.lang.Number}s to an array of bytes. * * Depending on the concrete type of {@link java.lang.Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the {@link java.lang.Number}s to be converted * @return a transformer that converts the provided input to an array of bytes */ public static PreparedTransformer1<Iterable<? extends java.lang.Number>, byte[]> toByteArray( Producer<? extends Iterable<? extends java.lang.Number>> input) { return new FunctionResult1<Iterable<? extends java.lang.Number>, byte[]>().withFunction(ArraysEx::toBytesLossy) .withNullResultOnNullInput() .withInput(input); } /** * Converts an {@link Iterable} of {@link java.lang.Number}s to an array of shorts. * * Depending on the concrete type of {@link java.lang.Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the {@link java.lang.Number}s to be converted * @return a transformer that converts the provided input to an array of shorts */ public static PreparedTransformer1<Iterable<? extends java.lang.Number>, short[]> toShortArray( Producer<? extends Iterable<? extends java.lang.Number>> input) { return new FunctionResult1<Iterable<? extends java.lang.Number>, short[]>().withFunction(ArraysEx::toShortsLossy) .withNullResultOnNullInput() .withInput(input); } /** * Converts an {@link Iterable} of {@link java.lang.Number}s to an array of ints. * * Depending on the concrete type of {@link java.lang.Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the {@link java.lang.Number}s to be converted * @return a transformer that converts the provided input to an array of ints */ public static PreparedTransformer1<Iterable<? extends java.lang.Number>, int[]> toIntegerArray( Producer<? extends Iterable<? extends java.lang.Number>> input) { return new FunctionResult1<Iterable<? extends java.lang.Number>, int[]>().withFunction(ArraysEx::toIntegersLossy) .withNullResultOnNullInput() .withInput(input); } /** * Converts an {@link Iterable} of {@link java.lang.Number}s to an array of longs. * * Depending on the concrete type of {@link java.lang.Number}, the conversion may result in rounding or truncation. * * @param input the producer that will provide the {@link java.lang.Number}s to be converted * @return a transformer that converts the provided input to an array of longs */ public static PreparedTransformer1<Iterable<? extends java.lang.Number>, long[]> toLongArray( Producer<? extends Iterable<? extends java.lang.Number>> input) { return new FunctionResult1<Iterable<? extends java.lang.Number>, long[]>().withFunction(ArraysEx::toLongsLossy) .withNullResultOnNullInput() .withInput(input); } } /** * Conversion transformers from Strings to something else */ public static abstract class String { private String() { } /** * Returns a transformer that converts a String input as if by Double::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Double> toDouble(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Double>() .withFunction(Double::valueOf) .withNullResultOnNullInput() .withInput(input); } /** * Returns a transformer that converts a String input as if by Float::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Float> toFloat(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Float>() .withFunction(Float::valueOf) .withNullResultOnNullInput() .withInput(input); } /** * Returns a transformer that converts a String input as if by Long::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Long> toLong(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Long>() .withFunction(Long::valueOf) .withNullResultOnNullInput() .withInput(input); } /** * Returns a transformer that converts a String input as if by Integer::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Integer> toInteger(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Integer>() .withFunction(Integer::valueOf) .withNullResultOnNullInput() .withInput(input); } /** * Returns a transformer that converts a String input as if by Short::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Short> toShort(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Short>() .withFunction(Short::valueOf) .withNullResultOnNullInput() .withInput(input); } /** * Returns a transformer that converts a String input as if by Byte::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Byte> toByte(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Byte>() .withFunction(Byte::valueOf) .withNullResultOnNullInput() .withInput(input); } /** * Returns a transformer that converts a String input as if by Boolean::valueOf * * @param input the producer that will provide the input String * @return a transformer that performs the desired conversion */ public static PreparedTransformer1<java.lang.String, Boolean> toBoolean(Producer<java.lang.String> input) { return new FunctionResult1<java.lang.String, Boolean>() .withFunction(Boolean::valueOf) .withNullResultOnNullInput() .withInput(input); } } /** * Converts an object to its String representation via its toString() method. * * @param input the producer that will provide the objects to be Stringified * @param <T> the type of object to be Stringified * @return a transformer that will provide the String representation of the inputted object */ public static <T> PreparedTransformer1<T, java.lang.String> toString(Producer<T> input) { return new FunctionResult1<T, java.lang.String>() .withFunction(T::toString) .withNullResultOnNullInput() .withInput(input); } }
44.717579
121
0.686473
3227230fa19419eeeb39a6dc27a3b885839a00c9
6,457
package com.squareup.okhttp.internal.http; import com.squareup.okhttp.C; import com.squareup.okhttp.I; import com.squareup.okhttp.J; import com.squareup.okhttp.K; import com.squareup.okhttp.Protocol; import com.squareup.okhttp.internal.l; import com.squareup.okhttp.internal.spdy.M; import com.squareup.okhttp.internal.spdy.d; import com.squareup.okhttp.v; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import okio.ByteString; import okio.o; import okio.x; public final class y implements A { private static final List<ByteString> a; private static final List<ByteString> b; private final m c; private final com.squareup.okhttp.internal.spdy.A d; private M e; static { ByteString[] arrayOfByteString1 = new ByteString[5]; arrayOfByteString1[0] = ByteString.encodeUtf8("connection"); arrayOfByteString1[1] = ByteString.encodeUtf8("host"); arrayOfByteString1[2] = ByteString.encodeUtf8("keep-alive"); arrayOfByteString1[3] = ByteString.encodeUtf8("proxy-connection"); arrayOfByteString1[4] = ByteString.encodeUtf8("transfer-encoding"); a = l.a(arrayOfByteString1); ByteString[] arrayOfByteString2 = new ByteString[8]; arrayOfByteString2[0] = ByteString.encodeUtf8("connection"); arrayOfByteString2[1] = ByteString.encodeUtf8("host"); arrayOfByteString2[2] = ByteString.encodeUtf8("keep-alive"); arrayOfByteString2[3] = ByteString.encodeUtf8("proxy-connection"); arrayOfByteString2[4] = ByteString.encodeUtf8("te"); arrayOfByteString2[5] = ByteString.encodeUtf8("transfer-encoding"); arrayOfByteString2[6] = ByteString.encodeUtf8("encoding"); arrayOfByteString2[7] = ByteString.encodeUtf8("upgrade"); b = l.a(arrayOfByteString2); } public y(m paramm, com.squareup.okhttp.internal.spdy.A paramA) { this.c = paramm; this.d = paramA; } private static boolean a(Protocol paramProtocol, ByteString paramByteString) { if (paramProtocol == Protocol.SPDY_3) return a.contains(paramByteString); if (paramProtocol == Protocol.HTTP_2) return b.contains(paramByteString); throw new AssertionError(paramProtocol); } public final K a(I paramI) { return new t(paramI.f(), o.a(this.e.f())); } public final x a(C paramC, long paramLong) { return this.e.g(); } public final void a() { this.e.g().close(); } public final void a(C paramC) { if (this.e != null) return; this.c.b(); boolean bool = this.c.c(); String str1 = b.a(this.c.f().k()); com.squareup.okhttp.internal.spdy.A localA = this.d; Protocol localProtocol = this.d.a(); com.squareup.okhttp.u localu = paramC.e(); ArrayList localArrayList = new ArrayList(10 + localu.a()); localArrayList.add(new d(d.b, paramC.d())); localArrayList.add(new d(d.c, b.a(paramC.a()))); String str2 = m.a(paramC.a()); int j; label222: ByteString localByteString; String str3; if (Protocol.SPDY_3 == localProtocol) { localArrayList.add(new d(d.g, str1)); localArrayList.add(new d(d.f, str2)); localArrayList.add(new d(d.d, paramC.a().getProtocol())); LinkedHashSet localLinkedHashSet = new LinkedHashSet(); int i = localu.a(); j = 0; if (j >= i) break label511; localByteString = ByteString.encodeUtf8(localu.a(j).toLowerCase(Locale.US)); str3 = localu.b(j); if ((!a(localProtocol, localByteString)) && (!localByteString.equals(d.b)) && (!localByteString.equals(d.c)) && (!localByteString.equals(d.d)) && (!localByteString.equals(d.e)) && (!localByteString.equals(d.f)) && (!localByteString.equals(d.g))) { if (!localLinkedHashSet.add(localByteString)) break label408; localArrayList.add(new d(localByteString, str3)); } } label408: label509: while (true) { j++; break label222; if (Protocol.HTTP_2 == localProtocol) { localArrayList.add(new d(d.e, str2)); break; } throw new AssertionError(); for (int k = 0; ; k++) { if (k >= localArrayList.size()) break label509; if (!((d)localArrayList.get(k)).h.equals(localByteString)) continue; localArrayList.set(k, new d(localByteString, ((d)localArrayList.get(k)).i.utf8() + '\000' + str3)); break; } } label511: this.e = localA.a(localArrayList, bool, true); this.e.e().a(this.c.a.b(), TimeUnit.MILLISECONDS); } public final void a(u paramu) { paramu.a(this.e.g()); } public final J b() { List localList = this.e.d(); Protocol localProtocol = this.d.a(); Object localObject1 = null; Object localObject2 = "HTTP/1.1"; v localv = new v(); localv.b(r.c, localProtocol.toString()); int i = localList.size(); int j = 0; while (j < i) { ByteString localByteString = ((d)localList.get(j)).h; String str = ((d)localList.get(j)).i.utf8(); Object localObject3 = localObject2; int k = 0; if (k < str.length()) { int m = str.indexOf(0, k); if (m == -1) m = str.length(); Object localObject4 = str.substring(k, m); if (localByteString.equals(d.a)); while (true) { int n = m + 1; localObject1 = localObject4; k = n; break; if (localByteString.equals(d.g)) { localObject3 = localObject4; localObject4 = localObject1; continue; } if (!a(localProtocol, localByteString)) localv.a(localByteString.utf8(), (String)localObject4); localObject4 = localObject1; } } j++; localObject2 = localObject3; } if (localObject1 == null) throw new ProtocolException("Expected ':status' header not present"); z localz = z.a((String)localObject2 + " " + localObject1); return (J)(J)new J().a(localProtocol).a(localz.b).a(localz.c).a(localv.a()); } public final void c() { } public final boolean d() { return true; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.squareup.okhttp.internal.http.y * JD-Core Version: 0.6.0 */
30.457547
251
0.633421
9646543a3c7cd101a47329b1539cbae533d1ffee
803
package com.manriqueweb.thetvdbclient.services; import com.manriqueweb.thetvdbclient.TheTvDBClient; import com.manriqueweb.thetvdbclient.entities.SerieResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Query; public interface SearchSeries { @GET("search/series") Call<SerieResponse> searchSeriesByName(@Query("name") String name, @Header(TheTvDBClient.HEADER_ACCEPT_LANGUAGE) String languages); @GET("search/series") Call<SerieResponse> searchSeriesByIMDB(@Query("imdbId") String imdbId, @Header(TheTvDBClient.HEADER_ACCEPT_LANGUAGE) String languages); @GET("search/series") Call<SerieResponse> searchSeriesByZap2itId(@Query("zap2itId") String zap2itId, @Header(TheTvDBClient.HEADER_ACCEPT_LANGUAGE) String languages); }
32.12
79
0.809465
66a183ba5ad6c96483b6b9fc5cab87aeee579b72
516
package com.google.android.gms.internal.ads; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; /* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */ public interface zzeok extends Closeable { void close() throws IOException; long position() throws IOException; int read(ByteBuffer byteBuffer) throws IOException; long size() throws IOException; void zzfc(long j) throws IOException; ByteBuffer zzh(long j, long j2) throws IOException; }
24.571429
69
0.746124
fc13c58c9bc5e5be64c068627d82408a7060d5d8
649
/** * */ package ficheros.excepciones; /** * Clase con las excepciones que se puede producir al leer un fichero de personal * @author Fabricio Isaac Maldonado */ @SuppressWarnings("serial") public class ExceptionLeerPersonal extends Exception { /** * Constructora por defecto de la excepcion */ public ExceptionLeerPersonal() { } /** * @param arg0 * Constructora con parametro String de la excepcion */ public ExceptionLeerPersonal(String arg0) { super(arg0); } /** * @param arg0 * Constructora con parametro Objeto Throwable de la excepcion */ public ExceptionLeerPersonal(Throwable arg0) { super(arg0); } }
18.027778
81
0.707242
77c182c975a1ae8b1745d3980b7a1d53d24af0de
367
package travel_agency.transport; public class Seat { private final int seatID; private boolean reserved; public Seat(int seatID) { this.seatID = seatID; reserved = false; } public int getSeatID() { return seatID; } public boolean isReserved() { return reserved; } public void setReserved(boolean reserved) { this.reserved = reserved; } }
15.291667
44
0.702997
4b992042c8bb3aff7c8d75675622aa6404ca3f19
2,324
package com.acme.testing.junit5.core.basic; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.RepetitionInfo; import org.junit.jupiter.api.TestInfo; public class RepeatedExampleTest { @BeforeEach public void setUp(TestInfo testInfo, RepetitionInfo repetitionInfo) { //Show info int currentRepetition = repetitionInfo.getCurrentRepetition(); int totalRepetitions = repetitionInfo.getTotalRepetitions(); String methodName = testInfo.getTestMethod().get().getName(); System.out.println(String.format("[SETUP] About to execute repetition %d of %d for %s", // currentRepetition, totalRepetitions, methodName)); } //No require info setUp @RepeatedTest(3) void shouldBeRepeatedTest3times(TestInfo testInfo) { System.out.println("[@Test] : shouldBeRepeatedTest3times :: "+testInfo); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } //No require info setUp @RepeatedTest(5) void shouldBeRepeatedTest5times(RepetitionInfo repetitionInfo) { System.out.println("[@Test] : shouldBeRepeatedTest5times repetition " + repetitionInfo.getCurrentRepetition() + " out of " + repetitionInfo.getTotalRepetitions()); assertEquals(5, repetitionInfo.getTotalRepetitions()); } //No require info setUp @RepeatedTest(value = 1, name = "{displayName} {currentRepetition}/{totalRepetitions}") @DisplayName("Repeat!") public void shouldBeRepeatedTest2times(TestInfo testInfo) { System.out.println("[@Test] : shouldBeRepeatedTest2times :: "+testInfo); //when use value = 2 then fail because equal expected 1/1 and value es 1/2 assertEquals("Repeat! 1/1", testInfo.getDisplayName()); } //No require info setUp @RepeatedTest(value = 1, name = RepeatedTest.LONG_DISPLAY_NAME) @DisplayName("Details...") public void shouldBeRepeatedTest4times(TestInfo testInfo) { System.out.println("[@Test] : shouldBeRepeatedTest4times :: "+testInfo); //when use value != 1 then fail because equal expected 1/1 and value es 1/X assertEquals("Details... :: repetition 1 of 1", testInfo.getDisplayName()); } }
36.3125
168
0.71988
7c64ce3dd51ba3cf061f59d6b12c0323ef1fcdbe
4,325
package com.showcase.register.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to JHipster. * * <p> * Properties are configured in the application.yml file. * </p> */ @ConfigurationProperties(prefix = "project", ignoreUnknownFields = false) public class RegisterProperties { private final Http http = new Http(); private final Security security = new Security(); private final Metrics metrics = new Metrics(); public Http getHttp() { return http; } public Security getSecurity() { return security; } public Metrics getMetrics() { return metrics; } private final Ribbon ribbon = new Ribbon(); public Ribbon getRibbon() { return ribbon; } public static class Http { private final Cache cache = new Cache(); public Cache getCache() { return cache; } public static class Cache { private int timeToLiveInDays = 1461; public int getTimeToLiveInDays() { return timeToLiveInDays; } public void setTimeToLiveInDays(int timeToLiveInDays) { this.timeToLiveInDays = timeToLiveInDays; } } } public static class Security { private final Authentication authentication = new Authentication(); public Authentication getAuthentication() { return authentication; } public static class Authentication { private final Jwt jwt = new Jwt(); public Jwt getJwt() { return jwt; } public static class Jwt { private String secret; private long tokenValidityInSeconds = 1800; private long tokenValidityInSecondsForRememberMe = 2592000; public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public long getTokenValidityInSeconds() { return tokenValidityInSeconds; } public void setTokenValidityInSeconds(long tokenValidityInSeconds) { this.tokenValidityInSeconds = tokenValidityInSeconds; } public long getTokenValidityInSecondsForRememberMe() { return tokenValidityInSecondsForRememberMe; } public void setTokenValidityInSecondsForRememberMe(long tokenValidityInSecondsForRememberMe) { this.tokenValidityInSecondsForRememberMe = tokenValidityInSecondsForRememberMe; } } } } public static class Metrics { private final Jmx jmx = new Jmx(); private final Logs logs = new Logs(); public Jmx getJmx() { return jmx; } public Logs getLogs() { return logs; } public static class Jmx { private boolean enabled = true; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Logs { private boolean enabled = false; private long reportFrequency = 60; public long getReportFrequency() { return reportFrequency; } public void setReportFrequency(int reportFrequency) { this.reportFrequency = reportFrequency; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } } public static class Ribbon { private String[] displayOnActiveProfiles; public String[] getDisplayOnActiveProfiles() { return displayOnActiveProfiles; } public void setDisplayOnActiveProfiles(String[] displayOnActiveProfiles) { this.displayOnActiveProfiles = displayOnActiveProfiles; } } }
24.573864
110
0.564393
798332cee61c7500e4a0485f9b1608cb6a32ab2a
1,476
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.ecd.model.v20200930; import com.aliyuncs.AcsResponse; import com.aliyuncs.ecd.transform.v20200930.GetSpMetadataResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GetSpMetadataResponse extends AcsResponse { private String spMetadata; private String requestId; public String getSpMetadata() { return this.spMetadata; } public void setSpMetadata(String spMetadata) { this.spMetadata = spMetadata; } public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public GetSpMetadataResponse getInstance(UnmarshallerContext context) { return GetSpMetadataResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
25.894737
78
0.750678
feea3c2aa403a1a11c411a0d0fbd0873aee58e77
618
package com.mzw.pattern.builder; /** * @author Jonathan Meng * @date 06/05/2019 */ public class BuilderPatternDemo { public static void main(String[] args) { MealBuilder mealBuilder = new MealBuilder(); Meal vegMeal = mealBuilder.prepareVegMeal(); System.out.println("veg meal"); vegMeal.showItems(); System.out.println("Total cost:" + vegMeal.getCost()); Meal nonVegMeal = mealBuilder.prepareNoneVegMeal(); System.out.println("\nNon-Veg meal"); nonVegMeal.showItems(); System.out.println("Total cost:" + nonVegMeal.getCost()); } }
28.090909
65
0.642395
bc01e7b4d0a78634848bad97e98c44e821b697e7
441
package aeadvent.code2021.day12.istvan; public record Cave(String name) { public static Cave fromString(String input) { return new Cave(input); } public boolean isBig() { var firstChar = name.charAt(0); return firstChar >= 'A' && firstChar <= 'Z'; } public boolean isStart() { return name.equals("start"); } public boolean isEnd() { return name.equals("end"); } }
20.045455
52
0.589569
9f22dc717acacd60ecbeabb1d85999db7420b1d4
941
/* * KVertexBetweennessWeightedScorer.java * Created on Apr 24, 2011 * Copyright(c) 2011 Yoshiaki Matsuzawa, Shizuoka University. All rights reserved. */ package kbdex.adapters.jung.scorer; import org.apache.commons.collections15.Transformer; import edu.uci.ics.jung.algorithms.scoring.PageRank; import edu.uci.ics.jung.algorithms.scoring.PageRankWithPriors; /** * @author macchan */ public class KVertexPageRankWeightedScorer<V, E> extends KVertexPageRankScorer<V> { private Transformer<E, ? extends Number> edgeWeights; public KVertexPageRankWeightedScorer( Transformer<E, ? extends Number> edgeWeights) { this.edgeWeights = edgeWeights; } public String getName() { return "Page Rank(Weighted)"; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected PageRankWithPriors<V, ?> createCalcurator() { return new PageRank(getGraph(), edgeWeights, ALPHA); } }
25.432432
83
0.727949
ac150a62bdc5d32d2ad7ddeaf53ce7efc9ef0707
962
package com.twu.biblioteca; public class PrinterTests { // @Test // public void ShouldReturnWelcomeStatementWhenProgramRuns() { // Library library = new Library(); // assertEquals("Welcome to Biblioteca. Your one-stop shop for great book titles in Bangalore!", library.Welcome()); //// assertThat(library.welcome(), is("")); // } // @Test // public void ShouldReturnListOfBooks() { // Library library = new Library(); // ArrayList<Book> bookArr = new ArrayList<Book>(); // bookArr.add(new Book("The Hobbit", "J.R.R. Tolkien", 1937)); // bookArr.add(new Book("The Hunger Games", "Suzanne Collins", 2008)); // bookArr.add(new Book("Becoming", "Michelle Obama", 2018)); // String booksInOrder = ""; // for (Book book : bookArr) { // booksInOrder += book.toString() + "\n"; // } // assertEquals(booksInOrder, Printer.printBooksList(bookArr)); // } }
37
123
0.606029
4cf1d848fc8d5261f968d75983fb9d5d90365fdd
4,648
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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% */ package io.joynr.messaging.bounceproxy.controller.directory; import io.joynr.messaging.info.ControlledBounceProxyInformation; import io.joynr.messaging.info.BounceProxyInformation; import io.joynr.messaging.info.BounceProxyStatusInformation; import java.util.List; /** * The directory stores all bounce proxy instances that are registered with the * bounce proxy controller. * * @author christina.strobel * */ public interface BounceProxyDirectory { /** * Returns all bounce proxy instances that have the right status to take new * channels. I.e. they must not be in a shutdown or excluded state. * * @return list of bound proxy instances that have the right status to * take new channels. */ public List<BounceProxyRecord> getAssignableBounceProxies(); /** * Updates the channel assignment for a bounce proxy, i.e. registers that a * channel was assigned to the bounce proxy instance. * * If there's no directory entry for the bounce proxy, the call is simply * ignored without warning. Make sure before calling this method that the * bounce proxy is registered. * * @param ccid the channel id * @param bpInfo the bounce proxy information * * @throws IllegalArgumentException * if no bounce proxy with this ID is registered in the * directory or if no channel with ccid is registered in the {@link ChannelDirectory}. */ public void updateChannelAssignment(String ccid, BounceProxyInformation bpInfo) throws IllegalArgumentException; /** * Gets a record of a bounce proxy. Before calling this method, it should be * checked with {@link #containsBounceProxy(String)} if a bounce proxy with * this ID has been added to the directory. * * @param bpId * the identifier of the bounce proxy * @return a bounce proxy record with this ID * @throws IllegalArgumentException * if no bounce proxy with this ID is registered in the * directory */ public BounceProxyRecord getBounceProxy(String bpId) throws IllegalArgumentException; /** * Checks whether a certain bounce proxy is registered in the directory. * * @param bpId * the identifier of the bounce proxy * @return <code>true</code> if there is a record for this bounce proxy, * <code>false</code> if it never has been registered. */ public boolean containsBounceProxy(String bpId); /** * Adds a new bounce proxy that hasn't been registered before to the * directory. Before adding a new bounce proxy, it should be checked with * {@link #containsBounceProxy(String)} whether a bounce proxy with this * identifier is already registered. * * @param bpInfo * information about the bounce proxy. * @throws IllegalArgumentException * if the bounce proxy has already been registered before */ public void addBounceProxy(ControlledBounceProxyInformation bpInfo) throws IllegalArgumentException; /** * Updates the record about an existing bounce proxy. The bounce proxy * record to be updated should be retrieved by * {@link #getBounceProxy(String)} before. * * @param bpRecord * the updated record of a bounce proxy * @throws IllegalArgumentException * if no bounce proxy with the same ID is registered in the * directory */ public void updateBounceProxy(BounceProxyRecord bpRecord) throws IllegalArgumentException; /** * Returns the list of registered bounce proxies including information such * as performance measures, freshness and status. * * @return list of registered bounce proxies including information such * as performance measures, freshness and status. */ public List<BounceProxyStatusInformation> getBounceProxyStatusInformation(); }
38.413223
116
0.688683
ececab2c03505bea14b5a2b4e4a169a734f4da30
21,815
package it.unimi.di.law.bubing.util; /* * Copyright (C) 2012-2017 Paolo Boldi, Massimo Santini, and Sebastiano Vigna * * 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. */ import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.fastutil.Size64; import it.unimi.dsi.fastutil.longs.LongHeapSemiIndirectPriorityQueue; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.channels.FileChannel.MapMode; import java.util.NoSuchElementException; //RELEASE-STATUS: DIST /** A set of memory-mapped queues of byte arrays. * * <p>An instance of this class handles a database of FIFO queues. Each queue is associated with a key (which is looked up by {@linkplain Reference2ObjectMap reference}, * for efficiency). Users can {@linkplain #enqueue(Object, byte[], int, int) enqueue} * and {@linkplain #dequeue(Object) dequeue} elements associated with a key in FIFO order. It is also possible * to {@linkplain #remove(Object) remove all} elements associated with a key. * * <p>The {@linkplain #ratio() ratio} between the used and allocated space can be checked periodically, * and the method {@link #collect(double)} can be used to compact elements until a target ratio * is reached. * * <p>Note that the metadata associated with all queues must fit into memory. The caching of the * content of the log files is performed at the operating system level by the memory-mapping system, * however, and does not use the Java heap. * * <h2>Internals</h2> * * <p>Queues are stored using a set of memory-mapped append-only log files. When garbage collection frees completely * a file, it is deleted. Each element contains a pointer to the position of the next element. * * <p>{@linkplain #collect(double) Garbage collection} is performed without keeping track of the * free space beforehand. Keys are kept in a queue prioritized by the pointer to the last element * of the associated FIFO queue that has been read (initially, the first element). * As we advance each pointer, we discover free space and we compact the structure. */ public class ByteArrayDiskQueues implements Closeable, Size64 { private static final boolean DEBUG = false; /** By default, we use 64 MiB log files. */ public static final int DEFAULT_LOG2_LOG_FILE_SIZE = 26; /** Metadata associated with a queue. */ public static final class QueueData implements Serializable { private static final long serialVersionUID = 1L; /** The pointer to the head of the list (the least recently enqueued, but not dequeued, element). */ public long head; /** The pointer to the tail of the list (the most recently enqueued element). */ public long tail; /** The number of elements in the list (always nonzero). */ public long count; /** The number of bytes used by the list. */ public long usage; } /** The base 2 logarithm of the byte size of a log file. */ protected final int log2LogFileSize; /** The byte size of a log file. */ protected final int logFileSize; /** The mask to extract the position inside a log file from a pointer. A pointer is formed by a position in the lowest * {@link #log2LogFileSize} bits and a log-file index in the remainig upper bits. */ protected final int logFilePositionMask; /** For each key, the associated {@link QueueData}. If a key is present, there is at least one associated element in the queue. */ public final Reference2ObjectOpenHashMap<Object,QueueData> key2QueueData; /** For each log-file index, the associated {@link RandomAccessFile}. An entry might be {@code null} if the log file has been deleted or it has not been opened yet. */ public final ObjectArrayList<RandomAccessFile> files; /** For each log-file index, the associated {@link ByteBuffer}. An entry might be {@code null} if the log file has been deleted or it has not been opened yet. */ public final ObjectArrayList<ByteBuffer> buffers; /** The overall number of elements in the queues. */ public long size; /** The overall number of bytes used by elements in the queues. */ public long used; /** The overall number of bytes allocated (a multiple of {@link #logFileSize}). */ public long allocated; /** The current pointer at which new elements can be appended. */ public long appendPointer; /** The index of the {@linkplain #currBuffer current buffer}. */ private int currBufferIndex; /** The current buffer. */ private ByteBuffer currBuffer; /** The directory there the log files must be created. */ private File dir; /** Creates a set of byte-array disk queues in the given directory using * log files of size 2<sup>{@value #DEFAULT_LOG2_LOG_FILE_SIZE}</sup>. * * @param dir a directory. */ public ByteArrayDiskQueues(final File dir) { this(dir, DEFAULT_LOG2_LOG_FILE_SIZE); } /** Creates a set of byte-array disk queues in the given directory using the specified * file size. * * @param dir a directory. * @param log2LogFileSize the base-2 logarithm of the size of a log file. */ public ByteArrayDiskQueues(final File dir, final int log2LogFileSize) { this.dir = dir; this.log2LogFileSize =log2LogFileSize; logFileSize = 1 << log2LogFileSize; logFilePositionMask = (1 << log2LogFileSize) - 1; key2QueueData = new Reference2ObjectOpenHashMap<>(); files = new ObjectArrayList<>(); buffers = new ObjectArrayList<>(); } /** Returns the name of a log file, given its index. * * @param logFileIndex the index of a log file. * @return its name ({@code logFileIndex} in hexadecimal zero-padded to eight digits). */ private File file(final int logFileIndex) { final String t = "00000000" + Integer.toHexString(logFileIndex); return new File(dir, t.substring(t.length() - 8)); } /** Returns the index of the buffer associated with a pointer. * * @param pointer a pointer. * @return the index of the buffer associated with {@code pointer}. */ private int bufferIndex(final long pointer) { return (int)(pointer >>> log2LogFileSize); } /** Returns the buffer position associated with a pointer. * * @param pointer a pointer. * @return the buffer position associated with {@code pointer}. */ private int bufferPosition(final long pointer) { return (int)(pointer & logFilePositionMask); } /** Enqueues an element (specified as a byte array) associated with a given key. * * <p>The element is a sequence of bytes specified as an array fragment. * * @param key a key. * @param array a byte array. */ public void enqueue(final Object key, byte[] array) throws FileNotFoundException, IOException { enqueue(key, array, 0, array.length); } /** Enqueues an element (specified as a byte-array fragment) associated with a given key. * * @param key a key. * @param array a byte array. * @param offset the first valid byte in {@code array}. * @param length the number of valid elements in {@code array}. */ public void enqueue(final Object key, byte[] array, final int offset, final int length) throws FileNotFoundException, IOException { QueueData queueData = key2QueueData.get(key); if (queueData == null) { queueData = new QueueData(); queueData.head = appendPointer; synchronized (key2QueueData) { key2QueueData.put(key, queueData); } } else { pointer(queueData.tail); writeLong(appendPointer); } queueData.count++; queueData.tail = appendPointer; final long start = appendPointer; pointer(appendPointer); writeLong(0); encodeInt(length); write(array, offset, length); appendPointer = pointer(); final long bytes = appendPointer - start; used += bytes; queueData.usage += bytes; assert used >= 0 : used; size++; } /** Dequeues the first element available for a given key. * * @param key a key. * @return the first element associated with {@code key}. */ public byte[] dequeue(final Object key) throws IOException { final QueueData queueData = key2QueueData.get(key); if (queueData == null) throw new NoSuchElementException(); final long head = queueData.head; pointer(queueData.head); queueData.count--; queueData.head = readLong(); final int length = decodeInt(); final byte[] result = new byte[length]; read(result, 0, length); final long bytes = pointer() - head; used -= bytes; queueData.usage -= bytes; // If we are dequeuing the last element, this is done on a throw-away QueueData if (queueData.count == 0) remove(key); size--; assert used >= 0 : used; return result; } /** Remove all elements associated with a given key. * * <p>Note that this is a constant-time operation that simply deletes the metadata * associated with the specified key. * * @param key a key. */ public void remove(final Object key) { final QueueData queueData; synchronized(key2QueueData) { queueData = key2QueueData.remove(key); } if (queueData == null) return; size -= queueData.count; used -= queueData.usage; } /** Returns the number of elements associated with the given key. * * <p>This method can be called by multiple threads. * * @param key a key. * @return the number of elements currently associated with {@code key}. */ public long count(final Object key) { final QueueData queueData; synchronized(key2QueueData) { queueData = key2QueueData.get(key); } return queueData == null ? 0 : queueData.count; } /** Returns the number of keys. * * @return the number of keys. */ public int numKeys() { return key2QueueData.size(); } /** Reads a byte at the current pointer. * * @return the byte at the current pointer. */ protected int read() throws IOException { if (! currBuffer.hasRemaining()) nextBuffer(); // Note that this can create a new log file. return currBuffer.get() & 0xFF; } /** Reads a long at the current pointer. * * @return the long at the current pointer. */ protected long readLong() throws IOException { long l = 0; for(int i = 0; i < 8; i++) { l <<= 8; l |= read(); } return l; } /** Reads a specified number of bytes at the current pointer. * * @param b the buffer into which the data will be read. * @param offset the start offset in array <code>b</code> at which the data will be written. * @param length the number of bytes to read. */ protected void read(final byte[] b, final int offset, final int length) throws IOException { if (length == 0) return; int read = 0; while(read < length) { int remaining = currBuffer.remaining(); if (remaining == 0) { nextBuffer(); remaining = logFileSize; } currBuffer.get(b, offset + read, Math.min(length - read, remaining)); read += Math.min(length - read, remaining); } } /** Writes a byte at the current pointer. * * @param b the byte to be written. */ protected void write(final byte b) throws IOException { if (! currBuffer.hasRemaining()) nextBuffer(); currBuffer.put(b); } /** Writes a long at the current pointer. * * @param l the long to be written. */ protected void writeLong(final long l) throws IOException { for(int i = 8; i-- != 0;) write((byte)(l >>> (i * 8))); } /** Writes a specified number of bytes at the current pointer. * * @param b the data. * @param offset the start offset in {@code b}. * @param length the number of bytes to write. */ protected void write(final byte[] b, final int offset, final int length) throws IOException { if (length == 0) return; int written = 0; while(written < length) { int remaining = currBuffer.remaining(); if (remaining == 0) { nextBuffer(); remaining = logFileSize; } currBuffer.put(b, offset + written, Math.min(length - written, remaining)); written += Math.min(length - written, remaining); } } /** Returns the current pointer. * * @return the current pointer. */ public long pointer() { return ((long)currBufferIndex << log2LogFileSize) + currBuffer.position(); } /** Sets the current pointer. The associated log file is opened if necessary. */ public void pointer(final long pointer) throws FileNotFoundException, IOException { currBufferIndex = bufferIndex(pointer); assert currBufferIndex <= buffers.size(); if (currBufferIndex == buffers.size() || (currBuffer = buffers.get(currBufferIndex)) == null) { if (currBufferIndex == buffers.size()) { files.size(currBufferIndex + 1); buffers.size(currBufferIndex + 1); } // We open the buffer associated with currBufferIndex. final File file = file(currBufferIndex); if (! file.exists()) allocated += logFileSize; final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); files.set(currBufferIndex, randomAccessFile); buffers.set(currBufferIndex, currBuffer = randomAccessFile.getChannel().map(MapMode.READ_WRITE, 0, logFileSize)); } currBuffer.position(bufferPosition(pointer)); } /** Creates a new buffer, or opens an old one, at the current pointer, which must be a multiple of {@link #logFileSize}. */ private void nextBuffer() throws FileNotFoundException, IOException { assert (pointer() & logFilePositionMask) == 0; pointer(pointer()); } public double ratio() { if (size == 0) return 1; if (DEBUG) System.err.println("Returning ratio " + (double)used / (allocated - ((logFileSize - bufferPosition(appendPointer)) & logFilePositionMask)) + "; used=" + used + ", allocated=" + allocated); return (double)used / (allocated - ((logFileSize - bufferPosition(appendPointer)) & logFilePositionMask)); } /** Computes the ratio between {@linkplain #used} space and {@linkplain #allocated} * space minus the gain plus one times {@link #logFileSize}. * * @param gain the number of buffers gained. * @return the ratio between {@linkplain #used used} space and {@linkplain #allocated} * space minus {@code gain} plus one times {@link #logFileSize}. */ private double gainedRatio(long gain) { if (size == 0) return 1; return (double)used / (allocated - ((logFileSize - bufferPosition(appendPointer)) & logFilePositionMask) - (gain << log2LogFileSize)); } /** Performs garbage collection until {@link #ratio()} is greater than the specified target ratio. * * @param targetRatio a {@link #ratio()} to reach. */ public void collect(final double targetRatio) throws IOException { final int n = key2QueueData.size(); if (DEBUG) System.err.println("Collection required, ratio=" + ratio()); if (n == 0 || ratio() >= targetRatio) return; if (DEBUG) System.err.println("Starting collection: used=" + used + ", allocated=" + allocated + ", ratio=" + ratio() + ", target ratio=" + targetRatio); final Object[] key = new Object[n]; final long[] currentPointer = new long[n]; final long[] previousPointer = new long[n]; final int[] array = new int[n]; // Dump the metadata map into an array of keys and a parallel key of head pointers. ObjectIterator<Reference2ObjectMap.Entry<Object, QueueData>> fastIterator = key2QueueData.reference2ObjectEntrySet().fastIterator(); for(int i = n; i-- != 0;) { Reference2ObjectMap.Entry<Object, QueueData> e = fastIterator.next(); key[i] = e.getKey(); previousPointer[i] = currentPointer[i] = e.getValue().head; array[i] = i; } // This queue holds the current pointer for each FIFO queue. final LongHeapSemiIndirectPriorityQueue queue = new LongHeapSemiIndirectPriorityQueue(currentPointer, array); // Remembers which log file will be deleted at the end. final LongArrayBitVector deleted = LongArrayBitVector.ofLength(buffers.size()); long collectPointer = currentPointer[queue.first()] & ~logFilePositionMask; // Safely remove previous files for(int buffer = bufferIndex(collectPointer); buffer-- != 0;) deleteBuffer(buffer); long gain = 0; // Keeps track of the number of ones in the deleted bit vector. long moved = 0; // Stats int top = queue.first(); byte[] t = new byte[1024]; // This is just to avoid calling gainedRatio() too much, as it's really slow. while((moved & 0x3FF) != 0 || gainedRatio(gain) < targetRatio) { // Read element pointer(currentPointer[top]); moved++; final long nextPointer = readLong(); final int length = decodeInt(); if (length > t.length) t = new byte[length]; read(t, 0, length); // for(int p = result.length; p-- != 0;) assert result[p] == (byte)p; // Just for unit tests assert collectPointer <= currentPointer[top] : Long.toHexString(collectPointer) + " > " + Long.toHexString(currentPointer[top]); // Write element at collection point final long movedEntryPointer = collectPointer; pointer(collectPointer); writeLong(nextPointer); encodeInt(length); write(t, 0, length); collectPointer = pointer(); // Fix pointers if (currentPointer[top] == previousPointer[top]) key2QueueData.get(key[top]).head = movedEntryPointer; else { pointer(previousPointer[top]); writeLong(movedEntryPointer); } previousPointer[top] = movedEntryPointer; final long previousCurrentPointerTop = currentPointer[top]; if (nextPointer != 0) { currentPointer[top] = nextPointer; assert nextPointer >= collectPointer; queue.changed(); } else { key2QueueData.get(key[top]).tail = movedEntryPointer; queue.dequeue(); if (queue.isEmpty()) break; } top = queue.first(); // Update the information about buffers that will be deleted for(int i = bufferIndex(previousCurrentPointerTop); i < bufferIndex(currentPointer[top]); i++) if (file(i).exists() && ! deleted.set(i, true)) gain++; for(int i = bufferIndex(movedEntryPointer); i <= bufferIndex(collectPointer); i++) if (deleted.set(i, false)) gain--; assert gain == deleted.count() : gain + " != " + deleted.count() + " " + deleted; } if (queue.isEmpty()) { // We moved all elements. Move append pointer to the end of the collected elements and delete all following buffers. appendPointer = collectPointer; final int usedBuffers = bufferIndex(collectPointer) + 1; for(int buffer = usedBuffers; buffer < buffers.size(); buffer++) deleteBuffer(buffer); buffers.size(usedBuffers); files.size(usedBuffers); assert ratio() == 1 : ratio() + " != 1"; } else { // Delete buffers marked as such. int d = 0; for(int buffer = bufferIndex(collectPointer + logFileSize - 1); buffer < bufferIndex(currentPointer[top]); buffer++) if (deleteBuffer(buffer)) d++; assert d == gain : deleted + " != " + gain; assert ratio() >= targetRatio : ratio() + " < " + targetRatio; } if (DEBUG) System.err.println("Ending collection: used=" + used + ", allocated=" + allocated + ", ratio=" + ratio() + ", moved " + moved + " elements (" + 100.0 * moved / size64() + "%)"); } /** Deletes a buffer, it it exists, updating {@link #buffers} and {@link #files}. * * <p>Note that existence is checked in the {@link #buffers} array, not on the filesystem. * * @param buffer a buffer index. * @return true if the buffer of given index exists. */ private boolean deleteBuffer(final int buffer) throws IOException { if (buffers.get(buffer) != null) { buffers.set(buffer, null); files.get(buffer).close(); files.set(buffer, null); file(buffer).delete(); allocated -= logFileSize; return true; } else { assert ! file(buffer).exists(); return false; } } /** Encodes using vByte a nonnegative integer at the current pointer. * @param value a nonnegative integer. */ protected int encodeInt(final int value) throws IOException { if (value < (1 << 7)) { write((byte)value); return 1; } if (value < (1 << 14)) { write((byte)(value >>> 7 | 0x80)); write((byte)(value & 0x7F)); return 2; } if (value < (1 << 21)) { write((byte)(value >>> 14 | 0x80)); write((byte)(value >>> 7 | 0x80)); write((byte)(value & 0x7F)); return 3; } if (value < (1 << 28)) { write((byte)(value >>> 21 | 0x80)); write((byte)(value >>> 14 | 0x80)); write((byte)(value >>> 7 | 0x80)); write((byte)(value & 0x7F)); return 4; } write((byte)(value >>> 28 | 0x80)); write((byte)(value >>> 21 | 0x80)); write((byte)(value >>> 14 | 0x80)); write((byte)(value >>> 7 | 0x80)); write((byte)(value & 0x7F)); return 5; } /** Decodes using vByte a nonnegative integer at the current pointer. * * @return a nonnegative integer decoded using vByte. */ protected int decodeInt() throws IOException { for(int x = 0; ;) { final int b = read(); x |= b & 0x7F; if ((b & 0x80) == 0) return x; x <<= 7; } } /** Returns the overall number of elements in the queues. * @return the overall number of elements in the queues. */ @Override public long size64() { return size; } @Override @Deprecated public int size() { return (int)Math.min(Integer.MAX_VALUE, size); } /** Closes all files. */ @Override public void close() throws IOException { for(RandomAccessFile file: files) if (file != null) file.close(); } }
35.413961
201
0.691497
570d5e7f6360d68471d9ba351641def97930202d
2,204
package com.sixsq.slipstream.module; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * 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. * -=================================================================- */ import com.sixsq.slipstream.exceptions.NotFoundException; import com.sixsq.slipstream.exceptions.ValidationException; import com.sixsq.slipstream.persistence.Target; import com.sixsq.slipstream.persistence.TargetContainerModule; import com.sixsq.slipstream.persistence.User; import org.restlet.data.Form; import java.util.HashSet; import java.util.Set; public abstract class TargetContainerModuleFormProcessor extends ModuleFormProcessor { public TargetContainerModuleFormProcessor(User user) { super(user); } @Override public void parseForm() throws ValidationException, NotFoundException { super.parseForm(); parseTargets(getForm()); } protected void parseTargets(Form form) throws ValidationException { Set<Target> targets = new HashSet<Target>(); for (String targetName : Target.getTargetScriptNames()) { addTarget(form, targets, targetName); } castToModule().setTargets(targets); } protected void addTarget(Form form, Set<Target> targets, String targetName) { String target = form.getFirstValue(targetName + "--script"); if (target != null) { targets.add(new Target(targetName, target)); } } private TargetContainerModule castToModule() { return (TargetContainerModule) getParametrized(); } }
31.042254
87
0.665608
f31ec4c0c864b5d8ad5a294eebe79aef888579d4
11,593
/* * 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.netbeans.api.autoupdate; import java.util.List; import org.netbeans.api.autoupdate.OperationContainer.OperationInfo; import org.netbeans.modules.autoupdate.services.UpdateManagerImpl; /** * * @author Radek Matous */ public class OperationContainerTest extends DefaultTestCase { public OperationContainerTest(String testName) { super(testName); } public void testCreateFor() { OperationContainer<InstallSupport> install = OperationContainer.createForInstall(); assertNotNull(install); assertNull("empty container",install.getSupport()); OperationContainer<OperationSupport> install2 = OperationContainer.createForDirectInstall(); assertNotNull(install2); assertNull("empty container",install2.getSupport()); OperationContainer<InstallSupport> update = OperationContainer.createForUpdate(); assertNotNull(update); assertNull("empty container",update.getSupport()); OperationContainer<OperationSupport> uninstall = OperationContainer.createForDirectUninstall(); assertNotNull(uninstall); assertNull("empty container",uninstall.getSupport()); OperationContainer<OperationSupport> update2 = OperationContainer.createForDirectUpdate(); assertNotNull(update2); assertNull("empty container",update2.getSupport()); OperationContainer<OperationSupport> enable = OperationContainer.createForEnable(); assertNotNull(enable); assertNull("empty container",enable.getSupport()); OperationContainer<OperationSupport> disable = OperationContainer.createForDirectDisable(); assertNotNull(disable); assertNull("empty container",disable.getSupport()); } public UpdateUnit getUpdateUnit(String codeNameBase) { UpdateUnit uu = UpdateManagerImpl.getInstance().getUpdateUnit(codeNameBase); assertNotNull(uu); return uu; } public UpdateElement getAvailableUpdate(UpdateUnit updateUnit, int idx) { List<UpdateElement> available = updateUnit.getAvailableUpdates(); assertTrue(available.size() > idx); return available.get(idx); } public void testAdd() { OperationContainer<InstallSupport> installContainer = OperationContainer.createForInstall(); UpdateUnit engineUnit = getUpdateUnit("org.yourorghere.engine"); assertNull("cannot be installed",engineUnit.getInstalled()); UpdateElement engineElement = getAvailableUpdate(engineUnit,0); assertNull("empty container",installContainer.getSupport()); assertNotNull(installContainer.add(engineElement)); assertNull("cannot add the same twice",installContainer.add(engineElement)); assertNotNull(installContainer.getSupport()); UpdateElement engineelement2 = getAvailableUpdate(engineUnit,1); assertNull("two available updates cannot be installed",installContainer.add(engineelement2)); UpdateUnit independentUnit = getUpdateUnit("org.yourorghere.independent"); assertNull("cannot be installed",independentUnit.getInstalled()); UpdateElement independentElement = getAvailableUpdate(independentUnit,0); assertNotNull(installContainer.add(independentElement)); assertNotNull(installContainer.getSupport()); OperationContainer[] containers = new OperationContainer[]{ OperationContainer.createForUpdate(), OperationContainer.createForDirectUpdate(), OperationContainer.createForEnable(), OperationContainer.createForDirectDisable(), OperationContainer.createForDirectUninstall() }; for (OperationContainer container : containers) { try { container.add(engineElement); fail("must be installed when update should be processed else IllegalArgumentException should be fired"); } catch(IllegalArgumentException iax) {} assertNull("empty container",container.getSupport()); } } public void testOperationInfo() { OperationContainer<InstallSupport> installContainer = OperationContainer.createForInstall(); UpdateUnit independentUnit = getUpdateUnit("org.yourorghere.independent"); assertNull("cannot be installed",independentUnit.getInstalled()); UpdateElement independentElement = getAvailableUpdate(independentUnit,0); OperationInfo info = installContainer.add(independentElement); assertNotNull(info); assertEquals(0,installContainer.listInvalid().size()); assertEquals(0, info.getRequiredElements().size()); assertEquals(0, info.getBrokenDependencies().size()); UpdateUnit dependingUnit = getUpdateUnit("org.yourorghere.depending"); assertNull("cannot be installed",dependingUnit.getInstalled()); UpdateElement dependingElement = getAvailableUpdate(dependingUnit,0); info = installContainer.add(dependingElement); assertNotNull(info); assertEquals(0,installContainer.listInvalid().size()); assertEquals(1, info.getRequiredElements().size()); assertEquals(0, info.getBrokenDependencies().size()); UpdateUnit engineUnit = getUpdateUnit("org.yourorghere.engine"); assertNull("cannot be installed",engineUnit.getInstalled()); UpdateElement engineUnitElement = getAvailableUpdate(engineUnit,0); assertEquals(engineUnitElement, info.getRequiredElements().toArray()[0]); assertEquals(0, info.getBrokenDependencies().size()); UpdateUnit brokenUnit = getUpdateUnit("org.yourorghere.brokendepending"); assertNull("cannot be installed",brokenUnit.getInstalled()); UpdateElement brokenElement = getAvailableUpdate(brokenUnit,0); info = installContainer.add(brokenElement); assertNotNull(info); assertEquals(0,installContainer.listInvalid().size()); assertEquals(0, info.getRequiredElements().size()); assertEquals(1, info.getBrokenDependencies().size()); } public void testAdditionalRequiredElements() { OperationContainer<InstallSupport> installContainer = OperationContainer.createForInstall(); UpdateUnit engineUnit = getUpdateUnit("org.yourorghere.engine"); assertNull("cannot be installed",engineUnit.getInstalled()); UpdateElement engineElement = getAvailableUpdate(engineUnit,0); OperationInfo<InstallSupport> engineInfo = installContainer.add(engineElement); assertNotNull(engineInfo); UpdateUnit independentUnit = getUpdateUnit("org.yourorghere.independent"); assertNull("cannot be installed",independentUnit.getInstalled()); UpdateElement independentElement = getAvailableUpdate(independentUnit,0); OperationInfo<InstallSupport> independentInfo = installContainer.add(independentElement); assertNotNull(independentInfo); UpdateUnit dependingUnit = getUpdateUnit("org.yourorghere.depending"); assertNull("cannot be installed",dependingUnit.getInstalled()); UpdateElement dependingElement = getAvailableUpdate(dependingUnit,0); OperationInfo dependingInfo = installContainer.add(dependingElement); assertNotNull(dependingInfo); assertEquals(0,installContainer.listInvalid().size()); assertEquals(0, dependingInfo.getRequiredElements().size()); assertEquals(0, dependingInfo.getBrokenDependencies().size()); installContainer.remove(engineInfo); assertEquals(1, dependingInfo.getRequiredElements().size()); installContainer.remove(independentInfo); assertEquals(2, dependingInfo.getRequiredElements().size()); assertEquals(0, dependingInfo.getBrokenDependencies().size()); installContainer.add(independentInfo.getUpdateElement()); assertEquals(1, dependingInfo.getRequiredElements().size()); assertEquals(0, dependingInfo.getBrokenDependencies().size()); installContainer.add(engineInfo.getUpdateElement()); assertEquals(0, dependingInfo.getRequiredElements().size()); assertEquals(0, dependingInfo.getBrokenDependencies().size()); } private OperationInfo<InstallSupport> addElemenetForInstall (String codeName, OperationContainer<InstallSupport> installContainer) { UpdateUnit unit = getUpdateUnit(codeName); assertNull("can install " + unit, unit.getInstalled ()); UpdateElement el = getAvailableUpdate (unit, 0); OperationInfo<InstallSupport> info = installContainer.add (el); assertNotNull ("OperationInfo not null for " + el, info); return info; } public void testListAllEquals () { OperationContainer<InstallSupport> installContainer = OperationContainer.createForInstall(); assertEquals(0, installContainer.listAll().size()); addElemenetForInstall ("org.yourorghere.independent", installContainer); addElemenetForInstall ("org.yourorghere.depending", installContainer); addElemenetForInstall ("org.yourorghere.engine", installContainer); List<? extends OperationInfo> infosI = installContainer.listAll (); List<? extends OperationInfo> infosII = installContainer.listAll (); assertEquals ("Both list have same size.", infosI.size (), infosII.size ()); for (int i = 0; i < infosI.size (); i++) { assertEquals (i + ". item is equal.", System.identityHashCode (infosI.get(i)), System.identityHashCode (infosII.get(i))); assertEquals (i + ". item is equal.", infosI.get(i), infosII.get(i)); } assertEquals ("Both list are equals.", installContainer.listAll(), installContainer.listAll()); } public void testListAll() { OperationContainer<InstallSupport> installContainer = OperationContainer.createForInstall(); assertEquals(0, installContainer.listAll().size()); addElemenetForInstall ("org.yourorghere.independent", installContainer); assertEquals(1, installContainer.listAll().size()); addElemenetForInstall ("org.yourorghere.depending", installContainer); assertEquals(2, installContainer.listAll().size()); OperationInfo<InstallSupport> info = addElemenetForInstall ("org.yourorghere.brokendepending", installContainer); assertEquals(3, installContainer.listAll ().size()); installContainer.remove(info); assertEquals(2, installContainer.listAll().size()); } }
50.404348
136
0.70301
4713089f4f054ba7ec74af392dd95b270ac8d1d8
1,269
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage.sqlite; import org.geogit.storage.ConfigDatabase; import org.geogit.storage.GraphDatabase; import org.geogit.storage.ObjectDatabase; import org.geogit.storage.StagingDatabase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Scopes; /** * Module for the Xerial SQLite storage backend. * <p> * More information about the SQLite jdbc driver available at {@link https * ://bitbucket.org/xerial/sqlite-jdbc}. * </p> * * @author Justin Deoliveira, Boundless */ public class XerialSQLiteModule extends AbstractModule { static Logger LOG = LoggerFactory.getLogger(XerialSQLiteModule.class); @Override protected void configure() { bind(ConfigDatabase.class).to(XerialConfigDatabase.class).in(Scopes.SINGLETON); bind(ObjectDatabase.class).to(XerialObjectDatabase.class).in(Scopes.SINGLETON); bind(GraphDatabase.class).to(XerialGraphDatabase.class).in(Scopes.SINGLETON); bind(StagingDatabase.class).to(XerialStagingDatabase.class).in(Scopes.SINGLETON); } }
32.538462
89
0.760441
ee5a8a5745f39ee59ea49af96df905e34bead102
4,493
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.cr.transform.v20181201; import java.util.ArrayList; import java.util.List; import com.aliyuncs.cr.model.v20181201.GetRepoSyncTaskResponse; import com.aliyuncs.cr.model.v20181201.GetRepoSyncTaskResponse.ImageFrom; import com.aliyuncs.cr.model.v20181201.GetRepoSyncTaskResponse.ImageTo; import com.aliyuncs.cr.model.v20181201.GetRepoSyncTaskResponse.LayerTasksItem; import com.aliyuncs.transform.UnmarshallerContext; public class GetRepoSyncTaskResponseUnmarshaller { public static GetRepoSyncTaskResponse unmarshall(GetRepoSyncTaskResponse getRepoSyncTaskResponse, UnmarshallerContext _ctx) { getRepoSyncTaskResponse.setRequestId(_ctx.stringValue("GetRepoSyncTaskResponse.RequestId")); getRepoSyncTaskResponse.setSyncRuleId(_ctx.stringValue("GetRepoSyncTaskResponse.SyncRuleId")); getRepoSyncTaskResponse.setProgress(_ctx.longValue("GetRepoSyncTaskResponse.Progress")); getRepoSyncTaskResponse.setSyncedSize(_ctx.longValue("GetRepoSyncTaskResponse.SyncedSize")); getRepoSyncTaskResponse.setTaskStatus(_ctx.stringValue("GetRepoSyncTaskResponse.TaskStatus")); getRepoSyncTaskResponse.setSyncTransAccelerate(_ctx.booleanValue("GetRepoSyncTaskResponse.SyncTransAccelerate")); getRepoSyncTaskResponse.setCrossUser(_ctx.booleanValue("GetRepoSyncTaskResponse.CrossUser")); getRepoSyncTaskResponse.setSyncTaskId(_ctx.stringValue("GetRepoSyncTaskResponse.SyncTaskId")); getRepoSyncTaskResponse.setSyncBatchTaskId(_ctx.stringValue("GetRepoSyncTaskResponse.SyncBatchTaskId")); getRepoSyncTaskResponse.setCode(_ctx.stringValue("GetRepoSyncTaskResponse.Code")); getRepoSyncTaskResponse.setIsSuccess(_ctx.booleanValue("GetRepoSyncTaskResponse.IsSuccess")); getRepoSyncTaskResponse.setTaskTrigger(_ctx.stringValue("GetRepoSyncTaskResponse.TaskTrigger")); ImageFrom imageFrom = new ImageFrom(); imageFrom.setRepoNamespaceName(_ctx.stringValue("GetRepoSyncTaskResponse.ImageFrom.RepoNamespaceName")); imageFrom.setInstanceId(_ctx.stringValue("GetRepoSyncTaskResponse.ImageFrom.InstanceId")); imageFrom.setImageTag(_ctx.stringValue("GetRepoSyncTaskResponse.ImageFrom.ImageTag")); imageFrom.setRepoName(_ctx.stringValue("GetRepoSyncTaskResponse.ImageFrom.RepoName")); imageFrom.setRegionId(_ctx.stringValue("GetRepoSyncTaskResponse.ImageFrom.RegionId")); getRepoSyncTaskResponse.setImageFrom(imageFrom); ImageTo imageTo = new ImageTo(); imageTo.setRepoNamespaceName(_ctx.stringValue("GetRepoSyncTaskResponse.ImageTo.RepoNamespaceName")); imageTo.setInstanceId(_ctx.stringValue("GetRepoSyncTaskResponse.ImageTo.InstanceId")); imageTo.setImageTag(_ctx.stringValue("GetRepoSyncTaskResponse.ImageTo.ImageTag")); imageTo.setRepoName(_ctx.stringValue("GetRepoSyncTaskResponse.ImageTo.RepoName")); imageTo.setRegionId(_ctx.stringValue("GetRepoSyncTaskResponse.ImageTo.RegionId")); getRepoSyncTaskResponse.setImageTo(imageTo); List<LayerTasksItem> layerTasks = new ArrayList<LayerTasksItem>(); for (int i = 0; i < _ctx.lengthValue("GetRepoSyncTaskResponse.LayerTasks.Length"); i++) { LayerTasksItem layerTasksItem = new LayerTasksItem(); layerTasksItem.setTaskStatus(_ctx.stringValue("GetRepoSyncTaskResponse.LayerTasks["+ i +"].TaskStatus")); layerTasksItem.setDigest(_ctx.stringValue("GetRepoSyncTaskResponse.LayerTasks["+ i +"].Digest")); layerTasksItem.setSyncedSize(_ctx.longValue("GetRepoSyncTaskResponse.LayerTasks["+ i +"].SyncedSize")); layerTasksItem.setSize(_ctx.longValue("GetRepoSyncTaskResponse.LayerTasks["+ i +"].Size")); layerTasksItem.setSyncLayerTaskId(_ctx.stringValue("GetRepoSyncTaskResponse.LayerTasks["+ i +"].SyncLayerTaskId")); layerTasksItem.setArtifactDigest(_ctx.stringValue("GetRepoSyncTaskResponse.LayerTasks["+ i +"].ArtifactDigest")); layerTasks.add(layerTasksItem); } getRepoSyncTaskResponse.setLayerTasks(layerTasks); return getRepoSyncTaskResponse; } }
59.118421
126
0.81371
2b4309ebadb22ddaf05677a049271063e111d203
3,692
package com.cose.easywu.message.fragment; import android.content.Intent; import android.preference.PreferenceManager; import android.view.View; import com.cose.easywu.db.HXUserInfo; import com.cose.easywu.find.activity.FindGoodsInfoActivity; import com.cose.easywu.home.activity.GoodsInfoActivity; import com.hyphenate.chat.EMMessage; import com.hyphenate.easeui.model.GoodsMessageHelper; import com.hyphenate.easeui.ui.EaseChatFragment; import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider; import com.hyphenate.exceptions.HyphenateException; import org.litepal.LitePal; public class MyChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper { @Override protected void setUpView() { // 设置聊天界面的监听,需要在父类 onActivityCreated 之前设置监听 setChatFragmentHelper(this); setOnGoodsItemClicked(new OnGoodsItemClicked() { @Override public void onclick(String g_id) { Intent intent = new Intent(getContext(), GoodsInfoActivity.class); intent.putExtra(GoodsMessageHelper.CHATTYPE, true); intent.putExtra(GoodsMessageHelper.GOODS_ID, g_id); startActivity(intent); } }); super.setUpView(); } // 在这个方法设置拓展消息 @Override public void onSetMessageAttributes(EMMessage message) { // 先拿到当前用户的信息 String uid = PreferenceManager.getDefaultSharedPreferences(getContext()).getString("u_id", ""); HXUserInfo hxUserInfo = LitePal.where("uid=?", uid).findFirst(HXUserInfo.class); if (hxUserInfo != null) { // 携带进消息里面去 message.setAttribute("uid", uid); message.setAttribute("nick", hxUserInfo.getNick()); message.setAttribute("photo", hxUserInfo.getPhoto()); } } @Override public void onEnterToChatDetails() { } @Override public void onAvatarClick(String username) { } @Override public void onAvatarLongClick(String username) { } @Override public boolean onMessageBubbleClick(EMMessage message) { //消息框点击事件,这里不做覆盖,如需覆盖,return true if (GoodsMessageHelper.isGoodsChatType(message)) { // 当消息为商品信息时,覆盖消息的点击事件 if (GoodsMessageHelper.isFindGoods(message)) { Intent intent = new Intent(getContext(), FindGoodsInfoActivity.class); intent.putExtra(GoodsMessageHelper.CHATTYPE, true); try { intent.putExtra(GoodsMessageHelper.GOODS_ID, message.getStringAttribute("goods_id")); intent.putExtra("isFindGoods", message.getBooleanAttribute("findGoods")); } catch (HyphenateException e) { e.printStackTrace(); } startActivity(intent); return true; } else { Intent intent = new Intent(getContext(), GoodsInfoActivity.class); intent.putExtra(GoodsMessageHelper.CHATTYPE, true); try { intent.putExtra(GoodsMessageHelper.GOODS_ID, message.getStringAttribute("goods_id")); } catch (HyphenateException e) { e.printStackTrace(); } startActivity(intent); return true; } } return false; } @Override public void onMessageBubbleLongClick(EMMessage message) { } @Override public boolean onExtendMenuItemClick(int itemId, View view) { return false; } @Override public EaseCustomChatRowProvider onSetCustomChatRowProvider() { return null; } }
33.261261
105
0.641658
fcc6b60c49390c74b9472323f3e52ea05b0b2ef3
979
package io.corbel.lib.token; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Cristian del Cerro */ public class TokenGrant { private final String accessToken; private final long expiresIn; public TokenGrant(String accessToken, long expiresIn) { this.accessToken = accessToken; this.expiresIn = expiresIn; } @JsonProperty("access_token") public String getAccessToken() { return accessToken; } @JsonProperty("expires_in") public long getExpiresIn() { return expiresIn; } @Override public int hashCode() { return Objects.hash(accessToken); } @Override public boolean equals(Object obj) { if (!(obj instanceof TokenGrant)) { return false; } TokenGrant that = (TokenGrant) obj; return Objects.equals(this.accessToken, that.accessToken) && Objects.equals(this.expiresIn, that.expiresIn); } // For JSon Convert purposes private TokenGrant() { accessToken = null; expiresIn = 0L; } }
19.196078
110
0.728294
72e826f2c2e5a53f5aa740f0dceca64233dfb352
639
package com.andyhawkes.express.functions; import com.andyhawkes.express.Function; import com.andyhawkes.express.exceptions.EvaluationException; import com.andyhawkes.express.utils.Converter; import java.io.FileInputStream; import java.io.IOException; public class LoadFileFunction implements Function { @Override public Object evaluate(Object arg) throws EvaluationException { String filename = Converter.toString(arg); try { return new FileInputStream(filename); } catch (IOException e) { throw new EvaluationException("file not found/readable: " + filename); } } }
29.045455
82
0.72457
8e33162605410dc1e737125063295d0d6d3d5097
4,006
package fr.esiea; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * * /list_items * * /buy_item?name=coquelicot&quantity=2 * * /add_item?name=coquelicot&sellin=10&quality=40&quantity=5&price=5.77 */ /** * Sample web application.<br/> * Run {@link #main(String[])} to launch. */ @SpringBootApplication @RestController public class SpringWebApplication { static HashMap<String, Item> db = new HashMap<>(); /** * Main method that run the application and launch the thread each 15 minutes * @param args */ public static void main(String[] args){ SpringApplication.run(SpringWebApplication.class); Runnable updateQualityTask = new GildedRose(db); ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.scheduleAtFixedRate(updateQualityTask, 0, 15, TimeUnit.MINUTES); } /** * Method in charge of generating the Json, we juste return the list of Item with toString function in it. * @return List<Item> */ @RequestMapping("/list_items") List<Item> listItems(){ List<Item> l = new ArrayList<>(db.values()); return l; } /** * Method that is decreasing if possible the quantity of an item, considering it as a buy. * @param name : String * @param quantity : int * @return String : Message of validation or failure */ @RequestMapping("/buy_item") String buyItem(@RequestParam("name") String name, @RequestParam("quantity") int quantity){ HashMap<Item, Integer> cool = new HashMap<>(); if(!db.containsKey(name)){ return "Impossible, l'item demandé n'existe pas ou n'est plus disponible."; } else{ if(db.get(name).getQuantity() < quantity){ return "Impossible l'article n'est pas disponible en quantité suffisante."; } else{ db.get(name).lowerQuantityBy(quantity); if(db.get(name).getQuantity() == 0){ db.remove(name); } return "Achat effectué ! ["+quantity+" "+name+"]"; } } } /** * Method that is going to register the differents parameters into new item int the HashMap. * @param name : String * @param sellIn : int * @param quality : int * @param qte : int * @param price : double * @return String : Message of validation or failure */ @RequestMapping("/add_item") String addItem(@RequestParam("name") String name, @RequestParam("sellin") int sellIn, @RequestParam("quality") int quality, @RequestParam("quantity") int qte, @RequestParam("price") double price){ Item i; if(name.equals("Backstage passes to a TAFKAL80ETC concert")){ i = new ItemBackstagePass(name, sellIn, quality, qte, price); }else if(name.equals("Aged Brie")){ i = new ItemBrie(name, sellIn, quality, qte, price); }else if(name.equals("Sulfuras, Hand of Ragnaros")){ i = new ItemSulfuras(name, sellIn, quality, qte, price); }else{ i = new Item(name, sellIn, quality,qte, price); } if (db.containsKey(name)){ db.get(name).increaseQuantityBy(qte); return "Nous venons d'ajouter "+qte+" à votre produit."; } else { db.put(name, i); return "Nous avons ajouté "+name+" à notre liste de produits."; } } }
33.949153
127
0.634548
78a15c4a342ff084a15e887015c83e11f3cd67eb
1,954
// Copyright 2000-2017 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.jetbrains.python.codeInsight; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.impl.LineMarkersPass; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author oleg */ public class PyLineSeparatorUtil { private PyLineSeparatorUtil() { } public interface Provider { boolean isSeparatorAllowed(@Nullable PsiElement element); } @Nullable public static LineMarkerInfo addLineSeparatorIfNeeded(@NotNull Provider provider, @NotNull PsiElement element) { final Ref<LineMarkerInfo> info = new Ref<>(null); ApplicationManager.getApplication().runReadAction(() -> { if (!provider.isSeparatorAllowed(element)) { return; } boolean hasSeparableBefore = false; final PsiElement parent = element.getParent(); if (parent == null) { return; } for (PsiElement child : parent.getChildren()) { if (child == element){ break; } if (provider.isSeparatorAllowed(child)) { hasSeparableBefore = true; break; } } if (!hasSeparableBefore) { return; } info.set(createLineSeparatorByElement(element)); }); return info.get(); } @NotNull private static LineMarkerInfo<PsiElement> createLineSeparatorByElement(@NotNull PsiElement element) { PsiElement anchor = PsiTreeUtil.getDeepestFirst(element); return LineMarkersPass.createMethodSeparatorLineMarker(anchor, EditorColorsManager.getInstance()); } }
32.032787
140
0.716991
1ee78f0ac8f2e79ba62e143330fde40fbb9cabc6
5,321
package com.ofte.file.services; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.Map; import org.apache.commons.io.IOUtils; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; import com.ofte.cassandra.services.CassandraInteracter; public class SFTPOperations { CassandraInteracter cassandraInteracter = new CassandraInteracter(); UniqueID uniqueID = new UniqueID(); public Session sftpConnection(String user, String password, String host) { int port = 22; JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(user, host, port); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); System.out.println("Establishing Connection..."); try { session.connect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Connection established."); return session; } public void uploadFile(Session session, Map<String, String> metaDataMap1, LinkedList<String> filesToUpload) { ChannelSftp channelSftp = null; ChannelSftp sftpChannel = null; try { sftpChannel = (ChannelSftp) session.openChannel("sftp"); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { sftpChannel.connect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("sftp channel opened and connected."); channelSftp = (ChannelSftp) sftpChannel; try { System.out.println(metaDataMap1.get("sftpAsDestination")); channelSftp.cd(metaDataMap1.get("sftpAsDestination")); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (filesToUpload.size() != 0) { for (int i = 0; i < filesToUpload.size(); i++) { File f = new File(metaDataMap1.get("sourceDirectory") + "\\" + filesToUpload.get(i)); System.out.println(f.getName()); try { String sftpTransferId = uniqueID.generateUniqueID(); metaDataMap1.put("sftpTransferId", sftpTransferId); metaDataMap1.put("sourceFileName", f.toString()); cassandraInteracter.schedulerTransferDetails( cassandraInteracter.connectCassandra(), metaDataMap1); System.out.println("before putting"); channelSftp.put(new FileInputStream(f), f.getName()); System.out.println("after putting"); metaDataMap1.put("destinationFile", metaDataMap1.get("sftpAsDestination") + "\\" + filesToUpload.get(i)); System.out.println(" metadata " + metaDataMap1); cassandraInteracter.updateSchedulerTransferDetails( cassandraInteracter.connectCassandra(), metaDataMap1); System.out.println("File transfered successfully to host."); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void downloadFile(Map<String, String> map, Session session, LinkedList<String> sftpFilesToProcess) { ChannelSftp sftpChannel = null; try { sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.cd(map.get("sftpAsSource")); } catch (JSchException | SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { sftpChannel.connect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("SFTP Channel created."); InputStream out = null; if (sftpFilesToProcess.size() > 0) { for (String fileinRemote : sftpFilesToProcess) { System.out.println(fileinRemote); try { String sftpTransferId = uniqueID.generateUniqueID(); out = sftpChannel .get(map.get("sftpAsSource") + "//" + fileinRemote); map.put("sftpTransferId", sftpTransferId); map.put("sourceFileName", map.get("sftpAsSource") + "//" + fileinRemote); cassandraInteracter.schedulerTransferDetails( cassandraInteracter.connectCassandra(), map); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } FileOutputStream fout = null; try { fout = new FileOutputStream(map.get("destinationDirectory") + "\\" + fileinRemote); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { IOUtils.copyLarge(out, fout); map.put("destinationFile", map.get("destinationDirectory") + "\\" + fileinRemote); cassandraInteracter.updateSchedulerTransferDetails( cassandraInteracter.connectCassandra(), map); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // File f = new File(remoteFile + "//" + fileinRemote); // f.delete(); } } sftpChannel.disconnect(); session.disconnect(); } }
29.893258
75
0.690848
7a78659aef4c3c2f783ae456ae09a46612e02141
1,395
// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.google.devtools.build.lib.bazel.rules.ninja.lexer; import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; /** Token types for {@link NinjaLexer}. */ public enum NinjaToken { ERROR("error"), BUILD("build"), RULE("rule"), TEXT("text"), IDENTIFIER("identifier"), VARIABLE("variable"), DEFAULT("default"), POOL("pool"), SUBNINJA("subninja"), INCLUDE("include"), COLON(":"), EQUALS("="), PIPE("|"), PIPE2("||"), INDENT("indent"), NEWLINE("newline"), ZERO("zero byte"), EOF("end of file"); private final byte[] bytes; NinjaToken(@Nullable String text) { this.bytes = text != null ? text.getBytes(StandardCharsets.ISO_8859_1) : new byte[0]; } public byte[] getBytes() { return bytes; } }
25.363636
89
0.688172
d57f5098293a701b449e6c31354ce36d2f3ca476
460
package com.loiane.java; import java.util.Scanner; public class Exerc02 { public static void main(String[]args) { Scanner scan = new Scanner(System.in); System.out.println("Entre com um numero :"); int num = scan.nextInt(); if(num >= 0){ System.out.println("O numero informado e positivo !"); }else{ System.out.println("O numero informado e negativo !"); } } }
20.909091
66
0.563043
53c0982902beb7f1ca4e5fe8649ea3c13b4171cd
11,629
/* Copyright (c) 2010-2015 Vanderbilt University * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package edu.vu.isis.ammo.dash; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.PorterDuff; import android.media.MediaRecorder; import android.media.MediaRecorder.OnInfoListener; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import edu.vu.isis.ammo.dash.dialogs.IDialogHelper; import edu.vu.isis.ammo.dash.provider.IncidentSchema.MediaTableSchema; import edu.vu.isis.ammo.dash.provider.IncidentSchemaBase.MediaTableSchemaBase; /** * Activity that is launched when a user wants to add an audio clip to a report. This activity * looks like dialog box on screen. * * This activity is responsible for setting up the audio controls * and also handling persistence of audio data once recording is finished. The file path of the * newly created audio file is returned upon activity finish. * @author demetri * */ public class AudioEntryActivity extends Activity implements OnClickListener, OnInfoListener, IDialogHelper { // =========================================================== // Constants // =========================================================== private static final Logger logger = LoggerFactory.getLogger("class.AudioEntryActivity"); private static final String DIRECTORY_AUDIO = "support/Dash/ammo_audio"; public static String INCIDENT_UUID = "incident_uuid"; /** View tags */ private static final int START_BUTTON_TAG = 1; private static final int CANCEL_BUTTON_TAG = 2; private static final int STOP_BUTTON_TAG = 3; // =========================================================== // Fields // =========================================================== private Button btnStart, btnStop, btnCancel; private MediaRecorder recorder = new MediaRecorder(); private boolean isRecording = false; private File currentFileRecording; private Uri mediaUri = null; private TextView tvTimer; private Handler timerHandler = new Handler(); private UpdateTimerTask updateTimerTask; private long startTime = 0; private String eventId = ""; // =========================================================== // Lifecycle // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WorkflowLogger.log("AudioEntryActivity - onCreate called"); setupView(); eventId = getIntent().getStringExtra(INCIDENT_UUID); disallowRotation(); if(eventId == null) { logger.error("null eventId"); cancelRecording(); } } private void disallowRotation() { //cannot force this in the AndroidManifest, because we want the user //to be able to pick a rotation and stick with it for this activity int orientation = getResources().getConfiguration().orientation; if(orientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { //for portrait or square. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } // =========================================================== // User Interaction // =========================================================== @Override public void onClick(View v) { switch ((Integer)v.getTag()) { case START_BUTTON_TAG: this.startRecording(); break; case CANCEL_BUTTON_TAG: this.cancelRecording(); break; case STOP_BUTTON_TAG: this.stopRecording(); break; default: // do nothing } } // =========================================================== // UI Setup // =========================================================== private void setupView() { setContentView(R.layout.alert_dialog_audio_entry); btnStart = (Button)findViewById(R.id.alertDialogAudioEntryStartButton); btnStart.setTag(START_BUTTON_TAG); btnStart.setOnClickListener(this); btnStart.getBackground().setColorFilter(Color.argb(255, 102, 255, 102), PorterDuff.Mode.MULTIPLY); btnCancel = (Button)findViewById(R.id.alertDialogAudioEntryCancelButton); btnCancel.setTag(CANCEL_BUTTON_TAG); btnCancel.setOnClickListener(this); btnStop = (Button)findViewById(R.id.alertDialogAudioEntryStopButton); btnStop.setTag(STOP_BUTTON_TAG); btnStop.setClickable(false); btnStop.setOnClickListener(this); btnStop.getBackground().setColorFilter(Color.argb(255, 255, 0, 0), PorterDuff.Mode.MULTIPLY); tvTimer = (TextView)findViewById(R.id.alertDialogTimerTextView); } // Sets the button attributes to how they should appear before recording. public void resetButtonAttributes() { btnStop.getBackground().setColorFilter(Color.argb(102, 255, 0, 0), PorterDuff.Mode.MULTIPLY); btnStop.setTextColor(Color.argb(102, 255, 255, 255)); btnStart.getBackground().setColorFilter(Color.argb(255, 102, 255, 102), PorterDuff.Mode.MULTIPLY); btnStart.setTextColor(Color.argb(255, 0, 0, 0)); } // =========================================================== // Audio Controls // =========================================================== private void setupMediaRecorder() { recorder.reset(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); recorder.setMaxDuration(30*1000); recorder.setOnInfoListener(this); } // Resets the media recorder, and begins audio recording. private void startRecording() { if (isRecording) { return; } this.setupMediaRecorder(); // Set the stop button to fully opaque. btnStop.getBackground().setColorFilter(Color.argb(255, 255, 0, 0), PorterDuff.Mode.MULTIPLY); btnStop.setTextColor(Color.argb(255, 255, 255, 255)); btnStop.setClickable(true); btnStart.getBackground().setColorFilter(Color.argb(102, 102, 255, 102), PorterDuff.Mode.MULTIPLY); btnStart.setTextColor(Color.argb(102, 0, 0, 0)); // The filepath we will be saving to should have already been set. If not, set it. if (currentFileRecording == null) { currentFileRecording = this.fileForSDCardWrite(); } String filepath = currentFileRecording.getAbsolutePath(); recorder.setOutputFile(filepath); try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } recorder.start(); WorkflowLogger.log("AudioEntryActivity - started recording audio"); Toast.makeText(this, "Now recording...", Toast.LENGTH_SHORT).show(); isRecording = true; // Start the timer counter. startTimer(); } private void startTimer() { updateTimerTask = new UpdateTimerTask(); startTime = System.currentTimeMillis(); timerHandler.removeCallbacks(updateTimerTask); timerHandler.postDelayed(updateTimerTask, 500); } // Remove the file if we were recording then exit the activity. private void cancelRecording() { if (isRecording) { recorder.stop(); currentFileRecording.delete(); isRecording = false; Toast.makeText(this, "Recording cancelled", Toast.LENGTH_LONG).show(); WorkflowLogger.log("AudioEntryActivity - cancelled recording audio"); } setResult(Activity.RESULT_CANCELED); finish(); } // Stop recording and write the file info to the incident provider. private void stopRecording() { if (isRecording) { recorder.stop(); WorkflowLogger.log("AudioEntryActivity - stopped recording"); WorkflowLogger.log("AudioEntryActivity - writing audio to file: " + currentFileRecording.getAbsolutePath()); isRecording = false; Uri uri = insertAudioEntryIntoIncidentProvider(); timerHandler.removeCallbacks(updateTimerTask); tvTimer.setText(""); Intent data = new Intent(); data.setData(uri); setResult(Activity.RESULT_OK, data); finish(); } } @Override public void finish() { super.finish(); if(isRecording) { cancelRecording(); } } private Uri insertAudioEntryIntoIncidentProvider() { // Store the fileUri in the content provider. ContentResolver cr = getContentResolver(); ContentValues cv = new ContentValues(); cv.put(MediaTableSchemaBase.EVENT_ID, eventId); cv.put(MediaTableSchemaBase.DATA_TYPE, MediaTableSchema.AUDIO_DATA_TYPE); cv.put(MediaTableSchemaBase.DATA, currentFileRecording.getAbsolutePath()); Util.addToGallery(currentFileRecording, "Dash Audio", "Audio taken for Dash", "audio/3gpp", this); mediaUri = cr.insert(MediaTableSchemaBase.CONTENT_URI, cv); logger.debug( "Inserted " + currentFileRecording.getAbsolutePath() + " into " + mediaUri.toString()); WorkflowLogger.log("AudioEntryActivity - inserted audio with uri: " + mediaUri); Toast.makeText(this, "Audio recording saved!", Toast.LENGTH_SHORT).show(); return mediaUri; } @Override public void onInfo(MediaRecorder mr, int what, int extra) { switch(what) { case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: this.stopRecording(); Toast.makeText(this, "Recording limit reached...stopping", Toast.LENGTH_SHORT).show(); break; default: // do nothing. } } // *********************************************************** private class UpdateTimerTask implements Runnable { @Override public void run() { final long start = startTime; long millis = System.currentTimeMillis() - start; int seconds = (int) (millis / 1000); int minutes = seconds / 60; seconds = seconds % 60; if (seconds < 10) { tvTimer.setText("(" + "" + minutes + ":0" + seconds + ")"); } else { tvTimer.setText("(" + "" + minutes + ":" + seconds + ")"); } timerHandler.postDelayed(this, 500); } } /** * Generates a new filename, sets this dialog's file member to that value, * and returns it. */ @Override public File fileForSDCardWrite() { File dir = new File(Environment.getExternalStorageDirectory(),DIRECTORY_AUDIO); String filename = String.valueOf(System.currentTimeMillis()); currentFileRecording = new File(dir, filename + "_audio.3gp"); return currentFileRecording; } }
34.202941
111
0.692235
9cf64f3aeb9090431a92bf2d305898107319c82f
1,271
/* * Copyright (c) 2017, WSO2 Inc. (http://wso2.com) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ballerinalang.composer.service.ballerina.parser.service.util; import org.ballerinalang.util.diagnostic.Diagnostic; import org.ballerinalang.util.diagnostic.DiagnosticListener; import java.util.List; /** * This Diagnostic Listener can be used to collect all the Diagnostic information. */ public class ComposerDiagnosticListener implements DiagnosticListener { List<Diagnostic> diagnostics; public ComposerDiagnosticListener(List<Diagnostic> diagnostics) { this.diagnostics = diagnostics; } @Override public void received(Diagnostic diagnostic) { diagnostics.add(diagnostic); } }
33.447368
82
0.75295
9822eb0a53bfc74dab03a379d890b8edbcc8fec2
514
import java.rmi.Remote; import java.rmi.RemoteException; import java.util.Vector; public interface ClientInterface extends Remote { public void refreshList(Vector namevec, Vector idvec) throws RemoteException; public void setMessage(String id, String msg, String time, Vector smileynum) throws RemoteException; public void initialMessage(Vector msgvec, Vector sendervec, Vector timevec, Vector<Vector> smileyvec) throws RemoteException; public Vector refresh() throws RemoteException; }
32.125
103
0.787938
9e63fba27e8a0959c23f1eac4b885edf7f8d1500
2,668
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gemstone.gemfire.cache.client.internal; import com.gemstone.gemfire.internal.cache.tier.MessageType; import com.gemstone.gemfire.internal.cache.tier.sockets.Message; public class GetFunctionAttributeOp { public static Object execute(ExecutablePool pool, String functionId) { AbstractOp op = new GetFunctionAttributeOpImpl(functionId); return pool.execute(op); } private GetFunctionAttributeOp() { // no instances allowed } static class GetFunctionAttributeOpImpl extends AbstractOp { private String functionId = null; public GetFunctionAttributeOpImpl(String functionId) { super(MessageType.GET_FUNCTION_ATTRIBUTES, 1); this.functionId = functionId; getMessage().addStringPart(this.functionId); } @Override protected Object processResponse(Message msg) throws Exception { return processObjResponse(msg, "getFunctionAttribute"); } @Override protected boolean isErrorResponse(int msgType) { return msgType == MessageType.REQUESTDATAERROR; } @Override protected long startAttempt(ConnectionStats stats) { return stats.startGet(); } @Override protected void endSendAttempt(ConnectionStats stats, long start) { stats.endGetSend(start, hasFailed()); } @Override protected void endAttempt(ConnectionStats stats, long start) { stats.endGet(start, hasTimedOut(), hasFailed()); } @Override protected void processSecureBytes(Connection cnx, Message message) throws Exception { } @Override protected boolean needsUserId() { return false; } @Override protected void sendMessage(Connection cnx) throws Exception { getMessage().setEarlyAck((byte)(getMessage().getEarlyAckByte() & Message.MESSAGE_HAS_SECURE_PART)); getMessage().send(false); } } }
31.388235
105
0.728261
bd113b83502416480feb7bcd6e992da03b5e7262
2,944
package chapter40_dynamic_programming; import java.util.Random; public class KnapsackProblem01LessSpace { public static void main(String[] args) { KnapsackProblem01LessSpace knapsackProblem01 = new KnapsackProblem01LessSpace(); int[] itemsWeight = knapsackProblem01.generateItems(10000, 15000); long start = System.currentTimeMillis(); System.out.println(knapsackProblem01.knapsack(itemsWeight, itemsWeight.length, 30000)); System.out.println(System.currentTimeMillis() - start); int[] itemsValue = knapsackProblem01.generateItems(10000, 15000); start = System.currentTimeMillis(); System.out.println(knapsackProblem01.knapsack3(itemsWeight, itemsValue, itemsWeight.length, 30000)); System.out.println(System.currentTimeMillis() - start); } public int knapsack(int[] itemsWeight, int itemsCount, int weightCapacity) { boolean[] states = new boolean[weightCapacity + 1]; // 第一行特殊处理 states[0] = true; if (itemsWeight[0] <= weightCapacity) { states[itemsWeight[0]] = true; } for (int i = 1; i < itemsCount; i++) { // 把 i 放到背包里 // 注意这里需要从大到小遍历避免重复计算的问题 for (int j = weightCapacity - itemsWeight[i]; j >= 0; j--) { if (states[j]) { states[j + itemsWeight[i]] = true; } } } // 查找最后一行中最接近背包容量并且为 true 的值 for (int i = weightCapacity; i >= 0; i--) { if (states[i]) { return i; } } return 0; } public int knapsack3(int[] itemsWeight, int[] itemsValue, int itemsCount, int weightCapacity) { int[] states = new int[weightCapacity + 1]; for (int j = 0; j < weightCapacity + 1; j++) { states[j] = -1; } states[0] = 0; if (itemsWeight[0] <= weightCapacity) { states[itemsWeight[0]] = itemsValue[0]; } for (int i = 1; i < itemsCount; i++) { // 注意这里需要从大到小遍历避免重复计算的问题 for (int j = weightCapacity - itemsWeight[i]; j >= 0; j--) { if (states[j] > 0) { int v = states[j] + itemsValue[i]; if (v > states[j + itemsWeight[i]]) { states[j + itemsWeight[i]] = v; } } } } int maxValue = -1; for (int j = weightCapacity; j >= 0; j--) { if (states[j] > maxValue) { maxValue = states[j]; } } return maxValue; } public int[] generateItems(int itemsCount, int singleItemMaxValue) { int[] items = new int[itemsCount]; Random random = new Random(); for (int i = 0; i < itemsCount; i++) { items[i] = random.nextInt(singleItemMaxValue + 1); } return items; } }
33.83908
108
0.532609
08231819ce5fd57269bdf6b634b944b6f6a6ffb2
891
package com.uiparts.richbuttons.demo.slice; import com.uiparts.richbuttons.demo.ResourceTable; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; public class MainAbilitySlice extends AbilitySlice { Button plastic; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); plastic = (Button) findComponentById(ResourceTable.Id_plastic); /* ShapeElement shapeElement = new ShapeElement(); shapeElement.setShape(ShapeElement.RECTANGLE); shapeElement.setCornerRadius(10); plastic.setBackground(shapeElement);*/ } @Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); } }
27
71
0.710438
c2f21f6b58cdcd9e2ca59549f7dc2ca996b9aae0
574
package com.wuroc.chapternine; public class AnImplementation implements AnInterface { @Override public void firstMethod() { System.out.println("firstMethod"); } @Override public void secondMethod() { System.out.println("secondMethod"); } public static void main(String[] args) { AnInterface i = new AnImplementation(); i.firstMethod(); i.secondMethod(); } } /* 如果我们在AnInterface中添加一个新的方法newMethod() * The type AnImplementation must * implement the inherited abstract method * AnInterface.newMethode() */
16.882353
55
0.681185
baa2fb5e1f6adbf8d088ee4213f6113244b87626
2,908
package org.ayo.robot.anim.path; import android.animation.ValueAnimator; import android.graphics.Path; import android.graphics.PathMeasure; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import org.ayo.robot.anim.BasePage; import org.ayo.robot.anim.R; /** * Created by Administrator on 2016/12/27. */ public class PathAnimDemo2 extends BasePage { private View ball; private static void startAnim(final ViewGroup v, Path path){ final PathMeasure mPathMeasure = new PathMeasure(path, false); float step = mPathMeasure.getLength() / (v.getChildCount() - 1); for (int i = 0; i < v.getChildCount(); i++){ View child = v.getChildAt(i); startAnim(child, path, i * step); } } private static void startAnim(final View v, Path path, float length){ final PathMeasure mPathMeasure = new PathMeasure(path, false); final float[] mCurrentPosition = new float[2]; ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, length); Log.e("aaaaa--11", mPathMeasure.getLength() + ""); valueAnimator.setDuration(1000); // 减速插值器 valueAnimator.setInterpolator(new LinearInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); Log.e("aaaaa--22", value + ""); // 获取当前点坐标封装到mCurrentPosition mPathMeasure.getPosTan(value, mCurrentPosition, null); moveBallTo(v, mCurrentPosition[0], mCurrentPosition[1]); } }); valueAnimator.start(); } private static void moveBallTo(View v, float x, float y){ FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) v.getLayoutParams(); lp.topMargin = (int) y; lp.leftMargin = (int) x; v.setLayoutParams(lp); } @Override protected int getLayoutId() { return R.layout.ac_demo_path_anim2; } @Override protected void onCreate2(View view, @Nullable Bundle bundle) { final PathFrameLayout pathLayout = (PathFrameLayout) findViewById(R.id.pathLayout); ball = pathLayout.getChildAt(0); pathLayout.setOnPathDrawFinished(new PathFrameLayout.OnPathDrawFinished() { @Override public void onPathCreated(Path path) { startAnim(pathLayout, path); } }); } @Override protected void onDestroy2() { } @Override protected void onPageVisibleChanged(boolean b, boolean b1, @Nullable Bundle bundle) { } }
30.93617
91
0.654058
0855b367e0e35591e80a7f58d924b494b87ac689
983
package org.squiddev.plethora.integration.cbmp; import codechicken.multipart.PartMap; import codechicken.multipart.TSlottedPart; import com.google.common.collect.Maps; import org.squiddev.plethora.api.meta.BasicMetaProvider; import org.squiddev.plethora.api.meta.IMetaProvider; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Locale; import java.util.Map; @IMetaProvider.Inject(value = TSlottedPart.class, modId = "forgemultipartcbe") public class MetaSlottedMultipart extends BasicMetaProvider<TSlottedPart> { @Nonnull @Override public Map<Object, Object> getMeta(@Nonnull TSlottedPart object) { int slots = object.getSlotMask(); int i = 0; Map<Integer, String> out = Maps.newHashMapWithExpectedSize(Integer.bitCount(i)); for (PartMap slot : PartMap.values()) { if ((slots & slot.mask) != 0) { out.put(++i, slot.name().toLowerCase(Locale.ENGLISH)); } } return Collections.<Object, Object>singletonMap("slots", out); } }
31.709677
82
0.765005
539c7f5d62789e2d29fada6ac28a0875092de272
846
package io.github.mmm.crypto.symmetric.key; import io.github.mmm.crypto.AbstractCryptoFactory; import io.github.mmm.crypto.key.KeyCreatorFactory; /** * Interface for a {@link AbstractCryptoFactory factory} to {@link #newKeyCreator() create} instances of * {@link SymmetricKeyCreator} for symmetric cryptographic keys.<br> * An instance of {@link SymmetricKeyCreatorFactory} therefore represents a configuration with specific * {@link java.security.Key} {@link java.security.Key#getAlgorithm() algorithm} and {@link java.security.Key#getFormat() * format}(s). * * @param <C> type of {@link SymmetricKeyCreator}. * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public interface SymmetricKeyCreatorFactory<C extends SymmetricKeyCreator<?>> extends KeyCreatorFactory { @Override C newKeyCreator(); }
36.782609
120
0.765957
cefda59a0572ca27eed6dc3727919ce0b7aac7eb
2,428
package com.ags.modules.sys.controller; import java.util.Arrays; import java.util.Map; import com.ags.common.validator.ValidatorUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ags.modules.sys.entity.ThOrderConfigEntity; import com.ags.modules.sys.service.ThOrderConfigService; import com.ags.common.utils.PageUtils; import com.ags.common.utils.R; /** * 订单看板配置表 * * @author AGS * @email AGS@gmail.com * @date 2019-11-05 16:13:02 */ @RestController @RequestMapping("sys/thorderconfig") public class ThOrderConfigController { @Autowired private ThOrderConfigService thOrderConfigService; /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("sys:thorderconfig:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = thOrderConfigService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("sys:thorderconfig:info") public R info(@PathVariable("id") Long id){ ThOrderConfigEntity thOrderConfig = thOrderConfigService.getById(id); return R.ok().put("thOrderConfig", thOrderConfig); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("sys:thorderconfig:save") public R save(@RequestBody ThOrderConfigEntity thOrderConfig){ thOrderConfigService.save(thOrderConfig); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("sys:thorderconfig:update") public R update(@RequestBody ThOrderConfigEntity thOrderConfig){ ValidatorUtils.validateEntity(thOrderConfig); thOrderConfigService.updateById(thOrderConfig); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("sys:thorderconfig:delete") public R delete(@RequestBody Long[] ids){ thOrderConfigService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
26.107527
77
0.702636
37c2359bb51c4bfd53a8a2a62ef2c139b9c3f972
236
package com.miage.pandemie.business.carte; import com.miage.pandemie.business.enumparam.ERole; /** * * @author alex */ public class Role extends Carte{ public Role(ERole role) { super("/Roles",role.name()); } }
16.857143
51
0.652542
9fa894cce42323da0d6035b5ff6a9ddeae8bbca3
930
package array; /** * 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 * 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 * 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。 * * 解法: * 1. O(N )的解法,对每个点进行模拟 * 2. O(N) 的解法是,设置两个变量, sum 判断当前的指针的有效性; total 则判断整个数组是否有解,有 * 就返回通过 sum 得到的下标,没有则返回-1。 */ public class GasStation { public static void main(String[] args) { int[] gas = new int[] {1,2,3,4,5}; int[] cost = new int[] {3,4,5,1,2}; System.out.println(canCompleteCircuit(gas, cost)); } static int canCompleteCircuit(int[] gas, int[] cost) { int result = -1; int total = 0; for (int i = 0, sum = 0; i < gas.length; i++) { total += gas[i] - cost[i]; sum += gas[i] - cost[i]; if (sum < 0) { sum = 0; result = i; } } return total >= 0 ? result + 1 : -1; } }
25.135135
77
0.517204
e8e8b973704b467bd1984c93251415583d2fbd97
839
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pl.altkom.gemalto.spring.ws.client; import java.net.Authenticator; import pl.altkom.gemalto.spring.ws.CrmWebServiceImplService; import pl.altkom.gemalto.spring.ws.Customer; /** * * @author admin */ public class Main { public static void main(String[] args) { Authenticator.setDefault(new WSAuthenticator()); CrmWebServiceImplService service = new CrmWebServiceImplService(); Customer res = service.getCrmWebServiceImplPort().loadById(1); System.out.println(res.getName()); System.out.println(res.getNip()); System.out.println(res.getId()); } }
23.971429
79
0.67938
070834ee76a0a7b8d1aa6baff49d43d990eb7fd9
2,468
@Override public double[] aggregatePredictions(BasePredictions bp) throws Exception { int numClasses = bp.getNumClasses(); double[] p = new double[numClasses]; double[][] r = new double[numClasses][numClasses]; int numBaseClassifiers = bp.getNumPredictions(); for (int i = 0; i < numBaseClassifiers; i++) { double[] distrib = bp.getPrediction(i); String[] predictedClasses = bp.getVersusClasses(i); int indexOfClass1 = bp.getClassIndex(predictedClasses[0]); int indexOfClass2 = bp.getClassIndex(predictedClasses[1]); r[indexOfClass1][indexOfClass2] = distrib[0]; r[indexOfClass2][indexOfClass1] = distrib[1]; } int t, j; int k = numClasses; int iter = 0; int max_iter = Math.max(Configuration.getInstance().WLWmaxIterations, k); double[][] Q = new double[k][k]; double[] Qp = new double[k]; double pQp; double eps = Configuration.getInstance().WLWepsilon / k; for (t = 0; t < k; t++) { p[t] = 1.0 / k; Q[t][t] = 0; for (j = 0; j < t; j++) { Q[t][t] += r[j][t] * r[j][t]; Q[t][j] = Q[j][t]; } for (j = t + 1; j < k; j++) { Q[t][t] += r[j][t] * r[j][t]; Q[t][j] = -r[j][t] * r[t][j]; } } for (iter = 0; iter < max_iter; iter++) { pQp = 0; for (t = 0; t < k; t++) { Qp[t] = 0; for (j = 0; j < k; j++) Qp[t] += Q[t][j] * p[j]; pQp += p[t] * Qp[t]; } double max_error = 0; for (t = 0; t < k; t++) { double error = Math.abs(Qp[t] - pQp); if (error > max_error) max_error = error; } if (max_error < eps) break; for (t = 0; t < k; t++) { double diff = (-Qp[t] + pQp) / Q[t][t]; p[t] += diff; pQp = (pQp + diff * (diff * Q[t][t] + 2 * Qp[t])) / (1 + diff) / (1 + diff); for (j = 0; j < k; j++) { Qp[j] = (Qp[j] + diff * Q[t][j]) / (1 + diff); p[j] /= (1 + diff); } } } if (iter >= max_iter) { throw new Exception("Maximal number of iterations reached!"); } return p; }
39.174603
92
0.419773
1ee34783dbad77459c6cf265130b8556b620da6c
3,587
package cfvbaibai.cardfantasy.engine.skill; import cfvbaibai.cardfantasy.GameUI; import cfvbaibai.cardfantasy.data.Skill; import cfvbaibai.cardfantasy.engine.*; import cfvbaibai.cardfantasy.data.SkillType; import java.util.List; public final class UnderworldCall { public static void apply(SkillResolver resolver, Skill cardSkill, CardInfo attacker, Player defenderHero, int victimCount) throws HeroDieSignal { GameUI ui = resolver.getStage().getUI(); int threshold=cardSkill.getImpact(); int damageInit=cardSkill.getImpact2(); List<CardInfo> victims = resolver.getStage().getRandomizer().pickRandom( defenderHero.getField().toList(), victimCount, true, null); ui.useSkill(attacker, victims, cardSkill, true); for (CardInfo victim : victims) { int damage = damageInit; OnAttackBlockingResult result = resolver.resolveAttackBlockingSkills(attacker, victim, cardSkill, damage); if (!result.isAttackable()) { continue; } else if(victim.isBoss()) { continue; } else{ int magicEchoSkillResult = resolver.resolveMagicEchoSkill(attacker, victim, cardSkill); if (magicEchoSkillResult==1||magicEchoSkillResult==2) { if(attacker.isDead()) { if (magicEchoSkillResult == 1) { continue; } } else { OnAttackBlockingResult result2 = resolver.resolveAttackBlockingSkills(victim, attacker, cardSkill, damageInit); if (!result2.isAttackable()) { if (magicEchoSkillResult == 1) { continue; } } else { if (attacker.getHP() >= attacker.getMaxHP() * threshold / 100) { int damage2 = result2.getDamage(); ui.attackCard(victim, attacker, cardSkill, damage2); resolver.resolveDeathSkills(victim, attacker, cardSkill, resolver.applyDamage(victim, attacker, cardSkill, damage2)); } else { damage = attacker.getMaxHP(); ui.attackCard(victim, attacker, cardSkill, damage); resolver.resolveDeathSkills(victim, attacker, cardSkill, resolver.applyDamage(victim, attacker, cardSkill,damage)); } } } if (magicEchoSkillResult == 1) { continue; } } if (victim.getHP() >= victim.getMaxHP() * threshold / 100) { damage = result.getDamage(); ui.attackCard(attacker, victim, cardSkill, damage); resolver.resolveDeathSkills(attacker, victim, cardSkill, resolver.applyDamage(attacker, victim, cardSkill,damage)); } else{ damage = victim.getMaxHP(); ui.attackCard(attacker, victim, cardSkill, damage); resolver.resolveDeathSkills(attacker, victim, cardSkill, resolver.applyDamage(attacker, victim, cardSkill,damage)); } } } } }
47.197368
153
0.51826
5c0b807aa075047912880c317900bfd92e80e777
2,365
package com.study.mz.study.recyclerview; import android.graphics.Rect; import android.os.Bundle; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.jaeger.library.StatusBarUtil; import com.mz.mzlibrary.MZBaseActivity; import com.mz.mzlibrary.widget.MZActionBar; import com.study.mz.study.R; import com.study.mz.study.boardcast.LocalBoardcastActivity; public class HorRecyclerViewActivity extends MZBaseActivity { private MZActionBar mActionBar; private RecyclerView mRvHor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hor_recycler_view); mActionBar = findViewById(R.id.action_bar); mActionBar.setStyle("HorRecyclerView"); mActionBar.setBackViewIcon(R.drawable.back,null); StatusBarUtil.setColor(HorRecyclerViewActivity.this,getResources().getColor(R.color.colorPrimary),0); mRvHor = findViewById(R.id.mRvHor); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HorRecyclerViewActivity.this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRvHor.setLayoutManager(linearLayoutManager); mRvHor.addItemDecoration(new MyDecoration()); mRvHor.setAdapter(new HorAdapter(HorRecyclerViewActivity.this, new HorAdapter.OnItemClickListener() { @Override public void onClick(int position) { Toast.makeText(HorRecyclerViewActivity.this, "点击了第"+(position+1)+"行", Toast.LENGTH_SHORT).show(); } @Override public void onLongClick(int position) { Toast.makeText(HorRecyclerViewActivity.this, "长按了第"+(position+1)+"行", Toast.LENGTH_SHORT).show(); } })); } private class MyDecoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.set(0,0,getResources().getDimensionPixelOffset(R.dimen.dividerHeight),0); } } }
39.416667
144
0.727273
83de230a6b72f8589298aaef025d1c6c30b0b4e1
4,605
package ru.spb.reshenie.vaadindemo.ui.moderator; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.function.ValueProvider; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import ru.spb.reshenie.vaadindemo.data.entity.Moderator; import ru.spb.reshenie.vaadindemo.data.service.ClubService; import ru.spb.reshenie.vaadindemo.data.service.ModeratorService; import ru.spb.reshenie.vaadindemo.ui.MainLayout; /** * Created by vkondratiev on 03.02.2022 * Description: */ @Route(value = "moderators", layout = MainLayout.class) @PageTitle(value = "Speaking Club | Moderators") public class ModeratorView extends VerticalLayout { private final Grid<Moderator> grid = new Grid<>(Moderator.class); private ModeratorForm form; private final TextField tfFilter = new TextField(); private final ModeratorService moderatorService; private final ClubService clubService; public ModeratorView(ModeratorService moderatorService, ClubService clubService) { this.moderatorService = moderatorService; this.clubService = clubService; addClassName("moderator-view"); setSizeFull(); configureGrid(); configureForm(); addComponents(); closeEditor(); updateList(); } private void addComponents() { add(createToolbar()); add(createContentLayout()); } private Component createToolbar() { configureFilterTextField(); Button addModerator = new Button(new Icon(VaadinIcon.PLUS)); addModerator.addClickListener(e -> addModerator()); HorizontalLayout toolbar = new HorizontalLayout(tfFilter, addModerator); toolbar.setClassName("moderator-toolbar"); return toolbar; } private void configureFilterTextField() { tfFilter.setPlaceholder("search..."); tfFilter.setClearButtonVisible(true); tfFilter.setPrefixComponent(new Icon(VaadinIcon.SEARCH)); tfFilter.setValueChangeMode(ValueChangeMode.LAZY); tfFilter.addValueChangeListener(e -> updateList()); } private void addModerator() { grid.asSingleSelect().clear(); openEditor(new Moderator()); } private Component createContentLayout() { HorizontalLayout content = new HorizontalLayout(grid, form); content.setFlexGrow(2, grid); content.setFlexGrow(1, form); content.setClassName("moderator-content"); content.setSizeFull(); return content; } private void configureGrid() { grid.addClassName("moderator-grid"); grid.setSizeFull(); grid.setColumns("firstName", "lastName", "email"); ValueProvider<Moderator, String> clubByModer = moderator -> moderator.getClub().getName(); grid.addColumn(clubByModer).setComparator(clubByModer).setHeader("Club"); grid.setPageSize(10); grid.setSelectionMode(Grid.SelectionMode.SINGLE); grid.asSingleSelect().addValueChangeListener(e -> openEditor(e.getValue())); } private void configureForm() { form = new ModeratorForm(clubService.findAll()); form.setWidth("25em"); form.addListener(ModeratorFormEvent.SaveEvent.class, event -> { moderatorService.save(event.getModerator()); updateList(); closeEditor(); }); form.addListener(ModeratorFormEvent.CloseEvent.class, event -> closeEditor()); form.addListener(ModeratorFormEvent.DeleteEvent.class, event -> { moderatorService.delete(event.getModerator()); updateList(); closeEditor(); }); } private void openEditor(Moderator moderator) { if (moderator == null) { return; } form.setModerator(moderator); form.setVisible(true); addClassName("moderator-editing"); } private void closeEditor() { form.setModerator(null); form.setVisible(false); removeClassName("moderator-editing"); } private void updateList() { grid.setItems(moderatorService.findAll(tfFilter.getValue())); } }
33.613139
98
0.683388
8b32c4c6dfaafab4f47e0bb82d72cd07892b5e35
780
package com.squareup.okhttp.internal.spdy; import java.io.IOException; import java.util.List; import java.util.Set; final class E extends com.squareup.okhttp.internal.c { E(A paramA, String paramString, Object[] paramArrayOfObject, int paramInt, List paramList) { super(paramString, paramArrayOfObject); } public final void b() { A.h(this.c).a(); try { this.c.i.a(this.a, ErrorCode.CANCEL); synchronized (this.c) { A.i(this.c).remove(Integer.valueOf(this.a)); return; } } catch (IOException localIOException) { } } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.squareup.okhttp.internal.spdy.E * JD-Core Version: 0.6.0 */
22.285714
92
0.644872
fcd0dc2cbcb610c5ad2a7e3a14a57506a66f16ad
5,733
package eu.sanjin.kurelic.cbc.business.services; import eu.sanjin.kurelic.cbc.business.utility.LocaleUtility; import eu.sanjin.kurelic.cbc.business.viewmodel.info.*; import eu.sanjin.kurelic.cbc.repo.dao.CityDescriptionDao; import eu.sanjin.kurelic.cbc.repo.dao.TripHistoryDao; import eu.sanjin.kurelic.cbc.repo.dao.UserDao; import eu.sanjin.kurelic.cbc.repo.dao.UserTravelHistoryDao; import eu.sanjin.kurelic.cbc.repo.entity.TripHistory; import eu.sanjin.kurelic.cbc.repo.values.TripTypeValues; import org.springframework.data.util.Pair; import org.springframework.stereotype.Service; import javax.persistence.Tuple; import javax.transaction.Transactional; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Locale; import java.util.Objects; @Service public class StatisticServiceImpl implements StatisticService { private final UserTravelHistoryDao userTravelHistoryDao; private final UserDao userDao; private final TripHistoryDao tripHistoryDao; private final CityDescriptionDao cityDescriptionDao; public StatisticServiceImpl( UserTravelHistoryDao userTravelHistoryDao, UserDao userDao, TripHistoryDao tripHistoryDao, CityDescriptionDao cityDescriptionDao ) { this.userTravelHistoryDao = userTravelHistoryDao; this.userDao = userDao; this.tripHistoryDao = tripHistoryDao; this.cityDescriptionDao = cityDescriptionDao; } @Override @Transactional public InfoItems getTopUsersByTravels(int limit) { InfoItems items = new InfoItems(); InfoItem item; // Check if (limit < 1) { return items; } // Logic var usernameCounterTuples = userTravelHistoryDao.getTopUsersByTravels(limit); for (var usernameCounterTuple : usernameCounterTuples) { item = new InfoItem(); // get user info - database query in for loop (statistics are not something heavily requested) var user = userDao.getUserInformation( usernameCounterTuple.get(UserTravelHistoryDao.TUPLE_USERNAME).toString() ); // fill info item item.addColumn(new InfoItemTextColumn(user.getUsername())); item.addColumn(new InfoItemTextColumn(user.getName())); item.addColumn(new InfoItemTextColumn(user.getSurname())); item.addColumn(new InfoItemTextColumn( usernameCounterTuple.get(UserTravelHistoryDao.TUPLE_NUMBER_OF_TRAVELS).toString() )); // add to items items.add(item); } return items; } @Override @Transactional public InfoItems getTopBusLinesByTravelling(Locale language, int limit) { // Check if (Objects.isNull(language) || limit < 1) { return new InfoItems(); } // Logic return getBusLineStatisticsInfoItems(tripHistoryDao.getMostTraveledSchedules(limit), language); } @Override @Transactional public InfoItems getOverbookedBusLines(Locale language, int limit) { // Check if (Objects.isNull(language) || limit < 1) { return new InfoItems(); } // Logic return getBusLineStatisticsInfoItems(tripHistoryDao.getLastFilledTripHistory(limit), language); } @Override @Transactional public Long getTotalNumberOfPassengers() { return userTravelHistoryDao.getAllUserTravelHistoryCount(); } @Override @Transactional public Long getTotalNumberOfTrips() { return tripHistoryDao.getTripHistoryCount(); } // Utility private InfoItems getBusLineStatisticsInfoItems(List<Tuple> dataList, Locale language) { InfoItems items = new InfoItems(); InfoItem item; Pair<String, String> cities; String lang = LocaleUtility.getLanguage(language); for (var data : dataList) { item = new InfoItem(); // get city title cities = getCityDescription(((TripHistory) data.get(TripHistoryDao.TUPLE_TRIP_HISTORY)), lang); // if something went wrong exit & returned already filled items (if any is filled) if (Objects.isNull(cities)) { return items; } // fill info item item.addColumn(new InfoItemTextColumn(cities.getFirst())); item.addColumn(new InfoItemIconColumn(InfoItemIconType.ARROW_ICON)); item.addColumn(new InfoItemTextColumn(cities.getSecond())); item.addColumn(new InfoItemTextColumn(((TripHistory) data.get(0)).getBusSchedule().getFromTime().format(DateTimeFormatter.ISO_TIME))); item.addColumn(new InfoItemTextColumn(data.get(TripHistoryDao.TUPLE_COUNTER).toString())); // add to items items.add(item); } return items; } private Pair<String, String> getCityDescription(TripHistory tripHistory, String language) { var city1 = cityDescriptionDao.getCityDescription( tripHistory.getBusSchedule().getBusLine().getCity1().getId(), language ); var city2 = cityDescriptionDao.getCityDescription( tripHistory.getBusSchedule().getBusLine().getCity2().getId(), language ); // if language is wrong if (Objects.isNull(city1) || Objects.isNull(city2)) { return null; } if (tripHistory.getTripType().getName().equals(TripTypeValues.B_TO_A.name())) { return Pair.of(city2.getTitle(), city1.getTitle()); } return Pair.of(city1.getTitle(), city2.getTitle()); } }
38.22
146
0.663701
d2d0c59b6a157376e3a0f9ca8526630a5cd28172
9,059
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content.pm; import java.text.Collator; import java.util.Comparator; import android.content.res.XmlResourceParser; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Parcel; import android.text.TextUtils; import android.util.Printer; /** * Base class containing information common to all package items held by the * package manager. This provides a very common basic set of attributes: a * label, icon, and meta-data. This class is not intended to be used by itself; * it is simply here to share common definitions between all items returned by * the package manager. As such, it does not itself implement Parcelable, but * does provide convenience methods to assist in the implementation of * Parcelable in subclasses. */ public class PackageItemInfo { /** * Public name of this item. From the "android:name" attribute. */ public String name; /** * Name of the package that this item is in. */ public String packageName; /** * A string resource identifier (in the package's resources) of this * component's label. From the "label" attribute or, if not set, 0. */ public int labelRes; /** * The string provided in the AndroidManifest file, if any. You probably * don't want to use this. You probably want * {@link PackageManager#getApplicationLabel} */ public CharSequence nonLocalizedLabel; /** * A drawable resource identifier (in the package's resources) of this * component's icon. From the "icon" attribute or, if not set, 0. */ public int icon; /** * A drawable resource identifier (in the package's resources) of this * component's logo. Logos may be larger/wider than icons and are displayed * by certain UI elements in place of a name or name/icon combination. From * the "logo" attribute or, if not set, 0. */ public int logo; /** * Additional meta-data associated with this component. This field will only * be filled in if you set the {@link PackageManager#GET_META_DATA} flag * when requesting the info. */ public Bundle metaData; public PackageItemInfo() { } public PackageItemInfo(PackageItemInfo orig) { name = orig.name; if (name != null) name = name.trim(); packageName = orig.packageName; labelRes = orig.labelRes; nonLocalizedLabel = orig.nonLocalizedLabel; if (nonLocalizedLabel != null) nonLocalizedLabel = nonLocalizedLabel.toString().trim(); icon = orig.icon; logo = orig.logo; metaData = orig.metaData; } /** * Retrieve the current textual label associated with this item. This will * call back on the given PackageManager to load the label from the * application. * * @param pm * A PackageManager from which the label can be loaded; usually * the PackageManager from which you originally retrieved this * item. * * @return Returns a CharSequence containing the item's label. If the item * does not have a label, its name is returned. */ public CharSequence loadLabel(PackageManager pm) { if (nonLocalizedLabel != null) { return nonLocalizedLabel; } if (labelRes != 0) { CharSequence label = pm.getText(packageName, labelRes, getApplicationInfo()); if (label != null) { return label.toString().trim(); } } if (name != null) { return name; } return packageName; } /** * Retrieve the current graphical icon associated with this item. This will * call back on the given PackageManager to load the icon from the * application. * * @param pm * A PackageManager from which the icon can be loaded; usually * the PackageManager from which you originally retrieved this * item. * * @return Returns a Drawable containing the item's icon. If the item does * not have an icon, the item's default icon is returned such as the * default activity icon. */ public Drawable loadIcon(PackageManager pm) { //System.out.println("icon:"+icon); if (icon != 0) { Drawable dr = pm.getDrawable(packageName, icon, getApplicationInfo()); if (dr != null) { return dr; } } return loadDefaultIcon(pm); } /** * Retrieve the default graphical icon associated with this item. * * @param pm * A PackageManager from which the icon can be loaded; usually * the PackageManager from which you originally retrieved this * item. * * @return Returns a Drawable containing the item's default icon such as the * default activity icon. * * @hide */ protected Drawable loadDefaultIcon(PackageManager pm) { return pm.getDefaultActivityIcon(); } /** * Retrieve the current graphical logo associated with this item. This will * call back on the given PackageManager to load the logo from the * application. * * @param pm * A PackageManager from which the logo can be loaded; usually * the PackageManager from which you originally retrieved this * item. * * @return Returns a Drawable containing the item's logo. If the item does * not have a logo, this method will return null. */ public Drawable loadLogo(PackageManager pm) { if (logo != 0) { Drawable d = pm .getDrawable(packageName, logo, getApplicationInfo()); if (d != null) { return d; } } return loadDefaultLogo(pm); } /** * Retrieve the default graphical logo associated with this item. * * @param pm * A PackageManager from which the logo can be loaded; usually * the PackageManager from which you originally retrieved this * item. * * @return Returns a Drawable containing the item's default logo or null if * no default logo is available. * * @hide */ protected Drawable loadDefaultLogo(PackageManager pm) { return null; } /** * Load an XML resource attached to the meta-data of this item. This will * retrieved the name meta-data entry, and if defined call back on the given * PackageManager to load its XML file from the application. * * @param pm * A PackageManager from which the XML can be loaded; usually the * PackageManager from which you originally retrieved this item. * @param name * Name of the meta-date you would like to load. * * @return Returns an XmlPullParser you can use to parse the XML file * assigned as the given meta-data. If the meta-data name is not * defined or the XML resource could not be found, null is returned. */ public XmlResourceParser loadXmlMetaData(PackageManager pm, String name) { if (metaData != null) { int resid = metaData.getInt(name); if (resid != 0) { return pm.getXml(packageName, resid, getApplicationInfo()); } } return null; } protected void dumpFront(Printer pw, String prefix) { if (name != null) { pw.println(prefix + "name=" + name); } pw.println(prefix + "packageName=" + packageName); if (labelRes != 0 || nonLocalizedLabel != null || icon != 0) { pw.println(prefix + "labelRes=0x" + Integer.toHexString(labelRes) + " nonLocalizedLabel=" + nonLocalizedLabel + " icon=0x" + Integer.toHexString(icon)); } } protected void dumpBack(Printer pw, String prefix) { } /** * Get the ApplicationInfo for the application to which this item belongs, * if available, otherwise returns null. * * @return Returns the ApplicationInfo of this item, or null if not known. * * @hide */ protected ApplicationInfo getApplicationInfo() { return null; } public static class DisplayNameComparator implements Comparator<PackageItemInfo> { public DisplayNameComparator(PackageManager pm) { mPM = pm; } public final int compare(PackageItemInfo aa, PackageItemInfo ab) { CharSequence sa = aa.loadLabel(mPM); if (sa == null) sa = aa.name; CharSequence sb = ab.loadLabel(mPM); if (sb == null) sb = ab.name; return sCollator.compare(sa.toString(), sb.toString()); } private final Collator sCollator = Collator.getInstance(); private PackageManager mPM; } public void writeToParcel(Parcel dest, int parcelableFlags) { dest.writeString(name); dest.writeString(packageName); dest.writeInt(labelRes); TextUtils.writeToParcel(nonLocalizedLabel, dest, parcelableFlags); dest.writeInt(icon); dest.writeInt(logo); dest.writeBundle(metaData); } }
30.60473
79
0.687052
5aaa947e618a304cd0905633b326d3b0dc68f108
716
package cn.tedu.note.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; /** * 对软件的业务层进行性能测试 */ @Component @Aspect public class TimeAspect { @Around("bean(*Service)") public Object test(ProceedingJoinPoint jp) throws Throwable { long t1 = System.currentTimeMillis(); Object val = jp.proceed();//目标业务方法 long t2 = System.currentTimeMillis(); long t = t2-t1; //JoinPoint 对象可以获取目标业务方法的 //详细信息: 方法签名, 调用参数等 Signature m = jp.getSignature(); //Signature: 签名, 这里是方法签名 System.out.println(m+"用时:"+t); return val; } }
18.842105
48
0.723464
53c38c9381cd90a72ca48a1f1521f5e2124fe998
1,136
package nl.davinci.davinciquest.Entity; /** * Created by Vincent on 8-12-2016. */ public class Highscore { private int id; private int score; private int userId; private int questId; private User user; private int markersCompleted; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getQuestId() { return questId; } public void setQuestId(int questId) { this.questId = questId; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public int getMarkersCompleted() { return markersCompleted; } public void setMarkersCompleted(int markersCompleted) { this.markersCompleted = markersCompleted; } }
15.777778
59
0.572183
a24e666cd3ba8f130ca3bc91bb07eec80eec79ca
8,712
package net.osmand.plus.backup; import android.os.AsyncTask; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.osmand.plus.OsmandApplication; import net.osmand.plus.backup.BackupImporter.CollectItemsResult; import net.osmand.plus.backup.BackupImporter.NetworkImportProgressListener; import net.osmand.plus.backup.ExportBackupTask.ItemProgressInfo; import net.osmand.plus.backup.ImportBackupItemsTask.ImportItemsListener; import net.osmand.plus.backup.NetworkSettingsHelper.BackupCollectListener; import net.osmand.plus.settings.backend.backup.SettingsHelper.CheckDuplicatesListener; import net.osmand.plus.settings.backend.backup.SettingsHelper.ImportListener; import net.osmand.plus.settings.backend.backup.SettingsHelper.ImportType; import net.osmand.plus.settings.backend.backup.items.CollectionSettingsItem; import net.osmand.plus.settings.backend.backup.items.FileSettingsItem; import net.osmand.plus.settings.backend.backup.items.ProfileSettingsItem; import net.osmand.plus.settings.backend.backup.items.SettingsItem; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ImportBackupTask extends AsyncTask<Void, ItemProgressInfo, List<SettingsItem>> { private final NetworkSettingsHelper helper; private final OsmandApplication app; private ImportListener importListener; private BackupCollectListener collectListener; private CheckDuplicatesListener duplicatesListener; private final BackupImporter importer; private List<SettingsItem> items = new ArrayList<>(); private List<SettingsItem> selectedItems = new ArrayList<>(); private List<Object> duplicates; private List<RemoteFile> remoteFiles; private final String key; private final Map<String, ItemProgressInfo> itemsProgress = new HashMap<>(); private final ImportType importType; ImportBackupTask(@NonNull String key, @NonNull NetworkSettingsHelper helper, @Nullable BackupCollectListener collectListener, boolean readData) { this.key = key; this.helper = helper; this.app = helper.getApp(); this.collectListener = collectListener; importer = new BackupImporter(app.getBackupHelper(), getProgressListener()); importType = readData ? ImportType.COLLECT_AND_READ : ImportType.COLLECT; } ImportBackupTask(@NonNull String key, @NonNull NetworkSettingsHelper helper, @NonNull List<SettingsItem> items, @Nullable ImportListener importListener, boolean forceReadData) { this.key = key; this.helper = helper; this.app = helper.getApp(); this.importListener = importListener; this.items = items; importer = new BackupImporter(app.getBackupHelper(), getProgressListener()); importType = forceReadData ? ImportType.IMPORT_FORCE_READ : ImportType.IMPORT; } ImportBackupTask(@NonNull String key, @NonNull NetworkSettingsHelper helper, @NonNull List<SettingsItem> items, @NonNull List<SettingsItem> selectedItems, @Nullable CheckDuplicatesListener duplicatesListener) { this.key = key; this.helper = helper; this.app = helper.getApp(); this.items = items; this.duplicatesListener = duplicatesListener; this.selectedItems = selectedItems; importer = new BackupImporter(app.getBackupHelper(), getProgressListener()); importType = ImportType.CHECK_DUPLICATES; } @Override protected List<SettingsItem> doInBackground(Void... voids) { switch (importType) { case COLLECT: case COLLECT_AND_READ: try { CollectItemsResult result = importer.collectItems(importType == ImportType.COLLECT_AND_READ); remoteFiles = result.remoteFiles; return result.items; } catch (IllegalArgumentException e) { NetworkSettingsHelper.LOG.error("Failed to collect items for backup", e); } catch (IOException e) { NetworkSettingsHelper.LOG.error("Failed to collect items for backup", e); } break; case CHECK_DUPLICATES: this.duplicates = getDuplicatesData(selectedItems); return selectedItems; case IMPORT: case IMPORT_FORCE_READ: if (items != null && items.size() > 0) { BackupHelper backupHelper = app.getBackupHelper(); PrepareBackupResult backup = backupHelper.getBackup(); for (SettingsItem item : items) { item.apply(); String fileName = item.getFileName(); if (fileName != null) { RemoteFile remoteFile = backup.getRemoteFile(item.getType().name(), fileName); if (remoteFile != null) { backupHelper.updateFileUploadTime(remoteFile.getType(), remoteFile.getName(), remoteFile.getClienttimems()); } } } } return items; } return null; } @Override protected void onPostExecute(@Nullable List<SettingsItem> items) { if (items != null && importType != ImportType.CHECK_DUPLICATES) { this.items = items; } else { selectedItems = items; } switch (importType) { case COLLECT: case COLLECT_AND_READ: collectListener.onBackupCollectFinished(items != null, false, this.items, remoteFiles); helper.importAsyncTasks.remove(key); break; case CHECK_DUPLICATES: if (duplicatesListener != null) { duplicatesListener.onDuplicatesChecked(duplicates, selectedItems); } helper.importAsyncTasks.remove(key); break; case IMPORT: case IMPORT_FORCE_READ: if (items != null && items.size() > 0) { boolean forceReadData = importType == ImportType.IMPORT_FORCE_READ; ImportItemsListener itemsListener = (succeed, needRestart) -> { helper.importAsyncTasks.remove(key); helper.finishImport(importListener, succeed, items, needRestart); }; new ImportBackupItemsTask(app, importer, items, itemsListener, forceReadData) .executeOnExecutor(app.getBackupHelper().getExecutor()); } break; } } @Override protected void onProgressUpdate(ItemProgressInfo... progressInfos) { if (importListener != null) { for (ItemProgressInfo info : progressInfos) { ItemProgressInfo prevInfo = getItemProgressInfo(info.type, info.fileName); if (prevInfo != null) { info.setWork(prevInfo.getWork()); } itemsProgress.put(info.type + info.fileName, info); if (info.isFinished()) { importListener.onImportItemFinished(info.type, info.fileName); } else if (info.getValue() == 0) { importListener.onImportItemStarted(info.type, info.fileName, info.getWork()); } else { importListener.onImportItemProgress(info.type, info.fileName, info.getValue()); } } } } @Nullable public ItemProgressInfo getItemProgressInfo(@NonNull String type, @NonNull String fileName) { return itemsProgress.get(type + fileName); } public List<SettingsItem> getItems() { return items; } public void setImportListener(ImportListener importListener) { this.importListener = importListener; } public void setDuplicatesListener(CheckDuplicatesListener duplicatesListener) { this.duplicatesListener = duplicatesListener; } ImportType getImportType() { return importType; } public List<Object> getDuplicates() { return duplicates; } public List<SettingsItem> getSelectedItems() { return selectedItems; } private List<Object> getDuplicatesData(List<SettingsItem> items) { List<Object> duplicateItems = new ArrayList<>(); for (SettingsItem item : items) { if (item instanceof ProfileSettingsItem) { if (item.exists()) { duplicateItems.add(((ProfileSettingsItem) item).getModeBean()); } } else if (item instanceof CollectionSettingsItem<?>) { CollectionSettingsItem<?> settingsItem = (CollectionSettingsItem<?>) item; List<?> duplicates = settingsItem.processDuplicateItems(); if (!duplicates.isEmpty() && settingsItem.shouldShowDuplicates()) { duplicateItems.addAll(duplicates); } } else if (item instanceof FileSettingsItem) { if (item.exists()) { duplicateItems.add(((FileSettingsItem) item).getFile()); } } } return duplicateItems; } private NetworkImportProgressListener getProgressListener() { return new NetworkImportProgressListener() { @Override public void itemExportStarted(@NonNull String type, @NonNull String fileName, int work) { publishProgress(new ItemProgressInfo(type, fileName, 0, work, false)); } @Override public void updateItemProgress(@NonNull String type, @NonNull String fileName, int progress) { publishProgress(new ItemProgressInfo(type, fileName, progress, 0, false)); } @Override public void itemExportDone(@NonNull String type, @NonNull String fileName) { publishProgress(new ItemProgressInfo(type, fileName, 0, 0, true)); if (isCancelled()) { importer.cancel(); } } }; } }
33.898833
116
0.741047
e6f7cea942cde11dc251790c68b162b6d7876dd6
254
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ /** * Beans used in providing FFDC context and support to open metadata and governance. */ package org.odpi.openmetadata.commonservices.ffdc.properties;
36.285714
84
0.76378
719e0fdb0a7432b89df7fea65f6fbbc0407db32f
1,547
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 废弃奖品池奖品 * * @author auto create * @since 1.0, 2019-08-19 15:59:02 */ public class AlipayMarketingCampaignPrizepoolPrizeDeleteModel extends AlipayObject { private static final long serialVersionUID = 1537842446954461899L; /** * 外部业务流水号,用来标识唯 一的业务动作,用于幂等 */ @ApiField("out_biz_id") private String outBizId; /** * 奖品池id,使用前请联系业务 对接同学提供 */ @ApiField("pool_id") private String poolId; /** * 奖品id,从奖品池内删除的奖品标识 */ @ApiField("prize_id") private String prizeId; /** * 表示业务来源,由营销技术提 供具体值 */ @ApiField("source") private String source; /** * PRIZE_PAUSED("PRIZE_PAUSED", "暂停状态"), PRIZE_CLOSED("PRIZE_CLOSED", "关闭状态"); 参数为空,默认暂停状态 */ @ApiField("status") private String status; public String getOutBizId() { return this.outBizId; } public void setOutBizId(String outBizId) { this.outBizId = outBizId; } public String getPoolId() { return this.poolId; } public void setPoolId(String poolId) { this.poolId = poolId; } public String getPrizeId() { return this.prizeId; } public void setPrizeId(String prizeId) { this.prizeId = prizeId; } public String getSource() { return this.source; } public void setSource(String source) { this.source = source; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } }
17.988372
85
0.664512
8f088873078e4deaeb57a5e35f392c72e6501387
17,926
package org.recap.matchingalgorithm.service; import com.google.common.collect.Lists; import org.apache.camel.ProducerTemplate; import org.apache.commons.collections.CollectionUtils; import org.apache.solr.client.solrj.SolrServerException; import org.recap.ScsbCommonConstants; import org.recap.ScsbConstants; import org.recap.executors.MatchingAlgorithmMVMsCGDCallable; import org.recap.executors.MatchingAlgorithmMonographCGDCallable; import org.recap.executors.MatchingAlgorithmSerialsCGDCallable; import org.recap.matchingalgorithm.MatchingCounter; import org.recap.model.jpa.*; import org.recap.repository.jpa.*; import org.recap.service.ActiveMqQueuesInfo; import org.recap.util.CommonUtil; import org.recap.util.MatchingAlgorithmUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import static org.recap.ScsbConstants.MATCHING_COUNTER_SHARED; /** * Created by angelind on 11/1/17. */ @Component public class MatchingAlgorithmUpdateCGDService { private static final Logger logger = LoggerFactory.getLogger(MatchingAlgorithmUpdateCGDService.class); @Autowired private BibliographicDetailsRepository bibliographicDetailsRepository; @Autowired private ProducerTemplate producerTemplate; @Autowired private CollectionGroupDetailsRepository collectionGroupDetailsRepository; @Autowired private InstitutionDetailsRepository institutionDetailsRepository; @Autowired private ReportDataDetailsRepository reportDataDetailsRepository; @Autowired private ItemChangeLogDetailsRepository itemChangeLogDetailsRepository; @Autowired private MatchingAlgorithmUtil matchingAlgorithmUtil; @Autowired private ItemDetailsRepository itemDetailsRepository; @Autowired private ActiveMqQueuesInfo activeMqQueuesInfo; @Autowired private CommonUtil commonUtil; /** * Gets report data details repository. * * @return the report data details repository */ public ReportDataDetailsRepository getReportDataDetailsRepository() { return reportDataDetailsRepository; } public MatchingAlgorithmUtil getMatchingAlgorithmUtil() { return matchingAlgorithmUtil; } public BibliographicDetailsRepository getBibliographicDetailsRepository() { return bibliographicDetailsRepository; } public ProducerTemplate getProducerTemplate() { return producerTemplate; } public CollectionGroupDetailsRepository getCollectionGroupDetailsRepository() { return collectionGroupDetailsRepository; } public InstitutionDetailsRepository getInstitutionDetailsRepository() { return institutionDetailsRepository; } public ItemChangeLogDetailsRepository getItemChangeLogDetailsRepository() { return itemChangeLogDetailsRepository; } public ItemDetailsRepository getItemDetailsRepository() { return itemDetailsRepository; } public static Logger getLogger() { return logger; } public ActiveMqQueuesInfo getActiveMqQueuesInfo() { return activeMqQueuesInfo; } private ExecutorService executorService; private Map collectionGroupMap; private Map institutionMap; /** * This method is used to update cgd process for monographs. * * @param batchSize the batch size * @throws IOException the io exception * @throws SolrServerException the solr server exception */ public void updateCGDProcessForMonographs(Integer batchSize) throws IOException, SolrServerException, InterruptedException { getLogger().info("Start CGD Process For Monographs."); getMatchingAlgorithmUtil().populateMatchingCounter(); ExecutorService executor = getExecutorService(50); processCallablesForMonographs(batchSize, executor, false); Integer updateItemsQ = getUpdatedItemsQ(); processCallablesForMonographs(batchSize, executor, true); getMatchingAlgorithmUtil().saveCGDUpdatedSummaryReport(ScsbConstants.MATCHING_SUMMARY_MONOGRAPH); List<String> allInstitutionCodesExceptSupportInstitution = commonUtil.findAllInstitutionCodesExceptSupportInstitution(); for (String institutionCode : allInstitutionCodesExceptSupportInstitution) { logger.info("{} Final Counter Value:{} " ,institutionCode, MatchingCounter.getSpecificInstitutionCounterMap(institutionCode).get(MATCHING_COUNTER_SHARED)); } while (updateItemsQ != 0) { Thread.sleep(10000); updateItemsQ = getActiveMqQueuesInfo().getActivemqQueuesInfo(ScsbConstants.UPDATE_ITEMS_Q); } executor.shutdown(); } private Integer getUpdatedItemsQ() throws InterruptedException { Integer updateItemsQ = getActiveMqQueuesInfo().getActivemqQueuesInfo(ScsbConstants.UPDATE_ITEMS_Q); if (updateItemsQ != null) { while (updateItemsQ != 0) { Thread.sleep(10000); updateItemsQ = getActiveMqQueuesInfo().getActivemqQueuesInfo(ScsbConstants.UPDATE_ITEMS_Q); } } return updateItemsQ; } private void processCallablesForMonographs(Integer batchSize, ExecutorService executor, boolean isPendingMatch) { List<Callable<Integer>> callables = new ArrayList<>(); long countOfRecordNum; if(isPendingMatch) { countOfRecordNum = getReportDataDetailsRepository().getCountOfRecordNumForMatchingPendingMonograph(ScsbCommonConstants.BIB_ID); } else { countOfRecordNum = getReportDataDetailsRepository().getCountOfRecordNumForMatchingMonograph(ScsbCommonConstants.BIB_ID); } logger.info(ScsbConstants.TOTAL_RECORDS + "{}", countOfRecordNum); int totalPagesCount = (int) (countOfRecordNum / batchSize); logger.info(ScsbConstants.TOTAL_PAGES + "{}" , totalPagesCount); for(int pageNum = 0; pageNum < totalPagesCount + 1; pageNum++) { Callable callable = new MatchingAlgorithmMonographCGDCallable(getReportDataDetailsRepository(), getBibliographicDetailsRepository(), pageNum, batchSize, getProducerTemplate(), getCollectionGroupMap(), getInstitutionEntityMap(), getItemChangeLogDetailsRepository(), getCollectionGroupDetailsRepository(), getItemDetailsRepository(),isPendingMatch,getInstitutionDetailsRepository()); callables.add(callable); } Map<String, List<Integer>> unProcessedRecordNumberMap = executeCallables(executor, callables); List<Integer> nonMonographRecordNums = unProcessedRecordNumberMap.get(ScsbConstants.NON_MONOGRAPH_RECORD_NUMS); List<Integer> exceptionRecordNums = unProcessedRecordNumberMap.get(ScsbConstants.EXCEPTION_RECORD_NUMS); getMatchingAlgorithmUtil().updateMonographicSetRecords(nonMonographRecordNums, batchSize); getMatchingAlgorithmUtil().updateExceptionRecords(exceptionRecordNums, batchSize); } /** * Update cgd process for serials. * * @param batchSize the batch size * @throws IOException the io exception * @throws SolrServerException the solr server exception */ public void updateCGDProcessForSerials(Integer batchSize) throws IOException, SolrServerException, InterruptedException { logger.info("Start CGD Process For Serials."); getMatchingAlgorithmUtil().populateMatchingCounter(); ExecutorService executor = getExecutorService(50); List<Callable<Integer>> callables = new ArrayList<>(); long countOfRecordNum = getReportDataDetailsRepository().getCountOfRecordNumForMatchingSerials(ScsbCommonConstants.BIB_ID); logger.info(ScsbConstants.TOTAL_RECORDS + "{}", countOfRecordNum); int totalPagesCount = (int) (countOfRecordNum / batchSize); logger.info(ScsbConstants.TOTAL_PAGES + "{}" , totalPagesCount); for(int pageNum=0; pageNum < totalPagesCount + 1; pageNum++) { Callable callable = new MatchingAlgorithmSerialsCGDCallable(getReportDataDetailsRepository(), getBibliographicDetailsRepository(), pageNum, batchSize, getProducerTemplate(), getCollectionGroupMap(), getInstitutionEntityMap(), getItemChangeLogDetailsRepository(), getCollectionGroupDetailsRepository(), getItemDetailsRepository(),institutionDetailsRepository); callables.add(callable); } setCGDUpdateSummaryReport(executor, callables, ScsbConstants.MATCHING_SUMMARY_SERIAL); } /** * Update cgd process for mv ms. * * @param batchSize the batch size * @throws IOException the io exception * @throws SolrServerException the solr server exception */ public void updateCGDProcessForMVMs(Integer batchSize) throws IOException, SolrServerException, InterruptedException { logger.info("Start CGD Process For MVMs."); getMatchingAlgorithmUtil().populateMatchingCounter(); ExecutorService executor = getExecutorService(50); List<Callable<Integer>> callables = new ArrayList<>(); long countOfRecordNum = getReportDataDetailsRepository().getCountOfRecordNumForMatchingMVMs(ScsbCommonConstants.BIB_ID); logger.info(ScsbConstants.TOTAL_RECORDS + "{}", countOfRecordNum); int totalPagesCount = (int) (countOfRecordNum / batchSize); logger.info(ScsbConstants.TOTAL_PAGES + "{}" , totalPagesCount); for(int pageNum=0; pageNum < totalPagesCount + 1; pageNum++) { Callable callable = new MatchingAlgorithmMVMsCGDCallable(getReportDataDetailsRepository(), getBibliographicDetailsRepository(), pageNum, batchSize, getProducerTemplate(), getCollectionGroupMap(), getInstitutionEntityMap(), getItemChangeLogDetailsRepository(), getCollectionGroupDetailsRepository(), getItemDetailsRepository(),institutionDetailsRepository); callables.add(callable); } setCGDUpdateSummaryReport(executor, callables, ScsbConstants.MATCHING_SUMMARY_MVM); } private Map<String, List<Integer>> executeCallables(ExecutorService executorService, List<Callable<Integer>> callables) { List<Integer> nonMonographRecordNumbers = new ArrayList<>(); List<Integer> exceptionRecordNumbers = new ArrayList<>(); Map<String, List<Integer>> unProcessedRecordNumberMap = new HashMap<>(); List<Future<Integer>> futures = getFutures(executorService, callables); if(futures != null) { for (Iterator<Future<Integer>> iterator = futures.iterator(); iterator.hasNext(); ) { Future future = iterator.next(); fetchAndPopulateRecordNumbers(nonMonographRecordNumbers, exceptionRecordNumbers, future); } } unProcessedRecordNumberMap.put(ScsbConstants.NON_MONOGRAPH_RECORD_NUMS, nonMonographRecordNumbers); unProcessedRecordNumberMap.put(ScsbConstants.EXCEPTION_RECORD_NUMS, exceptionRecordNumbers); return unProcessedRecordNumberMap; } private void fetchAndPopulateRecordNumbers(List<Integer> nonMonographRecordNumbers, List<Integer> exceptionRecordNumbers, Future future) { try { Map<String, List<Integer>> recordNumberMap = (Map<String, List<Integer>>) future.get(); if(recordNumberMap != null) { if(CollectionUtils.isNotEmpty(recordNumberMap.get(ScsbConstants.NON_MONOGRAPH_RECORD_NUMS))) { nonMonographRecordNumbers.addAll(recordNumberMap.get(ScsbConstants.NON_MONOGRAPH_RECORD_NUMS)); } if(CollectionUtils.isNotEmpty(recordNumberMap.get(ScsbConstants.EXCEPTION_RECORD_NUMS))) { exceptionRecordNumbers.addAll(recordNumberMap.get(ScsbConstants.EXCEPTION_RECORD_NUMS)); } } } catch (InterruptedException e) { logger.error(ScsbCommonConstants.LOG_ERROR,e); Thread.currentThread().interrupt(); } catch (ExecutionException e) { logger.error(ScsbCommonConstants.LOG_ERROR,e); } } private List<Future<Integer>> getFutures(ExecutorService executorService, List<Callable<Integer>> callables) { List<Future<Integer>> collectedFutures = null; try { List<Future<Integer>> futures = executorService.invokeAll(callables); collectedFutures = futures.stream().map(future -> { try { future.get(); return future; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } catch (ExecutionException e) { throw new IllegalStateException(e); } }).collect(Collectors.toList()); logger.info("No of Futures Collected : {}", collectedFutures.size()); } catch (Exception e) { logger.error(ScsbCommonConstants.LOG_ERROR,e); } return collectedFutures; } private ExecutorService getExecutorService(Integer numThreads) { if (null == executorService || executorService.isShutdown()) { executorService = Executors.newFixedThreadPool(numThreads); } return executorService; } /** * This method gets items count for serials matching. * * @param batchSize the batch size */ public void getItemsCountForSerialsMatching(Integer batchSize) { long countOfRecordNum = getReportDataDetailsRepository().getCountOfRecordNumForMatchingSerials(ScsbCommonConstants.BIB_ID); logger.info(ScsbConstants.TOTAL_RECORDS + "{}", countOfRecordNum); int totalPagesCount = (int) (countOfRecordNum / batchSize); logger.info(ScsbConstants.TOTAL_PAGES + "{}" , totalPagesCount); for(int pageNum = 0; pageNum < totalPagesCount + 1; pageNum++) { long from = pageNum * Long.valueOf(batchSize); List<ReportDataEntity> reportDataEntities = getReportDataDetailsRepository().getReportDataEntityForMatchingSerials(ScsbCommonConstants.BIB_ID, from, batchSize); List<List<ReportDataEntity>> reportDataEntityList = Lists.partition(reportDataEntities, 1000); for(List<ReportDataEntity> dataEntityList : reportDataEntityList) { updateMatchingCounter(pageNum, dataEntityList); } } } private void updateMatchingCounter(int pageNum, List<ReportDataEntity> dataEntityList) { List<Integer> bibIds = new ArrayList<>(); for(ReportDataEntity reportDataEntity : dataEntityList) { List<String> bibIdList = Arrays.asList(reportDataEntity.getHeaderValue().split(",")); bibIds.addAll(bibIdList.stream().map(Integer::parseInt).collect(Collectors.toList())); } logger.info("Bibs count in Page {} : {} " ,pageNum,bibIds.size()); List<BibliographicEntity> bibliographicEntities = getBibliographicDetailsRepository().findByIdIn(bibIds); for(BibliographicEntity bibliographicEntity : bibliographicEntities) { for(ItemEntity itemEntity : bibliographicEntity.getItemEntities()) { if(itemEntity.getCollectionGroupId().equals(getCollectionGroupMap().get(ScsbCommonConstants.SHARED_CGD))) { MatchingCounter.updateCGDCounter(itemEntity.getInstitutionEntity().getInstitutionCode(),false); } } } } /** * This method gets all collection group and puts it in a map. * * @return the collection group map */ public Map getCollectionGroupMap() { if (null == collectionGroupMap) { collectionGroupMap = new HashMap(); Iterable<CollectionGroupEntity> collectionGroupEntities = getCollectionGroupDetailsRepository().findAll(); for (Iterator<CollectionGroupEntity> iterator = collectionGroupEntities.iterator(); iterator.hasNext(); ) { CollectionGroupEntity collectionGroupEntity = iterator.next(); collectionGroupMap.put(collectionGroupEntity.getCollectionGroupCode(), collectionGroupEntity.getId()); } } return collectionGroupMap; } /** * This method gets all institution entity and puts it in a map. * * @return the institution entity map */ public Map getInstitutionEntityMap() { if (null == institutionMap) { institutionMap = new HashMap(); Iterable<InstitutionEntity> institutionEntities = getInstitutionDetailsRepository().findAll(); for (Iterator<InstitutionEntity> iterator = institutionEntities.iterator(); iterator.hasNext(); ) { InstitutionEntity institutionEntity = iterator.next(); institutionMap.put(institutionEntity.getInstitutionCode(), institutionEntity.getId()); } } return institutionMap; } private void setCGDUpdateSummaryReport(ExecutorService executor, List<Callable<Integer>> callables, String reportName) throws InterruptedException { getFutures(executor, callables); getMatchingAlgorithmUtil().saveCGDUpdatedSummaryReport(reportName); List<String> allInstitutionCodesExceptSupportInstitution = commonUtil.findAllInstitutionCodesExceptSupportInstitution(); for (String institutionCode : allInstitutionCodesExceptSupportInstitution) { logger.info("{} Final Counter Value:{} " ,institutionCode, MatchingCounter.getSpecificInstitutionCounterMap(institutionCode).get(MATCHING_COUNTER_SHARED)); } getUpdatedItemsQ(); executor.shutdown(); } }
47.049869
225
0.714214
49bbe0271f5cd80abb477a9b35b2ab00a5bd9752
99
package minek.ckan.v3.basic.model.enums; public enum ApprovalStatus { approved, denied }
16.5
41
0.717172
9ddb4eb280352ebd3405993675ce5f141c46130b
138
package com.tuyano.libro; public interface SampleBeanInterface { public String getMessage(); public void setMessage(String message); }
19.714286
40
0.797101
ba46b8c0868f1c199be36b0a7cc690f14a3bd5ce
5,180
/* * MIT License * * Copyright (c) 2018 atharva washimkar * Copyright (c) 2019 Vincent Palazzo vincenzopalazzodev@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.root101.swing.ui.animation; import javax.swing.*; import java.awt.Color; import java.awt.event.*; public class MaterialUITimer implements MouseListener, ActionListener, MouseMotionListener { private Color from, to; private boolean forward; private int alpha, steps; private int[] forwardDeltas, backwardDeltas; private JComponent component; private Timer timer; protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { if (component == null || !component.isEnabled()) { return; } this.from = component.getBackground(); this.to = to; this.forwardDeltas = new int[4]; this.backwardDeltas = new int[4]; forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; this.steps = steps; this.component = component; timer = new Timer(interval, this); component.setBackground(from); } private Color nextColor() { int rValue = from.getRed() - alpha * forwardDeltas[0]; int gValue = from.getGreen() - alpha * forwardDeltas[1]; int bValue = from.getBlue() - alpha * forwardDeltas[2]; int aValue = from.getAlpha() - alpha * forwardDeltas[3]; return new Color(rValue, gValue, bValue, aValue); } private Color previousColor() { int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; return new Color(rValue, gValue, bValue, aValue); } @Override public void mousePressed(MouseEvent me) { if (!me.getComponent().isEnabled()) { return; } alpha = steps - 1; forward = false; if (timer.isRunning()) { timer.stop(); } timer.start(); alpha = 0; forward = true; timer.start(); } @Override public void mouseReleased(MouseEvent me) { //do nothing } @Override public void mouseClicked(MouseEvent me) { //do nothing } @Override public void mouseExited(MouseEvent me) { if (!me.getComponent().isEnabled()) { return; } if (timer.isRunning()) { timer.stop(); } alpha = steps - 1; forward = false; timer.start(); } @Override public void mouseEntered(MouseEvent me) { if (!me.getComponent().isEnabled()) { return; } alpha = 0; forward = true; if (timer.isRunning()) { timer.stop(); } timer.start(); } @Override public void actionPerformed(ActionEvent ae) { if (forward) { component.setBackground(nextColor()); ++alpha; } else { component.setBackground(previousColor()); --alpha; } if (alpha == steps + 1 || alpha == -1) { if (timer.isRunning()) { timer.stop(); } } } @Override public void mouseDragged(MouseEvent e) { //do nothing this is util only implements interface MouseMotions } @Override public void mouseMoved(MouseEvent e) { //do nothing this is util only implements interface MouseMotions } }
31.204819
92
0.610618
7136376844586263745df3d25f2a595c5dc63e10
2,596
package com.intershop.adapter.payment.partnerpay.internal.service.config; import java.util.Collection; import java.util.function.Supplier; import javax.inject.Inject; import javax.inject.Named; import com.intershop.adapter.payment.partnerpay.internal.service.PartnerPayServiceIfc; import com.intershop.beehive.configuration.capi.common.Configuration; import com.intershop.component.repository.capi.BusinessObjectRepositoryContext; import com.intershop.component.repository.capi.BusinessObjectRepositoryContextProvider; import com.intershop.component.service.capi.service.ConfigurationProvider; import com.intershop.component.service.capi.service.ServiceConfigurationBO; import com.intershop.component.service.capi.service.ServiceConfigurationBORepository; @Named("PartnerPay_PartnerPayServiceConfigSupplier") public class PartnerPayServiceConfigSupplier implements Supplier<Configuration> { @Inject protected BusinessObjectRepositoryContextProvider boRepositoryCtxProvider; @Override public Configuration get() { ServiceConfigurationBO configBO = getServiceConfigurationBO(); ConfigurationProvider configProviderExt = configBO.getExtension(ConfigurationProvider.class); Configuration configuration = configProviderExt.getConfiguration(); return configuration; } private ServiceConfigurationBORepository getServiceConfigurationBORepository() { BusinessObjectRepositoryContext boRepositoryContext = boRepositoryCtxProvider.getBusinessObjectRepositoryContext(); ServiceConfigurationBORepository serviceConfigurationBORepository = boRepositoryContext.getRepository(ServiceConfigurationBORepository.EXTENSION_ID); return serviceConfigurationBORepository; } public ServiceConfigurationBO getServiceConfigurationBO() { ServiceConfigurationBORepository serviceConfigBORepository = getServiceConfigurationBORepository(); Collection<ServiceConfigurationBO> serviceConfigBOs = serviceConfigBORepository.getRunnableServiceConfigurationBOs(PartnerPayServiceIfc.class); if (serviceConfigBOs == null || (serviceConfigBOs.size() != 1)) { throw new IllegalStateException( "We've found " + (serviceConfigBOs == null ? " no" : serviceConfigBOs.size()) + " " + "PartnerPay services matching the marker interface " + PartnerPayServiceIfc.class + ". Please verify that your configuration is ok! " + "We expect only a single service"); } return serviceConfigBOs.iterator().next(); } }
44
157
0.782743
b3c971617c0a34cf96346a0402e32558d998b237
351
package com.savstanis.btcs.exceptions; public class SemanticAnalysisException extends RuntimeException { public SemanticAnalysisException() { } public SemanticAnalysisException(String message) { super(message); } public SemanticAnalysisException(String message, Throwable cause) { super(message, cause); } }
23.4
71
0.723647
8de1596489bb646eca42a76190591c2a48f59d5d
1,766
package pacman.game; import algorithms.core.ISearchAlgorithm; import java.awt.Point; /** * Интерфейс управления моделью игры. * <p> * Определяет базовый интерфейс управления моделью игры со стороны контроллера. */ public interface IControlableGameModel { //------------------------------------------------- Выполнение хода Пакмана /** * Запрашивает инициализацию новой игры с установленными параметрами. */ public void reinitializeGame(); /** * Возвращает <code>true</code>, если игра завершилась победой или * поражением Пакмана. * * @return <code>true</code>, если игра завершена */ public boolean isGameComplete(); /** * Устанавливает количество привидений в игре. * * @param ghostsNumber количество привидений в игре */ public void setGhostsNumber(int ghostsNumber); /** * Возвращает <code>true</code>, если Пакманом выполнил все переданные ему * действия. * * @return <code>true</code>, если Пакманом выполнил все свои действия */ public boolean isPacmanQueueEmpty(); /** * Запрашивает выполнение очередного действия Пакманом. * * @param algorithm алгоритм для расчёта действия * @param goal координата целевого расположения на игровом поле */ public void performPacmanAction(ISearchAlgorithm algorithm, Point goal); /** * Возвращает координату клетки игрового поля по координате на холсте * игрового поле. * * @param canvasCoordinate координата на холсте игрового поля, в пикселах * @return координата клетки игрового поля */ public Point getCellAddress(Point canvasCoordinate); }
29.433333
80
0.6359
e597821ea0f9426593443c803db04d67bc3dade7
7,350
package l9g.app.jsmtptest; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import javax.xml.bind.JAXB; import lombok.Getter; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import java.util.Date; import java.util.Properties; import java.util.logging.Level; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * * @author Thorsten Ludewig <t.ludewig@ostfalia.de> */ public class App { final static Logger LOGGER = LoggerFactory.getLogger(App.class. getName()); private static final String CONFIGURATION = "config.xml"; @Getter private static Configuration config; @Getter private static Options options = new Options(); public static Message createMimeMessage(String smtpHost, int smtpPort, String subject, String from, String to, String bcc) throws AddressException, MessagingException { /////////////////////////////////////////////////////////////////////////// Properties properties = new Properties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); properties.put("mail.smtp.starttls.enable", "true"); if( options.isDebug()) { LOGGER.info("enable mail debug"); properties.put("mail.debug", "true"); } Session session = Session.getDefaultInstance(properties); /////////////////////////////////////////////////////////////////////////// Message message = new MimeMessage(session); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); if (!Strings.isNullOrEmpty(bcc)) { message.setFrom(new InternetAddress(bcc + " <" + from + ">")); message.setReplyTo(InternetAddress.parse(bcc)); message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse( bcc)); } else { message.setFrom(new InternetAddress(from)); } message.setSubject(subject); message.setSentDate(new Date()); return message; } private static void readConfiguration(String configFileName) { LOGGER.info("reading configuration file {}", configFileName); try { Configuration c; File configFile = new File(configFileName); LOGGER.info("Config file: {}", configFile.getAbsolutePath()); if (configFile.exists() && configFile.canRead()) { c = JAXB.unmarshal(new FileReader(configFile), Configuration.class); LOGGER.debug("new config <{}>", c); if (c != null) { LOGGER.info("setting config"); config = c; } } else { LOGGER.info("Can NOT read config file"); } if (config == null) { LOGGER.error("config file NOT found"); System.exit(2); } } catch (FileNotFoundException e) { LOGGER.error("Configuratione file config.xml not found ", e); System.exit(2); } } private static void writeConfiguration() { Configuration c = new Configuration(); c.setAttachFile(""); c.setBcc("bcc email address"); c.setFrom("from email address"); c.setMessage("sample message"); c.setPassword("your password"); c.setUser("your user"); c.setSmtpHost("smtp host"); c.setSmtpPort(587); c.setSsl(false); c.setStartTls(true); c.setSubject("subject"); c.setTo("to email address"); File configFile = new File(CONFIGURATION); LOGGER.info("Writing config file: {}", configFile.getAbsolutePath()); JAXB.marshal(c, configFile); } public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { System.out.println(e.getMessage()); options.setHelp(true); } BuildProperties build = BuildProperties.getInstance(); LOGGER.info("Project Name : {}", build.getProjectName()); LOGGER.info("Project Version : {}", build.getProjectVersion()); LOGGER.info("Build Timestamp : {}", build.getTimestamp()); if (options.isInit()) { writeConfiguration(); System.exit(0); } if (options.isHelp() || !options.isSendMail()) { System.out.println("jSMTPtest usage:"); parser.printUsage(System.out); System.exit(0); } if (Strings.isNullOrEmpty(options.getConfigFileName())) { readConfiguration(CONFIGURATION); } else { readConfiguration(options.getConfigFileName()); } if ( options.isStarttls() || config.isStartTls()) { LOGGER.info( "Force use of STARTTLS"); System.getProperties().put("mail.smtp.starttls.enable", "true"); } if ( !Strings.isNullOrEmpty(options.getTlsProtocols())) { LOGGER.info( "Force use of TLS protocols: {}", options.getTlsProtocols()); System.getProperties().put("mail.smtp.ssl.protocols", options.getTlsProtocols()); } if (!Strings.isNullOrEmpty(options.getMailBcc())) config.setBcc(options.getMailBcc()); if (!Strings.isNullOrEmpty(options.getMailMessage())) config.setMessage(options.getMailMessage()); if (!Strings.isNullOrEmpty(options.getMailSubject())) config.setSubject(options.getMailSubject()); if (!Strings.isNullOrEmpty(options.getMailTo())) config.setTo(options.getMailTo()); try { Message message = createMimeMessage(config.getSmtpHost(), config.getSmtpPort(), config.getSubject(), config.getFrom(), config. getTo(), config.getBcc()); boolean hasAttachment = !Strings.isNullOrEmpty(config.getAttachFile()); if (hasAttachment) { Multipart multipart = new MimeMultipart(); // body BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(config.getMessage(), "text/plain; charset=utf-8"); multipart.addBodyPart(messageBodyPart); // attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(config.getAttachFile()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(config.getAttachFile()); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); } else { message.setContent(config.getMessage(), "text/plain; charset=utf-8"); } LOGGER.info("sending message."); Transport.send(message, message.getAllRecipients(), config.getUser(), config.getPassword()); LOGGER.info("done."); } catch (Exception ex) { java.util.logging.Logger.getLogger(App.class.getName()).log(Level.SEVERE, "Address error", ex); } } }
27.52809
102
0.648435
22677d4a1ec01b474a1c517ceadd2e69457ced89
1,815
package net.mgsx.game.plugins.g2d.systems; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import net.mgsx.game.core.GamePipeline; import net.mgsx.game.core.GameScreen; import net.mgsx.game.core.annotations.Editable; import net.mgsx.game.core.annotations.EditableSystem; import net.mgsx.game.core.annotations.Storable; import net.mgsx.game.core.components.Hidden; import net.mgsx.game.plugins.boundary.components.BoundaryComponent; import net.mgsx.game.plugins.g2d.components.BehindComponent; import net.mgsx.game.plugins.g2d.components.SpriteModel; @Storable("g2d.render") @EditableSystem("G2D Render") public class G2DRenderSystem extends IteratingSystem { private final GameScreen engine; private SpriteBatch batch = new SpriteBatch(); @Editable public boolean culling = false; @Editable public boolean depthTest = false; public G2DRenderSystem(GameScreen engine) { super(Family.all(SpriteModel.class).exclude(Hidden.class, BehindComponent.class).get(), GamePipeline.RENDER + 1); // TODO transparent ? this.engine = engine; } @Override public void update(float deltaTime) { batch.setProjectionMatrix(engine.camera.combined); batch.begin(); if(depthTest){ Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); }else{ Gdx.gl.glDisable(GL20.GL_DEPTH_TEST); } super.update(deltaTime); batch.end(); } @Override protected void processEntity(Entity entity, float deltaTime) { // optional component BoundaryComponent boundary = BoundaryComponent.components.get(entity); if(!culling || boundary == null || boundary.inside) SpriteModel.components.get(entity).sprite.draw(batch); } }
33
137
0.783471
3d747a5aa91c22ac0196b6191d9b1a19956b09b2
386
package pro.taskana.spi.history.api.events.task; import pro.taskana.task.api.models.Task; public class TaskUpdatedEvent extends TaskHistoryEvent { public TaskUpdatedEvent(String id, Task updatedTask, String userId, String details) { super(id, updatedTask, userId, details); eventType = TaskHistoryEventType.UPDATED.getName(); created = updatedTask.getModified(); } }
29.692308
87
0.766839
b5746a7ef48d860f8e57dcc3bf3467dccfd598cc
1,230
package ru.job4j.converter; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author Rustem Mukazhanov (r.mukazhanov@gmail.com) * @version $Id$ * @since 0.1 */ public class ConverterTest { /** * Test tengeToDollar. */ @Test public void when383TengeToDollarThen1() { Converter converter = new Converter(); int result = converter.tengeToDollar(383); assertThat(result, is(1)); } /** * Test tengeToEuro. */ @Test public void when424TengeToEuroThen1() { Converter converter = new Converter(); int result = converter.tengeToEuro(424); assertThat(result, is(1)); } /** * Test dollarToTenge. */ @Test public void when100dollarToTengeThen38300() { Converter converter = new Converter(); int result = converter.dollarToTenge(100); assertThat(result, is(38300)); } /** * Test euroToTenge. */ @Test public void when200EuroToTengeThen84800() { Converter converter = new Converter(); int result = converter.euroToTenge(200); assertThat(result, is(84800)); } }
22.363636
53
0.612195
6da2a9a30c89c80c56c1de2607aa552aae0b19ca
7,067
package com.github.yoojia.anyversion; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import android.util.Log; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by Yoojia.Chen * yoojia.chen@gmail.com * 2015-01-04 * AnyVersion - 自动更新 APK */ public class AnyVersion { private static final String TAG = "AnyVersion"; private static final Lock LOCK = new ReentrantLock(); private static AnyVersion ANY_VERSION = null; Application context; final VersionParser parser; private Future<?> workingTask; private Callback callback; private String url; private RemoteHandler remoteHandler; private final Version currentVersion; private final Handler mainHandler; private final ExecutorService threads; private final Installations installations; private final Downloads downloads; public static AnyVersion getInstance(){ try{ LOCK.lock(); if (ANY_VERSION == null) { throw new IllegalStateException("AnyVersion NOT init !"); } return ANY_VERSION; }finally { LOCK.unlock(); } } private AnyVersion(Application context, VersionParser parser) { Log.d(TAG, "AnyVersion init..."); this.context = context; this.parser = parser; this.threads = Executors.newSingleThreadExecutor(); this.installations = new Installations(); this.downloads = new Downloads(); this.mainHandler = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { Version version = (Version) msg.obj; new VersionDialog(AnyVersion.this.context, version, AnyVersion.this.downloads).show(); } }; String versionName = null; int versionCode = 0; try { PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(),0); versionName = pi.versionName; versionCode = pi.versionCode; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, e.getMessage()); } currentVersion = new Version(versionName, null, null, versionCode); } /** * 初始化 AnyVersion。 * @param context 必须是 Application * @param parser 服务端响应数据解析接口 */ public static void init(Application context, VersionParser parser){ Preconditions.requiredMainUIThread(); try{ LOCK.lock(); if (ANY_VERSION != null) { Log.e(TAG, "Duplicate init AnyVersion ! This VersionParser will be discard !"); Log.e(TAG, "AnyVersion recommend init on YOUR-Application.onCreate(...) ."); return; } }finally { LOCK.unlock(); } if (context == null) { throw new NullPointerException("Application Context CANNOT be null !"); } if (parser == null) { throw new NullPointerException("Parser CANNOT be null !"); } ANY_VERSION = new AnyVersion(context, parser); ANY_VERSION.installations.register(context); } /** * 注册接收新版本通知的 Receiver。 */ public static void registerReceiver(Context context, VersionReceiver receiver){ Broadcasts.register(context, receiver); } /** * 反注册接收新版本通知的 Receiver */ public static void unregisterReceiver(Context context, VersionReceiver receiver){ Broadcasts.unregister(context, receiver); } /** * 设置发现新版本时的回调接口。当 check(NotifyStyle.Callback) 时,此接口参数生效。 */ public void setCallback(Callback callback){ Preconditions.requireInited(); if (callback == null){ throw new NullPointerException("Callback CANNOT be null !"); } this.callback = callback; } /** * 设置检测远程版本的 URL。在使用内置 RemoteHandler 时,URL 是必须的。 */ public void setURL(String url){ Preconditions.requireInited(); checkRequiredURL(url); this.url = url; } /** * 设置自定义检测远程版本数据的接口 */ public void setCustomRemote(RemoteHandler remoteHandler){ Preconditions.requireInited(); if (remoteHandler == null){ throw new NullPointerException("RemoteHandler CANNOT be null !"); } this.remoteHandler = remoteHandler; } /** * 检测新版本,并指定发现新版本的处理方式 */ public void check(NotifyStyle style){ createRemoteRequestIfNeed(); check(this.url, this.remoteHandler, style); } /** * 按指定的 URL,检测新版本,并指定发现新版本的处理方式 */ public void check(String url, NotifyStyle style){ createRemoteRequestIfNeed(); check(url, this.remoteHandler, style); } private void check(final String url, final RemoteHandler remote, final NotifyStyle style){ Preconditions.requireInited(); if (NotifyStyle.Callback.equals(style) && callback == null){ throw new NullPointerException("If reply by callback, callback CANNOT be null ! " + "Call 'setCallback(...) to setup !'"); } final Callback core = new Callback() { @Override public void onVersion(Version remoteVersion) { // 检查是否为新版本 if (remoteVersion == null) return; if (currentVersion.code >= remoteVersion.code) return; switch (style){ case Callback: callback.onVersion(remoteVersion); break; case Broadcast: Broadcasts.send(context, remoteVersion); break; case Dialog: final Message msg = Message.obtain(ANY_VERSION.mainHandler, 0, remoteVersion); msg.sendToTarget(); break; } } }; remote.setOptions(url, parser, core); workingTask = threads.submit(remote); } /** * 取消当前正在检测的工作线程 */ public void cancelCheck(){ Preconditions.requireInited(); if (workingTask != null && !workingTask.isDone()){ workingTask.cancel(true); // force interrupt } } private void createRemoteRequestIfNeed(){ if (remoteHandler == null){ // 使用内置请求时,URL 地址是必须的。 checkRequiredURL(this.url); remoteHandler = new SimpleRemoteHandler(); } } private void checkRequiredURL(String url){ if (TextUtils.isEmpty(url)){ throw new NullPointerException("URL CANNOT be null or empty !"); } } }
31.269912
102
0.603226
1409c6b16e1d1e7bf553575b1c7ae8db174f3096
6,646
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.eclipse.imagen.media.opimage; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.DataBuffer; import java.awt.image.MultiPixelPackedSampleModel; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.renderable.RenderedImageFactory; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.ParameterBlock; import java.awt.image.renderable.RenderableImage; import org.eclipse.imagen.CRIFImpl; import org.eclipse.imagen.BorderExtender; import org.eclipse.imagen.ImageLayout; import java.util.Map; /** * @see SubsampleBinaryToGrayOpImage */ public class SubsampleBinaryToGrayCRIF extends CRIFImpl { /** Constructor. */ public SubsampleBinaryToGrayCRIF() { super("subsamplebinarytogray"); } /** * Creates a new instance of SubsampleBinaryToGrayOpImage in the rendered layer. * This method satisfies the implementation of RIF. * * @param paramBlock The source image, the X and Y scale factor */ public RenderedImage create(ParameterBlock paramBlock, RenderingHints renderHints) { // Get ImageLayout from renderHints if any. ImageLayout layout = RIFUtil.getImageLayoutHint(renderHints); // Get BorderExtender from renderHints if any. BorderExtender extender = RIFUtil.getBorderExtenderHint(renderHints); RenderedImage source = paramBlock.getRenderedSource(0); float xScale = paramBlock.getFloatParameter(0); float yScale = paramBlock.getFloatParameter(1); // Check and see if we are scaling by 1.0 in both x and y and no // translations. If so call the copy operation. if (xScale == 1.0F && yScale == 1.0F){ return new CopyOpImage(source, renderHints, layout); } // The image is assumed to have // a MultiPixelPackedSampleModel and a byte, ushort, // or int DataBuffer we can access the pixel data directly. // Note that there is a potential loophole that has not been // resolved by Java2D as to whether the underlying DataBuffer // must be of one of the standard types. Here we make the // assumption that it will be -- we can't check without // forcing an actual tile to be computed. // SampleModel sm = source.getSampleModel(); if ((sm instanceof MultiPixelPackedSampleModel) && (sm.getSampleSize(0) == 1) && (sm.getDataType() == DataBuffer.TYPE_BYTE || sm.getDataType() == DataBuffer.TYPE_USHORT || sm.getDataType() == DataBuffer.TYPE_INT)) { int srcWidth = source.getWidth(); int srcHeight= source.getHeight(); float floatTol = .1F * Math.min(xScale/(srcWidth*xScale+1.0F), yScale/(srcHeight*yScale+1.0F)); int invScale = (int) Math.round(1.0F/xScale); if(Math.abs((float)invScale - 1.0F/xScale) < floatTol && Math.abs((float)invScale - 1.0F/yScale) < floatTol){ switch (invScale){ case 2: return new SubsampleBinaryToGray2x2OpImage(source, layout, renderHints); case 4: return new SubsampleBinaryToGray4x4OpImage(source, layout, renderHints); default: break; } } return new SubsampleBinaryToGrayOpImage(source, layout, renderHints, xScale, yScale); }else{ throw new IllegalArgumentException(JaiI18N.getString("SubsampleBinaryToGray3")); } } /** * Creates a new instance of <code>AffineOpImage</code> * in the renderable layer. This method satisfies the * implementation of CRIF. */ public RenderedImage create(RenderContext renderContext, ParameterBlock paramBlock) { return paramBlock.getRenderedSource(0); } /** * Maps the output RenderContext into the RenderContext for the ith * source. * This method satisfies the implementation of CRIF. * * @param i The index of the source image. * @param renderContext The renderContext being applied to the operation. * @param paramBlock The ParameterBlock containing the sources * and the translation factors. * @param image The RenderableImageOp from which this method * was called. */ public RenderContext mapRenderContext(int i, RenderContext renderContext, ParameterBlock paramBlock, RenderableImage image) { float scale_x = paramBlock.getFloatParameter(0); float scale_y = paramBlock.getFloatParameter(1); AffineTransform scale = new AffineTransform(scale_x, 0.0, 0.0, scale_y, 0.0, 0.0); RenderContext RC = (RenderContext)renderContext.clone(); AffineTransform usr2dev = RC.getTransform(); usr2dev.concatenate(scale); RC.setTransform(usr2dev); return RC; } /** * Gets the bounding box for the output of <code>SubsampleBinaryToGrayOpImage</code>. * This method satisfies the implementation of CRIF. */ public Rectangle2D getBounds2D(ParameterBlock paramBlock) { RenderableImage source = paramBlock.getRenderableSource(0); float scale_x = paramBlock.getFloatParameter(0); float scale_y = paramBlock.getFloatParameter(1); // Get the source dimensions float x0 = (float)source.getMinX(); float y0 = (float)source.getMinY() ; float w = (float)source.getWidth(); float h = (float)source.getHeight(); // Forward map the source using x0, y0, w and h float d_x0 = x0 * scale_x; float d_y0 = y0 * scale_y; float d_w = w * scale_x; float d_h = h * scale_y; // debugging // System.out.println("*** CRIF getBounds2D() "); return new Rectangle2D.Float(d_x0, d_y0, d_w, d_h); } }
35.540107
101
0.664309
8f94e837ace4f67e0bdebbf49f778945c2c0ec47
673
package com.sap.cec.mkt.insight.models; import com.fasterxml.jackson.annotation.JsonProperty; import com.sap.cloud.sdk.result.ElementName; public class UserDetails { @ElementName("UserID") @JsonProperty("UserID") private String userID; @ElementName("FirstName") @JsonProperty("FirstName") private String firstName; @ElementName("LastName") @JsonProperty("LastName") private String lastName; public void setUserId(String userID) { this.userID = userID; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } }
21.03125
53
0.707281
a1a9c1073f9c5f735570f628366209f35575490b
1,498
package com.ruoyi.note.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.List; /** * Description: 模块功能描述 * <p> * User: luo0412 * Date: 2021-02-26 12:16 */ @ApiModel(value = "com-ruoyi-note-domain-NoteCareer") @Data @TableName(value = "note_career") public class NoteCareer { public static final String COL_IS_RECOMMAND = "is_recommand"; /** * 主键ID */ @TableId(value = "id", type = IdType.INPUT) @ApiModelProperty(value = "主键ID") private Long id; /** * 名称 */ @TableField(value = "`name`") @ApiModelProperty(value = "名称") private String name; /** * 父级ID(顶层ID为null) */ @TableField(value = "parent_id") @ApiModelProperty(value = "父级ID(顶层ID为null)") private Long parentId; /** * 是否推荐 */ @TableField(value = "is_recommended") @ApiModelProperty(value = "是否推荐") private Byte isRecommended; @TableField(exist = false) private List<NoteCareer> children; public static final String COL_ID = "id"; public static final String COL_NAME = "name"; public static final String COL_PARENT_ID = "parent_id"; public static final String COL_IS_RECOMMENDED = "is_recommended"; }
23.777778
69
0.684246
3a4531cdd720e9f273f1acef903de072a19d3e51
9,903
package mffs.base; import com.google.common.io.ByteArrayDataInput; import dan200.computer.api.IComputerAccess; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraftforge.common.ForgeDirection; import universalelectricity.core.vector.Vector3; import universalelectricity.prefab.multiblock.TileEntityMulti; import universalelectricity.prefab.network.PacketManager; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public abstract class TileEntityInventory extends TileEntityBase implements IInventory { protected ItemStack[] inventory = new ItemStack[this.getSizeInventory()]; public List getPacketUpdate() { List objects = new ArrayList(); objects.addAll(super.getPacketUpdate()); NBTTagCompound nbt = new NBTTagCompound(); this.writeToNBT(nbt); objects.add(nbt); return objects; } public void onReceivePacket(int packetID, ByteArrayDataInput dataStream) throws IOException { super.onReceivePacket(packetID, dataStream); if (super.worldObj.isRemote && (packetID == TileEntityBase.TilePacketType.DESCRIPTION.ordinal() || packetID == TileEntityBase.TilePacketType.INVENTORY.ordinal())) { this.readFromNBT(PacketManager.readNBTTagCompound(dataStream)); } } public void sendInventoryToClients() { NBTTagCompound nbt = new NBTTagCompound(); this.writeToNBT(nbt); PacketManager.sendPacketToClients(PacketManager.getPacket("MFFS", this, TileEntityBase.TilePacketType.INVENTORY.ordinal(), nbt)); } public ItemStack getStackInSlot(int i) { return this.inventory[i]; } public String getInvName() { return this.getBlockType().getLocalizedName(); } public void setInventorySlotContents(int i, ItemStack itemstack) { this.inventory[i] = itemstack; if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { itemstack.stackSize = this.getInventoryStackLimit(); } } public ItemStack decrStackSize(int i, int j) { if (this.inventory[i] != null) { ItemStack itemstack1; if (this.inventory[i].stackSize <= j) { itemstack1 = this.inventory[i]; this.inventory[i] = null; return itemstack1; } else { itemstack1 = this.inventory[i].splitStack(j); if (this.inventory[i].stackSize == 0) { this.inventory[i] = null; } return itemstack1; } } else { return null; } } public void openChest() { } public void closeChest() { } public boolean isUseableByPlayer(EntityPlayer entityplayer) { return super.worldObj.getBlockTileEntity(super.xCoord, super.yCoord, super.zCoord) == this; } public ItemStack getStackInSlotOnClosing(int slotID) { if (this.inventory[slotID] != null) { ItemStack itemstack = this.inventory[slotID]; this.inventory[slotID] = null; return itemstack; } else { return null; } } public int getInventoryStackLimit() { return 64; } public boolean isInvNameLocalized() { return true; } public boolean isStackValidForSlot(int slotID, ItemStack itemStack) { return true; } public boolean canIncreaseStack(int slotID, ItemStack itemStack) { if (this.getStackInSlot(slotID) == null) { return true; } else { return this.getStackInSlot(slotID).stackSize + 1 <= 64 ? this.getStackInSlot(slotID).isItemEqual(itemStack) : false; } } public void incrStackSize(int slot, ItemStack itemStack) { if (this.getStackInSlot(slot) == null) { this.setInventorySlotContents(slot, itemStack.copy()); } else if (this.getStackInSlot(slot).isItemEqual(itemStack)) { ++this.getStackInSlot(slot).stackSize; } } public Set getCards() { Set cards = new HashSet(); cards.add(this.getStackInSlot(0)); return cards; } public ItemStack tryPlaceInPosition(ItemStack itemStack, Vector3 position, ForgeDirection dir) { TileEntity tileEntity = position.getTileEntity(super.worldObj); ForgeDirection direction = dir.getOpposite(); if (tileEntity != null && itemStack != null) { if (tileEntity instanceof TileEntityMulti) { Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition; if (mainBlockPosition != null && !(mainBlockPosition.getTileEntity(super.worldObj) instanceof TileEntityMulti)) { return this.tryPlaceInPosition(itemStack, mainBlockPosition, direction); } } else { int i; int i; if (tileEntity instanceof TileEntityChest) { TileEntityChest[] chests = new TileEntityChest[]{(TileEntityChest) tileEntity, null}; for (i = 2; i < 6; ++i) { ForgeDirection searchDirection = ForgeDirection.getOrientation(i); Vector3 searchPosition = position.clone(); searchPosition.modifyPositionFromSide(searchDirection); if (searchPosition.getTileEntity(super.worldObj) != null && searchPosition.getTileEntity(super.worldObj).getClass() == chests[0].getClass()) { chests[1] = (TileEntityChest) searchPosition.getTileEntity(super.worldObj); break; } } TileEntityChest[] arr$ = chests; i = chests.length; for (int i$ = 0; i$ < i; ++i$) { TileEntityChest chest = arr$[i$]; if (chest != null) { for (int i = 0; i < chest.getSizeInventory(); ++i) { itemStack = this.addStackToInventory(i, chest, itemStack); if (itemStack == null) { return null; } } } } } else if (tileEntity instanceof ISidedInventory) { ISidedInventory inventory = (ISidedInventory) tileEntity; int[] slots = inventory.getAccessibleSlotsFromSide(direction.ordinal()); for (i = 0; i < slots.length; ++i) { if (inventory.canInsertItem(slots[i], itemStack, direction.ordinal())) { itemStack = this.addStackToInventory(slots[i], inventory, itemStack); } if (itemStack == null) { return null; } } } else if (tileEntity instanceof IInventory) { IInventory inventory = (IInventory) tileEntity; for (i = 0; i < inventory.getSizeInventory(); ++i) { itemStack = this.addStackToInventory(i, inventory, itemStack); if (itemStack == null) { return null; } } } } } return itemStack.stackSize <= 0 ? null : itemStack; } public ItemStack addStackToInventory(int slotIndex, IInventory inventory, ItemStack itemStack) { if (inventory.getSizeInventory() > slotIndex) { ItemStack stackInInventory = inventory.getStackInSlot(slotIndex); if (stackInInventory == null) { inventory.setInventorySlotContents(slotIndex, itemStack); if (inventory.getStackInSlot(slotIndex) == null) { return itemStack; } return null; } if (stackInInventory.isItemEqual(itemStack) && stackInInventory.isStackable()) { stackInInventory = stackInInventory.copy(); int stackLim = Math.min(inventory.getInventoryStackLimit(), itemStack.getMaxStackSize()); int rejectedAmount = Math.max(stackInInventory.stackSize + itemStack.stackSize - stackLim, 0); stackInInventory.stackSize = Math.min(Math.max(stackInInventory.stackSize + itemStack.stackSize - rejectedAmount, 0), inventory.getInventoryStackLimit()); itemStack.stackSize = rejectedAmount; inventory.setInventorySlotContents(slotIndex, stackInInventory); } } return itemStack.stackSize <= 0 ? null : itemStack; } public boolean mergeIntoInventory(ItemStack itemStack) { if (!super.worldObj.isRemote) { ForgeDirection[] arr$ = ForgeDirection.VALID_DIRECTIONS; int len$ = arr$.length; for (int i$ = 0; i$ < len$; ++i$) { ForgeDirection direction = arr$[i$]; if (itemStack != null) { itemStack = this.tryPlaceInPosition(itemStack, (new Vector3(this)).modifyPositionFromSide(direction), direction); } } if (itemStack != null) { super.worldObj.spawnEntityInWorld(new EntityItem(super.worldObj, (double) super.xCoord + 0.5D, (double) (super.yCoord + 1), (double) super.zCoord + 0.5D, itemStack)); } } return false; } public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); NBTTagList nbtTagList = nbttagcompound.getTagList("Items"); this.inventory = new ItemStack[this.getSizeInventory()]; for (int i = 0; i < nbtTagList.tagCount(); ++i) { NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbtTagList.tagAt(i); byte byte0 = nbttagcompound1.getByte("Slot"); if (byte0 >= 0 && byte0 < this.inventory.length) { this.inventory[byte0] = ItemStack.loadItemStackFromNBT(nbttagcompound1); } } } public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); NBTTagList nbtTagList = new NBTTagList(); for (int i = 0; i < this.inventory.length; ++i) { if (this.inventory[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte) i); this.inventory[i].writeToNBT(nbttagcompound1); nbtTagList.appendTag(nbttagcompound1); } } nbttagcompound.setTag("Items", nbtTagList); } public String getType() { return this.getInvName(); } public String[] getMethodNames() { return new String[]{"isActivate", "setActivate"}; } public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception { switch (method) { case 0: return new Object[]{this.isActive()}; case 1: this.setActive((Boolean) arguments[0]); return null; default: throw new Exception("Invalid method."); } } public boolean canAttachToSide(int side) { return true; } public void attach(IComputerAccess computer) { } public void detach(IComputerAccess computer) { } }
31.239748
170
0.712915
2008da2e702401c842425742e950e8e9078bbad4
472
package com.csselect.game; /** * This class represents a termination cause in which case the * termination is only caused by a command of the organiser, it is * a null object without functionality. */ public class OrganiserTermination extends Termination { private static final String TYPE = "organiser"; @Override public boolean checkTermination() { return false; } @Override public String toString() { return TYPE; } }
22.47619
66
0.690678
7370a55671ad9abb64b1182dc720a32ec53923e5
1,870
package com.infoclinika.mssharing.model.internal.repository; import com.infoclinika.mssharing.model.internal.entity.restorable.DeletedFileMetaData; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.Collection; import java.util.List; /** * @author Elena Kurilina */ public interface DeletedFileMetaDataRepository extends CrudRepository<DeletedFileMetaData, Long> { @Query("select new com.infoclinika.mssharing.model.internal.repository.DeletedItem(e.id, e.deletionDate, e.name," + " 'file', e.instrument.lab.name) from DeletedFileMetaData e left join e.instrument.lab l " + " where e.owner.id = :owner AND " + " l in (SELECT lm.lab FROM e.owner.labMemberships lm where lm.user.id = :owner)") List<DeletedItem> findByOwner(@Param("owner") long owner); @Query("select new com.infoclinika.mssharing.model.internal.repository.DeletedItem(e.id, e.deletionDate, e.name," + " 'file', e.instrument.lab.name) from DeletedFileMetaData e where e.instrument.lab.id in (:labs)") List<DeletedItem> findByLabs(@Param("labs") Collection<Long> labs); @Query("select new com.infoclinika.mssharing.model.internal.repository.DeletedItem(e.id, e.deletionDate, e.name, " + "'file', e.instrument.lab.name) " + " from DeletedFileMetaData e") List<DeletedItem> findAllDeleted(); @Query("select f from DeletedFileMetaData f where f.instrument.id=:instrument") List<DeletedFileMetaData> byInstrument(@Param("instrument") long instrument); @Query("select f from DeletedFileMetaData f where f.owner.id = :owner AND f.instrument.lab.id = :lab") List<DeletedFileMetaData> findByOwnerAndLab(@Param("owner") long owner, @Param("lab") long lab); }
51.944444
120
0.73369
19351ca557f3f3773b762419e9d9b96635962287
1,108
package com.donkeycode.service; import java.util.List; import com.donkeycode.boot.IBaseService; import com.donkeycode.core.page.PageFilter; import com.donkeycode.core.page.PageResult; import com.donkeycode.data.entity.BaseMenu; /** * 菜单资源管理 * @author liuyadu */ public interface BaseMenuService extends IBaseService<BaseMenu> { /** * 分页查询 * * @param pageParams * @return */ PageResult<BaseMenu> findListPage(PageFilter pageParams); /** * 查询列表 * @return */ List<BaseMenu> findAllList(); /** * 根据主键获取菜单 * * @param menuId * @return */ BaseMenu getMenu(Long menuId); /** * 检查菜单编码是否存在 * * @param menuCode * @return */ Boolean isExist(String menuCode); /** * 添加菜单资源 * * @param menu * @return */ BaseMenu addMenu(BaseMenu menu); /** * 修改菜单资源 * * @param menu * @return */ BaseMenu updateMenu(BaseMenu menu); /** * 移除菜单 * * @param menuId * @return */ void removeMenu(Long menuId); }
15.828571
65
0.564982
60cdef4910049bd5d1c82f67c618c95b86709e89
841
package org.cord.ignite.mode; import org.apache.ignite.cache.affinity.AffinityKeyMapped; /** * @author: cord * @date: 2018/8/15 23:05 */ public class PersonKey { private long id; @AffinityKeyMapped private long organizationId; public PersonKey(){ } public PersonKey(long id, long organizationId){ this.id = id; this.organizationId = organizationId; } public long id(){ return id; } public long organizationId(){ return organizationId; } @Override public boolean equals(Object o){ if(this == o){ return true; } if(o == null || getClass() != o.getClass()){ return false; } PersonKey key = (PersonKey)o; return id == key.id && organizationId == key.organizationId; } }
17.893617
68
0.576694
95698b5b31ed74ac401da4c87f30ca33b38d4016
718
package org.saiku.olap.util; import org.apache.commons.lang.StringUtils; public class SaikuDictionary { public enum DateFlag { CURRENT, LAST, AGO, EXACT, CURRENTWEEK, LASTWEEK, LAST7, CURRENTMONTH, LASTMONTH, CURRENTYEAR, LASTYEAR, IGNORE }; public final static String DateFlags = "DateFlags"; public static String getAllDateFlags() { return getDateFlags(DateFlag.values()); } public static String getAllPeriodFlags() { return getDateFlags(DateFlag.CURRENT, DateFlag.LAST, DateFlag.AGO); } public static String getDateFlags(DateFlag... flags) { if (flags != null) { return StringUtils.join(flags, "|"); } return StringUtils.join(DateFlag.values(), "|"); } }
17.95
69
0.703343
313edb22c4794de5cf62457b5026aab4088f65b8
1,354
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ml.action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.HandledTransportAction; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.tasks.Task; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.core.ml.action.ValidateJobConfigAction; public class TransportValidateJobConfigAction extends HandledTransportAction<ValidateJobConfigAction.Request, AcknowledgedResponse> { @Inject public TransportValidateJobConfigAction(TransportService transportService, ActionFilters actionFilters) { super(ValidateJobConfigAction.NAME, transportService, actionFilters, ValidateJobConfigAction.Request::new); } @Override protected void doExecute(Task task, ValidateJobConfigAction.Request request, ActionListener<AcknowledgedResponse> listener) { listener.onResponse(new AcknowledgedResponse(true)); } }
43.677419
133
0.804284
d6575f08e03b4affb7460c22d73607d41c3ebbd1
4,308
package org.smartregister.domain.db.mock; import org.joda.time.DateTime; import org.smartregister.domain.Event; import org.smartregister.domain.Obs; import java.util.List; import java.util.Map; /** * Created by kaderchowdhury on 20/11/17. */ public class EventMock extends Event { public EventMock(String baseEntityId, String eventId, String eventType, DateTime eventDate, String entityType, String providerId, String locationId, String formSubmissionId) { super(baseEntityId, eventId,eventType, eventDate, entityType, providerId, locationId, formSubmissionId,null,null); } @Override public List<Obs> getObs() { return super.getObs(); } @Override public void setObs(List<Obs> obs) { super.setObs(obs); } @Override public void addObs(Obs observation) { super.addObs(observation); } @Override public String getBaseEntityId() { return super.getBaseEntityId(); } @Override public void setBaseEntityId(String baseEntityId) { super.setBaseEntityId(baseEntityId); } @Override public String getLocationId() { return super.getLocationId(); } @Override public void setLocationId(String locationId) { super.setLocationId(locationId); } @Override public DateTime getEventDate() { return super.getEventDate(); } @Override public void setEventDate(DateTime eventDate) { super.setEventDate(eventDate); } @Override public String getEventType() { return super.getEventType(); } @Override public void setEventType(String eventType) { super.setEventType(eventType); } @Override public String getFormSubmissionId() { return super.getFormSubmissionId(); } @Override public void setFormSubmissionId(String formSubmissionId) { super.setFormSubmissionId(formSubmissionId); } @Override public String getProviderId() { return super.getProviderId(); } @Override public void setProviderId(String providerId) { super.setProviderId(providerId); } @Override public String getEventId() { return super.getEventId(); } @Override public void setEventId(String eventId) { super.setEventId(eventId); } @Override public String getEntityType() { return super.getEntityType(); } @Override public void setEntityType(String entityType) { super.setEntityType(entityType); } @Override public Map<String, String> getDetails() { return super.getDetails(); } @Override public void setDetails(Map<String, String> details) { super.setDetails(details); } @Override public void addDetails(String key, String val) { super.addDetails(key, val); } @Override public long getVersion() { return super.getVersion(); } @Override public void setVersion(long version) { super.setVersion(version); } @Override public Obs findObs(String parentId, boolean nonEmpty, String... fieldIds) { return super.findObs(parentId, nonEmpty, fieldIds); } @Override public Event withBaseEntityId(String baseEntityId) { return super.withBaseEntityId(baseEntityId); } @Override public Event withLocationId(String locationId) { return super.withLocationId(locationId); } @Override public Event withEventDate(DateTime eventDate) { return super.withEventDate(eventDate); } @Override public Event withEventType(String eventType) { return super.withEventType(eventType); } @Override public Event withFormSubmissionId(String formSubmissionId) { return super.withFormSubmissionId(formSubmissionId); } @Override public Event withProviderId(String providerId) { return super.withProviderId(providerId); } @Override public Event withEntityType(String entityType) { return super.withEntityType(entityType); } public Event withObs(List<Obs> obs) { return super.withObs(obs); } @Override public Event withObs(Obs observation) { return super.withObs(observation); } }
22.673684
179
0.660631
83d1070bd53f5ec04641a58ac8a3e8b9d0122a3c
52
package administracao; public class matricula { }
8.666667
24
0.769231
da8a5cf185848b21f3f686f18e7e686473932782
3,140
package edu.cooper.ece366.project.borsa.server.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import edu.cooper.ece366.project.borsa.server.exception.ResourceNotFoundException; import edu.cooper.ece366.project.borsa.server.model.Asset; import edu.cooper.ece366.project.borsa.server.model.Portfolio; import edu.cooper.ece366.project.borsa.server.model.User; import edu.cooper.ece366.project.borsa.server.repository.AssetRepository; import edu.cooper.ece366.project.borsa.server.repository.PortfolioRepository; import edu.cooper.ece366.project.borsa.server.repository.UserRepository; import edu.cooper.ece366.project.borsa.server.security.CurrentUser; import edu.cooper.ece366.project.borsa.server.security.UserPrincipal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.sound.sampled.Port; import java.util.List; @RestController @RequestMapping("/portfolios") public class AssetController { private static final Logger LOGGER = LoggerFactory.getLogger(AssetController.class); private ObjectMapper objectMapper = new ObjectMapper(); @Autowired private UserRepository userRepository; @Autowired private PortfolioRepository portfolioRepository; @Autowired private AssetRepository assetRepository; @GetMapping("/portfolio/assets") // TODO wire up to database calls via User -> Portfolio -> Asset @PreAuthorize("hasRole('USER')") public ResponseEntity<List<Asset>> getAssetsByUserId(@CurrentUser UserPrincipal userPrincipal) throws JsonProcessingException { Portfolio portfolio = portfolioRepository.findByUserId(userPrincipal.getId()) .orElseThrow(() -> new ResourceNotFoundException("User","id",userPrincipal.getId())); List<Asset> assets = assetRepository.findByPortfolio(portfolio) .orElseThrow(() -> new ResourceNotFoundException("Portfolio","id",portfolio.getId())); return new ResponseEntity<List<Asset>>(assets, HttpStatus.OK); } @PostMapping("/portfolio/assets/add") @PreAuthorize("hasRole('USER')") public ResponseEntity<Asset> addAsset(@CurrentUser UserPrincipal userPrincipal, @RequestBody Asset assetRequest) { // User user = userRepository.findById(userPrincipal.getId()) // .orElseThrow(() -> new ResourceNotFoundException("User","id",userPrincipal.getId())); Long userId = userPrincipal.getId(); Portfolio portfolio = portfolioRepository.findByUserId(userPrincipal.getId()) .orElseThrow(() -> new ResourceNotFoundException("Portfolio","id",userId)); assetRequest.setPortfolio(portfolio); Asset asset = assetRepository.save(assetRequest); return new ResponseEntity<Asset>(asset, HttpStatus.CREATED); } }
48.307692
103
0.756051
c7066f222fb4472c318468103145b80a83ddfed6
1,993
/** * * Copyright 2004-2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.interop.properties; public class PropertyLog { public static PropertyLog getInstance(String instanceName) { PropertyLog log = new PropertyLog(); log.init(instanceName); return log; } private String instanceName; public String getInstanceName() { return instanceName; } protected void init(String instanceName) { this.instanceName = instanceName; } public void debugUsingValue(String value) { System.out.println("PropertyLog.debugUsingValue(): NEEDS IMPLEMENTATION??"); } public void debugUsingDefaultValue(String defaultValue) { System.out.println("PropertyLog.debugUsingValue(): NEEDS IMPLEMENTATION??"); } public String errorMissingValueForRequiredProperty(String property, String context) { String msg = "PropertyLog.errorMissingValueForRequiredProperty(): property: " + property + ", context: " + context; System.out.println(msg); return msg; } public String errorMissingValueForRequiredSystemProperty(String property, String refProperty, String context) { String msg = "PropertyLog.errorMissingValueForRequiredSystemProperty(): property: " + property + ", refProperty: " + refProperty + ", context: " + context; System.out.println(msg); return msg; } }
34.964912
163
0.70296
d2329e6e821d4d0247bef5e00f74a211ba2256a1
1,249
package com.android.volley.orientation; /** * Created by Administrator on 2016/10/21. */ public class OrientationOperationFactory { public static OrientationOperation createOrientationOperation(int number) { OrientationOperation orientationOperation = null; switch (number) { case 1: orientationOperation = new Orientation1Operation(); break; case 2: orientationOperation = new Orientation2Operation(); break; case 3: orientationOperation = new Orientation3Operation(); break; case 4: orientationOperation = new Orientation4Operation(); break; case 5: orientationOperation = new Orientation5Operation(); break; case 6: orientationOperation = new Orientation6Operation(); break; case 7: orientationOperation = new Orientation7Operation(); break; case 8: orientationOperation = new Orientation8Operation(); break; } return orientationOperation; } }
27.755556
79
0.548439
a7b39d99ac4620a4005065231273f65494310282
332
package com.nlf.extend.session; import com.nlf.App; /** * session配置 */ public class SessionConfig { /** 默认保持秒数 */ public static final int DEFAULT_MAX_INACTIVE_INTERVAL = 1800; /** 保持秒数 */ public static final int MAX_INACTIVE_INTERVAL = App.getPropertyInt("session.max_inactive_interval",DEFAULT_MAX_INACTIVE_INTERVAL); }
25.538462
132
0.759036
f69c6bd80d1f86108cc6fee409734eeb27770d13
975
package com.tencentcloud.spring.boot.tim.resp.callback; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** *单聊消息已读上报后回调 * https://cloud.tencent.com/document/product/269/61696 */ @Data @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = false) public class C2cAfterMsgReport { /** * 回调命令 - C2C.CallbackAfterMsgReport */ @JsonProperty(value = "CallbackCommand") private String command; /** * 已读上报方 UserID */ @JsonProperty(value = "Report_Account") private String report; /** * 会话对端 UserID */ @JsonProperty(value = "Peer_Account") private String peer; /** * 已读时间 */ @JsonProperty(value = "LastReadTime") private Integer lastReadTime; /** * Report_Account 未读的单聊消息总数量(包含所有的单聊会话) */ @JsonProperty(value = "UnreadMsgNum") private Integer unreadMsgNum; }
19.897959
61
0.735385
d27ee09d286066b33dd0641d43db148b937b01b5
130
package projects.nyinyihtunlwin.news.network; /** * Created by Dell on 12/9/2017. */ public abstract class MMNewsResponse { }
14.444444
45
0.730769
9c258267a3a5f3b4c3001c1a8cbaa8451c33ee72
1,956
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.komamitsu.fluency.treasuredata.ingester; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.ingester.sender.Sender; import org.komamitsu.fluency.treasuredata.ingester.sender.TreasureDataSender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; public class TreasureDataIngester implements Ingester { private static final Logger LOG = LoggerFactory.getLogger(TreasureDataIngester.class); private final Config config; private final TreasureDataSender sender; public TreasureDataIngester(Config config, TreasureDataSender sender) { this.config = config; this.sender = sender; } @Override public void ingest(String tag, ByteBuffer dataBuffer) throws IOException { sender.send(tag, dataBuffer); } @Override public Sender getSender() { return sender; } @Override public void close() throws IOException { sender.close(); } public static class Config implements Instantiator<TreasureDataSender> { @Override public TreasureDataIngester createInstance(TreasureDataSender sender) { return new TreasureDataIngester(this, sender); } } }
27.549296
90
0.707566
9fe4458fa21b8494deb48bde584ae462de6ce2b8
2,953
package dev.cheerfun.pixivic.biz.web.comment.mapper; import dev.cheerfun.pixivic.biz.web.comment.po.Comment; import org.apache.ibatis.annotations.*; import java.util.List; public interface CommentMapper { @Insert("insert into comments (app_type, app_id,parent_id,reply_from,reply_from_name,reply_to,reply_to_name,content,create_date,liked_count,platform) " + "values (#{appType}, #{appId}, #{parentId}, #{replyFrom}, #{replyFromName},#{replyTo},#{replyToName}, #{content}, #{createDate,typeHandler=org.apache.ibatis.type.LocalDateTimeTypeHandler}, #{likedCount},#{platform})") @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "comment_id") int pushComment(Comment comment); @Select("select * from comments where app_type = #{appType} and app_id = #{appId}") @Results({ @Result(property = "id", column = "comment_id"), @Result(property = "appType", column = "app_type"), @Result(property = "appId", column = "app_id"), @Result(property = "parentId", column = "parent_id"), @Result(property = "replyTo", column = "reply_to"), @Result(property = "replyToName", column = "reply_to_name"), @Result(property = "replyFrom", column = "reply_from"), @Result(property = "replyFromName", column = "reply_from_name"), @Result(property = "createDate", column = "create_Date", typeHandler = org.apache.ibatis.type.LocalDateTimeTypeHandler.class), @Result(property = "likedCount", column = "liked_count") }) List<Comment> pullComment(String appType, Integer appId); @Update("replace into comment_summary (app_type, app_id, top_comment_count) select #{appType}, #{appId} ,count(*) from comments where app_type= #{appType} and app_id=#{appId} and parent_id=0") Integer countCommentSummary(String appType, String appId); @Select("select top_comment_count from comment_summary where app_type =#{appType} and app_id=#{appId}") Integer queryTopCommentCount(String appType, Integer appId); @Select("select * from comments where comment_id = #{commentId} ") @Results({ @Result(property = "id", column = "comment_id"), @Result(property = "appType", column = "app_type"), @Result(property = "appId", column = "app_id"), @Result(property = "parentId", column = "parent_id"), @Result(property = "replyTo", column = "reply_to"), @Result(property = "replyToName", column = "reply_to_name"), @Result(property = "replyFrom", column = "reply_from"), @Result(property = "replyFromName", column = "reply_from_name"), @Result(property = "createDate", column = "create_Date", typeHandler = org.apache.ibatis.type.LocalDateTimeTypeHandler.class), @Result(property = "likedCount", column = "liked_count") }) Comment queryCommentById(Integer commentId); }
59.06
229
0.663393
eddbb7e46c6b9e6adfa04315a9b6b565d875a04d
1,988
package dk.jarry.todo.entity; import java.time.ZonedDateTime; import java.util.UUID; public class ToDo { private String id; private String subject; private String body; private ZonedDateTime created; private ZonedDateTime updated; private ZonedDateTime start; private ZonedDateTime end; private Integer priority; private Integer importens; private String owner; private String createBy; private String updatedBy; public ToDo() { this.id = UUID.randomUUID().toString(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public ZonedDateTime getCreated() { return created; } public void setCreated(ZonedDateTime created) { this.created = created; } public ZonedDateTime getUpdated() { return updated; } public void setUpdated(ZonedDateTime updated) { this.updated = updated; } public ZonedDateTime getStart() { return start; } public void setStart(ZonedDateTime start) { this.start = start; } public ZonedDateTime getEnd() { return end; } public void setEnd(ZonedDateTime end) { this.end = end; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Integer getImportens() { return importens; } public void setImportens(Integer importens) { this.importens = importens; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } }
15.653543
48
0.711268
140a7224a326c71888bff3a5e26d4ad040101630
9,251
/* * 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.sling.jcr.resource.internal.helper.jcr; import static javax.jcr.Property.JCR_CONTENT; import static javax.jcr.Property.JCR_CREATED; import static javax.jcr.Property.JCR_DATA; import static javax.jcr.Property.JCR_ENCODING; import static javax.jcr.Property.JCR_FROZEN_PRIMARY_TYPE; import static javax.jcr.Property.JCR_LAST_MODIFIED; import static javax.jcr.Property.JCR_MIMETYPE; import static javax.jcr.nodetype.NodeType.NT_FILE; import static javax.jcr.nodetype.NodeType.NT_FROZEN_NODE; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.RepositoryException; import javax.jcr.ValueFormatException; import org.apache.sling.api.resource.ResourceMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class JcrNodeResourceMetadata extends ResourceMetadata { private static final long serialVersionUID = 1L; /** default log */ private static final Logger LOGGER = LoggerFactory.getLogger(JcrNodeResource.class); private final Node node; private Node contentNode; private boolean nodePromotionChecked = false; private long creationTime = -1; private boolean populated = false; public JcrNodeResourceMetadata(final Node inNode) { this.node = inNode; } private javax.jcr.Node promoteNode() { // check stuff for nt:file nodes try { if ((!nodePromotionChecked) && (node.isNodeType(javax.jcr.nodetype.NodeType.NT_FILE) || (node.isNodeType(javax.jcr.nodetype.NodeType.NT_FROZEN_NODE) && node.getProperty(javax.jcr.Property.JCR_FROZEN_PRIMARY_TYPE).getString().equals(javax.jcr.nodetype.NodeType.NT_FILE)))) { creationTime = node.getProperty(javax.jcr.Property.JCR_CREATED).getLong(); // continue our stuff with the jcr:content node // which might be nt:resource, which we support below // if the node is new, the content node might not exist yet if ((!node.isNew()) || node.hasNode(javax.jcr.Property.JCR_CONTENT)) { contentNode = node.getNode(javax.jcr.Property.JCR_CONTENT); } nodePromotionChecked = true; } } catch (final javax.jcr.RepositoryException re) { report(re); } return /* NPEX_NULL_EXP */ contentNode; } private void report(final RepositoryException re) { String nodePath = "<unknown node path>"; try { nodePath = contentNode != null ? contentNode.getPath() : node.getPath(); } catch (RepositoryException e) { // ignore } LOGGER.info( "setMetaData: Problem extracting metadata information for " + nodePath, re); } @Override public Object get(final Object key) { final Object result = super.get(key); if (result != null) { return result; } if (CREATION_TIME.equals(key)) { promoteNode(); internalPut(CREATION_TIME, creationTime); return creationTime; } else if (CONTENT_TYPE.equals(key)) { String contentType = null; final Node targetNode = promoteNode(); try { if (targetNode.hasProperty(JCR_MIMETYPE)) { contentType = targetNode.getProperty(JCR_MIMETYPE).getString(); } } catch (final RepositoryException re) { report(re); } internalPut(CONTENT_TYPE, contentType); return contentType; } else if (CHARACTER_ENCODING.equals(key)) { String characterEncoding = null; final Node targetNode = promoteNode(); try { if (targetNode.hasProperty(JCR_ENCODING)) { characterEncoding = targetNode.getProperty(JCR_ENCODING).getString(); } } catch (final RepositoryException re) { report(re); } internalPut(CHARACTER_ENCODING, characterEncoding); return characterEncoding; } else if (MODIFICATION_TIME.equals(key)) { long modificationTime = -1; final Node targetNode = promoteNode(); try { if (targetNode.hasProperty(JCR_LAST_MODIFIED)) { // We don't check node type, so JCR_LASTMODIFIED might not be a long final Property prop = targetNode.getProperty(JCR_LAST_MODIFIED); try { modificationTime = prop.getLong(); } catch (final ValueFormatException vfe) { LOGGER.debug("Property {} cannot be converted to a long, ignored ({})", prop.getPath(), vfe); } } } catch (final RepositoryException re) { report(re); } internalPut(MODIFICATION_TIME, modificationTime); return modificationTime; } else if (CONTENT_LENGTH.equals(key)) { long contentLength = -1; final Node targetNode = promoteNode(); try { // if the node has a jcr:data property, use that property if (targetNode.hasProperty(JCR_DATA)) { final Property prop = targetNode.getProperty(JCR_DATA); contentLength = JcrItemResource.getContentLength(prop); } else { // otherwise try to follow default item trail Item item = getPrimaryItem(targetNode); while (item != null && item.isNode()) { item = getPrimaryItem((Node) item); } if ( item != null ) { final Property data = (Property) item; // set the content length property as a side effect // for resources which are not nt:file based and whose // data is not in jcr:content/jcr:data this will lazily // set the correct content length contentLength = JcrItemResource.getContentLength(data); } } } catch (final RepositoryException re) { report(re); } internalPut(CONTENT_LENGTH, contentLength); return contentLength; } return null; } private Item getPrimaryItem(final Node node) throws RepositoryException { String name = node.getPrimaryNodeType().getPrimaryItemName(); if (name == null) { return null; } if (node.hasProperty(name)) { return node.getProperty(name); } else if (node.hasNode(name)) { return node.getNode(name); } else { return null; } } private void populate() { if (populated) { return; } get(CREATION_TIME); get(CONTENT_TYPE); get(CHARACTER_ENCODING); get(MODIFICATION_TIME); get(CONTENT_LENGTH); populated = true; } @Override public Set<Map.Entry<String, Object>> entrySet() { populate(); return super.entrySet(); } @Override public Set<String> keySet() { populate(); return super.keySet(); } @Override public Collection<Object> values() { populate(); return super.values(); } @Override public int size() { populate(); return super.size(); } @Override public boolean isEmpty() { return false; } @Override public boolean containsKey(final Object key) { if (super.containsKey(key)) { return true; } if (CREATION_TIME.equals(key) || CONTENT_TYPE.equals(key) || CHARACTER_ENCODING.equals(key) || MODIFICATION_TIME.equals(key) || CONTENT_LENGTH.equals(key)) { return true; } return false; } @Override public boolean containsValue(final Object value) { if (super.containsValue(value)) { return true; } if (!populated) { populate(); return super.containsValue(value); } return false; } }
34.909434
281
0.592476