hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e17558213a774cdcf4a1dd4a4462c48c0d79472
772
java
Java
src/main/java/mil/nga/crs/engineering/EngineeringDatum.java
ngageoint/coordinate-reference-systems-java
2567d52c1c64aeba3052f958923bf2e3d3dc4664
[ "MIT" ]
4
2021-06-24T14:19:01.000Z
2022-01-03T22:15:23.000Z
src/main/java/mil/nga/crs/engineering/EngineeringDatum.java
ngageoint/coordinate-reference-systems-java
2567d52c1c64aeba3052f958923bf2e3d3dc4664
[ "MIT" ]
null
null
null
src/main/java/mil/nga/crs/engineering/EngineeringDatum.java
ngageoint/coordinate-reference-systems-java
2567d52c1c64aeba3052f958923bf2e3d3dc4664
[ "MIT" ]
5
2021-06-24T16:53:43.000Z
2022-03-17T22:17:19.000Z
14.566038
54
0.632124
9,939
package mil.nga.crs.engineering; import mil.nga.crs.CRSType; import mil.nga.crs.common.ReferenceFrame; /** * Engineering Datum * * @author osbornb */ public class EngineeringDatum extends ReferenceFrame { /** * Constructor */ public EngineeringDatum() { super(CRSType.ENGINEERING); } /** * Constructor * * @param name * name */ public EngineeringDatum(String name) { super(name, CRSType.ENGINEERING); } /** * {@inheritDoc} */ @Override public int hashCode() { return super.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; return true; } }
3e1755c5a6718be8df138b2c2632670f773cef47
1,812
java
Java
shared/src/main/java/cn/edu/tsinghua/iginx/utils/Bitmap.java
Shoothzj/IginX
75a3b7dba9f28da90f0240980077dff1f07a3d88
[ "Apache-2.0" ]
16
2021-03-08T07:03:57.000Z
2022-03-24T21:31:44.000Z
shared/src/main/java/cn/edu/tsinghua/iginx/utils/Bitmap.java
Shoothzj/IginX
75a3b7dba9f28da90f0240980077dff1f07a3d88
[ "Apache-2.0" ]
38
2021-03-19T06:10:51.000Z
2022-01-21T03:34:46.000Z
shared/src/main/java/cn/edu/tsinghua/iginx/utils/Bitmap.java
Shoothzj/IginX
75a3b7dba9f28da90f0240980077dff1f07a3d88
[ "Apache-2.0" ]
13
2021-03-08T07:09:24.000Z
2022-02-22T12:28:17.000Z
29.704918
69
0.636313
9,940
/* * 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 cn.edu.tsinghua.iginx.utils; public class Bitmap { private final int size; private final byte[] bitmap; public Bitmap(int size) { this.size = size; this.bitmap = new byte[(int) Math.ceil(this.size * 1.0 / 8)]; } public Bitmap(int size, byte[] bitmap) { this.size = size; this.bitmap = bitmap; } public void mark(int i) { if (i < 0 || i >= size) throw new IllegalArgumentException("unexpected index"); int index = i / 8; int indexWithinByte = i % 8; bitmap[index] |= (1 << indexWithinByte); } public boolean get(int i) { if (i < 0 || i >= size) throw new IllegalArgumentException("unexpected index"); int index = i / 8; int indexWithinByte = i % 8; return (bitmap[index] & (1 << indexWithinByte)) != 0; } public byte[] getBytes() { return this.bitmap; } public int getSize() { return size; } }
3e17566bdc02d4e4c6a5a9e25c16bee6124cbe04
1,544
java
Java
android/app/src/main/java/net/zygotelabs/locker/MainActivity.java
Benderr-TP/Locker
af1ce883af194915d7447ac7c746c1414ae81174
[ "MIT" ]
2
2017-11-14T19:27:18.000Z
2019-08-08T11:17:44.000Z
android/app/src/main/java/net/zygotelabs/locker/MainActivity.java
Benderr-TP/Locker
af1ce883af194915d7447ac7c746c1414ae81174
[ "MIT" ]
null
null
null
android/app/src/main/java/net/zygotelabs/locker/MainActivity.java
Benderr-TP/Locker
af1ce883af194915d7447ac7c746c1414ae81174
[ "MIT" ]
5
2017-03-07T11:53:00.000Z
2020-10-12T06:32:26.000Z
28.592593
95
0.752591
9,941
package net.zygotelabs.locker; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new MainFragment()).commit(); } } public void onCheckboxClicked(View view){ MainFragment fragment = (MainFragment) getFragmentManager().findFragmentById(R.id.container); boolean checked = ((CheckBox) view).isChecked(); fragment.onCheckBoxClicked(checked); } public void enableProtection(View view){ MainFragment fragment = (MainFragment) getFragmentManager().findFragmentById(R.id.container); fragment.toggleLockProtection(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3e17569c150e7d83bad87ee8deacd46781bd17de
423
java
Java
src/Irretors/Irretors/Weekdays/Main.java
Trinity7509/JavaAdvancedOOP
2f831d596ae014af30e2e949ebc02130a3409786
[ "MIT" ]
1
2019-04-09T19:39:26.000Z
2019-04-09T19:39:26.000Z
src/Irretors/Irretors/Weekdays/Main.java
Trinity7509/JavaAdvancedOOP
2f831d596ae014af30e2e949ebc02130a3409786
[ "MIT" ]
null
null
null
src/Irretors/Irretors/Weekdays/Main.java
Trinity7509/JavaAdvancedOOP
2f831d596ae014af30e2e949ebc02130a3409786
[ "MIT" ]
null
null
null
30.214286
70
0.635934
9,942
package Irretors.Irretors.Weekdays; public class Main { public static void main(String[] args) { WeeklyCalendar calendar = new WeeklyCalendar(); calendar.addEntry("Friday", "sleep"); calendar.addEntry("Monday", "sport"); Iterable<WeeklyEntry> schedule = calendar.getWeeklySchedule(); for (WeeklyEntry entry : schedule) { System.out.println(entry); } } }
3e1757c08204494ea7e4a4615ea20477b45477cd
1,067
java
Java
core/src/main/java/org/tdar/core/bean/notification/emails/AccessRequestGrantedMessage.java
kant/tdar
c926c5b195694aa55dbd309986588ec9e8aac4a0
[ "Apache-2.0" ]
3
2016-02-29T19:36:49.000Z
2019-07-12T23:56:48.000Z
core/src/main/java/org/tdar/core/bean/notification/emails/AccessRequestGrantedMessage.java
kant/tdar
c926c5b195694aa55dbd309986588ec9e8aac4a0
[ "Apache-2.0" ]
58
2019-11-13T07:10:23.000Z
2022-03-31T17:57:07.000Z
core/src/main/java/org/tdar/core/bean/notification/emails/AccessRequestGrantedMessage.java
kant/tdar
c926c5b195694aa55dbd309986588ec9e8aac4a0
[ "Apache-2.0" ]
3
2018-11-17T03:45:35.000Z
2020-08-13T01:23:36.000Z
29.638889
119
0.703843
9,943
package org.tdar.core.bean.notification.emails; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import org.tdar.configuration.TdarConfiguration; import org.tdar.core.bean.notification.Email; import org.tdar.core.bean.resource.Resource; @Entity @DiscriminatorValue("ACCESS_GRANTED") public class AccessRequestGrantedMessage extends Email { private static final String DATE_FORMAT = "yyyy-MM-dd"; /** * */ private static final long serialVersionUID = 6549896844646538119L; @Override public String createSubjectLine() { Resource resource = (Resource) getMap().get(EmailKeys.RESOURCE); Date expires = (Date) getMap().get(EmailKeys.EXPIRES); String until = ""; if (expires != null) { until = " until " + new SimpleDateFormat(DATE_FORMAT).format(expires); } return TdarConfiguration.getInstance().getSiteAcronym() + ": Access Granted to " + resource.getTitle() + until; } }
3e17591325d24e350f4c9f616952a520bb456e23
533
java
Java
iwxxmCore/src/test/resources/iwxxm/3.1/output/org/w3/_1999/xlink/package-info.java
cb-steven-matison/iwxxmConverter
b2c0ac96f23680c667db11183d0689bc28cddf80
[ "Apache-2.0" ]
8
2019-12-18T06:46:04.000Z
2020-10-14T10:13:56.000Z
iwxxmCore/src/test/resources/iwxxm/3.1/output/org/w3/_1999/xlink/package-info.java
cb-steven-matison/iwxxmConverter
b2c0ac96f23680c667db11183d0689bc28cddf80
[ "Apache-2.0" ]
8
2019-07-15T12:51:38.000Z
2022-01-10T11:06:54.000Z
iwxxmCore/src/test/resources/iwxxm/3.1/output/org/w3/_1999/xlink/package-info.java
cb-steven-matison/iwxxmConverter
b2c0ac96f23680c667db11183d0689bc28cddf80
[ "Apache-2.0" ]
7
2019-06-11T10:25:12.000Z
2020-10-14T10:13:58.000Z
53.3
149
0.73546
9,944
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2019.05.06 at 11:11:25 PM MSK // @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/1999/xlink", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.w3._1999.xlink;
3e17598a87442a2c92290c0d2a16cdc69d915be9
925
java
Java
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/postgres/PostgresScriptExecutor.java
lifecycle-broker-providers/postgres-data-provider
cc4e25f4aaf56ce1b293b1a96c1df9987cf027dc
[ "Apache-2.0" ]
null
null
null
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/postgres/PostgresScriptExecutor.java
lifecycle-broker-providers/postgres-data-provider
cc4e25f4aaf56ce1b293b1a96c1df9987cf027dc
[ "Apache-2.0" ]
null
null
null
src/main/java/org/cloudfoundry/community/servicebroker/datalifecycle/postgres/PostgresScriptExecutor.java
lifecycle-broker-providers/postgres-data-provider
cc4e25f4aaf56ce1b293b1a96c1df9987cf027dc
[ "Apache-2.0" ]
null
null
null
34.259259
72
0.765405
9,945
package org.cloudfoundry.community.servicebroker.datalifecycle.postgres; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.core.io.ByteArrayResource; import org.springframework.jdbc.datasource.init.ScriptUtils; public class PostgresScriptExecutor { private Logger log = Logger.getLogger(PostgresScriptExecutor.class); public void execute(String script, Map<String, Object> creds) throws SQLException { String username = (String) creds.get("username"); String password = (String) creds.get("password"); String uri = "jdbc:" + (String) creds.get("uri"); log.info("Sanitizing " + uri + " " + " as " + username); Connection connection = DriverManager.getConnection(uri, username, password); ScriptUtils.executeSqlScript(connection, new ByteArrayResource(script.getBytes())); } }
3e1759a09c4463ae602a9520cd9f25c969324aaf
1,618
java
Java
src/main/java/seedu/ezwatchlist/model/show/RunningTime.java
tswuxia/main
936145b41747c7314f86108cb5b648d363569315
[ "MIT" ]
null
null
null
src/main/java/seedu/ezwatchlist/model/show/RunningTime.java
tswuxia/main
936145b41747c7314f86108cb5b648d363569315
[ "MIT" ]
null
null
null
src/main/java/seedu/ezwatchlist/model/show/RunningTime.java
tswuxia/main
936145b41747c7314f86108cb5b648d363569315
[ "MIT" ]
null
null
null
27.896552
93
0.647713
9,946
package seedu.ezwatchlist.model.show; import static java.util.Objects.requireNonNull; import static seedu.ezwatchlist.commons.util.AppUtil.checkArgument; /** * Represents a Show's Running Time in the watchlist. * Guarantees: immutable. */ public class RunningTime { // For now the running time will be an integer, since that is what the API returns it as. public static final String MESSAGE_CONSTRAINTS = "Running time can take any integer values, and it should not be blank"; public static final String MESSAGE_CONSTRAINTS2 = "Running time can take only positive values or zero."; public final int value; public RunningTime() { value = 0; } /** * Constructs an {@code RunningTime}. * * @param runningTime A valid running time. */ public RunningTime(int runningTime) { requireNonNull(runningTime); checkArgument(isValidRunningTime(runningTime), MESSAGE_CONSTRAINTS2); value = runningTime; } /** * Returns true if a given integer is a valid running time. */ public static boolean isValidRunningTime(int test) { return test >= 0; } @Override public String toString() { return String.valueOf(value); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof RunningTime // instanceof handles nulls && value == ((RunningTime) other).value); // state check } @Override public int hashCode() { return value; } }
3e1759fdd7fb6f22c807b41dcbf50f32ed9b1f74
6,795
java
Java
algorithm/src/ex6/BTreeTest2.java
Eskeptor/ComReport
83a6fad2d8f3b585b31e6f9ce5e39d0a6e168fc2
[ "MIT" ]
null
null
null
algorithm/src/ex6/BTreeTest2.java
Eskeptor/ComReport
83a6fad2d8f3b585b31e6f9ce5e39d0a6e168fc2
[ "MIT" ]
null
null
null
algorithm/src/ex6/BTreeTest2.java
Eskeptor/ComReport
83a6fad2d8f3b585b31e6f9ce5e39d0a6e168fc2
[ "MIT" ]
null
null
null
27.399194
156
0.529948
9,947
package ex6; import java.util.Map; import java.util.Random; import java.util.TreeMap; public class BTreeTest2 { private final BTree<Integer, String> mBTree; private final Map<Integer, String> mMap; private BTreeTest2.BTTestIteratorImpl<Integer, String> mIter; public BTreeTest2() { mBTree = new BTree<Integer, String>(); mMap = new TreeMap<Integer, String>(); mIter = new BTreeTest2.BTTestIteratorImpl<Integer, String>(); } public BTree<Integer, String> getBTree() { return mBTree; } public BTNode<Integer, String> getRootNode() { return mBTree.getRootNode(); } protected void add(Integer key, String value) { mMap.put(key, value); mBTree.insert(key, value); } protected void delete(Integer key) throws BTException { System.out.println("Delete key = " + key); String strVal1 = mMap.remove(key); String strVal2 = mBTree.delete(key); if (!isEqual(strVal1, strVal2)) { throw new BTException("Deleted key = " + key + " has different values: " + strVal1 + " | " + strVal2); } } private void clearData() { mBTree.clear(); mMap.clear(); } public void listItems(BTIteratorIF<Integer, String> iterImpl) { mBTree.list(iterImpl); } private boolean isEqual(String strVal1, String strVal2) { if ((strVal1 == null) && (strVal2 == null)) { return true; } if ((strVal1 == null) && (strVal2 != null)) { return false; } if ((strVal1 != null) && (strVal2 == null)) { return false; } if (!strVal1.equals(strVal2)) { return false; } return true; } public void validateSize() throws BTException { System.out.println("Validate size ..."); if (mMap.size() != mBTree.size()) { throw new BTException("Error in validateSize(): Failed to compare the size: " + mMap.size() + " <> " + mBTree.size()); } } public void validateSearch(Integer key) throws BTException { System.out.println("Validate search for key = " + key + " ..."); String strVal1 = mMap.get(key); String strVal2 = mBTree.search(key); if (!isEqual(strVal1, strVal2)) { throw new BTException("Error in validateSearch(): Failed to compare value for key = " + key); } } public void validateData() throws BTException { System.out.println("Validate data ..."); for (Map.Entry<Integer, String> entry : mMap.entrySet()) { try { // System.out.println("Search key = " + entry.getKey()); String strVal = mBTree.search(entry.getKey()); if (!isEqual(entry.getValue(), strVal)) { throw new BTException("Error in validateData(): Failed to compare value for key = " + entry.getKey()); } } catch (Exception ex) { ex.printStackTrace(); throw new BTException("Runtime Error in validateData(): Failed to compare value for key = " + entry.getKey() + " msg = " + ex.getMessage()); } } } public void validateOrder() throws BTException { System.out.println("Validate the order of the keys ..."); mIter.reset(); mBTree.list(mIter); if (!mIter.getStatus()) { throw new BTException("Error in validateData(): Failed to compare value for key = " + mIter.getCurrentKey()); } } public boolean validateAll() throws BTException { validateData(); validateSize(); validateOrder(); return true; } public void addKey(int i) { add(i, "value-" + i); } public void validateTestCase0() throws BTException { System.out.println("[B 트리 생성]"); add(1, "key1"); add(2, "key2"); add(3, "key3"); add(4, "key4"); add(5, "key5"); add(6, "key6"); add(7, "key7"); add(8, "key8"); add(9, "key9"); add(10, "key10"); add(13, "key13"); add(15, "key15"); add(17, "key17"); add(19, "key19"); add(20, "key20"); add(23, "key23"); add(25, "key25"); add(27, "key27"); add(28, "key28"); add(30, "key30"); add(31, "key31"); add(33, "key33"); add(34, "key34"); add(35, "key35"); add(36, "key36"); add(37, "key37"); add(38, "key38"); add(39, "key39"); add(40, "key40"); add(41, "key41"); add(45, "key45"); System.out.println("[B 트리 생성 완료]"); System.out.println("[B 트리 검증 시작]"); if(validateAll()) System.out.println("[B 트리 검증 완료]"); else System.out.println("[B 트리 검증 실패]"); } /* Main Entry for the test * param : args */ public static void main(String []args) { BTreeTest2 test = new BTreeTest2(); try { test.validateTestCase0(); System.out.println("BTree validation is successfully complete."); } catch (BTException btex) { System.out.println("BTException msg = " + btex.getMessage()); btex.printStackTrace(); } catch (Exception ex) { System.out.println("BTException msg = " + ex.getMessage()); ex.printStackTrace(); } } // // Randomly generate integer within the specified range // public static int randInt(int min, int max) { Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; } /* Inner class to implement BTree iterator */ class BTTestIteratorImpl<K extends Comparable, V> implements BTIteratorIF<K, V> { private K mCurrentKey; private K mPreviousKey; private boolean mStatus; public BTTestIteratorImpl() { reset(); } @Override public boolean item(K key, V value) { mCurrentKey = key; if ((mPreviousKey != null) && (mPreviousKey.compareTo(key) > 0)) { mStatus = false; return false; } mPreviousKey = key; return true; } public boolean getStatus() { return mStatus; } public K getCurrentKey() { return mCurrentKey; } public final void reset() { mPreviousKey = null; mStatus = true; } } }
3e175b4010389a64711d66499f45c3d9a4dc953d
191
java
Java
src/test/java/com/binavy/sawtooth/TestSample.java
binavy/sawtooth-java
ec3e7d32e5901034698779fd23760ff2e8fc81f3
[ "Apache-2.0" ]
null
null
null
src/test/java/com/binavy/sawtooth/TestSample.java
binavy/sawtooth-java
ec3e7d32e5901034698779fd23760ff2e8fc81f3
[ "Apache-2.0" ]
null
null
null
src/test/java/com/binavy/sawtooth/TestSample.java
binavy/sawtooth-java
ec3e7d32e5901034698779fd23760ff2e8fc81f3
[ "Apache-2.0" ]
null
null
null
14.692308
36
0.664921
9,948
package com.binavy.sawtooth; import org.junit.Assert; import org.junit.Test; public class TestSample { @Test public void testHello() { Assert.assertEquals(1+1, 3); } }
3e175bac61135cd0e385ea5a236c9525be2e92a4
327
java
Java
common/value/src/main/java/io/github/linuxcounter/common/value/SystemId.java
AbdulShaikz/unixcounter
3f176d583a48dede89c149f7451944e62c2a8770
[ "Apache-2.0" ]
8
2021-12-30T16:13:59.000Z
2022-02-11T20:16:43.000Z
common/value/src/main/java/io/github/linuxcounter/common/value/SystemId.java
AbdulShaikz/unixcounter
3f176d583a48dede89c149f7451944e62c2a8770
[ "Apache-2.0" ]
13
2021-12-30T12:07:09.000Z
2022-01-06T12:56:59.000Z
common/value/src/main/java/io/github/linuxcounter/common/value/SystemId.java
AbdulShaikz/unixcounter
3f176d583a48dede89c149f7451944e62c2a8770
[ "Apache-2.0" ]
2
2022-01-02T15:48:10.000Z
2022-01-06T15:44:05.000Z
20.4375
72
0.657492
9,949
package io.github.linuxcounter.common.value; public record SystemId(String value) { private static final SystemId NO_VALUE = new SystemId("__NO_VALUE__"); public SystemId(String value) { if (null == value || "".equals(value)) { this.value = NO_VALUE.value(); return; } this.value = value; } }
3e175e68c202e5733672ee4c457448e89e108abc
13,125
java
Java
src/main/java/cx/rain/mc/forgemod/sinocraft/data/provider/ProviderBlockState.java
luiqn2007/SinoCraft
6858b03d5c3be697b8f9ad3e78adad299cbeefa0
[ "MIT" ]
12
2020-07-21T03:04:33.000Z
2022-01-21T03:21:20.000Z
src/main/java/cx/rain/mc/forgemod/sinocraft/data/provider/ProviderBlockState.java
luiqn2007/SinoCraft
6858b03d5c3be697b8f9ad3e78adad299cbeefa0
[ "MIT" ]
10
2020-07-23T23:15:42.000Z
2022-01-17T04:09:37.000Z
src/main/java/cx/rain/mc/forgemod/sinocraft/data/provider/ProviderBlockState.java
luiqn2007/SinoCraft
6858b03d5c3be697b8f9ad3e78adad299cbeefa0
[ "MIT" ]
14
2020-06-25T12:05:10.000Z
2020-07-15T16:10:56.000Z
53.571429
199
0.638705
9,950
package cx.rain.mc.forgemod.sinocraft.data.provider; import cx.rain.mc.forgemod.sinocraft.SinoCraft; import cx.rain.mc.forgemod.sinocraft.api.block.IPlantType; import cx.rain.mc.forgemod.sinocraft.block.*; import cx.rain.mc.forgemod.sinocraft.block.tree.BlockLeavesGrowable; import cx.rain.mc.forgemod.sinocraft.block.plant.BlockPlant; import cx.rain.mc.forgemod.sinocraft.block.plant.BlockPlantMulti; import net.minecraft.block.Block; import net.minecraft.block.RotatedPillarBlock; import net.minecraft.data.DataGenerator; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.generators.*; import net.minecraftforge.common.data.ExistingFileHelper; public class ProviderBlockState extends BlockStateProvider { public ProviderBlockState(DataGenerator gen, ExistingFileHelper exFileHelper) { super(gen, SinoCraft.MODID, exFileHelper); } protected void simpleBlock(Block block, String texture) { simpleBlock(block, models().cubeAll("block/" + texture, modLoc("block/" + texture))); } protected void crossBlock(Block block, String texture) { simpleBlock(block, models().cross("block/" + texture, modLoc("block/" + texture))); } protected void logBlock(Block block, String side, String end) { if (!(block instanceof RotatedPillarBlock)) { throw new RuntimeException("Block is not rotatable."); } axisBlock((RotatedPillarBlock) block, "block/" + side, "block/" + end); } protected void axisBlock(RotatedPillarBlock block, String side, String end) { ModelBuilder<BlockModelBuilder> modelBuilder = models().cubeColumn(block.getRegistryName().getPath(), modLoc(side), modLoc(end)); getVariantBuilder(block) .partialState().with(RotatedPillarBlock.AXIS, Direction.Axis.X) .modelForState().modelFile(modelBuilder).rotationX(90).rotationY(90).addModel() .partialState().with(RotatedPillarBlock.AXIS, Direction.Axis.Y) .modelForState().modelFile(modelBuilder).rotationY(90).addModel() .partialState().with(RotatedPillarBlock.AXIS, Direction.Axis.Z) .modelForState().modelFile(modelBuilder).rotationX(90).addModel(); } protected void barkBlock(Block block, String all) { simpleBlock(block, models().cubeAll(block.getRegistryName().getPath(), modLoc("block/" + all))); } protected void cropsStaged(BlockPlant plant) { cropsStaged(plant, plant.getType().getName()); } protected void cropsStaged(BlockPlant plant, String name) { VariantBlockStateBuilder builder = getVariantBuilder(plant); IPlantType type = plant.getType(); if (type.getMaxHeight() > 1) { for (int i = 0; i <= plant.getMaxAge(); i++) { builder.partialState().with(plant.getAgeProperty(), i).with(BlockPlantMulti.IS_TOP, true).modelForState() .modelFile(models().crop("block/" + name + "_stage_top_" + i, modLoc("block/" + name + "_stage_top_" + i))) .addModel(); builder.partialState().with(plant.getAgeProperty(), i).with(BlockPlantMulti.IS_TOP, false).modelForState() .modelFile(models().crop("block/" + name + "_stage_bottom_" + i, modLoc("block/" + name + "_stage_bottom_" + i))) .addModel(); } } else { for (int i = 0; i <= plant.getMaxAge(); i++) { builder.partialState().with(plant.getAgeProperty(), i).modelForState() .modelFile(models().crop("block/" + name + "_stage_" + i, modLoc("block/" + name + "_stage_" + i))) .addModel(); } } } @Override protected void registerStatesAndModels() { simpleBlock(ModBlocks.VAT.get(), models().getExistingFile(modLoc("block/vat"))); MultiPartBlockStateBuilder stoneMill = getMultipartBuilder(ModBlocks.STONE_MILL.get()); for (int i = 1; i <= 16; i++) { stoneMill.part().modelFile(models().getExistingFile(modLoc("block/stone_mill" + i))). addModel(). condition(BlockStoneMill.ROTATE, i). condition(BlockStoneMill.HORIZONTAL_FACING, Direction.NORTH). end(); stoneMill.part().modelFile(models().getExistingFile(modLoc("block/stone_mill" + i))).rotationY(180). addModel(). condition(BlockStoneMill.ROTATE, i). condition(BlockStoneMill.HORIZONTAL_FACING, Direction.SOUTH). end(); stoneMill.part().modelFile(models().getExistingFile(modLoc("block/stone_mill" + i))).rotationY(270). addModel(). condition(BlockStoneMill.ROTATE, i). condition(BlockStoneMill.HORIZONTAL_FACING, Direction.WEST). end(); stoneMill.part().modelFile(models().getExistingFile(modLoc("block/stone_mill" + i))).rotationY(90). addModel(). condition(BlockStoneMill.ROTATE, i). condition(BlockStoneMill.HORIZONTAL_FACING, Direction.EAST). end(); } addCrops(); addTrees(); addBuildingBlocks(); addMachineBlocks(); addOtherBlock(); getVariantBuilder(ModBlocks.WOOD_PULP_BLOCK.get()).partialState().modelForState() .modelFile(models().getBuilder("block/wood_pump").texture("particle", modLoc("block/wood_pulp_still"))) .addModel(); } private void addCrops() { cropsStaged(ModBlocks.WHITE_RADISH_PLANT.get(), "white_radish_plant"); cropsStaged(ModBlocks.SUMMER_RADISH_PLANT.get(), "summer_radish_plant"); cropsStaged(ModBlocks.GREEN_RADISH_PLANT.get(), "green_radish_plant"); cropsStaged(ModBlocks.GREEN_PEPPER_PLANT.get(), "green_pepper_plant"); cropsStaged(ModBlocks.CHILI_PEPPER_PLANT.get(), "chili_pepper_plant"); cropsStaged(ModBlocks.CABBAGE_PLANT.get(), "celery_cabbage"); cropsStaged(ModBlocks.EGGPLANT_PLANT.get(), "eggplant"); cropsStaged(ModBlocks.MILLET_PLANT.get(), "millet"); cropsStaged(ModBlocks.SOYBEAN_PLANT.get(), "soybean"); cropsStaged(ModBlocks.RICE_PLANT.get()); cropsStaged(ModBlocks.SORGHUM_PLANT.get()); } private void addTrees() { logBlock(ModBlocks.PEACH_LOG.get(), "peach_log_side", "peach_log_end"); barkBlock(ModBlocks.PEACH_LOG_BARK.get(), "peach_log_side"); logBlock(ModBlocks.PEACH_LOG_STRIPPED.get(), "peach_log_stripped", "peach_log_end"); barkBlock(ModBlocks.PEACH_LOG_STRIPPED_BARK.get(), "peach_log_stripped"); simpleBlock(ModBlocks.PEACH_PLANK.get(), "peach_plank"); getVariantBuilder(ModBlocks.PEACH_LEAVES.get()) .partialState().with(BlockLeavesGrowable.getMatureProperty(), false).modelForState().modelFile(models().cubeAll("peach_leaves", modLoc("block/peach_leaves"))).addModel() .partialState().with(BlockLeavesGrowable.getMatureProperty(), true).modelForState().modelFile(models().cubeAll("peach_leaves_mature", modLoc("block/peach_leaves_mature"))).addModel(); crossBlock(ModBlocks.PEACH_SAPLING.get(), "peach_sapling"); logBlock(ModBlocks.WALNUT_LOG.get(), "walnut_log_side", "walnut_log_end"); barkBlock(ModBlocks.WALNUT_LOG_BARK.get(), "walnut_log_side"); logBlock(ModBlocks.WALNUT_LOG_STRIPPED.get(), "walnut_log_stripped", "walnut_log_end"); barkBlock(ModBlocks.WALNUT_LOG_STRIPPED_BARK.get(), "walnut_log_stripped"); simpleBlock(ModBlocks.WALNUT_PLANK.get(), "walnut_plank"); simpleBlock(ModBlocks.WALNUT_LEAVES.get(), "walnut_leaves"); crossBlock(ModBlocks.WALNUT_SAPLING.get(), "walnut_sapling"); logBlock(ModBlocks.MULBERRY_LOG.get(), "mulberry_log_side", "mulberry_log_end"); barkBlock(ModBlocks.MULBERRY_LOG_BARK.get(), "mulberry_log_side"); logBlock(ModBlocks.MULBERRY_LOG_STRIPPED.get(), "mulberry_log_stripped", "mulberry_log_end"); barkBlock(ModBlocks.MULBERRY_LOG_STRIPPED_BARK.get(), "mulberry_log_stripped"); simpleBlock(ModBlocks.MULBERRY_PLANK.get(), "mulberry_plank"); simpleBlock(ModBlocks.MULBERRY_LEAVES.get(), "mulberry_leaves"); crossBlock(ModBlocks.MULBERRY_SAPLING.get(), "mulberry_sapling"); logBlock(ModBlocks.PLUM_LOG.get(), "plum_log_side", "plum_log_end"); barkBlock(ModBlocks.PLUM_LOG_BARK.get(), "plum_log_side"); logBlock(ModBlocks.PLUM_LOG_STRIPPED.get(), "plum_log_stripped", "plum_log_end"); barkBlock(ModBlocks.PLUM_LOG_STRIPPED_BARK.get(), "plum_log_stripped"); simpleBlock(ModBlocks.PLUM_PLANK.get(), "plum_plank"); simpleBlock(ModBlocks.PLUM_LEAVES.get(), "plum_leaves"); crossBlock(ModBlocks.PLUM_SAPLING.get(), "plum_sapling"); } private void addBuildingBlocks() { simpleBlock(ModBlocks.WHITE_MARBLE.get()); simpleBlock(ModBlocks.RED_MARBLE.get()); simpleBlock(ModBlocks.BLACK_MARBLE.get()); } private void addMachineBlocks() { // Stove VariantBlockStateBuilder stoveBuilder = getVariantBuilder(ModBlocks.STOVE.get()); Direction stoveDirection = Direction.NORTH; for (int i = 0; i < 4; i++) { stoveBuilder.partialState().with(BlockStove.HORIZONTAL_FACING, stoveDirection).with(BlockStove.BURNING, false) .modelForState() .modelFile(models().getExistingFile(modLoc("block/stove_off"))) .rotationY(90 * i) .addModel(); stoveBuilder.partialState().with(BlockStove.HORIZONTAL_FACING, stoveDirection).with(BlockStove.BURNING, true) .modelForState() .modelFile(models().getExistingFile(modLoc("block/stove_on"))) .rotationY(90 * i) .addModel(); stoveDirection = stoveDirection.rotateY(); } getVariantBuilder(ModBlocks.POT.get()).partialState().modelForState() .modelFile(models().getExistingFile(modLoc("block/pot"))).addModel(); MultiPartBlockStateBuilder paperDryingRackBuilder = getMultipartBuilder(ModBlocks.PAPER_DRYING_RACK.get()); for (int i = 0; i <= 4; i++) { Direction paperDryingRackBuilderDirection = Direction.NORTH; for (int j = 0; j < 4; j++) { paperDryingRackBuilder.part().modelFile(models().getExistingFile(modLoc("block/paper_drying_rack" + i))) .rotationY(90 * j) .addModel() .condition(BlockPaperDryingRack.STATE, i) .condition(BlockPaperDryingRack.HORIZONTAL_FACING, paperDryingRackBuilderDirection) .end(); paperDryingRackBuilderDirection = paperDryingRackBuilderDirection.rotateY(); } } MultiPartBlockStateBuilder bellowsBuilder = getMultipartBuilder(ModBlocks.BELLOWS.get()); for (int i = 0; i <= 3; i++) { Direction bellowsBuilderDirection = Direction.EAST; for (int j = 0; j < 4; j++) { bellowsBuilder.part().modelFile(models().getExistingFile(modLoc("block/bellows" + i))) .rotationY(90 * j) .addModel() .condition(BlockBellows.STATE, i) .condition(BlockBellows.HORIZONTAL_FACING, bellowsBuilderDirection) .end(); bellowsBuilderDirection = bellowsBuilderDirection.rotateY(); } } } private void addOtherBlock() { simpleBlock(ModBlocks.TEA_TABLE.get(), models().getExistingFile(new ResourceLocation("air"))); getVariantBuilder(ModBlocks.TEACUP.get()).partialState() .with(BlockTeacup.WITH_TEA, false).modelForState().modelFile(new ModelFile.UncheckedModelFile(modLoc("block/teacup"))) .addModel().partialState() .with(BlockTeacup.WITH_TEA, true).modelForState().modelFile(new ModelFile.UncheckedModelFile(modLoc("block/teacup_with_tea"))) .addModel(); getVariantBuilder(ModBlocks.TEAPOT.get()).partialState() .with(BlockTeapot.FLUID, 0).modelForState().modelFile(new ModelFile.UncheckedModelFile(modLoc("block/teapot"))) .addModel().partialState() .with(BlockTeapot.FLUID, 1).modelForState().modelFile(new ModelFile.UncheckedModelFile(modLoc("block/teapot_without_lid"))) .addModel().partialState() .with(BlockTeapot.FLUID, 2).modelForState().modelFile(new ModelFile.UncheckedModelFile(modLoc("block/teapot_without_lid_with_tea"))) .addModel(); } }
3e175f20aa1f1e16aa4f41fa9c7bd20830ce1d3b
1,326
java
Java
fhir-persistence-cassandra/src/main/java/com/ibm/fhir/persistence/cassandra/cql/TenantDatasourceKey.java
mpayne2/FHIR
b251ffe71b1fa5c3f70b054f32affc864adc7338
[ "Apache-2.0" ]
209
2019-08-14T15:11:17.000Z
2022-03-25T10:30:35.000Z
fhir-persistence-cassandra/src/main/java/com/ibm/fhir/persistence/cassandra/cql/TenantDatasourceKey.java
mpayne2/FHIR
b251ffe71b1fa5c3f70b054f32affc864adc7338
[ "Apache-2.0" ]
1,944
2019-08-29T20:03:24.000Z
2022-03-31T22:38:28.000Z
fhir-persistence-cassandra/src/main/java/com/ibm/fhir/persistence/cassandra/cql/TenantDatasourceKey.java
mpayne2/FHIR
b251ffe71b1fa5c3f70b054f32affc864adc7338
[ "Apache-2.0" ]
134
2019-09-02T10:36:17.000Z
2022-03-06T15:08:07.000Z
22.474576
83
0.637255
9,951
/* * (C) Copyright IBM Corp. 2020, 2021 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.persistence.cassandra.cql; import java.util.Objects; /** * Key used to represent a tenant/datasource pair */ public class TenantDatasourceKey { // Id representing the tenant private final String tenantId; // Id representing the datasource for a given tenant private final String datasourceId; public TenantDatasourceKey(String tenantId, String datasourceId) { this.tenantId = tenantId; this.datasourceId = datasourceId; } @Override public int hashCode() { return Objects.hash(tenantId, datasourceId); } @Override public boolean equals(Object obj) { if (obj instanceof TenantDatasourceKey) { TenantDatasourceKey that = (TenantDatasourceKey)obj; return this.tenantId.equals(that.tenantId) && this.datasourceId.equals(that.datasourceId); } else { throw new IllegalArgumentException("obj is not a TenantDatasourceKey"); } } /** * @return the tenantId */ public String getTenantId() { return tenantId; } /** * @return the datasourceId */ public String getDatasourceId() { return datasourceId; } }
3e175f25ac78eb5155ec8c18203530b05c7b1086
934
java
Java
src/main/java/xxxjerzyxxx/soup/data/generators/client/BlockStateGenerator.java
jerzywilczek/Soup
e4848675046f226603893e0f8fb76fb5e627eea5
[ "Unlicense" ]
1
2021-07-04T23:24:35.000Z
2021-07-04T23:24:35.000Z
src/main/java/xxxjerzyxxx/soup/data/generators/client/BlockStateGenerator.java
jerzywilczek/Soup
e4848675046f226603893e0f8fb76fb5e627eea5
[ "Unlicense" ]
null
null
null
src/main/java/xxxjerzyxxx/soup/data/generators/client/BlockStateGenerator.java
jerzywilczek/Soup
e4848675046f226603893e0f8fb76fb5e627eea5
[ "Unlicense" ]
null
null
null
34.592593
142
0.773019
9,952
package xxxjerzyxxx.soup.data.generators.client; import net.minecraft.data.DataGenerator; import net.minecraft.world.level.block.Block; import net.minecraftforge.client.model.generators.BlockStateProvider; import net.minecraftforge.common.data.ExistingFileHelper; import xxxjerzyxxx.soup.Soup; import xxxjerzyxxx.soup.common.blocks.BlockRegisterer; import java.util.Objects; public class BlockStateGenerator extends BlockStateProvider { public BlockStateGenerator(DataGenerator gen, ExistingFileHelper exFileHelper) { super(gen, Soup.MODID, exFileHelper); } @Override protected void registerStatesAndModels() { cubeAllBlock(BlockRegisterer.MUSHROOM_STEW_BLOCK.get()); } private void cubeAllBlock(Block block){ simpleBlock(block); itemModels().cubeAll(Objects.requireNonNull(block.getRegistryName()).getPath(), modLoc("block/" + block.getRegistryName().getPath())); } }
3e175f5c2475ed2655059587d867ff7f3992c32e
386
java
Java
java-basic/design-pattern/src/main/java/com/desgin/mashibing/chainofresponsibility/abstractImpl/v3/ChainHandler.java
lastwhispers/code
8d4b926c5577525828e4f077e3901f4e869c7e4a
[ "Apache-2.0" ]
59
2020-04-08T06:48:13.000Z
2021-11-10T06:20:36.000Z
java-basic/design-pattern/src/main/java/com/desgin/mashibing/chainofresponsibility/abstractImpl/v3/ChainHandler.java
lastwhispers/code
8d4b926c5577525828e4f077e3901f4e869c7e4a
[ "Apache-2.0" ]
26
2020-11-01T03:16:16.000Z
2022-03-18T02:50:29.000Z
java-basic/design-pattern/src/main/java/com/desgin/mashibing/chainofresponsibility/abstractImpl/v3/ChainHandler.java
lastwhispers/code
8d4b926c5577525828e4f077e3901f4e869c7e4a
[ "Apache-2.0" ]
44
2020-04-09T01:34:40.000Z
2021-03-02T12:33:23.000Z
21.444444
67
0.683938
9,953
package com.desgin.mashibing.chainofresponsibility.abstractImpl.v3; /** * Created by cat on 2017-02-28. */ public abstract class ChainHandler { // 模板方法 public void execute(Chain chain){ handlePreProcess(); chain.proceed(); handlePostProcess(); } protected abstract void handlePreProcess(); protected abstract void handlePostProcess(); }
3e175f68a468ae8a49f58a52221a8fc6e69e7930
2,046
java
Java
junit4/example-junit-grpc-systemtest/src/test/java/examples/greeting/CreateGreetingST.java
testify-project/examples
eab4deba2bb9f68e43c1d022021f0a406122ffb2
[ "Apache-2.0" ]
null
null
null
junit4/example-junit-grpc-systemtest/src/test/java/examples/greeting/CreateGreetingST.java
testify-project/examples
eab4deba2bb9f68e43c1d022021f0a406122ffb2
[ "Apache-2.0" ]
null
null
null
junit4/example-junit-grpc-systemtest/src/test/java/examples/greeting/CreateGreetingST.java
testify-project/examples
eab4deba2bb9f68e43c1d022021f0a406122ffb2
[ "Apache-2.0" ]
1
2018-02-23T12:23:29.000Z
2018-02-23T12:23:29.000Z
28.416667
75
0.731672
9,954
/* * Copyright 2016-2017 Testify 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 examples.greeting; import static org.assertj.core.api.Assertions.assertThat; import javax.persistence.EntityManager; import org.junit.Test; import org.junit.runner.RunWith; import org.testifyproject.annotation.Application; import org.testifyproject.annotation.Module; import org.testifyproject.annotation.Real; import org.testifyproject.annotation.Sut; import org.testifyproject.annotation.VirtualResource; import org.testifyproject.junit4.SystemTest; import example.grpc.GreetingsGrpc; import example.grpc.common.GreetingId; import example.grpc.common.GreetingRequest; import examples.GreetingsServer; import fixture.TestModule; /** * * @author saden */ @Module(value = TestModule.class, test = true) @VirtualResource(value = "postgres", version = "9.4") @Application(value = GreetingsServer.class, start = "start", stop = "stop") @RunWith(SystemTest.class) public class CreateGreetingST { @Sut GreetingsGrpc.GreetingsBlockingStub sut; @Real EntityManager entityManager; @Test public void givenNameSayHelloShouldReturnHelloReply() { //Arrange String phrase = "Hello"; GreetingRequest request = GreetingRequest.newBuilder() .setPhrase(phrase) .build(); //Act GreetingId response = sut.create(request); //Assert assertThat(response).isNotNull(); assertThat(response.getId()).isNotEmpty(); } }
3e175fa365e6d63c37b18a464c1bd5f7b813e61a
629
java
Java
src/main/java/io/proleap/cobol/asg/metamodel/procedure/alter/AlterStatement.java
jmiodownik/proleap-cobol-parser
e66dfcb26130681a0ce9a5270e78769bbd168436
[ "MIT" ]
81
2018-03-29T23:39:01.000Z
2022-03-07T11:23:10.000Z
src/main/java/io/proleap/cobol/asg/metamodel/procedure/alter/AlterStatement.java
jmiodownik/proleap-cobol-parser
e66dfcb26130681a0ce9a5270e78769bbd168436
[ "MIT" ]
64
2017-03-27T11:15:15.000Z
2018-03-09T18:10:43.000Z
src/main/java/io/proleap/cobol/asg/metamodel/procedure/alter/AlterStatement.java
jmiodownik/proleap-cobol-parser
e66dfcb26130681a0ce9a5270e78769bbd168436
[ "MIT" ]
44
2019-01-03T11:48:54.000Z
2021-12-21T09:46:42.000Z
25.56
69
0.774648
9,955
/* * Copyright (C) 2017, Ulrich Wolffgang <hzdkv@example.com> * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package io.proleap.cobol.asg.metamodel.procedure.alter; import java.util.List; import io.proleap.cobol.CobolParser.AlterProceedToContext; import io.proleap.cobol.asg.metamodel.procedure.Statement; /** * Changes the transfer point specified in a GO TO statement. */ public interface AlterStatement extends Statement { ProceedTo addProceedTo(AlterProceedToContext ctx); List<ProceedTo> getProceedTos(); }
3e175fa550844a0f6a306a23e175a1b7d2579890
1,550
java
Java
src/main/java/com/example/iac/GreetingsApp.java
ldecaro/fargate-mesh
6eecd3f480b67e6a4aeafb013cd907af0962cbbc
[ "MIT" ]
null
null
null
src/main/java/com/example/iac/GreetingsApp.java
ldecaro/fargate-mesh
6eecd3f480b67e6a4aeafb013cd907af0962cbbc
[ "MIT" ]
null
null
null
src/main/java/com/example/iac/GreetingsApp.java
ldecaro/fargate-mesh
6eecd3f480b67e6a4aeafb013cd907af0962cbbc
[ "MIT" ]
null
null
null
37.804878
106
0.495484
9,956
package com.example.iac; import software.amazon.awscdk.core.App; import software.amazon.awscdk.core.Construct; public class GreetingsApp { static class Greetings extends Construct{ Greetings(Construct scope, String id, String appName, String domainName){ super(scope, id); // Containers/Services/Data Plane DataPlane dp = new DataPlane(this, appName+"-dp", DataPlane.DataPlaneProps.builder() .appName(appName) .terminationProtection(Boolean.FALSE) .build()); // Network/Infrastructure/ControlPlane ControlPlane cp = new ControlPlane(this, appName+"-cp", ControlPlane.ControlPlaneProps.builder() .appName(appName) .domain(domainName) .imageMorning(dp.getV1Asset()) .imageAfternoon(dp.getV2Asset()) .imageUI(dp.getUiImageAsset()) .terminationProtection(Boolean.FALSE) .build()); // Monitoring... cp.addDependency(dp); } } public static void main(String args[]){ App greetingsApp = new App(); new Greetings(greetingsApp, "greetings", "greetings", "example.com"); greetingsApp.synth(); } }
3e1760a535ec243117ba44c1bdff44e31f157dfe
7,491
java
Java
app/src/main/java/se/cygni/snake/websocket/event/EventSocketHandler.java
petalv/snakebot
424d37ede325c0145b96ec74f5d1968cc93ccba7
[ "MIT" ]
1
2021-02-28T00:10:32.000Z
2021-02-28T00:10:32.000Z
app/src/main/java/se/cygni/snake/websocket/event/EventSocketHandler.java
petalv/snakebot
424d37ede325c0145b96ec74f5d1968cc93ccba7
[ "MIT" ]
null
null
null
app/src/main/java/se/cygni/snake/websocket/event/EventSocketHandler.java
petalv/snakebot
424d37ede325c0145b96ec74f5d1968cc93ccba7
[ "MIT" ]
1
2016-02-22T13:18:44.000Z
2016-02-22T13:18:44.000Z
36.188406
126
0.666667
9,957
package se.cygni.snake.websocket.event; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import se.cygni.game.WorldState; import se.cygni.game.testutil.SnakeTestUtil; import se.cygni.game.transformation.AddWorldObjectAtRandomPosition; import se.cygni.game.worldobject.Food; import se.cygni.game.worldobject.Obstacle; import se.cygni.game.worldobject.SnakeBody; import se.cygni.game.worldobject.SnakeHead; import se.cygni.snake.api.GameMessage; import se.cygni.snake.api.GameMessageParser; import se.cygni.snake.api.event.MapUpdateEvent; import se.cygni.snake.api.model.Map; import se.cygni.snake.apiconversion.WorldStateConverter; import se.cygni.snake.event.InternalGameEvent; import se.cygni.snake.game.Game; import se.cygni.snake.game.GameManager; import se.cygni.snake.websocket.event.api.*; import java.io.IOException; /** * This is a per-connection websocket. That means a new instance will * be created for each connecting client. */ public class EventSocketHandler extends TextWebSocketHandler { private static Logger log = LoggerFactory.getLogger(EventSocketHandler.class); private WebSocketSession session; private String[] filterGameIds = new String[0]; private EventBus globalEventBus; private GameManager gameManager; @Autowired public EventSocketHandler(EventBus globalEventBus, GameManager gameManager) { this.globalEventBus = globalEventBus; this.gameManager = gameManager; log.info("EventSocketHandler started!"); } @Override public void afterConnectionEstablished(WebSocketSession session) { log.info("Opened new event session for " + session.getId()); this.session = session; globalEventBus.register(this); /* this.session = session; isConnected = true; // Lambda Runnable Runnable eventGenerator = () -> { while (isConnected) { long worldTick = 0; try { session.sendMessage(new TextMessage(GameMessageParser.encodeMessage(getRandomMapUpdateEvent(worldTick)))); worldTick++; Thread.sleep(250); log.info("World tick: {}", worldTick); } catch (Exception e) { e.printStackTrace(); } } }; new Thread(eventGenerator).start(); */ } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { super.afterConnectionClosed(session, status); globalEventBus.unregister(this); log.info("Removed session: {}", session.getId()); } @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { log.debug(message.getPayload()); ApiMessage apiMessage = ApiMessageParser.decodeMessage(message.getPayload()); if (apiMessage instanceof ListActiveGames) { sendListOfActiveGames(); } else if (apiMessage instanceof SetGameFilter) { setActiveGameFilter((SetGameFilter)apiMessage); } else if (apiMessage instanceof StartGame) { startGame((StartGame)apiMessage); } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); globalEventBus.unregister(this); log.info("Transport error, removed session: {}", session.getId()); } @Subscribe public void onInternalGameEvent(InternalGameEvent event) { log.info("EventSocketHandler got a message: " + event.getGameMessage().getType()); sendEvent(event.getGameMessage()); } private void sendEvent(GameMessage message) { if (!session.isOpen()) return; try { String gameId = org.apache.commons.beanutils.BeanUtils.getProperty(message, "gameId"); if (ArrayUtils.contains(filterGameIds, gameId)) { session.sendMessage(new TextMessage(GameMessageParser.encodeMessage(message))); } } catch (Exception e) { e.printStackTrace(); } } private void sendListOfActiveGames() { ActiveGamesList gamesList = new ActiveGamesList(gameManager.listGameIds()); try { if (session.isOpen()) { session.sendMessage(new TextMessage(ApiMessageParser.encodeMessage(gamesList))); } } catch (IOException e) { e.printStackTrace(); } } private void setActiveGameFilter(SetGameFilter gameFilter) { this.filterGameIds = gameFilter.getIncludedGameIds(); } private void startGame(StartGame apiMessage) { Game game = gameManager.getGame(apiMessage.getGameId()); if (game != null) { log.info("Starting game: {}", game.getGameId()); log.info("Active remote players: {}", game.getLiveAndRemotePlayers().size()); game.startGame(); } } private MapUpdateEvent getRandomMapUpdateEvent(long gameTick) { return new MapUpdateEvent(gameTick, "666", getRandomMap()); } private Map getRandomMap() { WorldState ws = new WorldState(15, 15); // Snake Python String snakeName = "python"; SnakeHead head = new SnakeHead(snakeName, "id_python", 101); SnakeBody body1 = new SnakeBody(116); SnakeBody body2 = new SnakeBody(115); head.setNextSnakePart(body1); body1.setNextSnakePart(body2); ws = SnakeTestUtil.replaceWorldObjectAt(ws, head, head.getPosition()); ws = SnakeTestUtil.replaceWorldObjectAt(ws, body1, body1.getPosition()); ws = SnakeTestUtil.replaceWorldObjectAt(ws, body2, body2.getPosition()); // Snake Cobra String snakeName2 = "cobra"; SnakeHead head2 = new SnakeHead(snakeName2, "id_cobra", 109); SnakeBody body21 = new SnakeBody(108); SnakeBody body22 = new SnakeBody(123); SnakeBody body23 = new SnakeBody(138); head2.setNextSnakePart(body21); body21.setNextSnakePart(body22); body22.setNextSnakePart(body23); ws = SnakeTestUtil.replaceWorldObjectAt(ws, head2, head2.getPosition()); ws = SnakeTestUtil.replaceWorldObjectAt(ws, body21, body21.getPosition()); ws = SnakeTestUtil.replaceWorldObjectAt(ws, body22, body22.getPosition()); ws = SnakeTestUtil.replaceWorldObjectAt(ws, body23, body23.getPosition()); // 10 Obstacles for (int x=0; x<10; x++) { AddWorldObjectAtRandomPosition ar = new AddWorldObjectAtRandomPosition(new Obstacle()); ws = ar.transform(ws); } // 5 Foods for (int x=0; x<10; x++) { AddWorldObjectAtRandomPosition ar = new AddWorldObjectAtRandomPosition(new Food()); ws = ar.transform(ws); } return WorldStateConverter.convertWorldState(ws, 1); } }
3e1760cefe7880cfff5bd8fbc3e294eb5b8186df
4,415
java
Java
biojava/src/org/biojava/utils/ChangeForwarder.java
rbouadjenek/DQBioinformatics
088c0e93754257592e3a0725897566af3823a92d
[ "Apache-2.0" ]
null
null
null
biojava/src/org/biojava/utils/ChangeForwarder.java
rbouadjenek/DQBioinformatics
088c0e93754257592e3a0725897566af3823a92d
[ "Apache-2.0" ]
null
null
null
biojava/src/org/biojava/utils/ChangeForwarder.java
rbouadjenek/DQBioinformatics
088c0e93754257592e3a0725897566af3823a92d
[ "Apache-2.0" ]
null
null
null
28.301282
88
0.663194
9,958
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ */ package org.biojava.utils; /** * This is a ChangeListener that is designed to adapt events of one type from * one source to events of another type emitted by another source. For example, * you could adapt events made by edits in a database to being events fired by * a sequence implementation. * * @author Matthew Pocock * @since 1.1 */ public class ChangeForwarder implements ChangeListener { private final Object source; private final transient ChangeSupport changeSupport; /** * Create a new ChangeForwarder for forwarding events. * * @param source the new source Object * @param changeSupport the ChangeSupport managing the listeners */ public ChangeForwarder(Object source, ChangeSupport changeSupport) { this.source = source; this.changeSupport = changeSupport; } /** * Retrieve the 'source' object for <code>ChangeEvent</code>s fired by this forwarder. * * @return the source Object */ public Object getSource() { return source; } /** * Return the underlying <code>ChangeSupport</code> instance that can be used to * fire <code>ChangeEvent</code>s and mannage listeners. * * @return the ChangeSupport delegate */ public ChangeSupport changeSupport() { return changeSupport; } /** * <p> * Return the new event to represent the originating event ce. * </p> * * <p> * The returned ChangeEvent is the event that will be fired, and should be * built from information in the original event. If it is null, then no event * will be fired. * </p> * * <p> * The default implementation just constructs a ChangeEvent of the same type * that chains back to ce. * </p> * * @param ce the originating ChangeEvent * @return a new ChangeEvent to pass on, or null if no event should be sent * @throws ChangeVetoException if for any reason this event can't be handled */ protected ChangeEvent generateEvent(ChangeEvent ce) throws ChangeVetoException { return new ChangeEvent( getSource(), ce.getType(), null, null, ce ); } public void preChange(ChangeEvent ce) throws ChangeVetoException { ChangeEvent nce = generateEvent(ce); if(nce != null) { // todo: this should be coupled with the synchronization in postChange synchronized(changeSupport) { changeSupport.firePreChangeEvent(nce); } } } public void postChange(ChangeEvent ce) { try { ChangeEvent nce = generateEvent(ce); if(nce != null) { // todo: this should be coupled with the synchronization in preChange synchronized(changeSupport) { changeSupport.firePostChangeEvent(nce); } } } catch (ChangeVetoException cve) { throw new AssertionFailure( "Assertion Failure: Change was vetoed after it had been accepted by preChange", cve ); } } /** * A ChangeForwarder that systematically uses a given type and wraps the old * event. * * @author Matthew Pocock * @since 1.4 */ public static class Retyper extends ChangeForwarder{ private final ChangeType type; /** * Create a new Retyper for forwarding events. * * @param source the new source Object * @param changeSupport the ChangeSupport managing the listeners * @param type the new ChangeType */ public Retyper(Object source, ChangeSupport changeSupport, ChangeType type) { super(source, changeSupport); this.type = type; } public ChangeType getType() { return type; } protected ChangeEvent generateEvent(ChangeEvent ce) throws ChangeVetoException { return new ChangeEvent(getSource(), getType(), null, null, ce); } } }
3e17614906e66e64c0eafdb83350d67877aa1735
11,133
java
Java
src/main/java/net/platform/dao/BeanTransformerAdapter.java
linbren/apifrm
d1e1b4988a0a6624fee52f20e6380f08c9013b9a
[ "Apache-2.0" ]
null
null
null
src/main/java/net/platform/dao/BeanTransformerAdapter.java
linbren/apifrm
d1e1b4988a0a6624fee52f20e6380f08c9013b9a
[ "Apache-2.0" ]
null
null
null
src/main/java/net/platform/dao/BeanTransformerAdapter.java
linbren/apifrm
d1e1b4988a0a6624fee52f20e6380f08c9013b9a
[ "Apache-2.0" ]
null
null
null
40.930147
120
0.621396
9,959
package net.platform.dao; import java.beans.PropertyDescriptor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.transform.ResultTransformer; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.NotWritablePropertyException; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.TypeMismatchException; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.util.StringUtils; /** * 重写spirng NameDJbcTemplate方法解决 * Hibernate sql查询数据库映射JavaBean大小写转换 * @author * 使用方式如下: Query query = getSession().createSQLQuery(sql).setResultTransformer(new BeanTransformerAdapter(entityClass)); 不用管Oracle字段的大写问题了,会匹配到java的对应字段。 * @param <T> */ public class BeanTransformerAdapter<T> implements ResultTransformer { private static final long serialVersionUID = -5714768181479644459L; /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); /** The class we are mapping to */ private Class<T> mappedClass; /** Whether we're strictly validating */ private boolean checkFullyPopulated = false; /** Whether we're defaulting primitives when mapping a null value */ private boolean primitivesDefaultedForNullValue = false; /** Map of the fields we provide mapping for */ private Map<String, PropertyDescriptor> mappedFields; /** Set of bean properties we provide mapping for */ private Set<String> mappedProperties; /** * Create a new BeanPropertyRowMapper for bean-style configuration. * @see #setMappedClass * @see #setCheckFullyPopulated */ public BeanTransformerAdapter() { } /** * Create a new BeanPropertyRowMapper, accepting unpopulated properties * in the target bean. * <p>Consider using the {@link #newInstance} factory method instead, * which allows for specifying the mapped type once only. * @param mappedClass the class that each row should be mapped to */ public BeanTransformerAdapter(Class<T> mappedClass) { initialize(mappedClass); } /** * Create a new BeanPropertyRowMapper. * @param mappedClass the class that each row should be mapped to * @param checkFullyPopulated whether we're strictly validating that * all bean properties have been mapped from corresponding database fields */ public BeanTransformerAdapter(Class<T> mappedClass, boolean checkFullyPopulated) { initialize(mappedClass); this.checkFullyPopulated = checkFullyPopulated; } /** * Set the class that each row should be mapped to. */ public void setMappedClass(Class<T> mappedClass) { if (this.mappedClass == null) { initialize(mappedClass); } else { if (!this.mappedClass.equals(mappedClass)) { throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to " + mappedClass + " since it is already providing mapping for " + this.mappedClass); } } } /** * Initialize the mapping metadata for the given class. * @param mappedClass the mapped class. */ protected void initialize(Class<T> mappedClass) { this.mappedClass = mappedClass; this.mappedFields = new HashMap<String, PropertyDescriptor>(); this.mappedProperties = new HashSet<String>(); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null) { this.mappedFields.put(pd.getName().toLowerCase(), pd); String underscoredName = underscoreName(pd.getName()); if (!pd.getName().toLowerCase().equals(underscoredName)) { this.mappedFields.put(underscoredName, pd); } this.mappedProperties.add(pd.getName()); } } } /** * Convert a name in camelCase to an underscored name in lower case. * Any upper case letters are converted to lower case with a preceding underscore. * @param name the string containing original name * @return the converted name */ private String underscoreName(String name) { if (!StringUtils.hasLength(name)) { return ""; } StringBuilder result = new StringBuilder(); result.append(name.substring(0, 1).toLowerCase()); for (int i = 1; i < name.length(); i++) { String s = name.substring(i, i + 1); String slc = s.toLowerCase(); if (!s.equals(slc)) { result.append("_").append(slc); } else { result.append(s); } } return result.toString(); } /** * Get the class that we are mapping to. */ public final Class<T> getMappedClass() { return this.mappedClass; } /** * Set whether we're strictly validating that all bean properties have been * mapped from corresponding database fields. * <p>Default is {@code false}, accepting unpopulated properties in the * target bean. */ public void setCheckFullyPopulated(boolean checkFullyPopulated) { this.checkFullyPopulated = checkFullyPopulated; } /** * Return whether we're strictly validating that all bean properties have been * mapped from corresponding database fields. */ public boolean isCheckFullyPopulated() { return this.checkFullyPopulated; } /** * Set whether we're defaulting Java primitives in the case of mapping a null value * from corresponding database fields. * <p>Default is {@code false}, throwing an exception when nulls are mapped to Java primitives. */ public void setPrimitivesDefaultedForNullValue(boolean primitivesDefaultedForNullValue) { this.primitivesDefaultedForNullValue = primitivesDefaultedForNullValue; } /** * Return whether we're defaulting Java primitives in the case of mapping a null value * from corresponding database fields. */ public boolean isPrimitivesDefaultedForNullValue() { return primitivesDefaultedForNullValue; } /** * Initialize the given BeanWrapper to be used for row mapping. * To be called for each row. * <p>The default implementation is empty. Can be overridden in subclasses. * @param bw the BeanWrapper to initialize */ protected void initBeanWrapper(BeanWrapper bw) { } /** * Retrieve a JDBC object value for the specified column. * <p>The default implementation calls * {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}. * Subclasses may override this to check specific value types upfront, * or to post-process values return from {@code getResultSetValue}. * @param rs is the ResultSet holding the data * @param index is the column index * @param pd the bean property that each result object is expected to match * (or {@code null} if none specified) * @return the Object value * @throws SQLException in case of extraction failure * @see org.springframework.jdbc.support.JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class) */ protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException { return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType()); } /** * Static factory method to create a new BeanPropertyRowMapper * (with the mapped class specified only once). * @param mappedClass the class that each row should be mapped to */ public static <T> BeanPropertyRowMapper<T> newInstance(Class<T> mappedClass) { BeanPropertyRowMapper<T> newInstance = new BeanPropertyRowMapper<T>(); newInstance.setMappedClass(mappedClass); return newInstance; } @Override public Object transformTuple(Object[] tuple, String[] aliases) { T mappedObject = BeanUtils.instantiate(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null); for (int i = 0; i < aliases.length; i++) { String column = aliases[i]; PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase()); if (pd != null) { try { Object value = tuple[i]; try { bw.setPropertyValue(pd.getName(), value); } catch (TypeMismatchException e) { if (value == null && primitivesDefaultedForNullValue) { logger.debug("Intercepted TypeMismatchException for column " + column + " and column '" + column + "' with value " + value + " when setting property '" + pd.getName() + "' of type " + pd.getPropertyType() + " on object: " + mappedObject); } else { throw e; } } if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException("Unable to map column " + column + " to property " + pd.getName(), ex); } } } if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) { throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties); } return mappedObject; } @Override public List transformList(List list) { return list; } }
3e17614d3008883d9dd7557914e9436ce8249157
3,756
java
Java
waggle-dance-core/src/test/java/com/hotels/bdp/waggledance/core/federation/service/PopulateStatusFederationServiceTest.java
groobyming/waggle-dance
2afb9d3843e23f247376101e22c31794bdd2af1d
[ "Apache-2.0" ]
146
2017-07-19T13:58:27.000Z
2021-06-02T07:43:18.000Z
waggle-dance-core/src/test/java/com/hotels/bdp/waggledance/core/federation/service/PopulateStatusFederationServiceTest.java
groobyming/waggle-dance
2afb9d3843e23f247376101e22c31794bdd2af1d
[ "Apache-2.0" ]
157
2017-08-08T16:07:40.000Z
2021-04-27T10:40:04.000Z
waggle-dance-core/src/test/java/com/hotels/bdp/waggledance/core/federation/service/PopulateStatusFederationServiceTest.java
groobyming/waggle-dance
2afb9d3843e23f247376101e22c31794bdd2af1d
[ "Apache-2.0" ]
34
2017-10-11T12:23:25.000Z
2021-06-07T15:43:28.000Z
38.326531
107
0.795793
9,960
/** * Copyright (C) 2016-2020 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hotels.bdp.waggledance.core.federation.service; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.hotels.bdp.waggledance.api.federation.service.FederationStatusService; import com.hotels.bdp.waggledance.api.model.AbstractMetaStore; import com.hotels.bdp.waggledance.api.model.MetaStoreStatus; import com.hotels.bdp.waggledance.mapping.service.impl.NotifyingFederationService; @RunWith(MockitoJUnitRunner.class) public class PopulateStatusFederationServiceTest { private @Mock NotifyingFederationService federationService; private @Mock FederationStatusService federationStatusService; private AbstractMetaStore federatedMetaStore1; private AbstractMetaStore federatedMetaStore2; private PopulateStatusFederationService service; @Before public void init() { federatedMetaStore1 = AbstractMetaStore.newFederatedInstance("name1", "uri"); federatedMetaStore2 = AbstractMetaStore.newFederatedInstance("name2", "uri"); when(federationService.get("federatedMetaStore1")).thenReturn(federatedMetaStore1); when(federationService.getAll()).thenReturn(Arrays.asList(federatedMetaStore1, federatedMetaStore2)); when(federationStatusService.checkStatus(federatedMetaStore1)).thenReturn(MetaStoreStatus.AVAILABLE); when(federationStatusService.checkStatus(federatedMetaStore2)).thenReturn(MetaStoreStatus.UNAVAILABLE); service = new PopulateStatusFederationService(federationService, federationStatusService); } @Test public void register() { service.register(federatedMetaStore1); verify(federationService).register(federatedMetaStore1); verifyNoInteractions(federationStatusService); } @Test public void update() { service.update(federatedMetaStore1, federatedMetaStore2); verify(federationService).update(federatedMetaStore1, federatedMetaStore2); verifyNoInteractions(federationStatusService); } @Test public void unregister() { service.unregister("federatedMetaStore1"); verify(federationService).unregister("federatedMetaStore1"); verifyNoInteractions(federationStatusService); } @Test public void get() { service.get("federatedMetaStore1"); verify(federationService).get("federatedMetaStore1"); verify(federationStatusService).checkStatus(federatedMetaStore1); assertThat(federatedMetaStore1.getStatus(), is(MetaStoreStatus.AVAILABLE)); } @Test public void getAll() { service.getAll(); verify(federationService).getAll(); verify(federationStatusService).checkStatus(federatedMetaStore1); assertThat(federatedMetaStore1.getStatus(), is(MetaStoreStatus.AVAILABLE)); verify(federationStatusService).checkStatus(federatedMetaStore2); assertThat(federatedMetaStore2.getStatus(), is(MetaStoreStatus.UNAVAILABLE)); } }
3e17618efb2a858fce809e9a57e1ab4aa5b08f98
4,524
java
Java
cincamipd/src/main/java/org/ciedayap/pabmm/pd/requirements/ConceptModel.java
mjdivan/cincamiPD
4ed69d98b46b5dab52179f587b89d5a3569dd050
[ "Apache-2.0" ]
null
null
null
cincamipd/src/main/java/org/ciedayap/pabmm/pd/requirements/ConceptModel.java
mjdivan/cincamiPD
4ed69d98b46b5dab52179f587b89d5a3569dd050
[ "Apache-2.0" ]
null
null
null
cincamipd/src/main/java/org/ciedayap/pabmm/pd/requirements/ConceptModel.java
mjdivan/cincamiPD
4ed69d98b46b5dab52179f587b89d5a3569dd050
[ "Apache-2.0" ]
null
null
null
25.851429
113
0.613395
9,961
/* * 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 org.ciedayap.pabmm.pd.requirements; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.ciedayap.utils.StringUtils; import org.ciedayap.pabmm.pd.SingleConcept; import org.ciedayap.pabmm.pd.exceptions.EntityPDException; /** * It represents the concept models associated with the calculable concepts. * * @author Mario Diván * @version 1.0 */ @XmlRootElement(name="ConceptModel") @XmlType(propOrder={"ID","name","specification","references","constraints"}) public class ConceptModel implements Serializable, SingleConcept{ /** * The ID related to the concept model */ private String ID; /** * The conceptual model´s name */ private String name; /** * The Conceptual model´s specification */ private String specification; /** * The references which substantiate the conceptual model */ private String references; /** * The constraints on the conceptual model */ private String constraints; /** * Default constructor */ public ConceptModel() {} /** * The constructor associated with the mandatory attributes * @param ID The identification related to the conceptual model * @param name The synthetic name for the conceptual model * @throws EntityPDException It is raised when some mandatory attribute is not defined */ public ConceptModel(String ID, String name) throws EntityPDException { if(StringUtils.isEmpty(ID)) throw new EntityPDException("The Conceptual model´s ID is not defined"); if(StringUtils.isEmpty(name)) throw new EntityPDException("The Conceptual model´s name is not defined"); this.ID=ID; this.name=name; } /** * A basic factory method * @param ID * @param name * @return A new ConceptModel´s instance * @throws EntityPDException It is raised when some mandatory attribute is not defined */ public static ConceptModel create(String ID, String name) throws EntityPDException { return new ConceptModel(ID,name); } @Override public boolean isDefinedProperties() { return !(StringUtils.isEmpty(ID) || StringUtils.isEmpty(name)); } @Override public String getCurrentClassName() { return this.getClass().getSimpleName(); } @Override public String getQualifiedCurrentClassName() { return this.getClass().getCanonicalName(); } @Override public String getUniqueID() { return getID(); } /** * @return the ID */ @XmlElement(name="ID", required=true) public String getID() { return ID; } /** * @param ID the ID to set */ public void setID(String ID) { this.ID = ID; } /** * @return the name */ @XmlElement(name="name", required=true) public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the specification */ @XmlElement(name="specification") public String getSpecification() { return specification; } /** * @param specification the specification to set */ public void setSpecification(String specification) { this.specification = specification; } /** * @return the references */ @XmlElement(name="references") public String getReferences() { return references; } /** * @param references the references to set */ public void setReferences(String references) { this.references = references; } /** * @return the constraints */ @XmlElement(name="constraints") public String getConstraints() { return constraints; } /** * @param constraints the constraints to set */ public void setConstraints(String constraints) { this.constraints = constraints; } }
3e1763b8c64586adca635a8b0cf0b53f920a330c
1,803
java
Java
RTEditor/src/main/java/com/onegravity/rteditor/RTEditTextListener.java
maysamrasoli/Doctor
669f9eb07c834f1ed725a552c09f5c2b6ddd3bb7
[ "Apache-2.0" ]
2
2016-06-19T08:53:13.000Z
2016-06-19T08:53:14.000Z
RTEditor/src/main/java/com/onegravity/rteditor/RTEditTextListener.java
maysamrasoli/Doctor
669f9eb07c834f1ed725a552c09f5c2b6ddd3bb7
[ "Apache-2.0" ]
null
null
null
RTEditor/src/main/java/com/onegravity/rteditor/RTEditTextListener.java
maysamrasoli/Doctor
669f9eb07c834f1ed725a552c09f5c2b6ddd3bb7
[ "Apache-2.0" ]
null
null
null
32.196429
97
0.711037
9,962
/* * Copyright 2015 Emanuel Moecklin * * 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.onegravity.rteditor; import android.text.Spannable; import com.onegravity.rteditor.spans.LinkSpan; /** * The interface to be implemented by the RTManager to listen to RTEditText events. */ public interface RTEditTextListener { /** * If this EditText changes focus the listener will be informed through this method. */ void onFocusChanged(RTEditText editor, boolean focused); /** * Provides details of the new selection, including the start and ending * character positions, and the id of this RTEditText component. */ void onSelectionChanged(RTEditText editor, int start, int end); /** * Text and or text effects have changed (used for undo/redo function). */ void onTextChanged(RTEditText editor, Spannable before, Spannable after, int selStartBefore, int selEndBefore, int selStartAfter, int selEndAfter); /** * A link in a LinkSpan has been clicked. */ public void onClick(RTEditText editor, LinkSpan span); /** * Rich text editing was enabled/disabled for this editor. */ public void onRichTextEditingChanged(RTEditText editor, boolean useRichText); }
3e1764869dd776b63dfa91c778b138af31bd346f
2,413
java
Java
app/src/main/java/com/zmtmt/zhibohao/activity/SpeedTestActivity.java
JunGeges/AliZhiBoHao
2dc8ebe6e23578b7919fbcbee09e5630fdf46997
[ "Apache-2.0" ]
1
2017-05-15T02:29:59.000Z
2017-05-15T02:29:59.000Z
app/src/main/java/com/zmtmt/zhibohao/activity/SpeedTestActivity.java
JunGeges/AliZhiBoHao
2dc8ebe6e23578b7919fbcbee09e5630fdf46997
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/zmtmt/zhibohao/activity/SpeedTestActivity.java
JunGeges/AliZhiBoHao
2dc8ebe6e23578b7919fbcbee09e5630fdf46997
[ "Apache-2.0" ]
null
null
null
40.216667
114
0.729383
9,963
package com.zmtmt.zhibohao.activity; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import com.zmtmt.zhibohao.R; public class SpeedTestActivity extends AppCompatActivity { private WebView mWebView; private TextView tv_0,tv_1,tv_2,tv_3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_speed_test); initViews(); initWeb(); } private void initViews() { mWebView = (WebView) findViewById(R.id.speed_test_wv); tv_0=(TextView)findViewById(R.id.tv_0); tv_1=(TextView)findViewById(R.id.tv_1); tv_2=(TextView)findViewById(R.id.tv_2);//0e94af tv_3=(TextView)findViewById(R.id.tv_3); buildSpannableString(tv_0,Color.RED,new Integer[]{5,15,18,22}); buildSpannableString(tv_1,Color.parseColor("#0E94AF"),new Integer[]{5,17,20,26}); buildSpannableString(tv_2,Color.parseColor("#0E94AF"),new Integer[]{5,15,18,24}); buildSpannableString(tv_3,Color.parseColor("#0E94AF"),new Integer[]{5,13,16,22}); } public void buildSpannableString(TextView tv,int color,Integer... ints){ SpannableString spannableString=new SpannableString(tv.getText().toString()); spannableString.setSpan(new ForegroundColorSpan(color),ints[0],ints[1], Spanned.SPAN_EXCLUSIVE_INCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(color),ints[2],ints[3], Spanned.SPAN_EXCLUSIVE_INCLUSIVE); tv.setText(spannableString); } private void initWeb() { WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setDefaultZoom(WebSettings.ZoomDensity.FAR); settings.setRenderPriority(WebSettings.RenderPriority.HIGH); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); mWebView.loadUrl("file:///android_asset/speedtest.html"); mWebView.setWebViewClient(new WebViewClient()); } }
3e176640886ea52ac4a822c2eab4a43b3f951146
2,402
java
Java
communote/plugins/communote-webservice-core-plugin/src/main/java/com/communote/plugins/webservice/CommunoteWebServiceDefinition.java
Communote/communote-server
e6a3541054baa7ad26a4eccbbdd7fb8937dead0c
[ "Apache-2.0" ]
26
2016-06-27T09:25:10.000Z
2022-01-24T06:26:56.000Z
communote/plugins/communote-webservice-core-plugin/src/main/java/com/communote/plugins/webservice/CommunoteWebServiceDefinition.java
Communote/communote-server
e6a3541054baa7ad26a4eccbbdd7fb8937dead0c
[ "Apache-2.0" ]
64
2016-06-28T14:50:46.000Z
2019-05-04T15:10:04.000Z
communote/plugins/communote-webservice-core-plugin/src/main/java/com/communote/plugins/webservice/CommunoteWebServiceDefinition.java
Communote/communote-server
e6a3541054baa7ad26a4eccbbdd7fb8937dead0c
[ "Apache-2.0" ]
4
2016-10-05T17:30:36.000Z
2019-10-26T15:44:00.000Z
26.395604
97
0.613239
9,964
package com.communote.plugins.webservice; /** * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> */ public class CommunoteWebServiceDefinition { /** * For example "http://schemas.microsoft.com/sharepoint/remoteapp/" */ private String nameSpaceUri; /** * For example MyRemoteEventService.class */ private Class<?> serviceClass; /** * For example "MyRemoteEventService" */ private String localPartName; /** * For example "RemoteEventReceiver" */ private String endpointName; /** * For example com.communote.plugin.myplugin */ private String pluginName; /** * for example "/Services/RemoteEventReceiver.svc" */ private String relativeUrlPattern; public String getEndpointName() { return endpointName; } public String getLocalPartName() { return localPartName; } public String getNameSpaceUri() { return nameSpaceUri; } public String getPluginName() { return pluginName; } public String getRelativeUrlPattern() { return relativeUrlPattern; } public Class<?> getServiceClass() { return serviceClass; } public void setEndpointName(String endpointName) { this.endpointName = endpointName; } public void setLocalPartName(String localPartName) { this.localPartName = localPartName; } /** * @param nameSpaceUri */ public void setNameSpaceUri(String nameSpaceUri) { this.nameSpaceUri = nameSpaceUri; } public void setPluginName(String pluginName) { this.pluginName = pluginName; } public void setRelativeUrlPattern(String relativeUrlPattern) { this.relativeUrlPattern = relativeUrlPattern; } public void setServiceClass(Class<?> serviceClass) { this.serviceClass = serviceClass; } @Override public String toString() { return "CommunoteWebServiceDefinition [nameSpaceUri=" + nameSpaceUri + ", serviceClass=" + serviceClass + ", localPartName=" + localPartName + ", endpointName=" + endpointName + ", pluginName=" + pluginName + ", relativeUrlPattern=" + relativeUrlPattern + "]"; } }
3e17664995c1513aa433e71b0430c81be479490a
7,192
java
Java
core/src/z/system/WorkerSystem.java
zonesgame/StendhalArcClient
70d9c37d1b4112349e4dbabc3206204b4446d6d0
[ "Apache-2.0" ]
1
2021-07-09T05:49:05.000Z
2021-07-09T05:49:05.000Z
core/src/z/system/WorkerSystem.java
zonesgame/StendhalArcClient
70d9c37d1b4112349e4dbabc3206204b4446d6d0
[ "Apache-2.0" ]
null
null
null
core/src/z/system/WorkerSystem.java
zonesgame/StendhalArcClient
70d9c37d1b4112349e4dbabc3206204b4446d6d0
[ "Apache-2.0" ]
2
2021-12-08T18:33:26.000Z
2022-01-06T23:46:55.000Z
32.107143
159
0.589405
9,965
package z.system; import arc.struct.Array; import arc.util.Structs; import mindustry.Vars; import mindustry.type.Item; import mindustry.type.ItemStack; import mindustry.world.Tile; import mindustry.world.meta.BlockFlag; import z.entities.type.WorkerTileEntity; import z.entities.type.base.BlockUnit; import z.world.blocks.caesar.HousingIso; import z.world.blocks.defense.WorkBlock; import static mindustry.Vars.indexer; import static mindustry.Vars.systemItems; import static z.debug.ZDebug.forceAddItem; /** * */ public class WorkerSystem { //工作优先级 public static final int PRIORITY_1 = 0; public static final int PRIORITY_2 = 1; public static final int PRIORITY_3 = 2; public static final int PRIORITY_4 = 3; public static final int PRIORITY_5 = 4; /** 是否紧急状态*/ private boolean stateOfEmergency = false; /** 当前工作优先级*/ private int curPriority = PRIORITY_5; /** 农民数量*/ public int peasant, peasantUse, peasantMax, peasantMaxNext; /** 工人数量*/ public int worker, workerUse, workerMax, workerMaxNext; /** 最大工人数量*/ public int maxCount; /** 当前工人数量*/ public int curCount; /** 空闲工人数量*/ public int idleCount; /** 工人死亡恢复速度*/ public float recoveryRate; // public WorkerPool<BlockUnit> workerPool; public WorkerSystem() { // workerPool = new WorkerPool<BlockUnit>(); } public void updateSystem() { { // 工人数量更新 peasantMax = peasantUse = peasantMaxNext; workerMax = workerUse = workerMaxNext; peasantMaxNext = workerMaxNext = 0; } if(stateOfEmergency) { stateOfEmergency = false; if(curPriority > PRIORITY_1) --curPriority; } else { if(curPriority < PRIORITY_5) ++curPriority; } } /** Block工作状态, 处理农民使用情况, Block是否可以执行工作*/ public boolean processWorking(Tile tile) { WorkerTileEntity entity = tile.ent(); int needPeasant = ((WorkBlock) tile.block()).needPeasants[entity.level()]; if(getPeasantUse() >= needPeasant){ if(entity.priority <= curPriority){ peasantUse -= needPeasant; return true; } }else{ stateOfEmergency = true; } // if(entity.priority <= curPriority && getPeasantUse() >= needPeasant) { // peasantUse -= needPeasant; // return true; // } else { // stateOfEmergency = true; // } return false; } /** Unit工作状态, 是否可以提供工作单位*/ public void processWorker(Tile tile) { workerUse -= tile.<WorkerTileEntity>ent().useWorker; } /** 处理房屋提供工人和农民情况*/ public void processOffer(Tile tile) { HousingIso block = (HousingIso) tile.block(); HousingIso.HousingIsoEntity entity = tile.ent(); peasantMaxNext += block.getOfferPeasant(entity); workerMaxNext += block.getOfferWorker(entity); } public boolean offerWorker(Tile tile) { WorkerTileEntity entity = tile.ent(); int needWorker = ((WorkBlock) tile.block()).workerMultiplier[entity.level()]; if(getWorkerUse() >= needWorker){ if(entity.priority <= curPriority){ workerUse -= needWorker; return true; } } return false; } private int getPeasantUse() { return peasantUse; } private int getWorkerUse() { return workerUse; } /** 获取运输存储的目标Tile*/ public Tile getTransportTile(BlockUnit unit, ItemStack item) { Tile returnValue = null; if (systemItems.isFood(item.item)) { Array<Tile> granaryArray = indexer.getAllied(unit.getTeam(), BlockFlag.granary).asArray().sort(Structs.comparingFloat(t -> t.dst(unit.x, unit.y))); granaryArray = unit.getNoDisableTarget(granaryArray); returnValue = transportTileNode(granaryArray, item.item); if(returnValue != null) return returnValue; } // 粮仓处理 end Array<Tile> warehouseArray = indexer.getAllied(unit.getTeam(), BlockFlag.warehouse).asArray().sort(Structs.comparingFloat(t -> t.dst(unit.x, unit.y))); warehouseArray = unit.getNoDisableTarget(warehouseArray); returnValue = transportTileNode(warehouseArray, item.item); return returnValue; } /** 获取得到物品的存储目标Tile*/ public Tile getGettingTile(BlockUnit unit, ItemStack itemGet) { Tile returnValue = null; if (Vars.systemItems.isFood(itemGet.item)) { Array<Tile> granaryArray = indexer.getAllied(unit.getTeam(), BlockFlag.granary).asArray().sort(Structs.comparingFloat(t -> t.dst(unit.x, unit.y))); granaryArray = unit.getNoDisableTarget(granaryArray); returnValue = gettingTileNode(granaryArray, itemGet.item, itemGet.amount); if (returnValue != null) return returnValue; } Array<Tile> warehouseArray = indexer.getAllied(unit.getTeam(), BlockFlag.warehouse).asArray().sort(Structs.comparingFloat(t -> t.dst(unit.x, unit.y))); warehouseArray = unit.getNoDisableTarget(warehouseArray); returnValue = gettingTileNode(warehouseArray, itemGet.item, itemGet.amount); return returnValue; // 未找到拥有物品 } private Tile transportTileNode(Array<Tile> arr, Item itemAccept) { // for (Tile node : arr) { for (int i = 0; i < arr.size; i++) { // 配置获取物品瓦砾 Tile node = arr.get(i); if (node.block().getItemCaesar(itemAccept, node, node)) // 根据配置<获取>目标 return node; } for (int i = 0; i < arr.size; i++) { // 配置接收物品瓦砾 Tile node = arr.get(i); if (node.block().acceptItemCaesar(itemAccept, node, node)) // 根据配置<接收>目标 return node; } if (forceAddItem) { for (int i = 0; i < arr.size; i++) { // 强制添加物品到能接收的块 Tile node = arr.get(i); if (node.block().acceptItem(itemAccept, node, node)) // 强制设置目标 return node; } } // 处理 end return null; } private Tile gettingTileNode(Array<Tile> arr, Item itemGet, int amount) { if (arr.size == 0) return null; Tile returnTile = null; // int curAmount = 0; // // for (int i = 0; i < arr.size; i++) { //// for (Tile node : arr) { // Tile node = arr.get(i); // int itemAmount = node.ent().items.get(itemGet); // if (itemAmount >= amount) // return node; // // if (itemAmount > curAmount) { // curAmount = itemAmount; // returnTile = node; // } // } for (int i = 0; i < arr.size; i++) { Tile node = arr.get(i); if (node.ent().items.get(itemGet) >= amount) return node; if (returnTile == null || node.ent().items.get(itemGet) > returnTile.ent().items.get(itemGet)) { returnTile = node; } } return returnTile.entity.items.get(itemGet) > 0 ? returnTile : null; } }
3e17668ff42b62b5d0eaa583cf1334d88aca19c7
23,920
java
Java
framework/widget/src/org/ofbiz/widget/menu/ModelMenu.java
hadilq/ofbiz
cb26ff60955895155dc21744cd06352dcb66519b
[ "Apache-2.0" ]
null
null
null
framework/widget/src/org/ofbiz/widget/menu/ModelMenu.java
hadilq/ofbiz
cb26ff60955895155dc21744cd06352dcb66519b
[ "Apache-2.0" ]
null
null
null
framework/widget/src/org/ofbiz/widget/menu/ModelMenu.java
hadilq/ofbiz
cb26ff60955895155dc21744cd06352dcb66519b
[ "Apache-2.0" ]
null
null
null
39.213115
150
0.662584
9,966
/******************************************************************************* * 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.ofbiz.widget.menu; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.collections.FlexibleMapAccessor; import org.ofbiz.base.util.string.FlexibleStringExpander; import org.ofbiz.widget.ModelWidget; import org.ofbiz.widget.ModelWidgetAction; import org.ofbiz.widget.ModelWidgetVisitor; import org.w3c.dom.Element; /** * Widget Library - Menu model class */ @SuppressWarnings("serial") public class ModelMenu extends ModelWidget { public static final String module = ModelMenu.class.getName(); protected List<ModelWidgetAction> actions; protected String defaultAlign; protected String defaultAlignStyle; protected FlexibleStringExpander defaultAssociatedContentId; protected String defaultCellWidth; protected String defaultDisabledTitleStyle; protected String defaultEntityName; protected Boolean defaultHideIfSelected; protected String defaultMenuItemName; protected String defaultPermissionEntityAction; protected String defaultPermissionOperation; protected String defaultPermissionStatusId; protected String defaultPrivilegeEnumId; protected String defaultSelectedStyle; protected String defaultTitleStyle; protected String defaultTooltipStyle; protected String defaultWidgetStyle; protected FlexibleStringExpander extraIndex; protected String fillStyle; protected String id; protected FlexibleStringExpander menuContainerStyleExdr; /** This List will contain one copy of each item for each item name in the order * they were encountered in the service, entity, or menu definition; item definitions * with constraints will also be in this list but may appear multiple times for the same * item name. * * When rendering the menu the order in this list should be following and it should not be * necessary to use the Map. The Map is used when loading the menu definition to keep the * list clean and implement the override features for item definitions. */ protected List<ModelMenuItem> menuItemList = new ArrayList<ModelMenuItem>(); /** This Map is keyed with the item name and has a ModelMenuItem for the value; items * with conditions will not be put in this Map so item definition overrides for items * with conditions is not possible. */ protected Map<String, ModelMenuItem> menuItemMap = new HashMap<String, ModelMenuItem>(); protected String menuLocation; protected String menuWidth; protected String orientation = "horizontal"; protected FlexibleMapAccessor<String> selectedMenuItemContextFieldName; protected String target; protected FlexibleStringExpander title; protected String tooltip; protected String type; // ===== CONSTRUCTORS ===== /** XML Constructor */ public ModelMenu(Element menuElement) { super(menuElement); // check if there is a parent menu to inherit from String parentResource = menuElement.getAttribute("extends-resource"); String parentMenu = menuElement.getAttribute("extends"); if (parentMenu.length() > 0 && !(parentMenu.equals(menuElement.getAttribute("name")) && UtilValidate.isEmpty(parentResource))) { ModelMenu parent = null; // check if we have a resource name (part of the string before the ?) if (UtilValidate.isNotEmpty(parentResource)) { try { parent = MenuFactory.getMenuFromLocation(parentResource, parentMenu); } catch (Exception e) { Debug.logError(e, "Failed to load parent menu definition '" + parentMenu + "' at resource '" + parentResource + "'", module); } } else { // try to find a menu definition in the same file Element rootElement = menuElement.getOwnerDocument().getDocumentElement(); List<? extends Element> menuElements = UtilXml.childElementList(rootElement, "menu"); //Uncomment below to add support for abstract menus //menuElements.addAll(UtilXml.childElementList(rootElement, "abstract-menu")); for (Element menuElementEntry : menuElements) { if (menuElementEntry.getAttribute("name").equals(parentMenu)) { parent = new ModelMenu(menuElementEntry); break; } } if (parent == null) { Debug.logError("Failed to find parent menu definition '" + parentMenu + "' in same document.", module); } } if (parent != null) { this.type = parent.type; this.target = parent.target; this.id = parent.id; this.title = parent.title; this.tooltip = parent.tooltip; this.defaultEntityName = parent.defaultEntityName; this.defaultTitleStyle = parent.defaultTitleStyle; this.defaultSelectedStyle = parent.defaultSelectedStyle; this.defaultWidgetStyle = parent.defaultWidgetStyle; this.defaultTooltipStyle = parent.defaultTooltipStyle; this.defaultMenuItemName = parent.defaultMenuItemName; this.menuItemList.addAll(parent.menuItemList); this.menuItemMap.putAll(parent.menuItemMap); this.defaultPermissionOperation = parent.defaultPermissionOperation; this.defaultPermissionEntityAction = parent.defaultPermissionEntityAction; this.defaultAssociatedContentId = parent.defaultAssociatedContentId; this.defaultPermissionStatusId = parent.defaultPermissionStatusId; this.defaultPrivilegeEnumId = parent.defaultPrivilegeEnumId; this.defaultHideIfSelected = parent.defaultHideIfSelected; this.orientation = parent.orientation; this.menuWidth = parent.menuWidth; this.defaultCellWidth = parent.defaultCellWidth; this.defaultDisabledTitleStyle = parent.defaultDisabledTitleStyle; this.defaultAlign = parent.defaultAlign; this.defaultAlignStyle = parent.defaultAlignStyle; this.fillStyle = parent.fillStyle; this.extraIndex = parent.extraIndex; this.selectedMenuItemContextFieldName = parent.selectedMenuItemContextFieldName; this.menuContainerStyleExdr = parent.menuContainerStyleExdr; if (parent.actions != null) { this.actions = new ArrayList<ModelWidgetAction>(); this.actions.addAll(parent.actions); } } } if (this.type == null || menuElement.hasAttribute("type")) this.type = menuElement.getAttribute("type"); if (this.target == null || menuElement.hasAttribute("target")) this.target = menuElement.getAttribute("target"); if (this.id == null || menuElement.hasAttribute("id")) this.id = menuElement.getAttribute("id"); if (this.title == null || menuElement.hasAttribute("title")) this.setTitle(menuElement.getAttribute("title")); if (this.tooltip == null || menuElement.hasAttribute("tooltip")) this.tooltip = menuElement.getAttribute("tooltip"); if (this.defaultEntityName == null || menuElement.hasAttribute("default-entity-name")) this.defaultEntityName = menuElement.getAttribute("default-entity-name"); if (this.defaultTitleStyle == null || menuElement.hasAttribute("default-title-style")) this.defaultTitleStyle = menuElement.getAttribute("default-title-style"); if (this.defaultSelectedStyle == null || menuElement.hasAttribute("default-selected-style")) this.defaultSelectedStyle = menuElement.getAttribute("default-selected-style"); if (this.defaultWidgetStyle == null || menuElement.hasAttribute("default-widget-style")) this.defaultWidgetStyle = menuElement.getAttribute("default-widget-style"); if (this.defaultTooltipStyle == null || menuElement.hasAttribute("default-tooltip-style")) this.defaultTooltipStyle = menuElement.getAttribute("default-tooltip-style"); if (this.defaultMenuItemName == null || menuElement.hasAttribute("default-menu-item-name")) this.defaultMenuItemName = menuElement.getAttribute("default-menu-item-name"); if (this.defaultPermissionOperation == null || menuElement.hasAttribute("default-permission-operation")) this.defaultPermissionOperation = menuElement.getAttribute("default-permission-operation"); if (this.defaultPermissionEntityAction == null || menuElement.hasAttribute("default-permission-entity-action")) this.defaultPermissionEntityAction = menuElement.getAttribute("default-permission-entity-action"); if (this.defaultPermissionStatusId == null || menuElement.hasAttribute("defaultPermissionStatusId")) this.defaultPermissionStatusId = menuElement.getAttribute("default-permission-status-id"); if (this.defaultPrivilegeEnumId == null || menuElement.hasAttribute("defaultPrivilegeEnumId")) this.defaultPrivilegeEnumId = menuElement.getAttribute("default-privilege-enum-id"); if (this.defaultAssociatedContentId == null || menuElement.hasAttribute("defaultAssociatedContentId")) this.setDefaultAssociatedContentId(menuElement.getAttribute("default-associated-content-id")); if (this.orientation == null || menuElement.hasAttribute("orientation")) this.orientation = menuElement.getAttribute("orientation"); if (this.menuWidth == null || menuElement.hasAttribute("menu-width")) this.menuWidth = menuElement.getAttribute("menu-width"); if (this.defaultCellWidth == null || menuElement.hasAttribute("default-cell-width")) this.defaultCellWidth = menuElement.getAttribute("default-cell-width"); if (menuElement.hasAttribute("default-hide-if-selected")) { String val = menuElement.getAttribute("default-hide-if-selected"); if (val != null && val.equalsIgnoreCase("true")) defaultHideIfSelected = Boolean.TRUE; else defaultHideIfSelected = Boolean.FALSE; } if (this.defaultDisabledTitleStyle == null || menuElement.hasAttribute("default-disabled-title-style")) this.defaultDisabledTitleStyle = menuElement.getAttribute("default-disabled-title-style"); if (this.selectedMenuItemContextFieldName == null || menuElement.hasAttribute("selected-menuitem-context-field-name")) this.selectedMenuItemContextFieldName = FlexibleMapAccessor.getInstance(menuElement.getAttribute("selected-menuitem-context-field-name")); if (this.menuContainerStyleExdr == null || menuElement.hasAttribute("menu-container-style")) this.setMenuContainerStyle(menuElement.getAttribute("menu-container-style")); if (this.defaultAlign == null || menuElement.hasAttribute("default-align")) this.defaultAlign = menuElement.getAttribute("default-align"); if (this.defaultAlignStyle == null || menuElement.hasAttribute("default-align-style")) this.defaultAlignStyle = menuElement.getAttribute("default-align-style"); if (this.fillStyle == null || menuElement.hasAttribute("fill-style")) this.fillStyle = menuElement.getAttribute("fill-style"); if (this.extraIndex == null || menuElement.hasAttribute("extra-index")) this.setExtraIndex(menuElement.getAttribute("extra-index")); // read all actions under the "actions" element Element actionsElement = UtilXml.firstChildElement(menuElement, "actions"); if (actionsElement != null) { if (this.actions == null) { this.actions = ModelMenuAction.readSubActions(this, actionsElement); } else { this.actions.addAll(ModelMenuAction.readSubActions(this, actionsElement)); ArrayList<ModelWidgetAction> actionsList = (ArrayList<ModelWidgetAction>)this.actions; actionsList.trimToSize(); } } // read in add item defs, add/override one by one using the menuItemList List<? extends Element> itemElements = UtilXml.childElementList(menuElement, "menu-item"); for (Element itemElement : itemElements) { ModelMenuItem modelMenuItem = new ModelMenuItem(itemElement, this); modelMenuItem = this.addUpdateMenuItem(modelMenuItem); } } /** * add/override modelMenuItem using the menuItemList and menuItemMap * * @return The same ModelMenuItem, or if merged with an existing item, the existing item. */ public ModelMenuItem addUpdateMenuItem(ModelMenuItem modelMenuItem) { // not a conditional item, see if a named item exists in Map ModelMenuItem existingMenuItem = this.menuItemMap.get(modelMenuItem.getName()); if (existingMenuItem != null) { // does exist, update the item by doing a merge/override existingMenuItem.mergeOverrideModelMenuItem(modelMenuItem); return existingMenuItem; } else { // does not exist, add to List and Map this.menuItemList.add(modelMenuItem); this.menuItemMap.put(modelMenuItem.getName(), modelMenuItem); return modelMenuItem; } } public ModelMenuItem getModelMenuItemByName(String name) { return this.menuItemMap.get(name); } /** * Renders this menu to a String, i.e. in a text format, as defined with the * MenuStringRenderer implementation. * * @param writer The Writer that the menu text will be written to * @param context Map containing the menu context; the following are * reserved words in this context: parameters (Map), isError (Boolean), * itemIndex (Integer, for lists only, otherwise null), bshInterpreter, * menuName (String, optional alternate name for menu, defaults to the * value of the name attribute) * @param menuStringRenderer An implementation of the MenuStringRenderer * interface that is responsible for the actual text generation for * different menu elements; implementing you own makes it possible to * use the same menu definitions for many types of menu UIs */ public void renderMenuString(Appendable writer, Map<String, Object> context, MenuStringRenderer menuStringRenderer) throws IOException { ModelWidgetAction.runSubActions(this.actions, context); if ("simple".equals(this.type)) { this.renderSimpleMenuString(writer, context, menuStringRenderer); } else { throw new IllegalArgumentException("The type " + this.getType() + " is not supported for menu with name " + this.getName()); } } public void runActions(Map<String, Object> context) { ModelWidgetAction.runSubActions(this.actions, context); } public int renderedMenuItemCount(Map<String, Object> context) { int count = 0; for (ModelMenuItem item : this.menuItemList) { if (item.shouldBeRendered(context)) count++; } return count; } public void renderSimpleMenuString(Appendable writer, Map<String, Object> context, MenuStringRenderer menuStringRenderer) throws IOException { // render menu open menuStringRenderer.renderMenuOpen(writer, context, this); // render formatting wrapper open menuStringRenderer.renderFormatSimpleWrapperOpen(writer, context, this); // render each menuItem row, except hidden & ignored rows for (ModelMenuItem item : this.menuItemList) { item.renderMenuItemString(writer, context, menuStringRenderer); } // render formatting wrapper close menuStringRenderer.renderFormatSimpleWrapperClose(writer, context, this); // render menu close menuStringRenderer.renderMenuClose(writer, context, this); } public String getDefaultEntityName() { return this.defaultEntityName; } public String getDefaultAlign() { return this.defaultAlign; } public String getDefaultAlignStyle() { return this.defaultAlignStyle; } public String getDefaultTitleStyle() { return this.defaultTitleStyle; } public String getDefaultDisabledTitleStyle() { return this.defaultDisabledTitleStyle; } public String getDefaultSelectedStyle() { return this.defaultSelectedStyle; } public String getDefaultWidgetStyle() { return this.defaultWidgetStyle; } public String getDefaultTooltipStyle() { return this.defaultTooltipStyle; } public String getDefaultMenuItemName() { return this.defaultMenuItemName; } public String getFillStyle() { return this.fillStyle; } public String getSelectedMenuItemContextFieldName(Map<String, Object> context) { String menuItemName = this.selectedMenuItemContextFieldName.get(context); if (UtilValidate.isEmpty(menuItemName)) { return this.defaultMenuItemName; } return menuItemName; } public String getCurrentMenuName(Map<String, Object> context) { return getName(); } public String getId() { return this.id; } public String getTitle(Map<String, Object> context) { return title.expandString(context); } public String getTooltip() { return this.tooltip; } public String getType() { return this.type; } @Override public String getBoundaryCommentName() { return menuLocation + "#" + getName(); } /** * @param string */ public void setDefaultEntityName(String string) { this.defaultEntityName = string; } /** * @param string */ public void setDefaultTitleStyle(String string) { this.defaultTitleStyle = string; } /** * @param string */ public void setDefaultSelectedStyle(String string) { this.defaultSelectedStyle = string; } /** * @param string */ public void setDefaultWidgetStyle(String string) { this.defaultWidgetStyle = string; } /** * @param string */ public void setDefaultTooltipStyle(String string) { this.defaultTooltipStyle = string; } /** * @param string */ public void setDefaultMenuItemName(String string) { this.defaultMenuItemName = string; } /** * @param menuLocation the menu location to set */ public void setMenuLocation(String menuLocation) { this.menuLocation = menuLocation; } /** * @param string */ public void setTarget(String string) { this.target = string; } /** * @param string */ public void setId(String string) { this.id = string; } /** * @param string */ public void setTitle(String string) { this.title = FlexibleStringExpander.getInstance(string); } /** * @param string */ public void setTooltip(String string) { this.tooltip = string; } /** * @param string */ public void setType(String string) { this.type = string; } /** * @param string */ public void setDefaultAssociatedContentId(String string) { this.defaultAssociatedContentId = FlexibleStringExpander.getInstance(string); } /** * @param string */ public void setMenuContainerStyle(String string) { this.menuContainerStyleExdr = FlexibleStringExpander.getInstance(string); } public String getDefaultAssociatedContentId(Map<String, Object> context) { return defaultAssociatedContentId.expandString(context); } public String getMenuContainerStyle(Map<String, Object> context) { return menuContainerStyleExdr.expandString(context); } /** * @param string */ public void setDefaultPermissionOperation(String string) { this.defaultPermissionOperation = string; } public String getDefaultPermissionStatusId() { return this.defaultPermissionStatusId; } /** * @param string */ public void setDefaultPermissionStatusId(String string) { this.defaultPermissionStatusId = string; } /** * @param string */ public void setDefaultPrivilegeEnumId(String string) { this.defaultPrivilegeEnumId = string; } public String getDefaultPrivilegeEnumId() { return this.defaultPrivilegeEnumId; } /** * @param string */ public void setOrientation(String string) { this.orientation = string; } public String getOrientation() { return this.orientation; } /** * @param string */ public void setMenuWidth(String string) { this.menuWidth = string; } public String getMenuWidth() { return this.menuWidth; } /** * @param string */ public void setDefaultCellWidth(String string) { this.defaultCellWidth = string; } public String getDefaultCellWidth() { return this.defaultCellWidth; } public String getDefaultPermissionOperation() { return this.defaultPermissionOperation; } /** * @param string */ public void setDefaultPermissionEntityAction(String string) { this.defaultPermissionEntityAction = string; } public String getDefaultPermissionEntityAction() { return this.defaultPermissionEntityAction; } /** * @param val */ public void setDefaultHideIfSelected(Boolean val) { this.defaultHideIfSelected = val; } public Boolean getDefaultHideIfSelected() { return this.defaultHideIfSelected; } public List<ModelMenuItem> getMenuItemList() { return menuItemList; } public String getExtraIndex(Map<String, Object> context) { try { return extraIndex.expandString(context); } catch (Exception ex) { return ""; } } public void setExtraIndex(String extraIndex) { this.extraIndex = FlexibleStringExpander.getInstance(extraIndex); } @Override public void accept(ModelWidgetVisitor visitor) throws Exception { visitor.visit(this); } }
3e176757fda42f6e3aafa50b122b3da15a63ea84
3,523
java
Java
src/main/java/com/devteam/core/module/data/db/EntityInfo.java
Devteamvietnam/iTap
a4b04d1b9d95a5ed879d9bf8d79583f7a8b59c03
[ "MIT" ]
1
2021-12-18T17:06:15.000Z
2021-12-18T17:06:15.000Z
src/main/java/com/devteam/core/module/data/db/EntityInfo.java
Devteamvietnam/iTap
a4b04d1b9d95a5ed879d9bf8d79583f7a8b59c03
[ "MIT" ]
1
2022-02-15T03:24:45.000Z
2022-02-15T03:24:45.000Z
src/main/java/com/devteam/core/module/data/db/EntityInfo.java
Devteamvietnam/iTap
a4b04d1b9d95a5ed879d9bf8d79583f7a8b59c03
[ "MIT" ]
1
2021-12-18T17:06:00.000Z
2021-12-18T17:06:00.000Z
30.111111
90
0.643486
9,967
package com.devteam.core.module.data.db; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Table; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.EntityType; import com.devteam.core.util.bean.BeanInspector; import com.devteam.core.util.ds.Arrays; import com.devteam.core.util.ds.Collections; import com.devteam.core.util.text.StringUtil; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @Getter @Setter public class EntityInfo { private String name; private String category; private String className; private String tableName; private List<FieldDescriptor> fields; private Set<String> checks; public EntityInfo(EntityType<?> type) { Class<?> javaType = type.getBindableJavaType(); name = javaType.getSimpleName(); className = javaType.getName(); tableName = javaType.getDeclaredAnnotation(Table.class).name(); int prefixIdx = tableName.indexOf('_'); if(prefixIdx > 0) { category = tableName.substring(0, prefixIdx); } else { category = tableName; } fields = new ArrayList<>(); BeanInspector<?> inspector = BeanInspector.get(javaType); for(Attribute<?, ?> sel : type.getAttributes()) { fields.add(new FieldDescriptor(inspector, sel)); } detectProblem(); } void addCheck(String ... check) { checks = Arrays.addToSet(checks, check); } void detectProblem() { for(FieldDescriptor sel : fields) { if(Collections.isNotEmpty(sel.checks)) { addCheck("TABLE_FIELD"); } } if(tableName.length() > 60) { addCheck("TABLE_NAME_LENGTH"); } } @NoArgsConstructor @Getter @Setter static public class FieldDescriptor { private String name; private String persistentType ; private String dataType; private String tableFieldName; private Set<String> checks; public FieldDescriptor(BeanInspector<?> inspector, Attribute<?, ?> attr) { name = attr.getName(); persistentType = attr.getPersistentAttributeType().toString(); dataType = attr.getJavaType().getSimpleName(); tableFieldName = name; Field field = inspector.getField(name); if(field != null) { Column columnAnnotation = field.getDeclaredAnnotation(Column.class); if(columnAnnotation != null) { if(!StringUtil.isEmpty(columnAnnotation.name())) { tableFieldName = columnAnnotation.name(); } } } else { PropertyDescriptor descriptor = inspector.getPropertyDescriptor(name); if(descriptor != null) { Column column = descriptor.getReadMethod().getDeclaredAnnotation(Column.class); if(column != null) { if(!StringUtil.isEmpty(column.name())) { tableFieldName = column.name(); } } } } detectProblem(); } void addCheck(String ... check) { checks = Arrays.addToSet(checks, check); } void detectProblem() { if(!"BASIC".equals(persistentType)) return; for(int i = 0; i < tableFieldName.length(); i++) { if(Character.isUpperCase(tableFieldName.charAt(i))) { addCheck("TABLE_FIELD"); break; } } } } }
3e176853166eb4a5301fc477614225e2b0357e8f
2,674
java
Java
src/main/java/com/vzome/core/commands/Command.java
david-hall/vzome-core
f32c64087cba18075b2e84576246ebbdc1631ed8
[ "Apache-2.0" ]
9
2019-01-16T04:15:31.000Z
2021-09-18T22:36:14.000Z
src/main/java/com/vzome/core/commands/Command.java
david-hall/vzome-core
f32c64087cba18075b2e84576246ebbdc1631ed8
[ "Apache-2.0" ]
82
2017-10-28T21:09:20.000Z
2022-02-27T00:10:07.000Z
src/main/java/com/vzome/core/commands/Command.java
david-hall/vzome-core
f32c64087cba18075b2e84576246ebbdc1631ed8
[ "Apache-2.0" ]
8
2017-10-28T21:55:34.000Z
2021-12-11T04:38:31.000Z
29.065217
111
0.608826
9,968
package com.vzome.core.commands; import java.util.logging.Level; import java.util.logging.Logger; import com.vzome.core.construction.ConstructionChanges; import com.vzome.core.construction.ConstructionList; /** * @author Scott Vorthmann */ public interface Command { public static final String LOADING_FROM_FILE = "org.vorthmann.zome.editor.Command.LOADING_FROM_FILE"; public static final String FIELD_ATTR_NAME = "org.vorthmann.zome.commands.Command.ALGEBRAIC_FIELD"; public static final String GENERIC_PARAM_NAME = "org.vorthmann.zome.editor.Command.GENERIC_PARAM"; /** * Get the parameter signature for this command. * Parameter are an ordered list of pre-existing Constructions. * Each parameter has a name (for UI purposes), and an abstract Construction type * (Point, Line, Segment, Plane, ...). * @return an array of { String, Class } pairs, one for each parameter. */ Object[][] getParameterSignature(); /** * Get the attribute signature for this command. * Attributes are an unordered set of primitive values. * Each attribute has a name , and a primitive type * (GoldenNumber, GoldenVector, Axis, Direction, GoldenMatrix, ...). * @return an array of { String, Class } pairs, one for each attribute. */ Object[][] getAttributeSignature(); ConstructionList apply( ConstructionList parameters, AttributeMap attributes, ConstructionChanges effects ) throws Failure; public interface Registry { Command getCommand( String name ); } public interface FailureChannel { void reportFailure( Failure f ); } public static class Failure extends Exception { private static final Logger logger = Logger .getLogger( "org.vorthmann.zome.commands" ); public Failure() { super(); } /** * @param message */ public Failure( String message ) { super( message ); if ( logger .isLoggable( Level.FINE ) ) logger .log( Level.FINE, "command failure: " + message ); } /** * @param message * @param cause */ public Failure( String message, Throwable cause ) { super( message, cause ); logger .log( Level.INFO, "command failure: " + message, cause ); } /** * @param cause */ public Failure( Throwable cause ) { super( cause ); logger .log( Level.INFO, "command failure", cause ); } } }
3e1768abc889394345b446e01d857bd8405f1053
2,049
java
Java
aws-java-sdk-codeartifact/src/main/java/com/amazonaws/services/codeartifact/model/transform/UpstreamRepositoryInfoMarshaller.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-codeartifact/src/main/java/com/amazonaws/services/codeartifact/model/transform/UpstreamRepositoryInfoMarshaller.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-codeartifact/src/main/java/com/amazonaws/services/codeartifact/model/transform/UpstreamRepositoryInfoMarshaller.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
36.589286
121
0.742801
9,969
/* * Copyright 2016-2021 Amazon.com, Inc. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codeartifact.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.codeartifact.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpstreamRepositoryInfoMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpstreamRepositoryInfoMarshaller { private static final MarshallingInfo<String> REPOSITORYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("repositoryName").build(); private static final UpstreamRepositoryInfoMarshaller instance = new UpstreamRepositoryInfoMarshaller(); public static UpstreamRepositoryInfoMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpstreamRepositoryInfo upstreamRepositoryInfo, ProtocolMarshaller protocolMarshaller) { if (upstreamRepositoryInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(upstreamRepositoryInfo.getRepositoryName(), REPOSITORYNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
3e176a1148199e3aaa99a9cf299633bce1de844d
936
java
Java
src/main/java/cz/encircled/test/model/Bid.java
encircled/websocket-bt
e2754764a30fe1225f75214b5865d252cabdccb7
[ "Apache-2.0" ]
null
null
null
src/main/java/cz/encircled/test/model/Bid.java
encircled/websocket-bt
e2754764a30fe1225f75214b5865d252cabdccb7
[ "Apache-2.0" ]
null
null
null
src/main/java/cz/encircled/test/model/Bid.java
encircled/websocket-bt
e2754764a30fe1225f75214b5865d252cabdccb7
[ "Apache-2.0" ]
null
null
null
18.72
54
0.605769
9,970
package cz.encircled.test.model; import java.math.BigDecimal; import java.util.Date; /** * @author Vlad on 19-Feb-17. */ public class Bid implements Comparable<Bid> { private BigDecimal amount; private String customerName; private Date bidDate; public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public Date getBidDate() { return bidDate; } public void setBidDate(Date bidDate) { this.bidDate = bidDate; } @Override public int compareTo(Bid o) { if(o == null || o.bidDate == null) { return 1; } else { return bidDate.compareTo(o.bidDate); } } }
3e176a992d3b9e9e3121370c959dcdd0ccb95765
1,420
java
Java
mongo/dao/BaseMongoDaoWithTimestamp.java
suxuekun/javaLib
8296a850e571b7271fa7c1db39681337cee87ced
[ "MIT" ]
null
null
null
mongo/dao/BaseMongoDaoWithTimestamp.java
suxuekun/javaLib
8296a850e571b7271fa7c1db39681337cee87ced
[ "MIT" ]
null
null
null
mongo/dao/BaseMongoDaoWithTimestamp.java
suxuekun/javaLib
8296a850e571b7271fa7c1db39681337cee87ced
[ "MIT" ]
null
null
null
22.903226
70
0.659859
9,971
package com.techstudio.dao; import org.bson.Document; import org.bson.conversions.Bson; abstract public class BaseMongoDaoWithTimestamp extends BaseMongoDao { private static String CURRENTDATEKEY = "$currentDate"; private static String LASTMODIFIED = "lastModified"; private static String TYPEKEY = "$type"; private static String TYPE = "timestamp"; public BaseMongoDaoWithTimestamp(String _name) { super(_name); } private void _addLastModified(Document update) { Document curDate = (Document) update.get(CURRENTDATEKEY); if (curDate == null) { curDate = new Document(); update.put(CURRENTDATEKEY, curDate); } curDate.put(LASTMODIFIED, new Document(TYPEKEY, TYPE)); } // -------------------------------------------------- // update funcitons // -------------------------------------------------- /** * @param filter * @param update * @return */ @Override public boolean update(Bson filter, Document update) { _addLastModified(update); return super.update(filter, update); } /** * @param filter * @param update * @return */ @Override public boolean insertOrUpdate(Bson filter, Document update) { _addLastModified(update); return super.insertOrUpdate(filter, update); } /** * * @param id * @param update * @return */ public boolean updateOne(String id,Document update){ _addLastModified(update); return super.updateOne(id, update); } }
3e176aaa73ead7a82b1ebfac742fcb0be21dbb70
135
java
Java
src/main/java/cn/kizzzy/io/FullyReader.java
Kizzzy/lib47-io
691a016e72884bd2afb51ade4da73fa90888923e
[ "Apache-2.0" ]
1
2022-01-11T05:47:50.000Z
2022-01-11T05:47:50.000Z
src/main/java/cn/kizzzy/io/FullyReader.java
Kizzzy/lib47-io
691a016e72884bd2afb51ade4da73fa90888923e
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/kizzzy/io/FullyReader.java
Kizzzy/lib47-io
691a016e72884bd2afb51ade4da73fa90888923e
[ "Apache-2.0" ]
null
null
null
16.875
79
0.814815
9,972
package cn.kizzzy.io; import java.io.InputStream; public abstract class FullyReader extends InputStream implements IFullyReader { }
3e176ad5b28b780071925c10012c6fbf39e6673f
1,937
java
Java
app/src/main/java/com/anly/githubapp/data/net/TrendingRepoDataSource.java
pxx11111/githubclient
89db6a104f31b9e8e5aab5c4e55aebbb0d87a0ad
[ "Apache-2.0" ]
1
2017-02-25T07:11:44.000Z
2017-02-25T07:11:44.000Z
app/src/main/java/com/anly/githubapp/data/net/TrendingRepoDataSource.java
pxx11111/githubclient
89db6a104f31b9e8e5aab5c4e55aebbb0d87a0ad
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/anly/githubapp/data/net/TrendingRepoDataSource.java
pxx11111/githubclient
89db6a104f31b9e8e5aab5c4e55aebbb0d87a0ad
[ "Apache-2.0" ]
null
null
null
30.265625
98
0.521941
9,973
package com.anly.githubapp.data.net; import com.anly.githubapp.common.util.AppLog; import com.anly.githubapp.data.api.TrendingApi; import com.anly.githubapp.data.model.TrendingRepo; import com.anly.githubapp.data.net.response.TrendingResultResp; import com.anly.githubapp.data.net.service.TrendingService; import java.util.ArrayList; import javax.inject.Inject; import rx.Observable; import rx.functions.Func1; /** * Created by mingjun on 16/7/20. */ public class TrendingRepoDataSource implements TrendingApi { TrendingService mTrendingService; @Inject public TrendingRepoDataSource(TrendingService service) { this.mTrendingService = service; } @Override public Observable<ArrayList<TrendingRepo>> getTrendingRepo(@LanguageType final int language) { return mTrendingService.getTrendingRepos() .map(new Func1<TrendingResultResp, ArrayList<TrendingRepo>>() { @Override public ArrayList<TrendingRepo> call(TrendingResultResp resp) { switch (language) { case LANG_JAVA: return resp.getJava(); case LANG_OC: return resp.getOc(); case LANG_SWIFT: return resp.getSwift(); case LANG_HTML: return resp.getHtml(); case LANG_PYTHON: return resp.getPython(); case LANG_BASH: return resp.getBash(); default: AppLog.w("unknown language"); break; } return null; } }); } }
3e176b040f5ead50084a01cfc0c1afdadad758d1
8,621
java
Java
3rdPartyServices/EnterpriseServices/NZone/server/src/main/java/org/societies/ext3p/nzone/server/NZoneCommsServer.java
societies/SOCIETIES-SCE-Services
ea2ed1f6a96e253e297dd64fd5db643a0268f193
[ "BSD-2-Clause" ]
null
null
null
3rdPartyServices/EnterpriseServices/NZone/server/src/main/java/org/societies/ext3p/nzone/server/NZoneCommsServer.java
societies/SOCIETIES-SCE-Services
ea2ed1f6a96e253e297dd64fd5db643a0268f193
[ "BSD-2-Clause" ]
null
null
null
3rdPartyServices/EnterpriseServices/NZone/server/src/main/java/org/societies/ext3p/nzone/server/NZoneCommsServer.java
societies/SOCIETIES-SCE-Services
ea2ed1f6a96e253e297dd64fd5db643a0268f193
[ "BSD-2-Clause" ]
null
null
null
34.902834
152
0.703051
9,974
/** * Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET * (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije * informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE * COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp., * INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM * ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC)) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Describe your class here... * * @author aleckey * */ package org.societies.ext3p.nzone.server; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.societies.api.comm.xmpp.datatypes.Stanza; import org.societies.api.comm.xmpp.exceptions.CommunicationException; import org.societies.api.comm.xmpp.exceptions.XMPPError; import org.societies.api.comm.xmpp.interfaces.ICommManager; import org.societies.api.comm.xmpp.interfaces.IFeatureServer; import org.societies.api.ext3p.schema.nzone.NzoneBean; import org.societies.api.ext3p.schema.nzone.NzoneBeanResult; import org.societies.api.ext3p.schema.nzone.UserDetails; public class NZoneCommsServer implements IFeatureServer { private static final List<String> NAMESPACES = Collections .unmodifiableList(Arrays .asList("http://societies.org/api/ext3p/schema/nzone")); private static final List<String> PACKAGES = Collections .unmodifiableList(Arrays .asList("org.societies.api.ext3p.schema.nzone")); // PRIVATE VARIABLES private ICommManager commManager; private NZoneServer nzoneServer; private static Logger LOG = LoggerFactory .getLogger(NZoneCommsServer.class); public ICommManager getCommManager() { return commManager; } public void setCommManager(ICommManager commManager) { this.commManager = commManager; } // METHODS public NZoneServer getNzoneServer() { return nzoneServer; } public void setNzoneServer(NZoneServer nzoneServer) { this.nzoneServer = nzoneServer; } public NZoneCommsServer() { } public void InitService() { // Registry Networking Directory with the Comms Manager try { getCommManager().register(this); LOG.info("Registered NZoneCommsServer with the xc manager"); } catch (CommunicationException e) { e.printStackTrace(); } } @Override public List<String> getJavaPackages() { return PACKAGES; } @Override public List<String> getXMLNamespaces() { return NAMESPACES; } /* Put your functionality here if there is NO return object, ie, VOID */ @Override public void receiveMessage(Stanza stanza, Object payload) { } /* Put your functionality here if there IS a return object */ @Override public Object getQuery(Stanza stanza, Object payload) throws XMPPError { if (LOG.isDebugEnabled()) LOG.debug("getQuery: Received a message!"); if (payload.getClass().equals(NzoneBean.class)) { if (LOG.isDebugEnabled()) LOG.debug("Remote call to NZone Comms Server"); NzoneBean messageBean = (NzoneBean) payload; NzoneBeanResult messageResult = new NzoneBeanResult(); messageResult.setResult(false); try { switch (messageBean.getMethod()) { case GET_ZONE_DETAILS: { messageResult.setZonedata(getNzoneServer().getNetZoneDetails()); messageResult.setResult(true); break; } case GET_MAIN_ZONE: { List<String> returnData = new ArrayList<String>(); returnData.add(getNzoneServer().getMainZoneCisID()); messageResult.setData(returnData); messageResult.setResult(true); break; } case GET_ZONE_LIST: { messageResult.setData(getNzoneServer().getZoneCisIDs()); messageResult.setResult(true); break; } case GET_USER_DETAILS: { messageResult.setUserdata(getNzoneServer().getUserDetails(stanza.getFrom().getBareJid(), messageBean.getData())); messageResult.setResult(true); break; } case GET_PREFERENCES: { List<String> returnData = new ArrayList<String>(); returnData.add(getNzoneServer().getPreferences(stanza.getFrom().getBareJid())); messageResult.setData(returnData); messageResult.setResult(true); break; } case SAVE_PREFERENCES: { messageResult.setResult(getNzoneServer().savePreferences(stanza.getFrom().getBareJid(), messageBean.getData().get(0))); break; } case GET_SHARE_PREFERENCES: { List<String> returnData = new ArrayList<String>(); returnData.add(getNzoneServer().getSharePreferences(stanza.getFrom().getBareJid())); messageResult.setData(returnData); messageResult.setResult(true); break; } case SAVE_SHARE_PREFERENCES: { messageResult.setResult(getNzoneServer().saveSharePreferences(stanza.getFrom().getBareJid(), messageBean.getData().get(0))); break; } case GET_MY_DETAILS: { List<UserDetails> returnData = new ArrayList<UserDetails>(); returnData.add(getNzoneServer().getProfileDetails(stanza.getFrom().getBareJid())); messageResult.setUserdata(returnData); messageResult.setResult(true); break; } case UPDATE_MY_DETAILS: { LOG.info("UPDATEMYDETAILS for user " + stanza.getFrom().getBareJid()); messageBean.getDetails().setUserid(stanza.getFrom().getBareJid()); // We need to check that the user only is allowed update their own record messageResult.setResult(getNzoneServer().updateMyDetails(messageBean.getDetails())); break; } case GET_SHARE_INFO: { messageResult.setShareinfo(getNzoneServer().getShareInfo(stanza.getFrom().getBareJid(), messageBean.getFriendid())); messageResult.setResult(true); break; } case UPDATE_SHARE_INFO: { messageResult.setResult(getNzoneServer().updateShareInfo(stanza.getFrom().getBareJid(), messageBean.getFriendid(), messageBean.getSharevalue())); break; } case UPDATE_INTERESTS: { messageResult.setResult(getNzoneServer().updateInterests(stanza.getFrom().getBareJid(), messageBean.getData())); break; } case UPDATE_USER_ZONE: { messageResult.setResult(getNzoneServer().updateUserLocation(stanza.getFrom().getBareJid(),messageBean.getData().get(0))); break; } } } catch (Exception e) { e.printStackTrace(); }; return messageResult; } return null; } /* * (non-Javadoc) * * @see * org.societies.comm.xmpp.interfaces.FeatureServer#setQuery(org.societies * .comm.xmpp.datatypes.Stanza, java.lang.Object) */ @Override public Object setQuery(Stanza arg0, Object arg1) throws XMPPError { // TODO Auto-generated method stub return null; } }
3e176b7665018594a3ce7c2813fba1c3eee58e6e
2,210
java
Java
src/main/javaopen/com/mindbright/asn1/ASN1Object.java
HaleyWang/SpringRemote
62e442731a4eda8e54dafb1dfb36064cd8dfa597
[ "MIT" ]
39
2019-02-26T02:02:38.000Z
2022-03-28T02:09:23.000Z
src/main/javaopen/com/mindbright/asn1/ASN1Object.java
HaleyWang/SpringRemote
62e442731a4eda8e54dafb1dfb36064cd8dfa597
[ "MIT" ]
2
2020-04-19T04:05:01.000Z
2022-03-27T02:10:18.000Z
src/main/javaopen/com/mindbright/asn1/ASN1Object.java
HaleyWang/SpringRemote
62e442731a4eda8e54dafb1dfb36064cd8dfa597
[ "MIT" ]
4
2020-03-17T07:23:33.000Z
2021-11-21T11:00:25.000Z
28.333333
79
0.553846
9,975
/****************************************************************************** * * Copyright (c) 1999-2011 Cryptzone Group AB. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code as * defined in and that are subject to the MindTerm Public Source License, * Version 2.0, (the 'License'). You may not use this file except in compliance * with the License. * * You should have received a copy of the MindTerm Public Source License * along with this software; see the file LICENSE. If not, write to * Cryptzone Group AB, Drakegatan 7, SE-41250 Goteborg, SWEDEN * *****************************************************************************/ package com.mindbright.asn1; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public abstract class ASN1Object { protected int tag; protected boolean isSet; protected ASN1Object(int tag) { this.tag = tag; } public final int getTag() { return tag; } public String getType() { String name = this.getClass().getName(); int i = name.lastIndexOf("."); if(i > 0) { name = name.substring(i + 1); } return name; } public void setValue() { isSet = true; } public boolean isSet() { return isSet; } public String toString() { return getType() + ": ..."; } public void decodeValue(ASN1Decoder decoder, InputStream in, int tag, int len) throws IOException { if(tag != this.tag) { throw new IOException("Invalid encoding, tag mismatch when decoding " + getType() + " (expected: " + this.tag + ", got: " + tag + ")"); } decodeValue(decoder, in, len); } protected void decodeValue(ASN1Decoder decoder, InputStream in, int len) throws IOException { throw new IOException("ASN1 decoder " + decoder + " couldn't decode " + getType()); } public abstract int encodeValue(ASN1Encoder encoder, OutputStream out) throws IOException; }
3e176b8b8e5116046c715ee723cb66cf1a844e2a
6,484
java
Java
pac4j-core/src/test/java/org/pac4j/core/profile/service/InMemoryProfileServiceTests.java
mmg-3/pac4j
09e8f9ef36362d50a13678f6d1c7c849b7b136c9
[ "Apache-2.0" ]
2,073
2015-01-06T12:05:25.000Z
2022-03-30T14:54:38.000Z
pac4j-core/src/test/java/org/pac4j/core/profile/service/InMemoryProfileServiceTests.java
mmg-3/pac4j
09e8f9ef36362d50a13678f6d1c7c849b7b136c9
[ "Apache-2.0" ]
1,088
2015-01-06T08:31:22.000Z
2022-03-29T06:59:55.000Z
pac4j-core/src/test/java/org/pac4j/core/profile/service/InMemoryProfileServiceTests.java
mmg-3/pac4j
09e8f9ef36362d50a13678f6d1c7c849b7b136c9
[ "Apache-2.0" ]
678
2015-01-26T12:23:12.000Z
2022-03-31T06:30:16.000Z
43.516779
131
0.703732
9,976
package org.pac4j.core.profile.service; import org.apache.shiro.authc.credential.DefaultPasswordService; import org.junit.*; import org.pac4j.core.exception.*; import org.pac4j.core.profile.CommonProfile; import org.pac4j.core.util.TestsConstants; import org.pac4j.core.credentials.UsernamePasswordCredentials; import org.pac4j.core.credentials.password.PasswordEncoder; import org.pac4j.core.credentials.password.ShiroPasswordEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; /** * Tests the {@link InMemoryProfileService}. * * @author Elie Roux * @since 2.1.0 */ public final class InMemoryProfileServiceTests implements TestsConstants { private static final String TEST_ID = "testId"; private static final String TEST_LINKED_ID = "testLinkedId"; private static final String TEST_USER = "testUser"; private static final String TEST_USER2 = "testUser2"; private static final String TEST_PASS = "testPass"; private static final String TEST_PASS2 = "testPass2"; private static final String IDPERSON1 = "idperson1"; private static final String IDPERSON2 = "idperson2"; private static final String IDPERSON3 = "idperson3"; public final static PasswordEncoder PASSWORD_ENCODER = new ShiroPasswordEncoder(new DefaultPasswordService()); public InMemoryProfileService<CommonProfile> inMemoryProfileService; @Before public void setUp() { inMemoryProfileService = new InMemoryProfileService<>(x -> new CommonProfile()); inMemoryProfileService.setPasswordEncoder(PASSWORD_ENCODER); final var password = PASSWORD_ENCODER.encode(PASSWORD); // insert sample data final Map<String, Object> properties1 = new HashMap<>(); properties1.put(USERNAME, GOOD_USERNAME); properties1.put(FIRSTNAME, FIRSTNAME_VALUE); var profile = new CommonProfile(); profile.build(IDPERSON1, properties1); inMemoryProfileService.create(profile, PASSWORD); // second person, final Map<String, Object> properties2 = new HashMap<>(); properties2.put(USERNAME, MULTIPLE_USERNAME); profile = new CommonProfile(); profile.build(IDPERSON2, properties2); inMemoryProfileService.create(profile, PASSWORD); final Map<String, Object> properties3 = new HashMap<>(); properties3.put(USERNAME, MULTIPLE_USERNAME); properties3.put(PASSWORD, password); profile = new CommonProfile(); profile.build(IDPERSON3, properties3); inMemoryProfileService.create(profile, PASSWORD); } @Test(expected = AccountNotFoundException.class) public void authentFailed() { final var credentials = new UsernamePasswordCredentials(BAD_USERNAME, PASSWORD); inMemoryProfileService.validate(credentials, null, null); } @Test public void authentSuccessSingleAttribute() { final var credentials = new UsernamePasswordCredentials(GOOD_USERNAME, PASSWORD); inMemoryProfileService.validate(credentials, null, null); final var profile = credentials.getUserProfile(); assertNotNull(profile); assertEquals(GOOD_USERNAME, profile.getUsername()); assertEquals(2, profile.getAttributes().size()); assertEquals(FIRSTNAME_VALUE, profile.getAttribute(FIRSTNAME)); } @Test public void testCreateUpdateFindDelete() { final var profile = new CommonProfile(); profile.setId(TEST_ID); profile.setLinkedId(TEST_LINKED_ID); profile.addAttribute(USERNAME, TEST_USER); // create inMemoryProfileService.create(profile, TEST_PASS); // check credentials final var credentials = new UsernamePasswordCredentials(TEST_USER, TEST_PASS); inMemoryProfileService.validate(credentials, null, null); final var profile1 = credentials.getUserProfile(); assertNotNull(profile1); // check data final var results = getData(TEST_ID); assertEquals(1, results.size()); final var result = results.get(0); assertEquals(5, result.size()); assertEquals(TEST_ID, result.get("id")); assertEquals(TEST_LINKED_ID, result.get(AbstractProfileService.LINKEDID)); assertNotNull(result.get(AbstractProfileService.SERIALIZED_PROFILE)); assertEquals(TEST_USER, result.get(USERNAME)); // findById final var profile2 = inMemoryProfileService.findById(TEST_ID); assertEquals(TEST_ID, profile2.getId()); assertEquals(TEST_LINKED_ID, profile2.getLinkedId()); assertEquals(TEST_USER, profile2.getUsername()); assertEquals(1, profile2.getAttributes().size()); // update with password profile.addAttribute(USERNAME, TEST_USER2); inMemoryProfileService.update(profile, TEST_PASS2); var results2 = getData(TEST_ID); assertEquals(1, results2.size()); var result2 = results2.get(0); assertEquals(5, result2.size()); assertEquals(TEST_ID, result2.get("id")); assertEquals(TEST_LINKED_ID, result2.get(AbstractProfileService.LINKEDID)); assertNotNull(result2.get(AbstractProfileService.SERIALIZED_PROFILE)); assertEquals(TEST_USER2, result2.get(USERNAME)); // check credentials final var credentials2 = new UsernamePasswordCredentials(TEST_USER2, TEST_PASS2); inMemoryProfileService.validate(credentials2, null, null); final var profile3 = credentials.getUserProfile(); assertNotNull(profile3); // update with no password update inMemoryProfileService.update(profile, null); results2 = getData(TEST_ID); assertEquals(1, results2.size()); result2 = results2.get(0); assertEquals(5, result2.size()); assertEquals(TEST_USER2, result2.get(USERNAME)); // check credentials inMemoryProfileService.validate(credentials2, null, null); final var profile4 = credentials.getUserProfile(); assertNotNull(profile4); // remove inMemoryProfileService.remove(profile); final var results3 = getData(TEST_ID); assertEquals(0, results3.size()); } private List<Map<String, Object>> getData(final String id) { return inMemoryProfileService.read(Arrays.asList("id", "username", "linkedid", "password", "serializedprofile"), "id", id); } }
3e176c0c5c545b21f45bd9553bba504c92c363bc
3,052
java
Java
checklistbank-mybatis-service/src/test/java/org/gbif/checklistbank/service/mybatis/mapper/DistributionMapperTest.java
ahahn-gbif/checklistbank
9bd65a831d9d6ed7b4e1f93e3b7e0ff8f51c7d4f
[ "Apache-2.0" ]
null
null
null
checklistbank-mybatis-service/src/test/java/org/gbif/checklistbank/service/mybatis/mapper/DistributionMapperTest.java
ahahn-gbif/checklistbank
9bd65a831d9d6ed7b4e1f93e3b7e0ff8f51c7d4f
[ "Apache-2.0" ]
null
null
null
checklistbank-mybatis-service/src/test/java/org/gbif/checklistbank/service/mybatis/mapper/DistributionMapperTest.java
ahahn-gbif/checklistbank
9bd65a831d9d6ed7b4e1f93e3b7e0ff8f51c7d4f
[ "Apache-2.0" ]
null
null
null
41.808219
107
0.716579
9,977
package org.gbif.checklistbank.service.mybatis.mapper; import org.gbif.api.model.checklistbank.Distribution; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.vocabulary.CitesAppendix; import org.gbif.api.vocabulary.Country; import org.gbif.api.vocabulary.EstablishmentMeans; import org.gbif.api.vocabulary.LifeStage; import org.gbif.api.vocabulary.OccurrenceStatus; import org.gbif.api.vocabulary.ThreatStatus; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DistributionMapperTest extends MapperITBase<DistributionMapper> { public DistributionMapperTest() { super(DistributionMapper.class, true); } @Test public void testMapper() throws Exception { assertTrue(mapper.listByChecklistUsage(usageKey, new PagingRequest()).isEmpty()); assertTrue(mapper.listByNubUsage(usageKey, new PagingRequest()).isEmpty()); Distribution obj = new Distribution(); obj.setAppendixCites(CitesAppendix.II); obj.setCountry(Country.ALGERIA); obj.setEndDayOfYear(1990); obj.setEstablishmentMeans(EstablishmentMeans.NATIVE); obj.setLifeStage(LifeStage.EMRYO); obj.setLocality("location location location"); obj.setLocationId("locID"); obj.setRemarks("remarks"); obj.setStartDayOfYear(1989); obj.setStatus(OccurrenceStatus.COMMON); obj.setTemporal("aha"); obj.setThreatStatus(ThreatStatus.CRITICALLY_ENDANGERED); // these should get ignored obj.setSource("sourcy s"); obj.setSourceTaxonKey(123); mapper.insert(usageKey, obj, citationKey1); Distribution obj2 = mapper.listByChecklistUsage(usageKey, new PagingRequest()).get(0); assertObject(obj, obj2, citation1, null); obj2 = mapper.listByNubUsage(nubKey, new PagingRequest()).get(0); // these are now nub source usage values assertObject(obj, obj2, datasetTitle, usageKey); } private void assertObject(Distribution obj, Distribution obj2, String source, Integer sourceTaxonKey) { assertEquals(obj.getAppendixCites(), obj2.getAppendixCites()); assertEquals(obj.getCountry(), obj2.getCountry()); assertEquals(obj.getEndDayOfYear(), obj2.getEndDayOfYear()); assertEquals(obj.getEstablishmentMeans(), obj2.getEstablishmentMeans()); assertEquals(obj.getLifeStage(), obj2.getLifeStage()); assertEquals(obj.getLocality(), obj2.getLocality()); assertEquals(obj.getLocationId(), obj2.getLocationId()); assertEquals(obj.getRemarks(), obj2.getRemarks()); assertEquals(obj.getStartDayOfYear(), obj2.getStartDayOfYear()); assertEquals(obj.getStatus(), obj2.getStatus()); assertEquals(obj.getTemporal(), obj2.getTemporal()); assertEquals(obj.getThreatStatus(), obj2.getThreatStatus()); assertEquals(source, obj2.getSource()); assertEquals(sourceTaxonKey, obj2.getSourceTaxonKey()); } }
3e176c3e03eb6c608d7391830ce3ff6669166437
939
java
Java
src/dae/animation/rig/timing/gui/SelectTool.java
samynk/DArtE
d041543596b275642584989637737f78382089ec
[ "BSD-2-Clause" ]
3
2015-02-19T12:59:21.000Z
2021-02-23T14:26:21.000Z
src/dae/animation/rig/timing/gui/SelectTool.java
samynk/DArtE
d041543596b275642584989637737f78382089ec
[ "BSD-2-Clause" ]
3
2015-02-06T19:52:50.000Z
2017-11-21T22:46:35.000Z
src/dae/animation/rig/timing/gui/SelectTool.java
samynk/DArtE
d041543596b275642584989637737f78382089ec
[ "BSD-2-Clause" ]
1
2021-02-23T14:26:22.000Z
2021-02-23T14:26:22.000Z
22.902439
69
0.600639
9,978
/* * Digital Arts and Entertainment */ package dae.animation.rig.timing.gui; import dae.animation.rig.timing.Behaviour; import java.awt.event.MouseEvent; /** * * @author Koen.Samyn */ public class SelectTool implements TimingTool{ private final FramePanel parent; public SelectTool(FramePanel parent){ this.parent = parent; } @Override public void mouseClicked(MouseEvent e) { Behaviour current = parent.getBehaviour(); if ( current != null ){ current.setCurrentFrame(parent.mouseXToFrame(e.getX())); int timeLineIndex = parent.mouseYToTimeLine(e.getY()); parent.setCurrentTimeLine(timeLineIndex); parent.repaint(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }
3e176d2380df34f8eaa280fab0c4a13af94fd9dd
404
java
Java
app/src/test/java/com/github/angads25/toggledemo/ExampleUnitTest.java
ch8n/android-toggle
3eb4736de3ee3b2ef322d2a6049232d70ff94d47
[ "Apache-2.0" ]
370
2018-02-12T12:17:55.000Z
2022-03-30T03:20:45.000Z
app/src/test/java/com/github/angads25/toggledemo/ExampleUnitTest.java
ch8n/android-toggle
3eb4736de3ee3b2ef322d2a6049232d70ff94d47
[ "Apache-2.0" ]
25
2018-02-17T06:08:12.000Z
2022-03-31T05:28:00.000Z
app/src/test/java/com/github/angads25/toggledemo/ExampleUnitTest.java
ch8n/android-toggle
3eb4736de3ee3b2ef322d2a6049232d70ff94d47
[ "Apache-2.0" ]
84
2018-02-22T07:56:49.000Z
2022-03-25T15:50:41.000Z
23.764706
81
0.710396
9,979
package com.github.angads25.toggledemo; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void additionIsCorrect() { assertEquals(4, 2 + 2); } }
3e176d836635da6889a2c8a95a0d54ffcee36829
5,809
java
Java
app/src/main/java/com/deshpande/blueprint/provider/BlueprintContentProvider.java
mohitd/BluePrint
656c5fd3cda1be3eb90b77aeb6dc4b35b0af6730
[ "MIT" ]
null
null
null
app/src/main/java/com/deshpande/blueprint/provider/BlueprintContentProvider.java
mohitd/BluePrint
656c5fd3cda1be3eb90b77aeb6dc4b35b0af6730
[ "MIT" ]
null
null
null
app/src/main/java/com/deshpande/blueprint/provider/BlueprintContentProvider.java
mohitd/BluePrint
656c5fd3cda1be3eb90b77aeb6dc4b35b0af6730
[ "MIT" ]
null
null
null
35.420732
135
0.596488
9,980
package com.deshpande.blueprint.provider; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.support.annotation.NonNull; import org.jetbrains.annotations.NotNull; public class BlueprintContentProvider extends ContentProvider { private static final UriMatcher uriMatcher = buildUriMatcher(); private TaskDbHelper openHelper; private static final int TASK = 100; private static final int TASK_WITH_ID = 101; private static final String TASK_WITH_ID_SELECTION = TaskContract.TaskEntry.TABLE_NAME + "." + TaskContract.TaskEntry._ID + " = ?"; private Cursor getTaskFromId(Uri uri, String[] projection, String sortOrder) { long id = TaskContract.TaskEntry.getTaskIdFromUri(uri); return openHelper.getReadableDatabase().query( TaskContract.TaskEntry.TABLE_NAME, projection, TASK_WITH_ID_SELECTION, new String[] { Long.toString(id) }, null, null, sortOrder ); } private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = TaskContract.CONTENT_AUTHORITY; matcher.addURI(authority, TaskContract.PATH_TASK, TASK); matcher.addURI(authority, TaskContract.PATH_TASK + "/#", TASK_WITH_ID); return matcher; } @Override public boolean onCreate() { openHelper = new TaskDbHelper(getContext()); return true; } @Override public String getType(@NotNull Uri uri) { final int match = uriMatcher.match(uri); switch (match) { case TASK: return TaskContract.TaskEntry.CONTENT_TYPE; case TASK_WITH_ID: return TaskContract.TaskEntry.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor cursor; switch (uriMatcher.match(uri)) { case TASK: cursor = openHelper.getReadableDatabase().query(TaskContract.TaskEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; case TASK_WITH_ID: cursor = getTaskFromId(uri, projection, sortOrder); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public Uri insert(@NonNull Uri uri, ContentValues values) { final SQLiteDatabase db = openHelper.getWritableDatabase(); Uri retUri; switch (uriMatcher.match(uri)) { case TASK: long _id = db.insert(TaskContract.TaskEntry.TABLE_NAME, null, values); if (_id > 0) { retUri = TaskContract.TaskEntry.buildTaskWithId(_id); } else { throw new SQLiteException("Failed to insert row into " + uri); } break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return retUri; } @Override public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = openHelper.getWritableDatabase(); int rowsDeleted; switch (uriMatcher.match(uri)) { case TASK: rowsDeleted = db.delete(TaskContract.TaskEntry.TABLE_NAME, selection, selectionArgs); break; case TASK_WITH_ID: long id = TaskContract.TaskEntry.getTaskIdFromUri(uri); rowsDeleted = db.delete(TaskContract.TaskEntry.TABLE_NAME, TaskContract.TaskEntry._ID + "=?", new String[]{Long.toString(id)}); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsDeleted > 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsDeleted; } @Override public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SQLiteDatabase db = openHelper.getWritableDatabase(); int rowsUpdated; switch (uriMatcher.match(uri)) { case TASK: rowsUpdated = db.update(TaskContract.TaskEntry.TABLE_NAME, values, selection, selectionArgs); break; case TASK_WITH_ID: long id = TaskContract.TaskEntry.getTaskIdFromUri(uri); rowsUpdated = db.update(TaskContract.TaskEntry.TABLE_NAME, values, TaskContract.TaskEntry._ID + "=?", new String[] { Long.toString(id) }); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsUpdated > 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsUpdated; } }
3e176e851471d39097096a55a3c741afec76db22
2,304
java
Java
app/src/main/java/com/somethingsimple/simplelist/view/settings/SettingsActivity.java
SomeSimpleThings/simplelist
8009b42397a5c3b420fd2be44b3ef3c845fcc493
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/somethingsimple/simplelist/view/settings/SettingsActivity.java
SomeSimpleThings/simplelist
8009b42397a5c3b420fd2be44b3ef3c845fcc493
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/somethingsimple/simplelist/view/settings/SettingsActivity.java
SomeSimpleThings/simplelist
8009b42397a5c3b420fd2be44b3ef3c845fcc493
[ "Apache-2.0" ]
null
null
null
39.050847
95
0.691406
9,981
package com.somethingsimple.simplelist.view.settings; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.widget.Toolbar; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.SwitchPreferenceCompat; import com.somethingsimple.simplelist.R; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_activity); Toolbar myToolbar = findViewById(R.id.toolbar_Settings); setSupportActionBar(myToolbar); getSupportFragmentManager() .beginTransaction() .replace(R.id.settings, new SettingsFragment()) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } public static class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.preferences, rootKey); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { SwitchPreferenceCompat darkThemePreference = getPreferenceManager().findPreference(getString(R.string.pref_dark_theme)); darkThemePreference.setOnPreferenceChangeListener((preference, newValue) -> { int nightMode = (boolean) newValue ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO; AppCompatDelegate.setDefaultNightMode(nightMode); return true; }); return super.onCreateView(inflater, container, savedInstanceState); } } }
3e176ee6068a3051c90b4bdb584714345fdb9d4f
5,223
java
Java
testbench/testsolutions/bl.unittest/test_gen/jetbrains/mps/baseLanguage/test/TestExpectedType_Test.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
testbench/testsolutions/bl.unittest/test_gen/jetbrains/mps/baseLanguage/test/TestExpectedType_Test.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
testbench/testsolutions/bl.unittest/test_gen/jetbrains/mps/baseLanguage/test/TestExpectedType_Test.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
46.633929
214
0.793988
9,982
package jetbrains.mps.baseLanguage.test; /*Generated by MPS */ import jetbrains.mps.MPSLaunch; import jetbrains.mps.lang.test.runtime.BaseTransformationTest; import org.junit.ClassRule; import jetbrains.mps.lang.test.runtime.TestParametersCache; import org.junit.Rule; import jetbrains.mps.lang.test.runtime.RunWithCommand; import org.junit.Test; import jetbrains.mps.lang.test.runtime.BaseTestBody; import jetbrains.mps.lang.test.runtime.TransformationTest; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.lang.test.runtime.CheckErrorMessagesRunnable; import jetbrains.mps.project.ProjectBase; import jetbrains.mps.internal.collections.runtime.ListSequence; import java.util.ArrayList; import jetbrains.mps.lang.test.runtime.CheckExpectedMessageRunnable; import jetbrains.mps.lang.test.runtime.CheckTypesAction; @MPSLaunch public class TestExpectedType_Test extends BaseTransformationTest { @ClassRule public static final TestParametersCache ourParamCache = new TestParametersCache(TestExpectedType_Test.class, "${mps_home}", "r:00000000-0000-4000-0000-011c895902c7(jetbrains.mps.baseLanguage.test@tests)", false); @Rule public final RunWithCommand myWithCommandRule = new RunWithCommand(this); public TestExpectedType_Test() { super(ourParamCache); } @Test public void test_ErrorMessagesCheck4395293866213260523() throws Throwable { new TestBody(this).test_ErrorMessagesCheck4395293866213260523(); } @Test public void test_NodeExpectedTypeCheck8101092317677991775() throws Throwable { new TestBody(this).test_NodeExpectedTypeCheck8101092317677991775(); } @Test public void test_NodeExpectedTypeCheck8101092317677995689() throws Throwable { new TestBody(this).test_NodeExpectedTypeCheck8101092317677995689(); } @Test public void test_NodeExpectedTypeCheck8101092317677999915() throws Throwable { new TestBody(this).test_NodeExpectedTypeCheck8101092317677999915(); } @Test public void test_NodeExpectedTypeCheck8101092317678002448() throws Throwable { new TestBody(this).test_NodeExpectedTypeCheck8101092317678002448(); } @Test public void test_NodeExpectedTypeCheck8101092317678005784() throws Throwable { new TestBody(this).test_NodeExpectedTypeCheck8101092317678005784(); } @Test public void test_NodeExpectedTypeCheck8101092317678009113() throws Throwable { new TestBody(this).test_NodeExpectedTypeCheck8101092317678009113(); } /*package*/ static class TestBody extends BaseTestBody { /*package*/ TestBody(TransformationTest owner) { super(owner); } public void test_ErrorMessagesCheck4395293866213260523() throws Exception { SNode nodeToCheck = getRealNodeById("4395293866213195828"); SNode operation = getRealNodeById("4395293866213260523"); new CheckErrorMessagesRunnable(nodeToCheck, false, false, ((ProjectBase) myProject).getPlatform()).includeSelf(false).exclude(ListSequence.fromList(new ArrayList<CheckExpectedMessageRunnable>())).run(); } public void test_NodeExpectedTypeCheck8101092317677991775() throws Exception { SNode nodeToCheck = getRealNodeById("8101092317677985822"); SNode operation = getRealNodeById("8101092317677991775"); addNodeById("8101092317677991990"); new CheckTypesAction.CheckExpectedType(nodeToCheck).checkTypeIs(getNodeById("8101092317677991990")); } public void test_NodeExpectedTypeCheck8101092317677995689() throws Exception { SNode nodeToCheck = getRealNodeById("8101092317677995687"); SNode operation = getRealNodeById("8101092317677995689"); addNodeById("8101092317677995690"); new CheckTypesAction.CheckExpectedType(nodeToCheck).checkTypeIs(getNodeById("8101092317677995690")); } public void test_NodeExpectedTypeCheck8101092317677999915() throws Exception { SNode nodeToCheck = getRealNodeById("8101092317677999913"); SNode operation = getRealNodeById("8101092317677999915"); addNodeById("8101092317677999916"); new CheckTypesAction.CheckExpectedType(nodeToCheck).checkTypeIs(getNodeById("8101092317677999916")); } public void test_NodeExpectedTypeCheck8101092317678002448() throws Exception { SNode nodeToCheck = getRealNodeById("8101092317678002446"); SNode operation = getRealNodeById("8101092317678002448"); addNodeById("8101092317678002449"); new CheckTypesAction.CheckExpectedType(nodeToCheck).checkTypeIs(getNodeById("8101092317678002449")); } public void test_NodeExpectedTypeCheck8101092317678005784() throws Exception { SNode nodeToCheck = getRealNodeById("8101092317678005782"); SNode operation = getRealNodeById("8101092317678005784"); addNodeById("8101092317678005785"); new CheckTypesAction.CheckExpectedType(nodeToCheck).checkTypeIs(getNodeById("8101092317678005785")); } public void test_NodeExpectedTypeCheck8101092317678009113() throws Exception { SNode nodeToCheck = getRealNodeById("8101092317678009111"); SNode operation = getRealNodeById("8101092317678009113"); addNodeById("8101092317678009114"); new CheckTypesAction.CheckExpectedType(nodeToCheck).checkTypeIs(getNodeById("8101092317678009114")); } } }
3e176f509a745f57b86340669ba6d60368b82377
152
java
Java
app/src/main/java/com/linkb/jstx/listener/OnMomentBgClickLisenter.java
hongchun166/jtxt
5ceac15b4a6bf510eb82bf5dd496c80b2d08a25d
[ "Apache-2.0" ]
1
2020-07-27T10:36:28.000Z
2020-07-27T10:36:28.000Z
app/src/main/java/com/linkb/jstx/listener/OnMomentBgClickLisenter.java
hongchun166/jtxt
5ceac15b4a6bf510eb82bf5dd496c80b2d08a25d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/linkb/jstx/listener/OnMomentBgClickLisenter.java
hongchun166/jtxt
5ceac15b4a6bf510eb82bf5dd496c80b2d08a25d
[ "Apache-2.0" ]
null
null
null
19
45
0.776316
9,983
package com.linkb.jstx.listener; import android.view.View; public interface OnMomentBgClickLisenter<T> { void onMomentBgClick(T obj,View view); }
3e176f61ec3eafeee22db30ec64f7b7ad308af6c
2,554
java
Java
sample_clients/pushapi_sample_java_client/src/main/java/com/ruckuswireless/lbs/BCTlsAuthentication.java
yeongsheng-tan/mqtt_gpb_client
b07d3870991d125834ec3599ee6c175f40806916
[ "BSD-3-Clause" ]
2
2015-12-11T09:36:05.000Z
2019-02-01T16:18:35.000Z
sample_clients/pushapi_sample_java_client/src/main/java/com/ruckuswireless/lbs/BCTlsAuthentication.java
yeongsheng-tan/mqtt_gpb_client
b07d3870991d125834ec3599ee6c175f40806916
[ "BSD-3-Clause" ]
5
2016-03-30T10:26:35.000Z
2018-02-04T03:42:29.000Z
sample_clients/pushapi_sample_java_client/src/main/java/com/ruckuswireless/lbs/BCTlsAuthentication.java
yeongsheng-tan/mqtt_gpb_client
b07d3870991d125834ec3599ee6c175f40806916
[ "BSD-3-Clause" ]
4
2016-06-28T02:54:51.000Z
2021-04-10T02:23:03.000Z
34.053333
125
0.653485
9,984
package com.ruckuswireless.lbs; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.List; import org.bouncycastle.crypto.tls.CertificateRequest; import org.bouncycastle.crypto.tls.TlsAuthentication; import org.bouncycastle.crypto.tls.TlsCredentials; /** * Created by yeongsheng on 14/4/15. */ public class BCTlsAuthentication implements TlsAuthentication { /** * The List of X509 - server certificates. */ List<Certificate> serverCertList; /** * Converts every server certificate in an X509-certificate and stores it * globally. * * @param serverCertificate * - The server certificate, which related server certificate * list needs to be notified. * @throws IOException * If an error occurs during the certificate retrieval. */ @Override public void notifyServerCertificate(final org.bouncycastle.crypto.tls.Certificate serverCertificate) throws IOException { System.out.println(serverCertificate.getCertificateList()[0].getSubject()); if (this.serverCertList == null) { final org.bouncycastle.asn1.x509.Certificate[] serverCertList = serverCertificate.getCertificateList(); if (serverCertList != null) { this.serverCertList = new ArrayList<Certificate>(); try { final CertificateFactory x509cf = CertificateFactory.getInstance("X509"); for (final org.bouncycastle.asn1.x509.Certificate cert : serverCertList) { this.serverCertList .add(x509cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()))); } } catch (final CertificateException e) { throw new IOException(e); } } } } /** * Returns the current available list of <em>server certificates</em>. * * @return Returns a List of the current available * <em>server certificates</em>. */ final List<Certificate> getServerCertList() { return this.serverCertList; } @Override public TlsCredentials getClientCredentials(final CertificateRequest certificateRequest) throws IOException { // TODO Auto-generated method stub return null; } }
3e17704ec50852bc811595385518891a0f3745b9
472
java
Java
src/main/java/com/example/application/repositories/ContactRepository.java
BerkayyyU/address-book
dbcf32cc22bd9c77ba975079a2267eb47d24414e
[ "Unlicense" ]
null
null
null
src/main/java/com/example/application/repositories/ContactRepository.java
BerkayyyU/address-book
dbcf32cc22bd9c77ba975079a2267eb47d24414e
[ "Unlicense" ]
null
null
null
src/main/java/com/example/application/repositories/ContactRepository.java
BerkayyyU/address-book
dbcf32cc22bd9c77ba975079a2267eb47d24414e
[ "Unlicense" ]
null
null
null
33.714286
99
0.826271
9,985
package com.example.application.repositories; import com.example.application.models.Contact; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface ContactRepository extends CrudRepository<Contact,Long> { List<Contact> findByFirstNameContainingOrLastNameContaining(String firstName, String lastName); List<Contact> findContactsByUserId(Long id); Contact findContactByIdAndUserId(Long contactID, Long userID ); }
3e177229112df3de614de6a0b9a0ae85045103af
2,809
java
Java
capstone-practice-track/src/main/java/org/launchcode/capstonepracticetrack/SecurityConfig.java
rdubois46/Capstone-PracticeTrack
a14362b7458c60c2de658fb7b9ff05d9c43e68df
[ "MIT" ]
2
2019-08-09T02:27:49.000Z
2019-09-15T01:30:05.000Z
capstone-practice-track/src/main/java/org/launchcode/capstonepracticetrack/SecurityConfig.java
rdubois46/Capstone-PracticeTrack
a14362b7458c60c2de658fb7b9ff05d9c43e68df
[ "MIT" ]
null
null
null
capstone-practice-track/src/main/java/org/launchcode/capstonepracticetrack/SecurityConfig.java
rdubois46/Capstone-PracticeTrack
a14362b7458c60c2de658fb7b9ff05d9c43e68df
[ "MIT" ]
null
null
null
36.960526
107
0.686365
9,986
package org.launchcode.capstonepracticetrack; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import javax.sql.DataSource; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .regexMatchers("/welcome/login", "/welcome/newAccount").permitAll() .regexMatchers("/webjars/.*").permitAll() .regexMatchers("/css/.*").permitAll() .regexMatchers("/welcome/login?[^/]*").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/welcome/login") .usernameParameter("username") .defaultSuccessUrl("/profile/", true) .permitAll() .and() .logout() .logoutUrl("/profile/logout") .invalidateHttpSession(true) .deleteCookies("JSESSIONID") .logoutSuccessUrl("/welcome/login?logout") .and() .rememberMe(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authProvider()); auth.userDetailsService(userDetailsService); } }
3e177550adb1ad18073aa1878bf142dabcc26a9e
3,046
java
Java
src/test/java/com/lodborg/intervaltree/DateIntervalTest.java
Terenfear/interval-tree
b3e0dba9e0648999db9c1d220d36eb7b0e51c94a
[ "MIT" ]
29
2016-09-04T15:00:28.000Z
2021-07-21T19:03:01.000Z
src/test/java/com/lodborg/intervaltree/DateIntervalTest.java
Terenfear/interval-tree
b3e0dba9e0648999db9c1d220d36eb7b0e51c94a
[ "MIT" ]
2
2016-10-31T17:38:38.000Z
2017-02-13T16:07:31.000Z
src/test/java/com/lodborg/intervaltree/DateIntervalTest.java
Terenfear/interval-tree
b3e0dba9e0648999db9c1d220d36eb7b0e51c94a
[ "MIT" ]
14
2016-11-01T04:12:59.000Z
2021-03-23T06:49:11.000Z
35.011494
132
0.716021
9,987
package com.lodborg.intervaltree; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Set; import com.lodborg.intervaltree.Interval.*; import static org.junit.Assert.*; public class DateIntervalTest { private static SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); @Test public void test_middlepointBounded() { assertEquals(parse("12.11.2005 22:20:15"), new DateInterval( parse("31.10.2005 10:20:15"), parse("25.11.2005 10:20:15"), Bounded.CLOSED).getMidpoint() ); assertEquals(parse("12.11.2005 10:20:15"), new DateInterval( parse("30.10.2005 10:20:15"), parse("25.11.2005 10:20:15"), Bounded.CLOSED).getMidpoint() ); } @Test public void test_middlepointUnbounded() { assertEquals(new Date(0), new DateInterval().getMidpoint()); assertEquals(new Date(4611677853814364403L), new DateInterval(new Date(-16329226047000L), Unbounded.CLOSED_LEFT).getMidpoint()); assertEquals(new Date(-4611694183040411404L), new DateInterval(new Date(-16329226047000L), Unbounded.CLOSED_RIGHT).getMidpoint()); assertEquals(new Date(4611677853814364403L), new DateInterval(new Date(-16329226047000L), Unbounded.OPEN_LEFT).getMidpoint()); assertEquals(new Date(-4611694183040411404L), new DateInterval(new Date(-16329226047000L), Unbounded.OPEN_RIGHT).getMidpoint()); } @Test public void test_middlepointStartAndEndOffByOne() { long tmp = 128643893; assertEquals(new Date(tmp + 1), new DateInterval(new Date(tmp), new Date(tmp + 1), Bounded.CLOSED_RIGHT).getMidpoint()); assertEquals(new Date(tmp), new DateInterval(new Date(tmp), new Date(tmp + 1), Bounded.CLOSED).getMidpoint()); assertEquals(new Date(tmp), new DateInterval(new Date(tmp), new Date(tmp), Bounded.CLOSED).getMidpoint()); assertNull(new DateInterval(new Date(tmp), new Date(tmp), Bounded.OPEN).getMidpoint()); } @Test public void test_dateIntervalTree(){ IntervalTree<Date> tree = new IntervalTree<>(); Date g = parse("30.09.2016 08:05:42"); Date f = parse("18.09.2016 23:22:00"); Date e = parse("12.09.2016 12:15:00"); Date d = parse("12.09.2016 12:14:59"); Date c = parse("01.03.2016 17:39:08"); Date b = parse("27.12.2015 08:05:42"); Date a = parse("08.04.2010 08:02:27"); DateInterval aa = new DateInterval(e, f, Bounded.CLOSED); Interval<Date> bb = aa.builder().greaterEqual(b).less(d).build(); DateInterval cc = new DateInterval(c, d, Bounded.CLOSED_RIGHT); DateInterval dd = new DateInterval(a, d, Bounded.OPEN); DateInterval ee = new DateInterval(e, g, Bounded.CLOSED_LEFT); tree.add(aa); tree.add(bb); tree.add(cc); tree.add(dd); tree.add(ee); Set<Interval<Date>> res = tree.query(new DateInterval(c, d, Bounded.OPEN)); assertEquals(3, res.size()); assertTrue(res.contains(bb)); assertTrue(res.contains(cc)); assertTrue(res.contains(dd)); } private static Date parse(String str){ try{ return sdf.parse(str); } catch (ParseException e) { return null; } } }
3e17758df3638340d0f93d073a04c48a5affdcaf
1,289
java
Java
src/main/java/org/cascadebot/cascadebot/commands/developer/GuildCommand.java
DeadlyFirex/CascadeBot
0b5c48f5d26ddf33e92ff46ad229989c45f386ed
[ "MIT" ]
1
2020-06-08T11:07:10.000Z
2020-06-08T11:07:10.000Z
src/main/java/org/cascadebot/cascadebot/commands/developer/GuildCommand.java
DeadlyFirex/CascadeBot
0b5c48f5d26ddf33e92ff46ad229989c45f386ed
[ "MIT" ]
null
null
null
src/main/java/org/cascadebot/cascadebot/commands/developer/GuildCommand.java
DeadlyFirex/CascadeBot
0b5c48f5d26ddf33e92ff46ad229989c45f386ed
[ "MIT" ]
null
null
null
25.78
131
0.725369
9,988
/* * Copyright (c) 2019 CascadeBot. All rights reserved. * Licensed under the MIT license. */ package org.cascadebot.cascadebot.commands.developer; import net.dv8tion.jda.api.entities.Member; import org.cascadebot.cascadebot.commandmeta.CommandContext; import org.cascadebot.cascadebot.commandmeta.ICommandRestricted; import org.cascadebot.cascadebot.commandmeta.ISubCommand; import org.cascadebot.cascadebot.commandmeta.Module; import org.cascadebot.shared.SecurityLevel; import java.util.Set; public class GuildCommand implements ICommandRestricted { @Override public void onCommand(Member sender, CommandContext context) { context.getUIMessaging().replyUsage(); } @Override public Module getModule() { return Module.DEVELOPER; } @Override public String description() { return "Allows administrative actions to be run on guilds."; } @Override public SecurityLevel getCommandLevel() { return SecurityLevel.DEVELOPER; } @Override public Set<ISubCommand> getSubCommands() { return Set.of(new GuildSaveSubCommand(), new GuildLeaveSubCommand(), new GuildFlagSubCommand(), new GuildInfoSubCommand()); } @Override public String command() { return "guild"; } }
3e1775c3e6081d7ab1c7ba5b24b6a1def38d5c6f
26,412
java
Java
demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationChessboardXCornerApp.java
YunLemon/BoofCV
299f2fdb4c47297dd5def501f9bd31d7c9a25f10
[ "Apache-2.0" ]
null
null
null
demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationChessboardXCornerApp.java
YunLemon/BoofCV
299f2fdb4c47297dd5def501f9bd31d7c9a25f10
[ "Apache-2.0" ]
null
null
null
demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationChessboardXCornerApp.java
YunLemon/BoofCV
299f2fdb4c47297dd5def501f9bd31d7c9a25f10
[ "Apache-2.0" ]
null
null
null
37.731429
118
0.717893
9,989
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.demonstrations.calibration; import boofcv.abst.fiducial.calib.CalibrationDetectorChessboardX; import boofcv.abst.fiducial.calib.ConfigChessboardX; import boofcv.abst.fiducial.calib.ConfigGridDimen; import boofcv.alg.feature.detect.chess.ChessboardCorner; import boofcv.alg.fiducial.calib.chess.ChessboardCornerClusterFinder.LineInfo; import boofcv.alg.fiducial.calib.chess.ChessboardCornerClusterFinder.Vertex; import boofcv.alg.fiducial.calib.chess.ChessboardCornerClusterToGrid.GridInfo; import boofcv.alg.fiducial.calib.chess.ChessboardCornerGraph; import boofcv.alg.geo.calibration.CalibrationObservation; import boofcv.alg.misc.ImageStatistics; import boofcv.alg.misc.PixelMath; import boofcv.core.graph.FeatureGraph2D; import boofcv.demonstrations.shapes.DetectBlackShapePanel; import boofcv.demonstrations.shapes.ShapeVisualizePanel; import boofcv.demonstrations.shapes.ThresholdControlPanel; import boofcv.gui.BoofSwingUtil; import boofcv.gui.DemonstrationBase; import boofcv.gui.StandardAlgConfigPanel; import boofcv.gui.calibration.DisplayPinholeCalibrationPanel; import boofcv.gui.feature.VisualizeFeatures; import boofcv.gui.image.VisualizeImageData; import boofcv.io.PathLabel; import boofcv.io.UtilIO; import boofcv.io.image.ConvertBufferedImage; import boofcv.io.image.SimpleImageSequence; import boofcv.struct.geo.PointIndex2D_F64; import boofcv.struct.image.GrayF32; import boofcv.struct.image.ImageBase; import boofcv.struct.image.ImageType; import georegression.metric.UtilAngle; import georegression.struct.point.Point2D_F64; import org.ddogleg.struct.DogArray; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import static boofcv.gui.BoofSwingUtil.MAX_ZOOM; import static boofcv.gui.BoofSwingUtil.MIN_ZOOM; /** * Detects a chessboard pattern for calibration. Visualizes internal computations. * * @author Peter Abeles */ public class DetectCalibrationChessboardXCornerApp extends DemonstrationBase { private ConfigChessboardX configDetector = new ConfigChessboardX(); private ConfigGridDimen configGridDimen = new ConfigGridDimen(5, 7, 1); // GUI Controls and visualization panels private DisplayPanel imagePanel = new DisplayPanel(); private ControlPanel controlPanel; // Workspace for visualized image data private BufferedImage visualized; private BufferedImage original; // The chessboard corner detector private CalibrationDetectorChessboardX detector; //-------------------- // used to compute feature intensity private final Object lockAlgorithm = new Object(); // workspace to store computed log intensity image used for visualizing feature intensity private GrayF32 logIntensity = new GrayF32(1, 1); //----------------- private final Object lockCorners = new Object(); private DogArray<ChessboardCorner> foundCorners = new DogArray<>(ChessboardCorner::new); private DogArray<PointIndex2D_F64> foundChessboard = new DogArray<>(PointIndex2D_F64::new); private DogArray<CalibrationObservation> foundGrids = new DogArray<>(CalibrationObservation::new); private DogArray<FeatureGraph2D> foundClusters = new DogArray<>(FeatureGraph2D::new); private boolean success; //----------------- DetectCalibrationChessboardXCornerApp( List<PathLabel> examples ) { super(true, true, examples, ImageType.single(GrayF32.class)); controlPanel = new ControlPanel(); add(BorderLayout.WEST, controlPanel); add(BorderLayout.CENTER, imagePanel); createAlgorithm(); imagePanel.getImagePanel().addKeyListener(new KeyAdapter() { @Override public void keyPressed( KeyEvent e ) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { streamPaused = !streamPaused; } } }); imagePanel.getImagePanel().addMouseListener(new MouseAdapter() { @Override public void mousePressed( MouseEvent e ) { Point2D_F64 p = imagePanel.pixelToPoint(e.getX(), e.getY()); if (SwingUtilities.isLeftMouseButton(e)) { System.out.printf("Clicked at %.2f , %.2f\n", p.x, p.y); } else if (SwingUtilities.isRightMouseButton(e)) { String text = ""; // show info for a corner if the user clicked near it if (controlPanel.showCorners) { synchronized (lockCorners) { ChessboardCorner best = null; int bextId = -1; // Must be closer if zoomed in. The on screen pixels represent a smaller distance double bestDistance = 10/imagePanel.getScale(); for (int i = 0; i < foundCorners.size; i++) { ChessboardCorner c = foundCorners.get(i); // make sure it's a visible corner if (c.level2 < controlPanel.detMinPyrLevel) continue; double d = c.distance(p); if (d < bestDistance) { bestDistance = d; best = c; bextId = i; } } if (best != null) { text = String.format("Corner #%d\n", bextId); text += String.format(" pixel (%7.1f , %7.1f )\n", best.x, best.y); text += String.format(" levels %d to %d\n", best.level1, best.level2); text += String.format(" levelMax %d\n", best.levelMax); text += String.format(" intensity %f\n", best.intensity); text += String.format(" orientation %.2f (deg)\n", UtilAngle.degree(best.orientation)); } else { text += String.format(" pixel (%7.1f , %7.1f )\n", p.x, p.y); } } } else { text += String.format(" pixel (%7.1f , %7.1f )\n", p.x, p.y); } controlPanel.setInfoText(text); } } }); } private void createAlgorithm() { synchronized (lockAlgorithm) { configDetector.detPyramidTopSize = controlPanel.detPyramidTop; configDetector.detNonMaxRadius = controlPanel.detRadius; configDetector.detNonMaxThresholdRatio = controlPanel.detNonMaxThreshold/100.0; configDetector.detRefinedXCornerThreshold = controlPanel.detRefinedXThresh; configDetector.connEdgeThreshold = controlPanel.connEdgeThreshold; configDetector.connOrientationTol = controlPanel.connOrientationTol; configDetector.connDirectionTol = controlPanel.connDirectionTol; configDetector.connAmbiguousTol = controlPanel.connAmbiguousTol; if (controlPanel.connMaxDistance == 0) configDetector.connMaxNeighborDistance = Double.MAX_VALUE; else configDetector.connMaxNeighborDistance = controlPanel.connMaxDistance; configGridDimen.numCols = controlPanel.gridCols; configGridDimen.numRows = controlPanel.gridRows; // check to see if it should be turned off. 0 is allowed, but we will set it to less than zero if (configDetector.connEdgeThreshold <= 0) configDetector.connEdgeThreshold = -1; detector = new CalibrationDetectorChessboardX(configDetector, configGridDimen); detector.getDetector().getDetector().useMeanShift = controlPanel.meanShift; if (controlPanel.anyGrid) { detector.getClusterToGrid().setCheckShape(null); } } } @Override protected void configureVideo( int which, SimpleImageSequence sequence ) { sequence.setLoop(true); } @Override protected void handleInputChange( int source, InputMethod method, int width, int height ) { visualized = ConvertBufferedImage.checkDeclare(width, height, visualized, BufferedImage.TYPE_INT_RGB); SwingUtilities.invokeLater(() -> { Dimension preferred = imagePanel.getPreferredSize(); boolean sizeChange = preferred.width != width || preferred.height != height; if (sizeChange) { imagePanel.setPreferredSize(new Dimension(width, height)); double scale = BoofSwingUtil.selectZoomToShowAll(imagePanel, width, height); // controlPanel.zoom = scale; // prevent it from broadcasting an event controlPanel.setZoom(scale); imagePanel.setScaleAndCenter(scale, width/2, height/2); controlPanel.setImageSize(width, height); } }); } @Override public void processImage( int sourceID, long frameID, BufferedImage buffered, ImageBase input ) { original = ConvertBufferedImage.checkCopy(buffered, original); GrayF32 gray = (GrayF32)input; GrayF32 featureImg; double processingTime; synchronized (lockAlgorithm) { long time0 = System.nanoTime(); boolean success = detector.process(gray); long time1 = System.nanoTime(); processingTime = (time1 - time0)*1e-6; // milliseconds featureImg = detector.getDetector().getDetector().getIntensityRaw(); // featureImg = detector.getDetector().getDetector().getIntensity2x2(); if (controlPanel.logIntensity) { PixelMath.logSign(featureImg, 0.2f, logIntensity); VisualizeImageData.colorizeSign(logIntensity, visualized, ImageStatistics.maxAbs(logIntensity)); } else { VisualizeImageData.colorizeSign(featureImg, visualized, ImageStatistics.maxAbs(featureImg)); } synchronized (lockCorners) { this.success = success; DogArray<ChessboardCorner> orig = detector.getDetector().getCorners(); foundCorners.reset(); for (int i = 0; i < orig.size; i++) { foundCorners.grow().setTo(orig.get(i)); } if (success) { CalibrationObservation detected = detector.getDetectedPoints(); foundChessboard.reset(); for (int i = 0; i < detected.size(); i++) { foundChessboard.grow().setTo(detected.get(i)); } } { DogArray<GridInfo> found = detector.getDetectorX().getFoundChessboard(); foundGrids.reset(); for (int i = 0; i < found.size; i++) { GridInfo grid = found.get(i); CalibrationObservation c = foundGrids.grow(); c.points.clear(); for (int j = 0; j < grid.nodes.size(); j++) { c.points.add(new PointIndex2D_F64(grid.nodes.get(j), j)); } } } foundClusters.reset(); DogArray<ChessboardCornerGraph> clusters = detector.getClusterFinder().getOutputClusters(); for (int i = 0; i < clusters.size; i++) { clusters.get(i).convert(foundClusters.grow()); } } } SwingUtilities.invokeLater(() -> { controlPanel.setProcessingTimeMS(processingTime); imagePanel.setBufferedImageNoChange(original); imagePanel.repaint(); }); } class DisplayPanel extends ShapeVisualizePanel { Ellipse2D.Double circle = new Ellipse2D.Double(); BasicStroke stroke2 = new BasicStroke(2); BasicStroke stroke5 = new BasicStroke(5); @Override protected void paintInPanel( AffineTransform tran, Graphics2D g2 ) { super.paintInPanel(tran, g2); BoofSwingUtil.antialiasing(g2); if (controlPanel.translucent > 0) { // this requires some explaining // for some reason it was decided that the transform would apply a translation, but not a scale // so this scale will be concatted on top of the translation in the g2 tran.setTransform(scale, 0, 0, scale, 0, 0); Composite beforeAC = g2.getComposite(); float translucent = controlPanel.translucent/100.0f; AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, translucent); g2.setComposite(ac); g2.drawImage(visualized, tran, null); g2.setComposite(beforeAC); } Line2D.Double line = new Line2D.Double(); if (controlPanel.showCorners) { synchronized (lockCorners) { for (int i = 0; i < foundCorners.size; i++) { ChessboardCorner c = foundCorners.get(i); if (c.level2 < controlPanel.detMinPyrLevel) continue; double x = c.x; double y = c.y; g2.setStroke(stroke5); g2.setColor(Color.BLACK); VisualizeFeatures.drawCircle(g2, x*scale, y*scale, 5, circle); g2.setStroke(stroke2); g2.setColor(Color.ORANGE); VisualizeFeatures.drawCircle(g2, x*scale, y*scale, 5, circle); double dx = 6*Math.cos(c.orientation); double dy = 6*Math.sin(c.orientation); g2.setStroke(stroke2); g2.setColor(Color.CYAN); line.setLine((x - dx)*scale, (y - dy)*scale, (x + dx)*scale, (y + dy)*scale); g2.draw(line); } if (controlPanel.showNumbers) { DisplayPinholeCalibrationPanel.drawIndexes(g2, 18, foundCorners.toList(), null, controlPanel.detMinPyrLevel, scale); } } } if (controlPanel.showClusters) { synchronized (lockCorners) { int width = img.getWidth(); int height = img.getHeight(); for (int i = 0; i < foundClusters.size; i++) { FeatureGraph2D graph = foundClusters.get(i); // draw black outline g2.setStroke(new BasicStroke(5)); g2.setColor(Color.black); renderGraph(g2, line, graph); // make each graph a different color depending on position FeatureGraph2D.Node n0 = graph.nodes.get(0); int color = (int)((n0.x/width)*255) << 16 | ((int)((n0.y/height)*200) + 55) << 8 | 255; g2.setColor(new Color(color)); g2.setStroke(new BasicStroke(3)); renderGraph(g2, line, graph); } } } if (controlPanel.showPerpendicular) { // Locking the algorithm will kill performance. synchronized (lockAlgorithm) { Font regular = new Font("Serif", Font.PLAIN, 12); g2.setFont(regular); BasicStroke thin = new BasicStroke(2); BasicStroke thick = new BasicStroke(4); // g2.setStroke(new BasicStroke(1)); // List<Vertex> vertexes = detector.getClusterFinder().getVertexes().toList(); List<LineInfo> lines = detector.getClusterFinder().getLines().toList(); for (int i = 0; i < lines.size(); i++) { LineInfo lineInfo = lines.get(i); if (lineInfo.isDisconnected() || lineInfo.parallel) continue; Vertex va = lineInfo.endA.dst; Vertex vb = lineInfo.endB.dst; ChessboardCorner ca = foundCorners.get(va.index); ChessboardCorner cb = foundCorners.get(vb.index); double intensity = lineInfo.intensity == -Double.MAX_VALUE ? Double.NaN : lineInfo.intensity; line.setLine(ca.x*scale, ca.y*scale, cb.x*scale, cb.y*scale); g2.setStroke(thick); g2.setColor(Color.BLACK); g2.draw(line); g2.setStroke(thin); g2.setColor(Color.ORANGE); g2.draw(line); float x = (float)((ca.x + cb.x)/2.0); float y = (float)((ca.y + cb.y)/2.0); g2.setColor(Color.RED); g2.drawString(String.format("%.1f", intensity), x*(float)scale, y*(float)scale); } } } if (controlPanel.anyGrid) { if (controlPanel.showChessboards) { synchronized (lockCorners) { for (int i = 0; i < foundGrids.size; i++) { CalibrationObservation c = foundGrids.get(i); DisplayPinholeCalibrationPanel.renderOrder(g2, scale, (List)c.points); if (controlPanel.showNumbers) { DisplayPinholeCalibrationPanel.drawNumbers(g2, c.points, null, scale); } } } } } else { if (success && controlPanel.showChessboards) { synchronized (lockCorners) { DisplayPinholeCalibrationPanel.renderOrder(g2, scale, (List)foundChessboard.toList()); if (controlPanel.showNumbers) { DisplayPinholeCalibrationPanel.drawNumbers(g2, foundChessboard.toList(), null, scale); } } } } } @Override public synchronized void setScale( double scale ) { controlPanel.setZoom(scale); super.setScale(controlPanel.zoom); } private void renderGraph( Graphics2D g2, Line2D.Double line, FeatureGraph2D graph ) { for (int j = 0; j < graph.edges.size; j++) { FeatureGraph2D.Edge e = graph.edges.get(j); Point2D_F64 a = graph.nodes.get(e.src); Point2D_F64 b = graph.nodes.get(e.dst); line.setLine(a.x*scale, a.y*scale, b.x*scale, b.y*scale); g2.draw(line); } } } class ControlPanel extends DetectBlackShapePanel implements ActionListener, ChangeListener, ThresholdControlPanel.Listener { JTextArea textArea = new JTextArea(); int gridRows = configGridDimen.numRows; int gridCols = configGridDimen.numCols; int detPyramidTop = configDetector.detPyramidTopSize; int detRadius = configDetector.detNonMaxRadius; int detNonMaxThreshold = (int)(configDetector.detNonMaxThresholdRatio*100); double detRefinedXThresh = configDetector.detRefinedXCornerThreshold; int connMaxDistance = 0; double connEdgeThreshold = configDetector.connEdgeThreshold; double connAmbiguousTol = configDetector.connAmbiguousTol; double connDirectionTol = configDetector.connDirectionTol; double connOrientationTol = configDetector.connOrientationTol; boolean showChessboards = true; boolean showNumbers = true; boolean showClusters = false; boolean showPerpendicular = false; boolean showCorners = false; boolean logIntensity = false; boolean meanShift = true; boolean anyGrid = false; int detMinPyrLevel = 0; int translucent = 0; JSlider sliderTranslucent = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); JCheckBox checkLogIntensity = checkbox("Log Intensity", logIntensity); JSpinner spinnerDRadius = spinner(detRadius, 1, 100, 1); JSpinner spinnerDNonMaxThreshold = spinner(detNonMaxThreshold, 0, 100, 5); JSpinner spinnerDRefinedXThreshold = spinner(detRefinedXThresh, 0.0, 20.0, 0.005, 2, 3); JSpinner spinnerDTop = spinner(detPyramidTop, 0, 10000, 50); JSpinner spinnerDMinPyrLevel = spinner(detMinPyrLevel, 0, 20, 1); JSpinner spinnerCEdgeThreshold = spinner(connEdgeThreshold, 0, 1.0, 0.1, 1, 3); JSpinner spinnerCAmbiguous = spinner(connAmbiguousTol, 0, 1.0, 0.05, 1, 3); JSpinner spinnerCDirectionTol = spinner(connDirectionTol, 0, 1.0, 0.05, 1, 3); JSpinner spinnerCOrientationTol = spinner(connOrientationTol, 0, 3.0, 0.05, 1, 3); JSpinner spinnerCMaxDistance = spinner(connMaxDistance, 0, 50000, 1); // select the calibration grid's dimensions JSpinner spinnerGridRows = spinner(gridRows, 3, 500, 1); JSpinner spinnerGridCols = spinner(gridCols, 3, 500, 1); JCheckBox checkShowTargets = checkbox("Chessboard", showChessboards); JCheckBox checkShowNumbers = checkbox("Numbers", showNumbers); JCheckBox checkShowClusters = checkbox("Clusters", showClusters); JCheckBox checkShowPerpendicular = checkbox("Perp.", showPerpendicular); JCheckBox checkShowCorners = checkbox("Corners", showCorners); JCheckBox checkMeanShift = checkbox("Mean Shift", meanShift); JCheckBox checkAnyGrid = checkbox("Any Grid", anyGrid); ControlPanel() { textArea.setEditable(false); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); selectZoom = spinner(1.0, MIN_ZOOM, MAX_ZOOM, 1.0); checkLogIntensity = checkbox("Log Intensity", logIntensity); sliderTranslucent.setMaximumSize(new Dimension(120, 26)); sliderTranslucent.setPreferredSize(sliderTranslucent.getMaximumSize()); sliderTranslucent.addChangeListener(this); StandardAlgConfigPanel controlPanel = new StandardAlgConfigPanel(); controlPanel.addCenterLabel("Detect", controlPanel); controlPanel.addAlignLeft(checkMeanShift); controlPanel.addAlignLeft(checkAnyGrid); controlPanel.addLabeled(spinnerDRadius, "Corner Radius"); controlPanel.addLabeled(spinnerDRefinedXThreshold, "Refined X Threshold"); controlPanel.addLabeled(spinnerDNonMaxThreshold, "Non-Max Threshold"); controlPanel.addLabeled(spinnerDTop, "Pyramid Top"); controlPanel.addCenterLabel("Connect", controlPanel); controlPanel.addLabeled(spinnerCEdgeThreshold, "Edge Threshold"); controlPanel.addLabeled(spinnerCMaxDistance, "Max Dist."); controlPanel.addLabeled(spinnerCOrientationTol, "Orientation Tol"); controlPanel.addLabeled(spinnerCDirectionTol, "Direction Tol"); controlPanel.addLabeled(spinnerCAmbiguous, "Ambiguous Tol"); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Controls", controlPanel); tabbedPane.addTab("Info", textArea); addLabeled(processingTimeLabel, "Time (ms)"); addLabeled(imageSizeLabel, "Image Size"); addLabeled(sliderTranslucent, "X-Corners"); addLabeled(selectZoom, "Zoom"); add(createCheckPanel()); add(createGridShapePanel()); add(tabbedPane); } void setInfoText( String text ) { SwingUtilities.invokeLater(() -> textArea.setText(text)); } JPanel createCheckPanel() { JPanel panelChecks = new JPanel(new GridLayout(0, 2)); panelChecks.add(checkShowTargets); panelChecks.add(checkShowNumbers); panelChecks.add(checkShowClusters); panelChecks.add(checkShowPerpendicular); panelChecks.add(checkShowCorners); panelChecks.add(checkLogIntensity); panelChecks.setPreferredSize(panelChecks.getMinimumSize()); panelChecks.setMaximumSize(panelChecks.getMinimumSize()); StandardAlgConfigPanel vertPanel = new StandardAlgConfigPanel(); vertPanel.add(panelChecks); vertPanel.addLabeled(spinnerDMinPyrLevel, "Min Level"); vertPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Visualize", TitledBorder.CENTER, TitledBorder.TOP)); return vertPanel; } JPanel createGridShapePanel() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(new JLabel("Grid Shape")); panel.add(Box.createHorizontalGlue()); panel.add(spinnerGridRows); panel.add(spinnerGridCols); // panel.setPreferredSize(panel.getMinimumSize()); // panel.setMaximumSize(panel.getMinimumSize()); return panel; } @Override public void actionPerformed( ActionEvent e ) { if (e.getSource() == checkShowCorners) { showCorners = checkShowCorners.isSelected(); imagePanel.repaint(); } else if (e.getSource() == checkLogIntensity) { logIntensity = checkLogIntensity.isSelected(); reprocessImageOnly(); } else if (e.getSource() == checkShowTargets) { showChessboards = checkShowTargets.isSelected(); imagePanel.repaint(); } else if (e.getSource() == checkShowNumbers) { showNumbers = checkShowNumbers.isSelected(); imagePanel.repaint(); } else if (e.getSource() == checkShowClusters) { showClusters = checkShowClusters.isSelected(); imagePanel.repaint(); } else if (e.getSource() == checkShowPerpendicular) { showPerpendicular = checkShowPerpendicular.isSelected(); imagePanel.repaint(); } else if (e.getSource() == checkMeanShift) { meanShift = checkMeanShift.isSelected(); createAlgorithm(); reprocessImageOnly(); } else if (e.getSource() == checkAnyGrid) { anyGrid = checkAnyGrid.isSelected(); spinnerGridCols.setEnabled(!anyGrid); spinnerGridRows.setEnabled(!anyGrid); createAlgorithm(); reprocessImageOnly(); } } @Override public void stateChanged( ChangeEvent e ) { if (e.getSource() == selectZoom) { zoom = ((Number)selectZoom.getValue()).doubleValue(); imagePanel.setScale(zoom); return; } if (e.getSource() == spinnerCOrientationTol) { connOrientationTol = ((Number)spinnerCOrientationTol.getValue()).doubleValue(); } else if (e.getSource() == spinnerCDirectionTol) { connDirectionTol = ((Number)spinnerCDirectionTol.getValue()).doubleValue(); } else if (e.getSource() == spinnerCAmbiguous) { connAmbiguousTol = ((Number)spinnerCAmbiguous.getValue()).doubleValue(); } else if (e.getSource() == spinnerDRefinedXThreshold) { detRefinedXThresh = ((Number)spinnerDRefinedXThreshold.getValue()).doubleValue(); } else if (e.getSource() == spinnerDNonMaxThreshold) { detNonMaxThreshold = ((Number)spinnerDNonMaxThreshold.getValue()).intValue(); } else if (e.getSource() == spinnerCEdgeThreshold) { connEdgeThreshold = ((Number)spinnerCEdgeThreshold.getValue()).doubleValue(); } else if (e.getSource() == spinnerDRadius) { detRadius = ((Number)spinnerDRadius.getValue()).intValue(); } else if (e.getSource() == spinnerDTop) { detPyramidTop = ((Number)spinnerDTop.getValue()).intValue(); } else if (e.getSource() == spinnerGridRows) { gridRows = ((Number)spinnerGridRows.getValue()).intValue(); } else if (e.getSource() == spinnerGridCols) { gridCols = ((Number)spinnerGridCols.getValue()).intValue(); } else if (e.getSource() == spinnerCMaxDistance) { connMaxDistance = ((Number)spinnerCMaxDistance.getValue()).intValue(); } else if (e.getSource() == spinnerDMinPyrLevel) { detMinPyrLevel = ((Number)spinnerDMinPyrLevel.getValue()).intValue(); imagePanel.repaint(); return; } else if (e.getSource() == sliderTranslucent) { translucent = ((Number)sliderTranslucent.getValue()).intValue(); imagePanel.repaint(); return; } createAlgorithm(); reprocessImageOnly(); } @Override public void imageThresholdUpdated() { createAlgorithm(); reprocessImageOnly(); } } public static void main( String[] args ) { List<PathLabel> examples = new ArrayList<>(); examples.add(new PathLabel("Chessboard 1", UtilIO.pathExample("calibration/mono/Sony_DSC-HX5V_Chess/frame06.jpg"))); examples.add(new PathLabel("Chessboard 2 ", UtilIO.pathExample("calibration/stereo/Bumblebee2_Chess/left03.jpg"))); examples.add(new PathLabel("Chessboard 3 ", UtilIO.pathExample("calibration/stereo/Bumblebee2_Chess/left06.jpg"))); examples.add(new PathLabel("Fisheye 1", UtilIO.pathExample("calibration/fisheye/chessboard/1.jpg"))); examples.add(new PathLabel("Fisheye 2", UtilIO.pathExample("calibration/fisheye/chessboard/20.jpg"))); examples.add(new PathLabel("Fisheye 3", UtilIO.pathExample("calibration/fisheye/chessboard/21.jpg"))); examples.add(new PathLabel("Chessboard Movie", UtilIO.pathExample("fiducial/chessboard/movie.mjpeg"))); SwingUtilities.invokeLater(() -> { DetectCalibrationChessboardXCornerApp app = new DetectCalibrationChessboardXCornerApp(examples); app.openExample(examples.get(0)); app.waitUntilInputSizeIsKnown(); app.display("Chessboard (X-Corner) Detector"); }); } }
3e1775e4c9c9564b1616d4f082d137c5f47efd27
7,046
java
Java
src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java
ksky8864/uroborosql
80cea94cc849dfe354a185f0af274e874cf4cad4
[ "MIT" ]
null
null
null
src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java
ksky8864/uroborosql
80cea94cc849dfe354a185f0af274e874cf4cad4
[ "MIT" ]
null
null
null
src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java
ksky8864/uroborosql
80cea94cc849dfe354a185f0af274e874cf4cad4
[ "MIT" ]
null
null
null
35.766497
110
0.751916
9,990
package jp.co.future.uroborosql.context; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.*; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collector; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; import org.slf4j.event.Level; import jp.co.future.uroborosql.UroboroSQL; import jp.co.future.uroborosql.config.SqlConfig; import jp.co.future.uroborosql.context.test.TestConsts; import jp.co.future.uroborosql.context.test.TestEnum1; import jp.co.future.uroborosql.parameter.Parameter; public class SqlContextFactoryTest { private SqlConfig sqlConfig; private SqlContextFactory sqlContextFactory; @Before public void setUp() throws Exception { sqlConfig = UroboroSQL .builder("jdbc:h2:mem:" + this.getClass().getSimpleName() + ";DB_CLOSE_DELAY=-1", "sa", "sa").build(); sqlContextFactory = sqlConfig.getSqlContextFactory(); } @Test public void testConst_class() { sqlContextFactory.addBindParamMapper((original, connection, parameterMapperManager) -> null); sqlContextFactory.setConstantClassNames(Arrays.asList(TestConsts.class.getName())); sqlContextFactory.initialize(); Map<String, Parameter> constParameterMap = sqlContextFactory.getConstParameterMap(); Map<String, ?> map = constParameterMap.entrySet().stream() .collect(Collector.of(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().getValue()), (m1, m2) -> { m1.putAll(m2); return m1; })); assertThat(map, is(mapOf( "CLS_STRING", "AAA", "CLS_INT", 1, "CLS_INNER_CLASS_ISTRING", TestConsts.InnerClass.ISTRING, // コンパイラによりバイトコード差異で安定しないためテストしない // "CLS_OVERLAP_OVERLAP_VAL", "重複テスト2", "CLS_BOOLEAN", TestConsts.BOOLEAN, "CLS_BYTE", TestConsts.BYTE, "CLS_SHORT", TestConsts.SHORT, "CLS_LONG", TestConsts.LONG, "CLS_DOUBLE", TestConsts.DOUBLE, "CLS_FLOAT", TestConsts.FLOAT, "CLS_BIG_DECIMAL", TestConsts.BIG_DECIMAL, "CLS_BYTES", TestConsts.BYTES, "CLS_SQL_DATE", TestConsts.SQL_DATE, "CLS_SQL_TIME", TestConsts.SQL_TIME, "CLS_SQL_TIMESTAMP", TestConsts.SQL_TIMESTAMP, "CLS_SQL_ARRAY", TestConsts.SQL_ARRAY, "CLS_SQL_REF", TestConsts.SQL_REF, "CLS_SQL_BLOB", TestConsts.SQL_BLOB, "CLS_SQL_CLOB", TestConsts.SQL_CLOB, "CLS_SQL_SQLXML", TestConsts.SQL_SQLXML, "CLS_SQL_STRUCT", TestConsts.SQL_STRUCT, "CLS_ENUM", TestConsts.ENUM, "CLS_LOCAL_DATE", TestConsts.LOCAL_DATE, "CLS_UTIL_DATE", TestConsts.UTIL_DATE, "CLS_NULL", TestConsts.NULL, "CLS_OBJECT_STR", TestConsts.OBJECT_STR, "CLS_IGNORE", TestConsts.IGNORE, "CLS_CUSTOMMAPPER_TARGET", TestConsts.CUSTOMMAPPER_TARGET ))); } private Map<String, ?> mapOf(final Object... args) { Map<String, Object> map = new HashMap<>(); for (int i = 0; i < args.length; i += 2) { map.put((String) args[i], args[i + 1]); } return map; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testConst_enum() { sqlContextFactory.setEnumConstantPackageNames(Arrays.asList(TestEnum1.class.getPackage().getName())); sqlContextFactory.initialize(); Map<String, Parameter> constParameterMap = sqlContextFactory.getConstParameterMap(); Set<String> set = constParameterMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().getValue()) .collect(Collectors.toSet()); assertThat( set, is(new HashSet<>(Arrays.asList("CLS_TEST_ENUM1_A=A", "CLS_TEST_ENUM1_B=B", "CLS_TEST_ENUM1_C=C", "CLS_PACKTEST_TEST_ENUM2_D=D", "CLS_PACKTEST_TEST_ENUM2_E=E", "CLS_PACKTEST_TEST_ENUM2_F=F", "CLS_PACKTEST_TEST_ENUM2_INNER_G=G", "CLS_PACKTEST_TEST_ENUM2_INNER_H=H", "CLS_PACKTEST_TEST_ENUM2_INNER_I=I")))); for (Parameter parameter : constParameterMap.values()) { assertThat(parameter.getValue(), isA((Class) Enum.class)); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testConst_enumForJar() { sqlContextFactory.setEnumConstantPackageNames(Arrays.asList(Level.class.getPackage().getName())); sqlContextFactory.initialize(); Map<String, Parameter> constParameterMap = sqlContextFactory.getConstParameterMap(); Set<String> set = constParameterMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().getValue()) .collect(Collectors.toSet()); assertThat( set, is(new HashSet<>(Arrays.asList("CLS_LEVEL_ERROR=ERROR", "CLS_LEVEL_DEBUG=DEBUG", "CLS_LEVEL_WARN=WARN", "CLS_LEVEL_TRACE=TRACE", "CLS_LEVEL_INFO=INFO")))); for (Parameter parameter : constParameterMap.values()) { assertThat(parameter.getValue(), isA((Class) Enum.class)); } } @SuppressWarnings("deprecation") @Test public void testAutoBindParameterCreator() throws Exception { List<AutoBindParameterCreator> creators = new ArrayList<>(); sqlContextFactory.setAutoBindParameterCreators(creators); sqlContextFactory.initialize(); SqlContext ctx = sqlContextFactory.createSqlContext(); assertThat(ctx.getParam("DUMMY"), is(nullValue())); creators.add(() -> { ConcurrentHashMap<String, Parameter> params = new ConcurrentHashMap<>(); return params; }); sqlContextFactory.initialize(); ctx = sqlContextFactory.createSqlContext(); assertThat(ctx.getParam("DUMMY"), is(nullValue())); creators.add(() -> { ConcurrentHashMap<String, Parameter> params = new ConcurrentHashMap<>(); params.put("DUMMY", new Parameter("DUMMY", "dummy_value")); return params; }); sqlContextFactory.initialize(); ctx = sqlContextFactory.createSqlContext(); assertThat(sqlContextFactory.getAutoBindParameterCreators(), is(creators)); assertThat(ctx.getParam("DUMMY").getValue(), is("dummy_value")); } @Test public void testSetDefaultResultSetType() throws Exception { sqlContextFactory.initialize(); sqlContextFactory.setDefaultResultSetType(ResultSet.TYPE_FORWARD_ONLY); assertThat(sqlContextFactory.createSqlContext().getResultSetType(), is(ResultSet.TYPE_FORWARD_ONLY)); sqlContextFactory.setDefaultResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); assertThat(sqlContextFactory.createSqlContext().getResultSetType(), is(ResultSet.TYPE_SCROLL_INSENSITIVE)); sqlContextFactory.setDefaultResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); assertThat(sqlContextFactory.createSqlContext().getResultSetType(), is(ResultSet.TYPE_SCROLL_SENSITIVE)); } @Test public void testSetDefaultResultSetConcurrency() throws Exception { sqlContextFactory.initialize(); sqlContextFactory.setDefaultResultSetConcurrency(ResultSet.CONCUR_READ_ONLY); assertThat(sqlContextFactory.createSqlContext().getResultSetConcurrency(), is(ResultSet.CONCUR_READ_ONLY)); sqlContextFactory.setDefaultResultSetConcurrency(ResultSet.CONCUR_UPDATABLE); assertThat(sqlContextFactory.createSqlContext().getResultSetConcurrency(), is(ResultSet.CONCUR_UPDATABLE)); } }
3e177624c92c4bb126b1329b5c74ab68417620b2
2,126
java
Java
Workspace/net.jp2p.container/src/net/jp2p/container/context/Jp2pServiceDescriptor.java
chaupal/jp2p
fa669ac267c75128cf83eda28588013c59ae9200
[ "Apache-2.0" ]
8
2015-04-07T03:01:15.000Z
2022-01-13T03:16:29.000Z
Workspace/net.jp2p.container/src/net/jp2p/container/context/Jp2pServiceDescriptor.java
chaupal/jp2p
fa669ac267c75128cf83eda28588013c59ae9200
[ "Apache-2.0" ]
null
null
null
Workspace/net.jp2p.container/src/net/jp2p/container/context/Jp2pServiceDescriptor.java
chaupal/jp2p
fa669ac267c75128cf83eda28588013c59ae9200
[ "Apache-2.0" ]
5
2016-04-05T07:08:03.000Z
2019-10-15T16:18:19.000Z
25.011765
82
0.610536
9,991
/******************************************************************************* * Copyright (c) 2014 Chaupal. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0.html *******************************************************************************/ package net.jp2p.container.context; import net.jp2p.container.utils.Utils; public class Jp2pServiceDescriptor implements Comparable<Jp2pServiceDescriptor>{ String name; String context; boolean optional = false; public Jp2pServiceDescriptor( String name ) { this( name, false ); } public Jp2pServiceDescriptor( String name, boolean optional) { super(); this.name = name; this.optional = optional; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public boolean isOptional() { return optional; } @Override public String toString() { return this.context + ":" + this.name; } @Override public int hashCode() { String str = this.context + ":" + this.name; return str.hashCode(); } @Override public boolean equals(Object obj) { if( super.equals(obj)) return true; if( !( obj instanceof Jp2pServiceDescriptor)) return false; if( Utils.isNull( this.context )) return false; Jp2pServiceDescriptor descriptor = (Jp2pServiceDescriptor) obj; return this.name.equals( descriptor.getName() ); } @Override public int compareTo(Jp2pServiceDescriptor o) { if(( context == null ) && ( o.getContext() != null )) return -1; if(( context != null ) && ( o.getContext() == null )) return 1; if(( context != null ) && ( o.getContext() != null )) return this.context.compareTo( o.getContext()); return this.name.compareTo( o.getName() ); } }
3e1776f5e7fe71eed1e7d6a4eab7e54762802d1b
2,693
java
Java
kit/src/main/java/com/oracle/javafx/scenebuilder/kit/metadata/property/value/list/DoubleListPropertyMetadata.java
zippoy/scenebuilder
7585da203d1c14282d17d06633af934904cb9624
[ "BSD-3-Clause" ]
524
2018-05-09T16:29:46.000Z
2022-03-30T16:17:24.000Z
kit/src/main/java/com/oracle/javafx/scenebuilder/kit/metadata/property/value/list/DoubleListPropertyMetadata.java
zippoy/scenebuilder
7585da203d1c14282d17d06633af934904cb9624
[ "BSD-3-Clause" ]
317
2018-05-25T12:20:46.000Z
2022-03-30T19:14:29.000Z
kit/src/main/java/com/oracle/javafx/scenebuilder/kit/metadata/property/value/list/DoubleListPropertyMetadata.java
zippoy/scenebuilder
7585da203d1c14282d17d06633af934904cb9624
[ "BSD-3-Clause" ]
226
2018-05-09T20:35:25.000Z
2022-03-26T12:00:46.000Z
48.963636
100
0.770516
9,992
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.javafx.scenebuilder.kit.metadata.property.value.list; import com.oracle.javafx.scenebuilder.kit.metadata.property.value.DoublePropertyMetadata; import com.oracle.javafx.scenebuilder.kit.metadata.property.value.DoublePropertyMetadata.DoubleKind; import com.oracle.javafx.scenebuilder.kit.metadata.util.InspectorPath; import com.oracle.javafx.scenebuilder.kit.metadata.util.PropertyName; import java.util.List; /** * */ public class DoubleListPropertyMetadata extends ListValuePropertyMetadata<Double> { private final static DoublePropertyMetadata itemMetadata = new DoublePropertyMetadata(new PropertyName("unused"), //NOI18N DoubleKind.COORDINATE, true, 0.0, InspectorPath.UNUSED); public DoubleListPropertyMetadata(PropertyName name, boolean readWrite, List<Double> defaultValue, InspectorPath inspectorPath) { super(name, Double.class, itemMetadata, readWrite, defaultValue, inspectorPath); } }
3e177709e87bc315d0e27dc7002e276d263b52fa
2,273
java
Java
MS_LIBRARY/src/org/yeastrc/ms/writer/mzidentml/jaxb/CVListType.java
yeastrc/msdapl
0239d2dc34a41702eec39ee4cf1de95593044777
[ "Apache-2.0" ]
4
2017-04-13T21:04:57.000Z
2021-07-16T19:42:16.000Z
MS_LIBRARY/src/org/yeastrc/ms/writer/mzidentml/jaxb/CVListType.java
yeastrc/msdapl
0239d2dc34a41702eec39ee4cf1de95593044777
[ "Apache-2.0" ]
null
null
null
MS_LIBRARY/src/org/yeastrc/ms/writer/mzidentml/jaxb/CVListType.java
yeastrc/msdapl
0239d2dc34a41702eec39ee4cf1de95593044777
[ "Apache-2.0" ]
2
2016-06-16T17:16:40.000Z
2017-07-27T18:48:45.000Z
27.719512
124
0.644523
9,993
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // 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: 2011.08.01 at 02:54:01 PM PDT // package org.yeastrc.ms.writer.mzidentml.jaxb; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * The list of controlled vocabularies used in the * file. * * <p>Java class for CVListType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CVListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="cv" type="{http://psidev.info/psi/pi/mzIdentML/1.1}cvType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CVListType", propOrder = { "cv" }) @XmlRootElement(name="cvList") public class CVListType { @XmlElement(required = true) protected List<CvType> cv; /** * Gets the value of the cv property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the cv property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCv().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CvType } * * */ public List<CvType> getCv() { if (cv == null) { cv = new ArrayList<CvType>(); } return this.cv; } }
3e1777ba3b50848933ea217c2ce9a1173bf61a19
1,935
java
Java
sql/src/test/java/io/crate/expression/scalar/ArrayLowerFunctionTest.java
chaudum/crate
ad4a35126e4e09dc372edd1c8c97bf589cef96ca
[ "Apache-2.0" ]
1
2020-02-03T11:59:41.000Z
2020-02-03T11:59:41.000Z
sql/src/test/java/io/crate/expression/scalar/ArrayLowerFunctionTest.java
chaudum/crate
ad4a35126e4e09dc372edd1c8c97bf589cef96ca
[ "Apache-2.0" ]
null
null
null
sql/src/test/java/io/crate/expression/scalar/ArrayLowerFunctionTest.java
chaudum/crate
ad4a35126e4e09dc372edd1c8c97bf589cef96ca
[ "Apache-2.0" ]
null
null
null
32.79661
75
0.703359
9,994
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.expression.scalar; import org.junit.Test; public class ArrayLowerFunctionTest extends AbstractScalarFunctionsTest { @Test public void testSecondArgumentIsNull() { assertEvaluate("array_lower([1, 2], null)", null); } @Test public void testSingleDimensionArrayValidDimension() { assertEvaluate("array_lower([4, 5], 1)", 1); } @Test public void testSingleDimensionArrayInvalidDimension() { assertEvaluate("array_lower([4, 5], 3)", null); } @Test public void testMultiDimensionArrayValidDimension() { assertEvaluate("array_lower([[1, 2, 3], [3, 4]], 2)", 1); } @Test public void testMultiDimensionArrayInvalidDimension() { assertEvaluate("array_lower([[1, 2, 3], [3, 4]], 3)", null); } @Test public void testEmptyArray() { assertEvaluate("array_lower(cast([] as array(integer)), 1)", null); } }
3e1778243acb52f9ab757cf10fab281e1d34f002
1,584
java
Java
src/com/android/camera/data/DataUtils.java
iamluciano/Camera2
8c374a9469bdca6f5d05b2a13dbc878043b61ba0
[ "Apache-2.0" ]
34
2018-12-08T04:57:02.000Z
2022-02-28T01:40:25.000Z
src/com/android/camera/data/DataUtils.java
iamluciano/Camera2
8c374a9469bdca6f5d05b2a13dbc878043b61ba0
[ "Apache-2.0" ]
2
2019-01-11T12:02:07.000Z
2019-02-20T06:28:57.000Z
src/com/android/camera/data/DataUtils.java
iamluciano/Camera2
8c374a9469bdca6f5d05b2a13dbc878043b61ba0
[ "Apache-2.0" ]
20
2019-01-05T11:31:13.000Z
2021-11-02T15:48:13.000Z
27.789474
89
0.626263
9,995
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera.data; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; public class DataUtils { /** * Get the file path from a Media storage URI. */ public static String getPathFromURI(ContentResolver contentResolver, Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = contentResolver.query(contentUri, proj, null, null, null); if (cursor == null) { return null; } try { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (!cursor.moveToFirst()) { return null; } else { return cursor.getString(columnIndex); } } finally { cursor.close(); } } }
3e1779d1d9371ae5eaac1cea9c54c631009dcdd2
355
java
Java
src/main/java/com/yunxin/utils/BinSturcture/BinType.java
hedingwei/yunxin-utils
c15cb71917b309490e7e50775daf1ebe78f74007
[ "MIT" ]
1
2020-05-09T07:15:25.000Z
2020-05-09T07:15:25.000Z
src/main/java/com/yunxin/utils/BinSturcture/BinType.java
hedingwei/yunxin-utils
c15cb71917b309490e7e50775daf1ebe78f74007
[ "MIT" ]
null
null
null
src/main/java/com/yunxin/utils/BinSturcture/BinType.java
hedingwei/yunxin-utils
c15cb71917b309490e7e50775daf1ebe78f74007
[ "MIT" ]
null
null
null
13.653846
38
0.51831
9,996
package com.yunxin.utils.BinSturcture; public enum BinType { BYTE(0), UBYTE(0), SHORT(1), USHORT(2), INT(3), UINT(4), LONG(5), ULONG(6), STRING(7), BYTEARRAY(8); private byte type; private BinType(byte type) { this.type = type; } BinType(int i) { this.type = (byte) i; } }
3e1779ffedf4c059478f9ae640cb8b953ab4075e
644
java
Java
social-multiplication-mm/microservices.book.api/src/main/java/microservices/book/api/services/persistent/DatabaseException.java
akabanov57/social-multiplication-mm
98abf0472d6073400ce4697a33fa7ce4c902af5e
[ "MIT" ]
null
null
null
social-multiplication-mm/microservices.book.api/src/main/java/microservices/book/api/services/persistent/DatabaseException.java
akabanov57/social-multiplication-mm
98abf0472d6073400ce4697a33fa7ce4c902af5e
[ "MIT" ]
null
null
null
social-multiplication-mm/microservices.book.api/src/main/java/microservices/book/api/services/persistent/DatabaseException.java
akabanov57/social-multiplication-mm
98abf0472d6073400ce4697a33fa7ce4c902af5e
[ "MIT" ]
null
null
null
24.769231
95
0.76087
9,997
package microservices.book.api.services.persistent; public class DatabaseException extends RuntimeException { private static final long serialVersionUID = 5446373091216402531L; public DatabaseException() {} public DatabaseException(String message) { super(message); } public DatabaseException(Throwable cause) { super(cause); } public DatabaseException(String message, Throwable cause) { super(message, cause); } public DatabaseException( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
3e177acafe068f0004209955d0f318cc37b1f3fe
456
java
Java
src/test/java/fi/kapsi/janner/fmireader/connection/FmiConnectionTest.java
jaruotsa/fmi-reader
ed96437b3b5ce961613d7cb25e7f37b1fddcf715
[ "MIT" ]
null
null
null
src/test/java/fi/kapsi/janner/fmireader/connection/FmiConnectionTest.java
jaruotsa/fmi-reader
ed96437b3b5ce961613d7cb25e7f37b1fddcf715
[ "MIT" ]
null
null
null
src/test/java/fi/kapsi/janner/fmireader/connection/FmiConnectionTest.java
jaruotsa/fmi-reader
ed96437b3b5ce961613d7cb25e7f37b1fddcf715
[ "MIT" ]
null
null
null
24
100
0.734649
9,998
package fi.kapsi.janner.fmireader.connection; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; /** * Created by janne on 17/05/17. */ public class FmiConnectionTest { @Test public void testBaseAddress() throws Exception { Connection connection = new FmiConnection("secret-api-key"); assertThat(connection.getBaseAddress(), is("http://data.fmi.fi/fmi-apikey/secret-api-key/wfs")); } }
3e177bf2d14b6cba7fdf3dcd182cd0d6377a0764
9,713
java
Java
sponge/src/main/java/com/griefdefender/migrator/RedProtectMigrator.java
martin1194/GriefDefender
73452825ab79a8714f86d5e2b08e2505b315caad
[ "MIT" ]
104
2019-06-16T00:15:27.000Z
2022-03-22T07:15:14.000Z
sponge/src/main/java/com/griefdefender/migrator/RedProtectMigrator.java
martin1194/GriefDefender
73452825ab79a8714f86d5e2b08e2505b315caad
[ "MIT" ]
423
2019-07-24T01:50:30.000Z
2022-03-24T21:59:24.000Z
sponge/src/main/java/com/griefdefender/migrator/RedProtectMigrator.java
martin1194/GriefDefender
73452825ab79a8714f86d5e2b08e2505b315caad
[ "MIT" ]
142
2019-07-25T06:44:26.000Z
2022-03-19T14:55:06.000Z
50.06701
166
0.622671
9,999
/* * This file is part of GriefDefender, licensed under the MIT License (MIT). * * Copyright (c) bloodmc * Copyright (c) contributors * * 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.griefdefender.migrator; import com.google.common.reflect.TypeToken; import com.griefdefender.GriefDefenderPlugin; import com.griefdefender.api.claim.ClaimTypes; import com.griefdefender.configuration.ClaimDataConfig; import com.griefdefender.configuration.ClaimStorageData; import com.griefdefender.internal.util.BlockUtil; import com.griefdefender.util.PermissionUtil; import com.griefdefender.util.PlayerUtil; import net.kyori.text.TextComponent; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RedProtectMigrator { private static final String USERNAME_PATTERN = "[a-zA-Z0-9_]+"; public static void migrate(World world, Path redProtectFilePath, Path gpClaimDataPath) throws FileNotFoundException, ClassNotFoundException { if (!GriefDefenderPlugin.getGlobalConfig().getConfig().migrator.redProtectMigrator) { return; } int count = 0; try { GriefDefenderPlugin.getInstance().getLogger().info("Starting RedProtect region data migration for world " + world.getProperties().getWorldName() + "..."); ConfigurationLoader<CommentedConfigurationNode> regionManager = HoconConfigurationLoader.builder().setPath(redProtectFilePath).build(); CommentedConfigurationNode region = regionManager.load(); GriefDefenderPlugin.getInstance().getLogger().info("Scanning RedProtect regions in world data file '" + redProtectFilePath + "'..."); for (Object key:region.getChildrenMap().keySet()){ String rname = key.toString(); if (!region.getNode(rname).hasMapChildren()){ continue; } int maxX = region.getNode(rname,"maxX").getInt(); int maxY = region.getNode(rname,"maxY").getInt(255); int maxZ = region.getNode(rname,"maxZ").getInt(); int minX = region.getNode(rname,"minX").getInt(); int minY = region.getNode(rname,"minY").getInt(0); int minZ = region.getNode(rname,"minZ").getInt(); List<String> owners = new ArrayList<String>(); owners.addAll(region.getNode(rname,"owners").getList(TypeToken.of(String.class))); List<String> members = new ArrayList<String>(); members.addAll(region.getNode(rname,"members").getList(TypeToken.of(String.class))); String creator = region.getNode(rname,"creator").getString(); String welcome = region.getNode(rname,"welcome").getString(); // create GP claim data file GriefDefenderPlugin.getInstance().getLogger().info("Migrating RedProtect region data '" + rname + "'..."); UUID ownerUniqueId = null; if (validate(creator)) { try { // check cache first ownerUniqueId = PermissionUtil.getInstance().lookupUserUniqueId(creator); if (ownerUniqueId == null) { ownerUniqueId = UUID.fromString(getUUID(creator)); } } catch (Throwable e) { // assume admin claim } } UUID claimUniqueId = UUID.randomUUID(); Location<World> lesserBoundaryCorner = new Location<>(world, minX, minY, minZ); Location<World> greaterBoundaryCorner = new Location<>(world, maxX, maxY, maxZ); Path claimFilePath = gpClaimDataPath.resolve(claimUniqueId.toString()); if (!Files.exists(claimFilePath)) { Files.createFile(claimFilePath); } ClaimStorageData claimStorage = new ClaimStorageData(claimFilePath, world.getUniqueId()); ClaimDataConfig claimDataConfig = claimStorage.getConfig(); claimDataConfig.setName(TextComponent.of(rname)); claimDataConfig.setWorldUniqueId(world.getUniqueId()); claimDataConfig.setOwnerUniqueId(ownerUniqueId); claimDataConfig.setLesserBoundaryCorner(BlockUtil.getInstance().posToString(lesserBoundaryCorner)); claimDataConfig.setGreaterBoundaryCorner(BlockUtil.getInstance().posToString(greaterBoundaryCorner)); claimDataConfig.setDateLastActive(Instant.now()); claimDataConfig.setType(ownerUniqueId == null ? ClaimTypes.ADMIN : ClaimTypes.BASIC); if (!welcome.equals("")) { claimDataConfig.setGreeting(TextComponent.of(welcome)); } List<String> rpUsers = new ArrayList<>(owners); rpUsers.addAll(members); List<UUID> builders = claimDataConfig.getBuilders(); for (String builder : rpUsers) { if (!validate(builder)) { continue; } UUID builderUniqueId = null; try { builderUniqueId = PermissionUtil.getInstance().lookupUserUniqueId(creator); if (builderUniqueId == null) { builderUniqueId = UUID.fromString(getUUID(builder)); } } catch (Throwable e) { GriefDefenderPlugin.getInstance().getLogger().error("Could not locate a valid UUID for user '" + builder + "' in region '" + rname + "'. Skipping..."); continue; } if (!builders.contains(builderUniqueId) && ownerUniqueId != null && !builderUniqueId.equals(ownerUniqueId)) { builders.add(builderUniqueId); } } claimDataConfig.setRequiresSave(true); claimStorage.save(); GriefDefenderPlugin.getInstance().getLogger().info("Successfully migrated RedProtect region data '" + rname + "' to '" + claimFilePath + "'"); count++; } GriefDefenderPlugin.getInstance().getLogger().info("Finished RedProtect region data migration for world '" + world.getProperties().getWorldName() + "'." + " Migrated a total of " + count + " regions."); } catch (IOException e) { e.printStackTrace(); } catch (ObjectMappingException e) { e.printStackTrace(); } } private static boolean validate(final String username){ Matcher matcher = Pattern.compile(USERNAME_PATTERN).matcher(username); return matcher.matches(); } // Below taken from https://github.com/FabioZumbi12/Sponge-Redprotect-19/blob/master/src/main/java/br/net/fabiozumbi12/redprotect/MojangUUIDs.java public static String getUUID(String player) { try { URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + player); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); if (line == null){ return null; } // JSONObject jsonProfile = (JSONObject) new JSONParser().parse(line); String name = "";//(String) jsonProfile.get("id"); return toUUID(name); } catch (Exception ex) { ex.printStackTrace(); } return null; } private static String toUUID(String uuid){ return uuid.substring(0, 8) + "-" + uuid.substring(8, 12) + "-" + uuid.substring(12, 16) + "-" + uuid.substring(16, 20) + "-" + uuid.substring(20, 32); } }
3e177cc9c31ec7ef41786dd67649ff3f1e8a4054
1,493
java
Java
src/main/java/com/palyrobotics/frc2022/util/service/NetworkLoggerService.java
team8/FRC-2022-Public
6c618d4bac72c9534c76ee7fa6efb80cd47f58df
[ "MIT" ]
null
null
null
src/main/java/com/palyrobotics/frc2022/util/service/NetworkLoggerService.java
team8/FRC-2022-Public
6c618d4bac72c9534c76ee7fa6efb80cd47f58df
[ "MIT" ]
null
null
null
src/main/java/com/palyrobotics/frc2022/util/service/NetworkLoggerService.java
team8/FRC-2022-Public
6c618d4bac72c9534c76ee7fa6efb80cd47f58df
[ "MIT" ]
null
null
null
26.192982
104
0.712659
10,000
package com.palyrobotics.frc2022.util.service; import com.esotericsoftware.minlog.Log; import com.esotericsoftware.minlog.Log.Logger; import com.palyrobotics.frc2022.util.http.LightHttpServer; import edu.wpi.first.wpilibj.Timer; // control center logging public class NetworkLoggerService extends ServerServiceBase implements RobotService { private static final int kPort = 4000; private final Timer mTimer = new Timer(); private Logger mLogger = new Logger() { @Override public void log(int level, String category, String message, Throwable exception) { if (category != null && (category.equals("kryo") || category.equals("kryo.FieldSerializerConfig"))) { // Kryonet can possibly log when this function is called, creating a recursive // loop return; } double timeSeconds = mTimer.get(); long timeMilliseconds = Math.round(timeSeconds * 1000.0); var log = new LogEntry(timeMilliseconds, level, category, message, exception); if (!mServer.getConnected()) { // If we aren't connected, forward to system out which goes to driver station if (level == Log.LEVEL_ERROR) { System.err.println(log); } else { System.out.println(log); } } else { mServer.addLog(log); } } }; public NetworkLoggerService(LightHttpServer mServer) { super(mServer); } @Override public int getPort() { return kPort; } @Override public void start() { mTimer.start(); Log.setLogger(mLogger); Log.set(Log.LEVEL_TRACE); } }
3e177e0818ba89ae74140de625fa622fd29cb11b
2,173
java
Java
Mage/src/main/java/mage/abilities/condition/common/XorLessLifeCondition.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage/src/main/java/mage/abilities/condition/common/XorLessLifeCondition.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage/src/main/java/mage/abilities/condition/common/XorLessLifeCondition.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
31.042857
106
0.54809
10,001
package mage.abilities.condition.common; import mage.abilities.Ability; import mage.abilities.condition.Condition; import mage.game.Game; import mage.players.Player; import mage.players.PlayerList; import java.util.UUID; /** * * @author maurer.it_at_gmail.com */ public class XorLessLifeCondition implements Condition { public enum CheckType { AN_OPPONENT, CONTROLLER, TARGET_OPPONENT, EACH_PLAYER } private final CheckType type; private final int amount; public XorLessLifeCondition ( CheckType type , int amount) { this.type = type; this.amount = amount; } @Override public boolean apply(Game game, Ability source) { boolean conditionApplies = false; /* 104.5. If a player loses the game, that player leaves the game. Once a player leaves the game, their life check is no longer valid. IE Anya, Merciless Angel */ switch ( this.type ) { case AN_OPPONENT: for ( UUID opponentUUID : game.getOpponents(source.getControllerId()) ) { conditionApplies |= game.getPlayer(opponentUUID).isInGame() && game.getPlayer(opponentUUID).getLife() <= amount; } break; case CONTROLLER: conditionApplies = game.getPlayer(source.getControllerId()).getLife() <= amount; break; case TARGET_OPPONENT: //TODO: Implement this. break; case EACH_PLAYER: int maxLife = 0; PlayerList playerList = game.getState().getPlayersInRange(source.getControllerId(), game); for ( UUID pid : playerList ) { Player p = game.getPlayer(pid); if (p != null && p.isInGame()) { if (maxLife < p.getLife()) { maxLife = p.getLife(); } } } conditionApplies = maxLife <= amount; break; } return conditionApplies; } }
3e177e2b401e1d9bf2d5a2ee8111894df82e52a1
5,461
java
Java
src/main/java/com/arpnetworking/metrics/common/sources/ActorSource.java
ArpNetworking/metrics-aggregator-daemon
3125c7d8e9fd71eacc9dd79621f3202adb35db5e
[ "Apache-2.0" ]
6
2016-04-15T03:22:13.000Z
2018-08-07T22:29:24.000Z
src/main/java/com/arpnetworking/metrics/common/sources/ActorSource.java
ArpNetworking/metrics-aggregator-daemon
3125c7d8e9fd71eacc9dd79621f3202adb35db5e
[ "Apache-2.0" ]
92
2016-02-08T23:43:10.000Z
2021-03-25T17:39:48.000Z
src/main/java/com/arpnetworking/metrics/common/sources/ActorSource.java
ArpNetworking/metrics-aggregator-daemon
3125c7d8e9fd71eacc9dd79621f3202adb35db5e
[ "Apache-2.0" ]
13
2016-04-25T10:52:13.000Z
2020-06-08T16:51:07.000Z
32.313609
118
0.598791
10,002
/* * Copyright 2016 Smartsheet * * 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.arpnetworking.metrics.common.sources; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.actor.Props; import akka.pattern.Patterns; import com.arpnetworking.steno.Logger; import com.arpnetworking.steno.LoggerFactory; import com.fasterxml.jackson.annotation.JacksonInject; import net.sf.oval.constraint.NotEmpty; import net.sf.oval.constraint.NotNull; import java.time.Duration; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; /** * Serves as a base class for actor-based sources. * * @author Brandon Arp (brandon dot arp at smartsheet dot com) */ public abstract class ActorSource extends BaseSource { @Override public void start() { if (_actor == null) { _actor = _actorSystem.actorOf(createProps(), _actorName); } } @Override public void stop() { if (_actor != null) { try { Patterns.gracefulStop( _actor, SHUTDOWN_TIMEOUT, PoisonPill.getInstance()).toCompletableFuture().get( SHUTDOWN_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { LOGGER.warn() .setMessage("Interrupted stopping actor source") .addData("name", getName()) .addData("actor", _actor) .addData("actorName", _actorName) .log(); } catch (final TimeoutException | ExecutionException e) { LOGGER.error() .setMessage("Actor source stop timed out or failed") .addData("name", getName()) .addData("actor", _actor) .addData("actorName", _actorName) .addData("timeout", SHUTDOWN_TIMEOUT) .setThrowable(e) .log(); } _actor = null; } } /** * Return the {@link ActorSystem} used by this source. * * @return The {@link ActorSystem} used by this source. */ protected ActorSystem getActorSystem() { return _actorSystem; } /** * Return an {@link ActorRef} to this source's Akka actor. * * @return An {@link ActorRef} to this source's Akka actor. */ protected ActorRef getActor() { return _actor; } /** * Create a props for the actor to be created at the provided path. * * @return A props to create the actor with. */ protected abstract Props createProps(); /** * Protected constructor. * * @param builder Instance of {@link Builder}. */ protected ActorSource(final Builder<?, ? extends ActorSource> builder) { super(builder); _actorName = builder._actorName; _actorSystem = builder._actorSystem; } private ActorRef _actor = null; private final String _actorName; private final ActorSystem _actorSystem; private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(1); private static final Logger LOGGER = LoggerFactory.getLogger(ActorSource.class); /** * ActorSource {@link BaseSource.Builder} implementation. * * @param <B> type of the builder * @param <S> type of the object to be built * @author Brandon Arp (brandon dot arp at inscopemetrics dot io) */ public abstract static class Builder<B extends Builder<B, S>, S extends Source> extends BaseSource.Builder<B, S> { /** * Protected constructor for subclasses. * * @param targetConstructor The constructor for the concrete type to be created by this builder. */ protected Builder(final Function<B, S> targetConstructor) { super(targetConstructor); } /** * Sets the actor path. Cannot be null or empty. * * @param value The name. * @return This instance of {@link Builder} */ public final B setActorName(final String value) { _actorName = value; return self(); } /** * Sets the actor system to launch the actor in. * * @param value The actor system. * @return This instance of {@link Builder} */ public final B setActorSystem(final ActorSystem value) { _actorSystem = value; return self(); } @NotNull @NotEmpty private String _actorName; @JacksonInject private ActorSystem _actorSystem; } }
3e177ffb78530847d062519e76f2f5c725e8b44b
14,899
java
Java
src/com/google/javascript/jscomp/JSDocInfoPrinter.java
natansun/closure-compiler
d5615b9fd2db45bf128499a4287452589eea7481
[ "Apache-2.0" ]
null
null
null
src/com/google/javascript/jscomp/JSDocInfoPrinter.java
natansun/closure-compiler
d5615b9fd2db45bf128499a4287452589eea7481
[ "Apache-2.0" ]
null
null
null
src/com/google/javascript/jscomp/JSDocInfoPrinter.java
natansun/closure-compiler
d5615b9fd2db45bf128499a4287452589eea7481
[ "Apache-2.0" ]
null
null
null
28.217803
97
0.598027
10,003
/* * Copyright 2014 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Ordering; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; /** * Prints a JSDocInfo, used for preserving type annotations in ES6 transpilation. * */ public final class JSDocInfoPrinter { private final boolean useOriginalName; private final boolean printDesc; public JSDocInfoPrinter(boolean useOriginalName) { this(useOriginalName, false); } /** * @param useOriginalName Whether to use the original name field when printing types. * @param printDesc Whether to print block, param, and return descriptions. */ public JSDocInfoPrinter(boolean useOriginalName, boolean printDesc) { this.useOriginalName = useOriginalName; this.printDesc = printDesc; } public String print(JSDocInfo info) { boolean multiline = false; List<String> parts = new ArrayList<>(); parts.add("/**"); if (info.isExterns()) { parts.add("@externs"); } else if (info.isTypeSummary()) { parts.add("@typeSummary"); } if (info.isExport()) { parts.add("@export"); } else if (info.getVisibility() != null && info.getVisibility() != Visibility.INHERITED) { parts.add("@" + info.getVisibility().toString().toLowerCase()); } if (info.isAbstract()) { parts.add("@abstract"); } if (info.hasLendsName()) { parts.add(buildAnnotationWithType("lends", info.getLendsName().getRoot())); } if (info.hasConstAnnotation() && !info.isDefine()) { parts.add("@const"); } if (info.isFinal()) { parts.add("@final"); } String description = info.getDescription(); if (description != null) { multiline = true; parts.add("@desc " + description); } if (info.isWizaction()) { parts.add("@wizaction"); } if (info.isPolymerBehavior()) { parts.add("@polymerBehavior"); } if (info.isPolymer()) { parts.add("@polymer"); } if (info.isCustomElement()) { parts.add("@customElement"); } if (info.isMixinClass()) { parts.add("@mixinClass"); } if (info.isMixinFunction()) { parts.add("@mixinFunction"); } if (info.isDisposes()) { parts.add("@disposes"); } if (info.isExpose()) { parts.add("@expose"); } if (info.isNoSideEffects()) { parts.add("@nosideeffects"); } if (info.isNoCompile()) { parts.add("@nocompile"); } if (info.isNoInline()) { parts.add("@noinline"); } if (info.isIdGenerator()) { parts.add("@idGenerator {unique}"); } if (info.isConsistentIdGenerator()) { parts.add("@idGenerator {consistent}"); } if (info.isStableIdGenerator()) { parts.add("@idGenerator {stable}"); } if (info.isXidGenerator()) { parts.add("@idGenerator {xid}"); } if (info.isMappedIdGenerator()) { parts.add("@idGenerator {mapped}"); } if (info.makesDicts()) { parts.add("@dict"); } if (info.makesStructs()) { parts.add("@struct"); } if (info.makesUnrestricted()) { parts.add("@unrestricted "); } if (info.isConstructor()) { parts.add("@constructor"); } if (info.isInterface() && !info.usesImplicitMatch()) { parts.add("@interface"); } if (info.isInterface() && info.usesImplicitMatch()) { parts.add("@record"); } if (info.hasBaseType()) { multiline = true; Node typeNode = stripBang(info.getBaseType().getRoot()); parts.add(buildAnnotationWithType("extends", typeNode)); } for (JSTypeExpression type : info.getExtendedInterfaces()) { multiline = true; Node typeNode = stripBang(type.getRoot()); parts.add(buildAnnotationWithType("extends", typeNode)); } for (JSTypeExpression type : info.getImplementedInterfaces()) { multiline = true; Node typeNode = stripBang(type.getRoot()); parts.add(buildAnnotationWithType("implements", typeNode)); } if (info.hasThisType()) { multiline = true; Node typeNode = stripBang(info.getThisType().getRoot()); parts.add(buildAnnotationWithType("this", typeNode)); } if (info.getParameterCount() > 0) { multiline = true; for (String name : info.getParameterNames()) { parts.add("@param " + buildParamType(info, name)); } } if (info.hasReturnType()) { multiline = true; parts.add( buildAnnotationWithType("return", info.getReturnType(), info.getReturnDescription())); } if (!info.getThrownTypes().isEmpty()) { parts.add(buildAnnotationWithType("throws", info.getThrownTypes().get(0))); } ImmutableList<String> names = info.getTemplateTypeNames(); if (!names.isEmpty()) { parts.add("@template " + Joiner.on(", ").join(names)); multiline = true; } ImmutableMap<String, Node> typeTransformations = info.getTypeTransformations(); if (!typeTransformations.isEmpty()) { multiline = true; for (Map.Entry<String, Node> e : typeTransformations.entrySet()) { String name = e.getKey(); String tranformationDefinition = new CodePrinter.Builder(e.getValue()).build(); parts.add("@template " + name + " := " + tranformationDefinition + " =:"); } } if (info.isOverride()) { parts.add("@override"); } if (info.hasType() && !info.isDefine()) { if (info.isInlineType()) { parts.add(typeNode(info.getType().getRoot())); } else { parts.add(buildAnnotationWithType("type", info.getType())); } } if (info.isDefine()) { parts.add(buildAnnotationWithType("define", info.getType())); } if (info.hasTypedefType()) { parts.add(buildAnnotationWithType("typedef", info.getTypedefType())); } if (info.hasEnumParameterType()) { parts.add(buildAnnotationWithType("enum", info.getEnumParameterType())); } if (info.isImplicitCast()) { parts.add("@implicitCast"); } if (info.isNoCollapse()) { parts.add("@nocollapse"); } Set<String> suppressions = info.getSuppressions(); if (!suppressions.isEmpty()) { // Print suppressions in sorted order to avoid non-deterministic output. String[] arr = suppressions.toArray(new String[0]); Arrays.sort(arr, Ordering.natural()); parts.add("@suppress {" + Joiner.on(',').join(arr) + "}"); multiline = true; } if (info.isDeprecated()) { parts.add("@deprecated " + info.getDeprecationReason()); multiline = true; } if (info.isPolymer()) { multiline = true; parts.add("@polymer"); } if (info.isPolymerBehavior()) { multiline = true; parts.add("@polymerBehavior"); } if (info.isMixinFunction()) { multiline = true; parts.add("@mixinFunction"); } if (info.isMixinClass()) { multiline = true; parts.add("@mixinClass"); } if (info.isCustomElement()) { multiline = true; parts.add("@customElement"); } if (info.getClosurePrimitiveId() != null) { parts.add("@closurePrimitive {" + info.getClosurePrimitiveId() + "}"); } if (info.isNgInject()) { parts.add("@ngInject"); } if (printDesc && info.getBlockDescription() != null) { String cleaned = info.getBlockDescription().replaceAll("\n\\s*\\*\\s*", "\n"); if (!cleaned.isEmpty()) { multiline = true; cleaned = cleaned.trim(); if (parts.size() > 1) { // If there is more than one part - the opening "/**" - then add blank line between the // description and everything else. cleaned += '\n'; } parts.add(1, cleaned); } } StringBuilder sb = new StringBuilder(); if (multiline) { Joiner.on("\n").appendTo(sb, parts); } else { Joiner.on(" ").appendTo(sb, parts); sb.append(" */"); } // Ensure all lines start with " *", and then ensure all non blank lines have a space after // the *. String s = sb.toString().replaceAll("\n", "\n *").replaceAll("\n \\*([^ \n])", "\n * $1"); if (multiline) { s += "\n */\n"; } else { s += " "; } return s; } private Node stripBang(Node typeNode) { if (typeNode.getToken() == Token.BANG) { typeNode = typeNode.getFirstChild(); } return typeNode; } private String buildAnnotationWithType(String annotation, JSTypeExpression type) { return buildAnnotationWithType(annotation, type, null); } private String buildAnnotationWithType( String annotation, JSTypeExpression type, String description) { return buildAnnotationWithType(annotation, type.getRoot(), description); } private String buildAnnotationWithType(String annotation, Node type) { return buildAnnotationWithType(annotation, type, null); } private String buildAnnotationWithType(String annotation, Node type, String description) { StringBuilder sb = new StringBuilder(); sb.append("@"); sb.append(annotation); sb.append(" {"); appendTypeNode(sb, type); sb.append("}"); if (description != null) { sb.append(" "); sb.append(description); } return sb.toString(); } private String buildParamType(JSDocInfo info, String name) { JSTypeExpression type = info.getParameterType(name); if (type != null) { String p = "{" + typeNode(type.getRoot()) + "} " + name + (printDesc && info.getDescriptionForParameter(name) != null // Don't add a leading space; the parser retained it. ? info.getDescriptionForParameter(name) : ""); return p.trim(); } else { return name; } } private String typeNode(Node typeNode) { StringBuilder sb = new StringBuilder(); appendTypeNode(sb, typeNode); return sb.toString(); } private void appendTypeNode(StringBuilder sb, Node typeNode) { if (useOriginalName && typeNode.getOriginalName() != null) { sb.append(typeNode.getOriginalName()); return; } if (typeNode.getToken() == Token.BANG) { sb.append("!"); appendTypeNode(sb, typeNode.getFirstChild()); } else if (typeNode.getToken() == Token.EQUALS) { appendTypeNode(sb, typeNode.getFirstChild()); sb.append("="); } else if (typeNode.getToken() == Token.PIPE) { sb.append("("); Node lastChild = typeNode.getLastChild(); for (Node child = typeNode.getFirstChild(); child != null; child = child.getNext()) { appendTypeNode(sb, child); if (child != lastChild) { sb.append("|"); } } sb.append(")"); } else if (typeNode.getToken() == Token.ITER_REST) { sb.append("..."); if (typeNode.hasChildren() && !typeNode.getFirstChild().isEmpty()) { appendTypeNode(sb, typeNode.getFirstChild()); } } else if (typeNode.getToken() == Token.STAR) { sb.append("*"); } else if (typeNode.getToken() == Token.QMARK) { sb.append("?"); if (typeNode.hasChildren()) { appendTypeNode(sb, typeNode.getFirstChild()); } } else if (typeNode.isFunction()) { appendFunctionNode(sb, typeNode); } else if (typeNode.getToken() == Token.LC) { sb.append("{"); Node lb = typeNode.getFirstChild(); Node lastColon = lb.getLastChild(); for (Node colon = lb.getFirstChild(); colon != null; colon = colon.getNext()) { if (colon.hasChildren()) { sb.append(colon.getFirstChild().getString()).append(":"); appendTypeNode(sb, colon.getLastChild()); } else { sb.append(colon.getString()); } if (colon != lastColon) { sb.append(","); } } sb.append("}"); } else if (typeNode.isVoid()) { sb.append("void"); } else if (typeNode.isTypeOf()) { sb.append("typeof "); appendTypeNode(sb, typeNode.getFirstChild()); } else { if (typeNode.hasChildren()) { sb.append(typeNode.getString()) .append("<"); Node child = typeNode.getFirstChild(); Node last = child.getLastChild(); for (Node type = child.getFirstChild(); type != null; type = type.getNext()) { appendTypeNode(sb, type); if (type != last) { sb.append(","); } } sb.append(">"); } else { sb.append(typeNode.getString()); } } } private void appendFunctionNode(StringBuilder sb, Node function) { boolean hasNewOrThis = false; sb.append("function("); Node first = function.getFirstChild(); if (first.isNew()) { sb.append("new:"); appendTypeNode(sb, first.getFirstChild()); hasNewOrThis = true; } else if (first.isThis()) { sb.append("this:"); appendTypeNode(sb, first.getFirstChild()); hasNewOrThis = true; } else if (first.isEmpty()) { sb.append(")"); return; } else if (!first.isParamList()) { sb.append("):"); appendTypeNode(sb, first); return; } Node paramList = null; if (first.isParamList()) { paramList = first; } else if (first.getNext().isParamList()) { paramList = first.getNext(); } if (paramList != null) { boolean firstParam = true; for (Node param : paramList.children()) { if (!firstParam || hasNewOrThis) { sb.append(","); } appendTypeNode(sb, param); firstParam = false; } } sb.append(")"); Node returnType = function.getLastChild(); if (!returnType.isEmpty()) { sb.append(":"); appendTypeNode(sb, returnType); } } }
3e1780d3889f0682779390af53dfdcebd830ceca
1,191
java
Java
src/main/java/com/microsoft/graph/requests/extensions/IDocumentCommentReplyCollectionPage.java
isabella232/msgraph-beta-sdk-java
7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/graph/requests/extensions/IDocumentCommentReplyCollectionPage.java
isabella232/msgraph-beta-sdk-java
7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8
[ "MIT" ]
1
2021-02-23T20:48:12.000Z
2021-02-23T20:48:12.000Z
src/main/java/com/microsoft/graph/requests/extensions/IDocumentCommentReplyCollectionPage.java
isabella232/msgraph-beta-sdk-java
7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8
[ "MIT" ]
null
null
null
45.807692
152
0.720403
10,004
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.DocumentComment; import com.microsoft.graph.models.extensions.DocumentCommentReply; import java.util.Arrays; import java.util.EnumSet; import com.google.gson.JsonObject; import com.microsoft.graph.requests.extensions.IDocumentCommentReplyCollectionRequestBuilder; import com.microsoft.graph.http.IBaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Document Comment Reply Collection Page. */ public interface IDocumentCommentReplyCollectionPage extends IBaseCollectionPage<DocumentCommentReply, IDocumentCommentReplyCollectionRequestBuilder> { }
3e17812027249ea83b8537712e143e58b4109fa1
453
java
Java
src/DataAnalysis/IDataProcessor.java
PedroCardouzo/StockAnalytics
0617de41f10abbffb7f246b779b81e52e6489fea
[ "MIT" ]
null
null
null
src/DataAnalysis/IDataProcessor.java
PedroCardouzo/StockAnalytics
0617de41f10abbffb7f246b779b81e52e6489fea
[ "MIT" ]
null
null
null
src/DataAnalysis/IDataProcessor.java
PedroCardouzo/StockAnalytics
0617de41f10abbffb7f246b779b81e52e6489fea
[ "MIT" ]
2
2018-05-03T01:17:09.000Z
2018-05-21T19:28:12.000Z
37.75
88
0.746137
10,005
package DataAnalysis; import DataReceiver.StockData; // interface of a DataProcessor. Every Data processor will have to implement their own public interface IDataProcessor { double[][] simpleMovingAverage(int sampleSize, StockData[] data, String field); double[][] exponentialMovingAverage(int sampleSize, StockData[] data, String field); double[][] rsi(int period, StockData[] data, String field); double[][] obv(StockData[] data); }
3e1781a03d06ebebbb80d6c11fec370175dcb0d9
4,640
java
Java
app/LostLuggage/src/main/java/is103/lostluggage/Controllers/AddNewDataViewController.java
daronozdemir/Corendon-project
5c18d5e1ea4f619fd1e801f22de0ffa0a9b80c14
[ "MIT" ]
32
2018-02-03T14:09:24.000Z
2022-02-14T16:32:39.000Z
app/LostLuggage/src/main/java/is103/lostluggage/Controllers/AddNewDataViewController.java
mbelduque/Corendon-LostLuggage
fa0612a9615afa66a6ca0be4363828e1aabad8b8
[ "MIT" ]
null
null
null
app/LostLuggage/src/main/java/is103/lostluggage/Controllers/AddNewDataViewController.java
mbelduque/Corendon-LostLuggage
fa0612a9615afa66a6ca0be4363828e1aabad8b8
[ "MIT" ]
20
2018-02-03T14:21:11.000Z
2021-11-23T17:16:10.000Z
38.666667
97
0.68944
10,006
/* * 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 is103.lostluggage.Controllers; import is103.lostluggage.Controllers.Admin.OverviewUserController; import is103.lostluggage.Controllers.Service.ServiceEditFoundLuggageViewController; import is103.lostluggage.Database.MyJDBC; import static is103.lostluggage.MainApp.getDatabase; import is103.lostluggage.Model.Service.Data.ServiceGetDataFromDB; import is103.lostluggage.Model.Data; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; /** * FXML Controller class * * @author Poek Ligthart */ public class AddNewDataViewController implements Initializable { //TableView colorTable kolommen. //colorTable public static ObservableList<Data> colorList; @FXML private TableView<Data> colorTable; @FXML private TableColumn<Data, String> ralCode; @FXML private TableColumn<Data, String> englishColor; @FXML private TableColumn<Data, String> dutchColor; //typeTable public static ObservableList<Data> typeList; @FXML private TableView<Data> typeTable; @FXML private TableColumn<Data, String> luggageTypeId; @FXML private TableColumn<Data, String> englishType; @FXML private TableColumn<Data, String> dutchType; //locationTable public static ObservableList<Data> locationList; @FXML private TableView<Data> locationTable; @FXML private TableColumn<Data, String> locationID; @FXML private TableColumn<Data, String> englishLocation; @FXML private TableColumn<Data, String> dutchLocation; //flightTable public static ObservableList<Data> flightList; @FXML private TableView<Data> flightTable; @FXML private TableColumn<Data, String> flightNr; @FXML private TableColumn<Data, String> airline; @FXML private TableColumn<Data, String> from; @FXML private TableColumn<Data, String> to; @Override public void initialize(URL url, ResourceBundle rb) { ralCode.setCellValueFactory(new PropertyValueFactory<>("ralCode")); englishColor.setCellValueFactory(new PropertyValueFactory<>("english")); dutchColor.setCellValueFactory(new PropertyValueFactory<>("dutch")); colorTable.setItems(colorList); ServiceGetDataFromDB colors = new ServiceGetDataFromDB("color", "*", null); try { ResultSet colorResultSet = colors.getServiceDetailsResultSet(); while (colorResultSet.next()){ //Database gegevens in de tableview variabelen plaatsen. String ralCode = colorResultSet.getString("ralCode"); String english = colorResultSet.getString("english"); String dutch = colorResultSet.getString("dutch"); //De results toevagen aan de observable list colorList.add(new Data( ralCode, english, dutch )); } //end while loop } catch (SQLException ex) { Logger.getLogger(OverviewUserController.class.getName()).log(Level.SEVERE, null, ex); } } } // luggageTypeId.setCellValueFactory(new PropertyValueFactory<>("luggageType")); // englishType.setCellValueFactory(new PropertyValueFactory<>("englishType")); // dutchType.setCellValueFactory(new PropertyValueFactory<>("dutchType")); // locationID.setCellValueFactory(new PropertyValueFactory<>("locationID")); // englishLocation.setCellValueFactory(new PropertyValueFactory<>("englishLocation")); // dutchLocation.setCellValueFactory(new PropertyValueFactory<>("dutchLocation")); // flightNr.setCellValueFactory(new PropertyValueFactory<>("flightNr")); // airline.setCellValueFactory(new PropertyValueFactory<>("airline")); // from.setCellValueFactory(new PropertyValueFactory<>("from")); // to.setCellValueFactory(new PropertyValueFactory<>("to"));
3e1781aaf2e6579045150576352d65201c1151f9
480
java
Java
Create-Refabricated-Lib/src/main/java/com/simibubi/create/lib/helper/PlayerEntityHelper.java
ExoPlant/Create-Refabricated
e7ff94403e281ae645dd326a8b4370a3f9251365
[ "MIT" ]
null
null
null
Create-Refabricated-Lib/src/main/java/com/simibubi/create/lib/helper/PlayerEntityHelper.java
ExoPlant/Create-Refabricated
e7ff94403e281ae645dd326a8b4370a3f9251365
[ "MIT" ]
null
null
null
Create-Refabricated-Lib/src/main/java/com/simibubi/create/lib/helper/PlayerEntityHelper.java
ExoPlant/Create-Refabricated
e7ff94403e281ae645dd326a8b4370a3f9251365
[ "MIT" ]
null
null
null
25.263158
67
0.8
10,007
package com.simibubi.create.lib.helper; import com.simibubi.create.lib.mixin.accessor.PlayerEntityAccessor; import com.simibubi.create.lib.utility.MixinHelper; import net.minecraft.entity.player.PlayerEntity; public class PlayerEntityHelper { public static void closeScreen (PlayerEntity player) { get(player).create$closeScreen(); } private static PlayerEntityAccessor get(PlayerEntity player) { return MixinHelper.cast(player); } private PlayerEntityHelper() {} }
3e1781c09c2a63fe829d256c0bb35ef9ea0173c5
6,698
java
Java
aspsp-mock-server/src/test/java/de/adorsys/aspsp/aspspmockserver/web/PsuControllerTest.java
erdincozden/xs2a
f9654f47a13eda78a20d1c8d17366c1f79333a76
[ "Apache-2.0" ]
null
null
null
aspsp-mock-server/src/test/java/de/adorsys/aspsp/aspspmockserver/web/PsuControllerTest.java
erdincozden/xs2a
f9654f47a13eda78a20d1c8d17366c1f79333a76
[ "Apache-2.0" ]
null
null
null
aspsp-mock-server/src/test/java/de/adorsys/aspsp/aspspmockserver/web/PsuControllerTest.java
erdincozden/xs2a
f9654f47a13eda78a20d1c8d17366c1f79333a76
[ "Apache-2.0" ]
null
null
null
37.830508
196
0.719833
10,008
/* * Copyright 2018-2018 adorsys GmbH & Co KG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.adorsys.aspsp.aspspmockserver.web; import de.adorsys.aspsp.aspspmockserver.service.PsuService; import de.adorsys.psd2.aspsp.mock.api.account.AspspAccountDetails; import de.adorsys.psd2.aspsp.mock.api.psu.AspspAuthenticationObject; import de.adorsys.psd2.aspsp.mock.api.psu.Psu; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.ResponseEntity; import java.util.Collections; import java.util.Currency; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.springframework.http.HttpStatus.*; @RunWith(MockitoJUnitRunner.class) public class PsuControllerTest { private static final String ASPSP_PSU_ID = "ec818c89-4346-4f16-b5c8-d781b040200c"; private static final String WRONG_ASPSP_PSU_ID = "WRONG_ASPSP_PSU_ID"; private static final String PSU_ID = "aspsp"; private static final String WRONG_PSU_ID = "zzz"; private static final String E_MAIL = "upchh@example.com"; private static final String PSU_PASSWORD = "zzz"; private static final String WRONG_E_MAIL = "wrong e-mail"; private static final Currency EUR = Currency.getInstance("EUR"); private static final String ACCOUNT_ID = "ACCOUNT1-0000-0000-0000-a000q000000t"; private static final String IBAN = "DE123456789"; private static final String CORRECT_PAYMENT_PRODUCT = "sepa-credit-transfers"; @InjectMocks private PsuController psuController; @Mock private PsuService psuService; @Before public void setUp() { when(psuService.createPsuAndReturnId(getPsu(null, E_MAIL, getDetails(false), getProducts()))) .thenReturn(PSU_ID); when(psuService.createPsuAndReturnId(getPsu(null, WRONG_E_MAIL, getDetails(false), getProducts()))) .thenReturn(null); when(psuService.getAllPsuList()).thenReturn(Collections.singletonList(getPsu(PSU_ID, E_MAIL, getDetails(false), getProducts()))); when(psuService.getPsuByPsuId(PSU_ID)).thenReturn(Optional.of(getPsu(PSU_ID, E_MAIL, getDetails(false), getProducts()))); when(psuService.getPsuByPsuId(WRONG_PSU_ID)).thenReturn(Optional.empty()); when(psuService.getAllowedPaymentProducts(PSU_ID)).thenReturn(getProducts()); when(psuService.getAllowedPaymentProducts(WRONG_PSU_ID)).thenReturn(null); when(psuService.deletePsuByAspspPsuId(ASPSP_PSU_ID)).thenReturn(true); when(psuService.deletePsuByAspspPsuId(WRONG_ASPSP_PSU_ID)).thenReturn(false); } @Test public void createPsu_Success() { //When ResponseEntity actualResult = psuController.createPsu(getPsu(null, E_MAIL, getDetails(false), getProducts())); //Then assertThat(actualResult.getStatusCode()).isEqualTo(OK); assertThat(actualResult.getBody()).isEqualTo(PSU_ID); } @Test public void createPsu_Failure_wrong_email() { //When: ResponseEntity actualResponse = psuController.createPsu(getPsu(null, WRONG_E_MAIL, getDetails(false), getProducts())); //Then assertThat(actualResponse.getStatusCode()).isEqualTo(BAD_REQUEST); } @Test public void readAllPsuList_Success() { //When ResponseEntity actualResult = psuController.readAllPsuList(); //Then assertThat(actualResult.getStatusCode()).isEqualTo(OK); assertThat(actualResult.getBody()).isEqualTo(Collections.singletonList(getPsu(PSU_ID, E_MAIL, getDetails(false), getProducts()))); } @Test public void readPsuById_Success() { //When ResponseEntity actualResult = psuController.readPsuById(PSU_ID); //Then assertThat(actualResult.getStatusCode()).isEqualTo(OK); assertThat(actualResult.getBody()).isEqualTo(getPsu(PSU_ID, E_MAIL, getDetails(false), getProducts())); } @Test public void readPsuById_Failure_wrong_id() { //When ResponseEntity actualResult = psuController.readPsuById(WRONG_PSU_ID); //Then assertThat(actualResult.getStatusCode()).isEqualTo(NO_CONTENT); } @Test public void readPaymentProductsById_Success() { //When ResponseEntity actualResult = psuController.readPaymentProductsById(PSU_ID); //Then assertThat(actualResult.getStatusCode()).isEqualTo(OK); assertThat(actualResult.getBody()).isEqualTo(getProducts()); } @Test public void readPaymentProductsById_Failure_wrong_id() { //When ResponseEntity actualResult = psuController.readPaymentProductsById(WRONG_PSU_ID); //Then assertThat(actualResult.getStatusCode()).isEqualTo(NO_CONTENT); } @Test public void deletePsu_Success() { //When ResponseEntity actualResult = psuController.deletePsu(ASPSP_PSU_ID); //Then assertThat(actualResult.getStatusCode()).isEqualTo(NO_CONTENT); } @Test public void deletePsu_Failure_wrong_id() { //When ResponseEntity actualResult = psuController.deletePsu(WRONG_ASPSP_PSU_ID); //Then assertThat(actualResult.getStatusCode()).isEqualTo(NOT_FOUND); } private List<String> getProducts() { return Collections.singletonList(CORRECT_PAYMENT_PRODUCT); } private Psu getPsu(String psuId, String email, List<AspspAccountDetails> details, List<String> products) { return new Psu(ASPSP_PSU_ID, email, PSU_ID, PSU_PASSWORD, details, products, Collections.singletonList(new AspspAuthenticationObject("SMS_OTP", "sms"))); } private List<AspspAccountDetails> getDetails(boolean isEmpty) { return isEmpty ? Collections.emptyList() : Collections.singletonList(new AspspAccountDetails(ACCOUNT_ID, IBAN, null, null, null, null, EUR, "Alfred", null, null, null, null, null, null, null, Collections.emptyList())); } }
3e17820ad8e5739c89b2dd189ce90c2c53b933dd
1,988
java
Java
src/main/java/nc/network/gui/OpenGuiPacket.java
ThizThizzyDizzy/NuclearCraft
ce40952542e422a6e509dc756aa0415766732655
[ "MIT" ]
180
2016-01-13T07:49:52.000Z
2021-10-01T03:47:59.000Z
src/main/java/nc/network/gui/OpenGuiPacket.java
ThizThizzyDizzy/NuclearCraft
ce40952542e422a6e509dc756aa0415766732655
[ "MIT" ]
742
2016-01-18T04:42:34.000Z
2021-09-26T16:35:50.000Z
src/main/java/nc/network/gui/OpenGuiPacket.java
ThizThizzyDizzy/NuclearCraft
ce40952542e422a6e509dc756aa0415766732655
[ "MIT" ]
150
2016-01-18T04:18:35.000Z
2021-09-01T18:15:06.000Z
29.671642
160
0.742958
10,009
package nc.network.gui; import io.netty.buffer.ByteBuf; import nc.NuclearCraft; import nc.tile.ITileGui; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; import net.minecraftforge.fml.common.network.simpleimpl.*; import net.minecraftforge.fml.relauncher.Side; public class OpenGuiPacket implements IMessage { private BlockPos pos; private int guiID = -1; public OpenGuiPacket() { } public OpenGuiPacket(BlockPos pos, int guiID) { this.pos = pos; this.guiID = guiID; } @Override public void fromBytes(ByteBuf buf) { pos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); guiID = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeInt(pos.getX()); buf.writeInt(pos.getY()); buf.writeInt(pos.getZ()); buf.writeInt(guiID); } public static class Handler implements IMessageHandler<OpenGuiPacket, IMessage> { @Override public IMessage onMessage(OpenGuiPacket message, MessageContext ctx) { if (ctx.side == Side.SERVER) { FMLCommonHandler.instance().getWorldThread(ctx.netHandler).addScheduledTask(() -> processMessage(message, ctx)); } return null; } void processMessage(OpenGuiPacket message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().player; World world = player.getServerWorld(); if (!world.isBlockLoaded(message.pos) || !world.isBlockModifiable(player, message.pos)) { return; } TileEntity tile = world.getTileEntity(message.pos); FMLNetworkHandler.openGui(player, NuclearCraft.instance, message.guiID, player.getServerWorld(), message.pos.getX(), message.pos.getY(), message.pos.getZ()); if (tile instanceof ITileGui) { ((ITileGui) tile).beginUpdatingPlayer(player); } } } }
3e178232bf0b0ac0103b4e7673cffb7fea9437c7
2,045
java
Java
flink-core/src/main/java/org/apache/flink/types/parser/FloatValueParser.java
daniel-pape/flink
0ba53558f9b56b1e17c84ab8e4ee639ca09b9133
[ "BSD-3-Clause" ]
1
2022-02-19T21:11:52.000Z
2022-02-19T21:11:52.000Z
flink-core/src/main/java/org/apache/flink/types/parser/FloatValueParser.java
daniel-pape/flink
0ba53558f9b56b1e17c84ab8e4ee639ca09b9133
[ "BSD-3-Clause" ]
15
2015-02-04T22:56:50.000Z
2015-06-25T13:44:53.000Z
flink-core/src/main/java/org/apache/flink/types/parser/FloatValueParser.java
daniel-pape/flink
0ba53558f9b56b1e17c84ab8e4ee639ca09b9133
[ "BSD-3-Clause" ]
3
2016-01-09T18:48:42.000Z
2019-07-12T13:26:47.000Z
27.635135
102
0.713447
10,010
/* * 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.flink.types.parser; import org.apache.flink.types.FloatValue; /** * Parses a text field into a {@link FloatValue} */ public class FloatValueParser extends FieldParser<FloatValue> { private FloatValue result; @Override public int parseField(byte[] bytes, int startPos, int limit, byte[] delimiter, FloatValue reusable) { int i = startPos; final int delimLimit = limit - delimiter.length + 1; while (i < limit) { if (i < delimLimit && delimiterNext(bytes, i, delimiter)) { break; } i++; } if (i > startPos && (Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[i - 1]))) { setErrorState(ParseErrorState.NUMERIC_VALUE_ILLEGAL_CHARACTER); return -1; } String str = new String(bytes, startPos, i - startPos); try { float value = Float.parseFloat(str); reusable.setValue(value); this.result = reusable; return (i == limit) ? limit : i + delimiter.length; } catch (NumberFormatException e) { setErrorState(ParseErrorState.NUMERIC_VALUE_FORMAT_ERROR); return -1; } } @Override public FloatValue createValue() { return new FloatValue(); } @Override public FloatValue getLastResult() { return this.result; } }
3e1782761edebe62222313df2b7220937f4b9453
2,899
java
Java
src/main/java/cn/edu/seu/itcompany/neteasy/UndergroundMaze.java
personajian/newer-coder
28289f2075f576209cf968fb2b2c01a2f8ad94cd
[ "MIT" ]
null
null
null
src/main/java/cn/edu/seu/itcompany/neteasy/UndergroundMaze.java
personajian/newer-coder
28289f2075f576209cf968fb2b2c01a2f8ad94cd
[ "MIT" ]
null
null
null
src/main/java/cn/edu/seu/itcompany/neteasy/UndergroundMaze.java
personajian/newer-coder
28289f2075f576209cf968fb2b2c01a2f8ad94cd
[ "MIT" ]
null
null
null
28.70297
92
0.460849
10,011
package cn.edu.seu.itcompany.neteasy; import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; /**青蛙跳出地下迷宫 * https://www.nowcoder.com/questionTerminal/571cfbe764824f03b5c0bfd2eb0a8ddf * @Author personajian * @Date 2017/8/11 9:11 */ public class UndergroundMaze { private static int startx,starty,endx,endy,n,m,a[][],book[][],p; //分别为起点的坐标和出口的坐标,行和列 private static int min=Integer.MAX_VALUE;//体力值,默认最大 private static LinkedList<Point> linkedList = new LinkedList<>(); private static int next[][]=new int[][]{{0,1},{1,0},{0,-1},{-1,0}};//分别为右,下,左,上移动时需要加的坐标 private static String path = ""; public static void main(String []args){ Scanner sc=new Scanner(System.in); n=sc.nextInt();//n行 m=sc.nextInt();//m列 p=sc.nextInt();//体力 startx=0;starty=0; endx=0;endy=m-1; a=new int[n][m]; book=new int[n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ a[i][j]=sc.nextInt(); } }//输入行和列 dfs(0, 0, 0); if(min==Integer.MAX_VALUE){ System.out.println("Can not escape!"); }else { System.out.println(path.substring(0,path.length()-1)); } } public static void dfs(int curx,int cury,int curt){ linkedList.add(new Point(curx, cury)); if(curt>p){ return; } if(curx==endx&&cury==endy&&curt<min){ min=curt; savePath(); return; } int tx=0; int ty=0; for(int i=0;i<=3;i++){//遍历四个方向,规定顺时针遍历 tx=curx+next[i][0]; ty=cury+next[i][1]; if(tx<0||tx>=n||ty<0||ty>=m){ continue; } if(a[tx][ty]==1&&book[tx][ty]==0){ book[tx][ty]=1; switch (i) { case 0: curt+=1; break; case 1: break; case 2: curt+=1; case 3: curt+=3; break; default: break; } dfs(tx, ty, curt); linkedList.removeLast(); book[tx][ty]=0; } } } private static class Point{ int x, y; public Point(int x,int y){ this.x=x; this.y=y; } }//点类 private static void savePath() { Iterator<Point> iterator = linkedList.iterator(); StringBuilder sb = new StringBuilder(); while (iterator.hasNext()) { Point point = iterator.next(); sb.append("[").append(point.x).append(",").append(point.y).append("],"); } path = sb.toString(); } }
3e178342dfc0a846749ed2e0c912826f544fcf07
8,544
java
Java
src/main/java/com/wujunshen/controller/BookController.java
TANGKUO/spring-cloud-provider-book
595fc3769d99bb069cfdf788354dda5b11eb1556
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wujunshen/controller/BookController.java
TANGKUO/spring-cloud-provider-book
595fc3769d99bb069cfdf788354dda5b11eb1556
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wujunshen/controller/BookController.java
TANGKUO/spring-cloud-provider-book
595fc3769d99bb069cfdf788354dda5b11eb1556
[ "Apache-2.0" ]
null
null
null
44.989474
227
0.650094
10,012
package com.wujunshen.controller; import com.wujunshen.entity.Book; import com.wujunshen.entity.Books; import com.wujunshen.exception.ResultStatusCode; import com.wujunshen.service.BookService; import com.wujunshen.vo.BaseResultVo; import io.swagger.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.MediaType; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.validation.constraints.NotNull; /** * User:frankwoo(吴峻申) <br> * Date:2016-10-17 <br> * Time:17:21 <br> * Mail:upchh@example.com <br> */ @RestController @Api(value = "/", description = "有关书籍的操作") public class BookController { private static final Logger LOGGER = LoggerFactory.getLogger(BookController.class); @Autowired private BookService bookService; @Autowired private DiscoveryClient discoveryClient; /** * 本地服务实例的信息 * * @return */ @GetMapping("/instance-info") @ApiIgnore public ServiceInstance showInfo() { ServiceInstance localServiceInstance = this.discoveryClient. getLocalServiceInstance(); return localServiceInstance; } @PostMapping(value = "/api/books", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ApiOperation(value = "添加某本书籍", httpMethod = "POST", notes = "添加成功返回bookId", response = BaseResultVo.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = BaseResultVo.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public BaseResultVo saveBook(@Validated @ApiParam(value = "添加的某本书籍信息", required = true) @RequestBody Book book) { BaseResultVo baseResultVo = new BaseResultVo(); baseResultVo.setData(bookService.saveBook(book)); baseResultVo.setCode(ResultStatusCode.OK.getCode()); baseResultVo.setMessage(ResultStatusCode.OK.getMessage()); return baseResultVo; } @GetMapping(value = "/api/books", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ApiOperation(value = "查询所有书籍", httpMethod = "GET", notes = "查询所有书籍", response = BaseResultVo.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = BaseResultVo.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public BaseResultVo getBooks() { Books books = bookService.getBooks(); BaseResultVo baseResultVo = new BaseResultVo(); if (books != null && books.getBookList().size() != 0) { baseResultVo.setData(books); baseResultVo.setCode(ResultStatusCode.OK.getCode()); baseResultVo.setMessage(ResultStatusCode.OK.getMessage()); } else { baseResultVo.setCode(ResultStatusCode.DATA_QUERY_ERROR.getCode()); baseResultVo.setData("Query books failed"); baseResultVo.setMessage(ResultStatusCode.DATA_QUERY_ERROR.getMessage()); } return baseResultVo; } @GetMapping(value = "/api/books/{bookId:[0-9]*}") @ApiOperation(value = "查询某本书籍", httpMethod = "GET", notes = "根据bookId,查询到某本书籍", response = BaseResultVo.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = BaseResultVo.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public BaseResultVo getBook(@ApiParam(value = "书籍ID", required = true) @PathVariable("bookId") Integer bookId) { LOGGER.info("请求参数bookId值:" + bookId); Book book = bookService.getBook(bookId); BaseResultVo baseResultVo = new BaseResultVo(); if (book != null) { LOGGER.info("查询到书籍ID为" + bookId + "的书籍"); baseResultVo.setData(book); baseResultVo.setCode(ResultStatusCode.OK.getCode()); baseResultVo.setMessage(ResultStatusCode.OK.getMessage()); } else { LOGGER.info("没有查询到书籍ID为" + bookId + "的书籍"); baseResultVo.setCode(ResultStatusCode.DATA_QUERY_ERROR.getCode()); baseResultVo.setData("Query book failed id=" + bookId); baseResultVo.setMessage(ResultStatusCode.DATA_QUERY_ERROR.getMessage()); } return baseResultVo; } @PutMapping(value = "/api/books/{bookId:[0-9]*}") @ApiOperation(value = "更新某本书籍", httpMethod = "PUT", notes = "更新的某本书籍信息", response = BaseResultVo.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = BaseResultVo.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public BaseResultVo updateBook(@NotNull @ApiParam(value = "要更新的某本书籍ID", required = true) @PathVariable("bookId") Integer bookId, @Validated @NotNull @ApiParam(value = "要更新的某本书籍信息", required = true) @RequestBody Book book) { LOGGER.info("请求参数bookId值:" + bookId); BaseResultVo baseResultVo = new BaseResultVo(); if (bookId == null && book == null) { baseResultVo.setCode(ResultStatusCode.DATA_INPUT_ERROR.getCode()); baseResultVo.setMessage(ResultStatusCode.DATA_INPUT_ERROR.getMessage()); return baseResultVo; } if (bookService.getBook(bookId) == null) { baseResultVo.setCode(ResultStatusCode.DATA_QUERY_ERROR.getCode()); baseResultVo.setData("book id=" + bookId + " not existed"); baseResultVo.setMessage(ResultStatusCode.DATA_QUERY_ERROR.getMessage()); return baseResultVo; } Book updatedBook = bookService.updateBook(book); if (updatedBook != null) { baseResultVo.setData(updatedBook); baseResultVo.setCode(ResultStatusCode.OK.getCode()); baseResultVo.setMessage(ResultStatusCode.OK.getMessage()); } else { baseResultVo.setCode(ResultStatusCode.DATA_UPDATED_ERROR.getCode()); baseResultVo.setData("Update book failed id=" + book.getBookId()); baseResultVo.setMessage(ResultStatusCode.DATA_UPDATED_ERROR.getMessage()); } return baseResultVo; } @DeleteMapping(value = "/api/books/{bookId:[0-9]*}") @ApiOperation(value = "删除某本书籍信息", httpMethod = "DELETE", notes = "删除某本书籍信息", response = BaseResultVo.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = BaseResultVo.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public BaseResultVo deleteBook(@ApiParam(value = "要删除的某本书籍ID", required = true) @PathVariable("bookId") Integer bookId) { BaseResultVo baseResultVo = new BaseResultVo(); if (bookService.deleteBook(bookId) == 1) { baseResultVo.setData("Deleted book id=" + bookId); baseResultVo.setCode(ResultStatusCode.OK.getCode()); baseResultVo.setMessage(ResultStatusCode.OK.getMessage()); } else { baseResultVo.setCode(ResultStatusCode.DATA_DELETED_ERROR.getCode()); baseResultVo.setData("Deleted book failed id=" + bookId); baseResultVo.setMessage(ResultStatusCode.DATA_DELETED_ERROR.getMessage()); } return baseResultVo; } }
3e17854eff62a7007160d359950e15a70133e642
1,909
java
Java
components/event-simulator/org.wso2.carbon.event.simulator.admin/src/main/java/org/wso2/carbon/event/simulator/admin/CSVFileInfoDto.java
tharindu-bandara/carbon-event-processing
25a21513e49711031bf5027529edeef301bfa226
[ "Apache-2.0" ]
10
2015-03-11T11:30:46.000Z
2019-04-08T01:41:29.000Z
components/event-simulator/org.wso2.carbon.event.simulator.admin/src/main/java/org/wso2/carbon/event/simulator/admin/CSVFileInfoDto.java
tharindu-bandara/carbon-event-processing
25a21513e49711031bf5027529edeef301bfa226
[ "Apache-2.0" ]
20
2015-01-14T09:20:27.000Z
2020-01-02T09:36:28.000Z
components/event-simulator/org.wso2.carbon.event.simulator.admin/src/main/java/org/wso2/carbon/event/simulator/admin/CSVFileInfoDto.java
tharindu-bandara/carbon-event-processing
25a21513e49711031bf5027529edeef301bfa226
[ "Apache-2.0" ]
131
2015-01-16T09:21:36.000Z
2022-03-04T12:25:27.000Z
25.797297
80
0.682032
10,013
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.event.simulator.admin; public class CSVFileInfoDto { private String filePath; private String fileName; private String streamID; private long delayBetweenEventsInMillis; private String status; public CSVFileInfoDto(){ this.fileName=null; this.filePath=null; this.streamID=null; this.delayBetweenEventsInMillis = 0; } public String getStreamID() { return streamID; } public void setStreamID(String streamID) { this.streamID = streamID; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public long getDelayBetweenEventsInMillis() { return delayBetweenEventsInMillis; } public void setDelayBetweenEventsInMillis(long delayBetweenEventsInMillis) { this.delayBetweenEventsInMillis = delayBetweenEventsInMillis; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
3e1785d5594a49f681f164d412a7c1932be4afbf
1,411
java
Java
app/src/main/java/me/jessyan/mvparms/demo/mvp/model/api/cache/CommonCache.java
tianwenju/MVPArms-master
6bfa1a04acb07b75042fdad7f5a064019c594b16
[ "Apache-2.0" ]
1
2017-03-14T10:11:29.000Z
2017-03-14T10:11:29.000Z
app/src/main/java/me/jessyan/mvparms/demo/mvp/model/api/cache/CommonCache.java
tianwenju/MVPArms-master
6bfa1a04acb07b75042fdad7f5a064019c594b16
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/jessyan/mvparms/demo/mvp/model/api/cache/CommonCache.java
tianwenju/MVPArms-master
6bfa1a04acb07b75042fdad7f5a064019c594b16
[ "Apache-2.0" ]
null
null
null
37.342105
136
0.768147
10,014
package me.jessyan.mvparms.demo.mvp.model.api.cache; import java.util.List; import java.util.concurrent.TimeUnit; import io.rx_cache.DynamicKey; import io.rx_cache.EvictProvider; import io.rx_cache.LifeCache; import io.rx_cache.Reply; import me.jessyan.mvparms.demo.mvp.model.entity.User; import rx.Observable; /** * Created by jess on 8/30/16 13:53 * Contact with ychag@example.com */ public interface CommonCache { @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES) Observable<Reply<List<User>>> getUsers(Observable<List<User>> oUsers, DynamicKey idLastUserQueried, EvictProvider evictProvider); // @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES) // Observable<Reply<HomePicEntity>> getDailyList(Observable<HomePicEntity> service, DynamicKey publishTime, EvictProvider provider); // // @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES) // Observable<Reply<FindMoreEntity>> getFindMore(Observable<FindMoreEntity> service, DynamicKey id, EvictProvider provider); // // // @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES) // Observable<Reply<HotStrategyEntity>> getHotStrategy(Observable<HotStrategyEntity> service, DynamicKey id, EvictProvider provider); // // // @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES) // Observable<Reply<FindDetailEntity>> getFindDetail(Observable<FindDetailEntity> service, DynamicKey id, EvictProvider provider); }
3e1785f3af78f53ad01bc0aeb377687c702b184a
2,166
java
Java
src/main/java/com/digitalpebble/storm/crawler/util/ConfUtils.java
GuiForget/storm-crawler
30a060647aba5560b70e3439aed2ac9bfd28c38b
[ "Apache-2.0" ]
null
null
null
src/main/java/com/digitalpebble/storm/crawler/util/ConfUtils.java
GuiForget/storm-crawler
30a060647aba5560b70e3439aed2ac9bfd28c38b
[ "Apache-2.0" ]
null
null
null
src/main/java/com/digitalpebble/storm/crawler/util/ConfUtils.java
GuiForget/storm-crawler
30a060647aba5560b70e3439aed2ac9bfd28c38b
[ "Apache-2.0" ]
null
null
null
34.380952
80
0.685134
10,015
/** * Licensed to DigitalPebble Ltd under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * DigitalPebble 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.digitalpebble.storm.crawler.util; import java.util.Map; import backtype.storm.utils.Utils; /** TODO replace by calls to backtype.storm.utils.Utils **/ public class ConfUtils { public static int getInt(Map<String, Object> conf, String key, int defaultValue) { Object obj = Utils.get(conf, key, defaultValue); return Utils.getInt(obj); } public static long getLong(Map<String, Object> conf, String key, long defaultValue) { return (Long) Utils.get(conf, key, defaultValue); } public static float getFloat(Map<String, Object> conf, String key, float defaultValue) { Object obj = Utils.get(conf, key, defaultValue); if (obj instanceof Double) return ((Double) obj).floatValue(); return (Float) obj; } public static boolean getBoolean(Map<String, Object> conf, String key, boolean defaultValue) { Object obj = Utils.get(conf, key, defaultValue); return Utils.getBoolean(obj, defaultValue); } public static String getString(Map<String, Object> conf, String key) { return (String) Utils.get(conf, key, null); } public static String getString(Map<String, Object> conf, String key, String defaultValue) { return (String) Utils.get(conf, key, defaultValue); } }
3e1786f038805a9018c1a94e5ec19b63ef007ee8
961
java
Java
Android-RatingBar/app/src/main/java/com/example/user/lab43_12273sudonot/MainActivity.java
sudtanj/Android-Small-Apps-Collection
f6f242876fb091427f7d66b5dbc94d9123804c67
[ "MIT" ]
1
2019-08-05T21:02:00.000Z
2019-08-05T21:02:00.000Z
Android-RatingBar/app/src/main/java/com/example/user/lab43_12273sudonot/MainActivity.java
sudtanj/Android-Small-Apps-Collection
f6f242876fb091427f7d66b5dbc94d9123804c67
[ "MIT" ]
null
null
null
Android-RatingBar/app/src/main/java/com/example/user/lab43_12273sudonot/MainActivity.java
sudtanj/Android-Small-Apps-Collection
f6f242876fb091427f7d66b5dbc94d9123804c67
[ "MIT" ]
null
null
null
31
72
0.687825
10,016
package com.example.user.lab43_12273sudonot; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.RatingBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity { RatingBar rating; TextView percent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); percent=(TextView) findViewById(R.id.textView); rating=(RatingBar) findViewById(R.id.ratingBar); rating.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { String sRatingBar = String.valueOf(rating.getRating()); percent.setText(sRatingBar); return false; } }); } }
3e1787a468a538e4daff81f76714abb052823e71
19,044
java
Java
java/src/com/wparam/kb/inputmethod/latin/settings/SettingsValues.java
wparam-git/androidkb
4295fa18805505c402a179cf4e605c1b9273310d
[ "Info-ZIP" ]
null
null
null
java/src/com/wparam/kb/inputmethod/latin/settings/SettingsValues.java
wparam-git/androidkb
4295fa18805505c402a179cf4e605c1b9273310d
[ "Info-ZIP" ]
null
null
null
java/src/com/wparam/kb/inputmethod/latin/settings/SettingsValues.java
wparam-git/androidkb
4295fa18805505c402a179cf4e605c1b9273310d
[ "Info-ZIP" ]
null
null
null
48.705882
100
0.714661
10,017
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wparam.kb.inputmethod.latin.settings; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.util.Log; import android.view.inputmethod.EditorInfo; import com.wparam.kb.inputmethod.annotations.UsedForTesting; import com.wparam.kb.inputmethod.keyboard.internal.KeySpecParser; import com.wparam.kb.inputmethod.latin.Constants; import com.wparam.kb.inputmethod.latin.Dictionary; import com.wparam.kb.inputmethod.latin.InputAttributes; import com.wparam.kb.inputmethod.latin.R; import com.wparam.kb.inputmethod.latin.RichInputMethodManager; import com.wparam.kb.inputmethod.latin.SubtypeSwitcher; import com.wparam.kb.inputmethod.latin.SuggestedWords; import com.wparam.kb.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.wparam.kb.inputmethod.latin.utils.CollectionUtils; import com.wparam.kb.inputmethod.latin.utils.InputTypeUtils; import com.wparam.kb.inputmethod.latin.utils.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; /** * When you call the constructor of this class, you may want to change the current system locale by * using {@link com.wparam.kb.inputmethod.latin.utils.RunInLocale}. */ public final class SettingsValues { private static final String TAG = SettingsValues.class.getSimpleName(); // "floatMaxValue" and "floatNegativeInfinity" are special marker strings for // Float.NEGATIVE_INFINITE and Float.MAX_VALUE. Currently used for auto-correction settings. private static final String FLOAT_MAX_VALUE_MARKER_STRING = "floatMaxValue"; private static final String FLOAT_NEGATIVE_INFINITY_MARKER_STRING = "floatNegativeInfinity"; // From resources: public final int mDelayUpdateOldSuggestions; public final int[] mSymbolsPrecededBySpace; public final int[] mSymbolsFollowedBySpace; public final int[] mWordConnectors; public final SuggestedWords mSuggestPuncList; public final String mWordSeparators; public final int mSentenceSeparator; public final CharSequence mHintToSaveText; public final boolean mCurrentLanguageHasSpaces; // From preferences, in the same order as xml/prefs.xml: public final boolean mAutoCap; public final boolean mVibrateOn; public final boolean mSoundOn; public final boolean mKeyPreviewPopupOn; private final boolean mShowsVoiceInputKey; public final boolean mIncludesOtherImesInLanguageSwitchList; public final boolean mShowsLanguageSwitchKey; public final boolean mUseContactsDict; public final boolean mUseDoubleSpacePeriod; public final boolean mBlockPotentiallyOffensive; // Use bigrams to predict the next word when there is no input for it yet public final boolean mBigramPredictionEnabled; public final boolean mGestureInputEnabled; public final boolean mGestureTrailEnabled; public final boolean mGestureFloatingPreviewTextEnabled; public final boolean mSlidingKeyInputPreviewEnabled; public final boolean mPhraseGestureEnabled; public final int mKeyLongpressTimeout; public final Locale mLocale; // From the input box public final InputAttributes mInputAttributes; // Deduced settings public final int mKeypressVibrationDuration; public final float mKeypressSoundVolume; public final int mKeyPreviewPopupDismissDelay; private final boolean mAutoCorrectEnabled; public final float mAutoCorrectionThreshold; public final boolean mCorrectionEnabled; public final int mSuggestionVisibility; public final boolean mBoostPersonalizationDictionaryForDebug; public final boolean mUseOnlyPersonalizationDictionaryForDebug; // Setting values for additional features public final int[] mAdditionalFeaturesSettingValues = new int[AdditionalFeaturesSettingUtils.ADDITIONAL_FEATURES_SETTINGS_SIZE]; // Debug settings public final boolean mIsInternal; public SettingsValues(final SharedPreferences prefs, final Locale locale, final Resources res, final InputAttributes inputAttributes) { mLocale = locale; // Get the resources mDelayUpdateOldSuggestions = res.getInteger(R.integer.config_delay_update_old_suggestions); mSymbolsPrecededBySpace = StringUtils.toCodePointArray(res.getString(R.string.symbols_preceded_by_space)); Arrays.sort(mSymbolsPrecededBySpace); mSymbolsFollowedBySpace = StringUtils.toCodePointArray(res.getString(R.string.symbols_followed_by_space)); Arrays.sort(mSymbolsFollowedBySpace); mWordConnectors = StringUtils.toCodePointArray(res.getString(R.string.symbols_word_connectors)); Arrays.sort(mWordConnectors); final String[] suggestPuncsSpec = KeySpecParser.splitKeySpecs(res.getString( R.string.suggested_punctuations)); mSuggestPuncList = createSuggestPuncList(suggestPuncsSpec); mWordSeparators = res.getString(R.string.symbols_word_separators); mSentenceSeparator = res.getInteger(R.integer.sentence_separator); mHintToSaveText = res.getText(R.string.hint_add_to_dictionary); mCurrentLanguageHasSpaces = res.getBoolean(R.bool.current_language_has_spaces); // Store the input attributes if (null == inputAttributes) { mInputAttributes = new InputAttributes(null, false /* isFullscreenMode */); } else { mInputAttributes = inputAttributes; } // Get the settings preferences mAutoCap = prefs.getBoolean(Settings.PREF_AUTO_CAP, true); mVibrateOn = Settings.readVibrationEnabled(prefs, res); mSoundOn = Settings.readKeypressSoundEnabled(prefs, res); mKeyPreviewPopupOn = Settings.readKeyPreviewPopupEnabled(prefs, res); mSlidingKeyInputPreviewEnabled = prefs.getBoolean( Settings.PREF_SLIDING_KEY_INPUT_PREVIEW, true); mShowsVoiceInputKey = needsToShowVoiceInputKey(prefs, res); final String autoCorrectionThresholdRawValue = prefs.getString( Settings.PREF_AUTO_CORRECTION_THRESHOLD, res.getString(R.string.auto_correction_threshold_mode_index_modest)); mIncludesOtherImesInLanguageSwitchList = prefs.getBoolean( Settings.PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST, false); mShowsLanguageSwitchKey = Settings.readShowsLanguageSwitchKey(prefs); mUseContactsDict = prefs.getBoolean(Settings.PREF_KEY_USE_CONTACTS_DICT, true); mUseDoubleSpacePeriod = prefs.getBoolean(Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, true); mBlockPotentiallyOffensive = Settings.readBlockPotentiallyOffensive(prefs, res); mAutoCorrectEnabled = Settings.readAutoCorrectEnabled(autoCorrectionThresholdRawValue, res); mBigramPredictionEnabled = readBigramPredictionEnabled(prefs, res); // Compute other readable settings mKeyLongpressTimeout = Settings.readKeyLongpressTimeout(prefs, res); mKeypressVibrationDuration = Settings.readKeypressVibrationDuration(prefs, res); mKeypressSoundVolume = Settings.readKeypressSoundVolume(prefs, res); mKeyPreviewPopupDismissDelay = Settings.readKeyPreviewPopupDismissDelay(prefs, res); mAutoCorrectionThreshold = readAutoCorrectionThreshold(res, autoCorrectionThresholdRawValue); mGestureInputEnabled = Settings.readGestureInputEnabled(prefs, res); mGestureTrailEnabled = prefs.getBoolean(Settings.PREF_GESTURE_PREVIEW_TRAIL, true); mGestureFloatingPreviewTextEnabled = prefs.getBoolean( Settings.PREF_GESTURE_FLOATING_PREVIEW_TEXT, true); mPhraseGestureEnabled = Settings.readPhraseGestureEnabled(prefs, res); mCorrectionEnabled = mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect; final String showSuggestionsSetting = prefs.getString( Settings.PREF_SHOW_SUGGESTIONS_SETTING, res.getString(R.string.prefs_suggestion_visibility_default_value)); mSuggestionVisibility = createSuggestionVisibility(res, showSuggestionsSetting); AdditionalFeaturesSettingUtils.readAdditionalFeaturesPreferencesIntoArray( prefs, mAdditionalFeaturesSettingValues); mIsInternal = Settings.isInternal(prefs); mBoostPersonalizationDictionaryForDebug = Settings.readBoostPersonalizationDictionaryForDebug(prefs); mUseOnlyPersonalizationDictionaryForDebug = Settings.readUseOnlyPersonalizationDictionaryForDebug(prefs); } // Only for tests private SettingsValues(final Locale locale) { // TODO: locale is saved, but not used yet. May have to change this if tests require. mLocale = locale; mDelayUpdateOldSuggestions = 0; mSymbolsPrecededBySpace = new int[] { '(', '[', '{', '&' }; Arrays.sort(mSymbolsPrecededBySpace); mSymbolsFollowedBySpace = new int[] { '.', ',', ';', ':', '!', '?', ')', ']', '}', '&' }; Arrays.sort(mSymbolsFollowedBySpace); mWordConnectors = new int[] { '\'', '-' }; Arrays.sort(mWordConnectors); mSentenceSeparator = Constants.CODE_PERIOD; final String[] suggestPuncsSpec = new String[] { "!", "?", ",", ":", ";" }; mSuggestPuncList = createSuggestPuncList(suggestPuncsSpec); mWordSeparators = "&\t \n()[]{}*&<>+=|.,;:!?/_\""; mHintToSaveText = "Touch again to save"; mCurrentLanguageHasSpaces = true; mInputAttributes = new InputAttributes(null, false /* isFullscreenMode */); mAutoCap = true; mVibrateOn = true; mSoundOn = true; mKeyPreviewPopupOn = true; mSlidingKeyInputPreviewEnabled = true; mShowsVoiceInputKey = true; mIncludesOtherImesInLanguageSwitchList = false; mShowsLanguageSwitchKey = true; mUseContactsDict = true; mUseDoubleSpacePeriod = true; mBlockPotentiallyOffensive = true; mAutoCorrectEnabled = true; mBigramPredictionEnabled = true; mKeyLongpressTimeout = 300; mKeypressVibrationDuration = 5; mKeypressSoundVolume = 1; mKeyPreviewPopupDismissDelay = 70; mAutoCorrectionThreshold = 1; mGestureInputEnabled = true; mGestureTrailEnabled = true; mGestureFloatingPreviewTextEnabled = true; mPhraseGestureEnabled = true; mCorrectionEnabled = mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect; mSuggestionVisibility = 0; mIsInternal = false; mBoostPersonalizationDictionaryForDebug = false; mUseOnlyPersonalizationDictionaryForDebug = false; } @UsedForTesting public static SettingsValues makeDummySettingsValuesForTest(final Locale locale) { return new SettingsValues(locale); } public boolean isApplicationSpecifiedCompletionsOn() { return mInputAttributes.mApplicationSpecifiedCompletionOn; } public boolean isSuggestionsRequested(final int displayOrientation) { return mInputAttributes.mIsSettingsSuggestionStripOn && (mCorrectionEnabled || isSuggestionStripVisibleInOrientation(displayOrientation)); } public boolean isSuggestionStripVisibleInOrientation(final int orientation) { return (mSuggestionVisibility == SUGGESTION_VISIBILITY_SHOW_VALUE) || (mSuggestionVisibility == SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE && orientation == Configuration.ORIENTATION_PORTRAIT); } public boolean isWordSeparator(final int code) { return mWordSeparators.contains(String.valueOf((char)code)); } public boolean isWordConnector(final int code) { return Arrays.binarySearch(mWordConnectors, code) >= 0; } public boolean isWordCodePoint(final int code) { return Character.isLetter(code) || isWordConnector(code); } public boolean isUsuallyPrecededBySpace(final int code) { return Arrays.binarySearch(mSymbolsPrecededBySpace, code) >= 0; } public boolean isUsuallyFollowedBySpace(final int code) { return Arrays.binarySearch(mSymbolsFollowedBySpace, code) >= 0; } public boolean shouldInsertSpacesAutomatically() { return mInputAttributes.mShouldInsertSpacesAutomatically; } public boolean isVoiceKeyEnabled(final EditorInfo editorInfo) { final boolean shortcutImeEnabled = SubtypeSwitcher.getInstance().isShortcutImeEnabled(); final int inputType = (editorInfo != null) ? editorInfo.inputType : 0; return shortcutImeEnabled && mShowsVoiceInputKey && !InputTypeUtils.isPasswordInputType(inputType); } public boolean isLanguageSwitchKeyEnabled() { if (!mShowsLanguageSwitchKey) { return false; } final RichInputMethodManager imm = RichInputMethodManager.getInstance(); if (mIncludesOtherImesInLanguageSwitchList) { return imm.hasMultipleEnabledIMEsOrSubtypes(false /* include aux subtypes */); } else { return imm.hasMultipleEnabledSubtypesInThisIme(false /* include aux subtypes */); } } public boolean isSameInputType(final EditorInfo editorInfo) { return mInputAttributes.isSameInputType(editorInfo); } // Helper functions to create member values. private static SuggestedWords createSuggestPuncList(final String[] puncs) { final ArrayList<SuggestedWordInfo> puncList = CollectionUtils.newArrayList(); if (puncs != null) { for (final String puncSpec : puncs) { // TODO: Stop using KeySpceParser.getLabel(). puncList.add(new SuggestedWordInfo(KeySpecParser.getLabel(puncSpec), SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.KIND_HARDCODED, Dictionary.DICTIONARY_HARDCODED, SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */)); } } return new SuggestedWords(puncList, false /* typedWordValid */, false /* hasAutoCorrectionCandidate */, true /* isPunctuationSuggestions */, false /* isObsoleteSuggestions */, false /* isPrediction */); } private static final int SUGGESTION_VISIBILITY_SHOW_VALUE = R.string.prefs_suggestion_visibility_show_value; private static final int SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE = R.string.prefs_suggestion_visibility_show_only_portrait_value; private static final int SUGGESTION_VISIBILITY_HIDE_VALUE = R.string.prefs_suggestion_visibility_hide_value; private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] { SUGGESTION_VISIBILITY_SHOW_VALUE, SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE, SUGGESTION_VISIBILITY_HIDE_VALUE }; private static int createSuggestionVisibility(final Resources res, final String suggestionVisiblityStr) { for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) { if (suggestionVisiblityStr.equals(res.getString(visibility))) { return visibility; } } throw new RuntimeException("Bug: visibility string is not configured correctly"); } private static boolean readBigramPredictionEnabled(final SharedPreferences prefs, final Resources res) { return prefs.getBoolean(Settings.PREF_BIGRAM_PREDICTIONS, res.getBoolean( R.bool.config_default_next_word_prediction)); } private static float readAutoCorrectionThreshold(final Resources res, final String currentAutoCorrectionSetting) { final String[] autoCorrectionThresholdValues = res.getStringArray( R.array.auto_correction_threshold_values); // When autoCorrectionThreshold is greater than 1.0, it's like auto correction is off. final float autoCorrectionThreshold; try { final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting); if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) { final String val = autoCorrectionThresholdValues[arrayIndex]; if (FLOAT_MAX_VALUE_MARKER_STRING.equals(val)) { autoCorrectionThreshold = Float.MAX_VALUE; } else if (FLOAT_NEGATIVE_INFINITY_MARKER_STRING.equals(val)) { autoCorrectionThreshold = Float.NEGATIVE_INFINITY; } else { autoCorrectionThreshold = Float.parseFloat(val); } } else { autoCorrectionThreshold = Float.MAX_VALUE; } } catch (final NumberFormatException e) { // Whenever the threshold settings are correct, never come here. Log.w(TAG, "Cannot load auto correction threshold setting." + " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting + ", autoCorrectionThresholdValues: " + Arrays.toString(autoCorrectionThresholdValues), e); return Float.MAX_VALUE; } return autoCorrectionThreshold; } private static boolean needsToShowVoiceInputKey(SharedPreferences prefs, Resources res) { final String voiceModeMain = res.getString(R.string.voice_mode_main); final String voiceMode = prefs.getString(Settings.PREF_VOICE_MODE_OBSOLETE, voiceModeMain); final boolean showsVoiceInputKey = voiceMode == null || voiceMode.equals(voiceModeMain); if (!showsVoiceInputKey) { // Migrate settings from PREF_VOICE_MODE_OBSOLETE to PREF_VOICE_INPUT_KEY // Set voiceModeMain as a value of obsolete voice mode settings. prefs.edit().putString(Settings.PREF_VOICE_MODE_OBSOLETE, voiceModeMain).apply(); // Disable voice input key. prefs.edit().putBoolean(Settings.PREF_VOICE_INPUT_KEY, false).apply(); } return prefs.getBoolean(Settings.PREF_VOICE_INPUT_KEY, true); } }
3e1788fd49a837d0ec22be488a70365e04ba3c77
15,113
java
Java
app/src/main/java/pers/zhc/tools/BaseActivity.java
bczhc2/test
8f910db1a420ed73da3a02c2044d8cb1213a653b
[ "MIT" ]
1
2020-02-13T04:27:37.000Z
2020-02-13T04:27:37.000Z
app/src/main/java/pers/zhc/tools/BaseActivity.java
bczhc2/test
8f910db1a420ed73da3a02c2044d8cb1213a653b
[ "MIT" ]
null
null
null
app/src/main/java/pers/zhc/tools/BaseActivity.java
bczhc2/test
8f910db1a420ed73da3a02c2044d8cb1213a653b
[ "MIT" ]
null
null
null
48.751613
162
0.492027
10,018
package pers.zhc.tools; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import pers.zhc.tools.crashhandler.CrashHandler; import pers.zhc.tools.utils.Common; import pers.zhc.tools.utils.DialogUtil; import pers.zhc.tools.utils.ExternalJNI; import pers.zhc.tools.utils.PermissionRequester; import pers.zhc.u.common.ReadIS; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Stack; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author bczhc * 代码首先是给人读的,只是恰好可以执行! * Machine does not care, but I care! */ public class BaseActivity extends Activity { public final App app = new App(); protected final String TAG = this.getClass().getName(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); app.addActivity(this); CrashHandler.install(this); ExternalJNI.ex(this); new PermissionRequester(() -> { }).requestPermission(this, Manifest.permission.INTERNET, RequestCode.REQUEST_PERMISSION_INTERNET); if (Infos.LAUNCHER_CLASS.equals(this.getClass())) { checkForUpdate(null); } } protected void checkForUpdate(@Nullable CheckForUpdateResultInterface checkForUpdateResultInterface) { new Thread(() -> { System.out.println("check update..."); int myVersionCode = BuildConfig.VERSION_CODE; String myVersionName = BuildConfig.VERSION_NAME; try { String appURL = Infos.ZHC_STATIC_WEB_URL_STRING + "/res/app/" + getString(R.string.app_name) + "/debug"; URL jsonURL = new URL(appURL + "/output.json"); InputStream is = jsonURL.openStream(); StringBuilder sb = new StringBuilder(); new ReadIS(is).read(s -> sb.append(s).append("\n")); is.close(); JSONArray jsonArray = new JSONArray(sb.toString()); JSONObject jsonObject = jsonArray.getJSONObject(0).getJSONObject("apkData"); int remoteVersionCode = jsonObject.getInt("versionCode"); String remoteVersionName = jsonObject.getString("versionName"); String remoteFileName = jsonObject.getString("outputFile"); long fileSize = -1; final String length = "length"; if (jsonObject.has(length)) { fileSize = jsonObject.getLong(length); } boolean update = true; try { String[] split = remoteVersionName.split("_"); long remoteBuildTime = Long.parseLong(split[1]); String[] split1 = myVersionName.split("_"); long myBuildTime = Long.parseLong(split1[1]); update = remoteBuildTime > myBuildTime; } catch (Exception ignored) { } if (checkForUpdateResultInterface != null) { checkForUpdateResultInterface.onCheckForUpdateResult(update); } if (update) { long finalFileSize = fileSize; runOnUiThread(() -> { AlertDialog.Builder adb = new AlertDialog.Builder(this); TextView tv = new TextView(this); tv.setText(getString(R.string.version_info, myVersionName, myVersionCode , remoteVersionName, remoteVersionCode)); AlertDialog ad = adb.setTitle(R.string.found_update_whether_to_install) .setNegativeButton(R.string.cancel, (dialog, which) -> { }) .setPositiveButton(R.string.confirm, (dialog, which) -> { ExecutorService es = Executors.newCachedThreadPool(); new PermissionRequester(() -> { Dialog downloadDialog = new Dialog(this); DialogUtil.setDialogAttr(downloadDialog, false , ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT , false); RelativeLayout rl = View.inflate(this, R.layout.progress_bar, null) .findViewById(R.id.rl); rl.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TextView progressTextView = rl.findViewById(R.id.progress_tv); TextView barTextView = rl.findViewById(R.id.progress_bar_title); barTextView.setText(R.string.downloading); ProgressBar pb = rl.findViewById(R.id.progress_bar); SeekBar seekBar = new SeekBar(this); seekBar.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); progressTextView.setText(R.string.please_wait); downloadDialog.setContentView(rl); downloadDialog.setCanceledOnTouchOutside(false); downloadDialog.setCancelable(true); final OutputStream[] os = new OutputStream[1]; final InputStream[] downloadInputStream = new InputStream[1]; downloadDialog.setOnCancelListener(dialog1 -> { es.shutdownNow(); Thread thread = new Thread(() -> { try { os[0].close(); downloadInputStream[0].close(); } catch (IOException | NullPointerException e) { e.printStackTrace(); } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); downloadDialog.show(); es.execute(() -> { try { URL apkURL = new URL(appURL + "/" + remoteFileName); URLConnection urlConnection = apkURL.openConnection(); downloadInputStream[0] = urlConnection.getInputStream(); File apkDir = new File(Common.getExternalStoragePath(this) + File.separatorChar + getString(R.string.some_tools_app), getString(R.string.apk)); if (!apkDir.exists()) { System.out.println("apkDir.mkdirs() = " + apkDir.mkdirs()); } File apk = new File(apkDir, remoteFileName); os[0] = new FileOutputStream(apk, false); int readLen; long read = 0L; byte[] buffer = new byte[1024]; while ((readLen = downloadInputStream[0].read(buffer)) != -1) { os[0].write(buffer, 0, readLen); read += readLen; long finalRead = read; runOnUiThread(() -> { progressTextView.setText(getString(R.string.download_progress , finalRead, finalFileSize)); pb.setProgress((int) (((double) finalRead) / ((double) finalFileSize) * 100D)); }); } runOnUiThread(() -> Common.installApk(this, apk)); } catch (IOException e) { e.printStackTrace(); } finally { downloadDialog.dismiss(); } }); es.shutdown(); }).requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, RequestCode.REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE); }) .setView(tv).create(); DialogUtil.setDialogAttr(ad, false, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT , false); ad.setCanceledOnTouchOutside(false); ad.show(); }); } } catch (IOException e) { Common.showException(e, this); } catch (JSONException e) { e.printStackTrace(); } }).start(); } @Override protected void onDestroy() { app.pop(); super.onDestroy(); } /** * onConfigurationChanged * the package:android.content.res.Configuration. * * @param newConfig, The new device configuration. * 当设备配置信息有改动(比如屏幕方向的改变,实体键盘的推开或合上等)时, * 并且如果此时有activity正在运行,系统会调用这个函数。 * 注意:onConfigurationChanged只会监测应用程序在AndroidManifest.xml中通过 * android:configChanges="xxxx"指定的配置类型的改动; * 而对于其他配置的更改,则系统会onDestroy()当前Activity,然后重启一个新的Activity实例。 */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // 检测屏幕的方向:纵向或横向 if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { //当前为横屏, 在此处添加额外的处理代码 Log.d(TAG, "onConfigurationChanged: 当前为横屏"); } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { //当前为竖屏, 在此处添加额外的处理代码 Log.d(TAG, "onConfigurationChanged: 当前为竖屏"); } //检测实体键盘的状态:推出或者合上 if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { //实体键盘处于推出状态,在此处添加额外的处理代码 Log.d(TAG, "onConfigurationChanged: 实体键盘处于推出状态"); } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) { //实体键盘处于合上状态,在此处添加额外的处理代码 Log.d(TAG, "onConfigurationChanged: 实体键盘处于合上状态"); } } protected byte ckV() { try { URLConnection urlConnection = new URL(Infos.ZHC_URL_STRING + "/i.zhc?t=tools_v").openConnection(); InputStream is = urlConnection.getInputStream(); byte[] b = new byte[urlConnection.getContentLength()]; System.out.println("is.read(b) = " + is.read(b)); return b[0]; } catch (IOException ignored) { } return 1; } protected interface CheckForUpdateResultInterface { /** * callback * * @param update b */ void onCheckForUpdateResult(boolean update); } public static class Infos { public static final String ZHC_URL_STRING = "http://bczhc.free.idcfengye.com"; public static final String ZHC_STATIC_WEB_URL_STRING = "http://bczhc.gitee.io/web"; public static final Class<?> LAUNCHER_CLASS = MainActivity.class; } public static class RequestCode { public static final int START_ACTIVITY_0 = 0; public static final int START_ACTIVITY_1 = 1; public static final int START_ACTIVITY_2 = 2; public static final int START_ACTIVITY_3 = 3; @SuppressWarnings("unused") public static final int START_ACTIVITY_4 = 4; public static final int REQUEST_PERMISSION_INTERNET = 5; public static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 6; public static final int REQUEST_CAPTURE_SCREEN = 7; public static final int REQUEST_OVERLAY = 8; } public static class BroadcastIntent { public static final String START_FLOATING_BOARD = "pers.zhc.tools.START_FB"; } public static class App { private final Stack<Activity> activities; App() { activities = new Stack<>(); } void addActivity(Activity activity) { if (!activities.contains(activity)) { activities.push(activity); } } void pop() { activities.pop(); } public void finishAllActivities() { for (Activity activity : activities) { if (activity != null) { activity.finish(); } } } } }
3e17890e0125fbf45b30036709ae80bce7cfd465
1,596
java
Java
coeey/com/google/android/gms/auth/api/accounttransfer/zzq.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
1
2021-08-21T17:56:56.000Z
2021-08-21T17:56:56.000Z
coeey/com/google/android/gms/auth/api/accounttransfer/zzq.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
null
null
null
coeey/com/google/android/gms/auth/api/accounttransfer/zzq.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
1
2018-11-26T08:56:33.000Z
2018-11-26T08:56:33.000Z
31.294118
73
0.476817
10,019
package com.google.android.gms.auth.api.accounttransfer; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.internal.zzbek; import java.util.List; public final class zzq implements Creator<zzp> { public final /* synthetic */ Object createFromParcel(Parcel parcel) { List list = null; int zzd = zzbek.zzd(parcel); int i = 0; List list2 = null; List list3 = null; List list4 = null; List list5 = null; while (parcel.dataPosition() < zzd) { int readInt = parcel.readInt(); switch (65535 & readInt) { case 1: i = zzbek.zzg(parcel, readInt); break; case 2: list5 = zzbek.zzac(parcel, readInt); break; case 3: list4 = zzbek.zzac(parcel, readInt); break; case 4: list3 = zzbek.zzac(parcel, readInt); break; case 5: list2 = zzbek.zzac(parcel, readInt); break; case 6: list = zzbek.zzac(parcel, readInt); break; default: zzbek.zzb(parcel, readInt); break; } } zzbek.zzaf(parcel, zzd); return new zzp(i, list5, list4, list3, list2, list); } public final /* synthetic */ Object[] newArray(int i) { return new zzp[i]; } }
3e17891b5c9a7faac20060dd8d71febe4d646535
619
java
Java
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/JvmExit.java
gautamworah96/randomizedtesting
006d90480cf0f343ca6140cdd2706efd6ec382dd
[ "Apache-2.0" ]
109
2015-09-03T00:46:36.000Z
2022-01-16T17:38:22.000Z
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/JvmExit.java
gautamworah96/randomizedtesting
006d90480cf0f343ca6140cdd2706efd6ec382dd
[ "Apache-2.0" ]
107
2015-09-02T05:37:35.000Z
2022-03-16T15:41:49.000Z
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/JvmExit.java
gautamworah96/randomizedtesting
006d90480cf0f343ca6140cdd2706efd6ec382dd
[ "Apache-2.0" ]
33
2015-10-30T14:21:05.000Z
2022-02-08T05:32:12.000Z
24.76
93
0.610662
10,020
package com.carrotsearch.ant.tasks.junit4.slave; final class JvmExit { final static void halt(final int code) { // try to exit gracefully by calling system.exit. If we terminate within 5 seconds, fine. // If not, halt the JVM. final Thread exiter = new Thread() { @Override public void run() { System.exit(code); } }; long deadline = System.currentTimeMillis() + 5 * 1000; exiter.start(); try { while (System.currentTimeMillis() < deadline) { Thread.sleep(500); } } catch (Throwable t) {} Runtime.getRuntime().halt(code); } }
3e17893af0fa777444a493b066a157bf6db9af48
1,309
java
Java
spring-data-neo4j-rx/src/main/java/org/neo4j/springframework/data/core/cypher/BooleanLiteral.java
harissecic/sdn-rx
80e52e8c05d798ede84ee092fd81cd247c415622
[ "Apache-2.0" ]
null
null
null
spring-data-neo4j-rx/src/main/java/org/neo4j/springframework/data/core/cypher/BooleanLiteral.java
harissecic/sdn-rx
80e52e8c05d798ede84ee092fd81cd247c415622
[ "Apache-2.0" ]
null
null
null
spring-data-neo4j-rx/src/main/java/org/neo4j/springframework/data/core/cypher/BooleanLiteral.java
harissecic/sdn-rx
80e52e8c05d798ede84ee092fd81cd247c415622
[ "Apache-2.0" ]
null
null
null
27.851064
75
0.728037
10,021
/* * Copyright (c) 2019-2020 "Neo4j," * Neo4j Sweden AB [https://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.springframework.data.core.cypher; import static org.apiguardian.api.API.Status.*; import org.apiguardian.api.API; /** * The boolean literal. * * @author Michael J. Simons * @soundtrack Bad Religion - Age Of Unreason * @since 1.0 */ @API(status = EXPERIMENTAL, since = "1.0") public final class BooleanLiteral extends Literal<Boolean> { static final BooleanLiteral TRUE = new BooleanLiteral(true); static final BooleanLiteral FALSE = new BooleanLiteral(false); private BooleanLiteral(boolean content) { super(content); } @Override public String asString() { return getContent().toString(); } }
3e1789bd50ddb92d848a5204c5b3f37cfb9ae21e
1,612
java
Java
src/com/jayantkrish/jklol/ccg/supertag/PosContextFeatureGenerator.java
jayantk/jklol
d27532ca83e212d51066cf28f52621acc3fd44cc
[ "BSD-2-Clause" ]
9
2015-05-12T18:31:19.000Z
2020-04-09T18:04:41.000Z
src/com/jayantkrish/jklol/ccg/supertag/PosContextFeatureGenerator.java
jayantk/jklol
d27532ca83e212d51066cf28f52621acc3fd44cc
[ "BSD-2-Clause" ]
4
2016-02-01T23:15:26.000Z
2016-03-25T16:54:04.000Z
src/com/jayantkrish/jklol/ccg/supertag/PosContextFeatureGenerator.java
jayantk/jklol
d27532ca83e212d51066cf28f52621acc3fd44cc
[ "BSD-2-Clause" ]
6
2015-03-20T15:12:38.000Z
2021-10-15T07:08:09.000Z
32.24
103
0.699752
10,022
package com.jayantkrish.jklol.ccg.supertag; import java.util.Map; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.primitives.Ints; import com.jayantkrish.jklol.preprocessing.FeatureGenerator; import com.jayantkrish.jklol.sequence.LocalContext; /** * Generates features based on the part-of-speech tags of the surrounding * words in a sentence. * * @author jayant */ public class PosContextFeatureGenerator implements FeatureGenerator<LocalContext<WordAndPos>, String> { private static final long serialVersionUID = 1L; private final int[][] offsets; public PosContextFeatureGenerator(int[][] offsets) { this.offsets = Preconditions.checkNotNull(offsets); } @Override public Map<String, Double> generateFeatures(LocalContext<WordAndPos> item) { Map<String, Double> weights = Maps.newHashMap(); for (int j = 0; j < offsets.length; j++) { StringBuilder featureBuilder = new StringBuilder(); featureBuilder.append("POS_"); featureBuilder.append(Joiner.on("_").join(Ints.asList(offsets[j]))); featureBuilder.append("="); for (int i = 0; i < offsets[j].length; i++) { WordAndPos word = item.getItem(offsets[j][i], WordAndPosFeatureGenerator.END_FUNCTION); featureBuilder.append(word.getPos()); if (i != offsets[j].length - 1) { featureBuilder.append("_"); } } String featureName = featureBuilder.toString().intern(); weights.put(featureName, 1.0); } return weights; } }
3e178a42784a5d0e842062c3fc8eec27a062d410
359
java
Java
Hafta-4/odev2-kodlama/movie-api-spring-boot/src/main/java/dev/patika/movieapispringboot/movie/controller/MovieCreateResponse.java
isakilikya/patika-spring-bootcamp
8fe092f42a9141da2c25c32224a0b4433c49458b
[ "MIT" ]
null
null
null
Hafta-4/odev2-kodlama/movie-api-spring-boot/src/main/java/dev/patika/movieapispringboot/movie/controller/MovieCreateResponse.java
isakilikya/patika-spring-bootcamp
8fe092f42a9141da2c25c32224a0b4433c49458b
[ "MIT" ]
null
null
null
Hafta-4/odev2-kodlama/movie-api-spring-boot/src/main/java/dev/patika/movieapispringboot/movie/controller/MovieCreateResponse.java
isakilikya/patika-spring-bootcamp
8fe092f42a9141da2c25c32224a0b4433c49458b
[ "MIT" ]
null
null
null
19.944444
77
0.690808
10,023
package dev.patika.movieapispringboot.movie.controller; import lombok.Builder; import lombok.Getter; @Getter @Builder public class MovieCreateResponse { private Long id; public static MovieCreateResponse convertToMovieCreateREsponse(Long id) { return MovieCreateResponse.builder() .id(id) .build(); } }
3e178a6384609b470f21e3cbab0657ec87f4a140
1,510
java
Java
android/src/main/java/com/oblador/shimmer/RNShimmeringView.java
chaseholland/react-native-shimmer
fbc83807cb8f88b65e8d437e29765303b877cff8
[ "MIT" ]
1
2021-05-19T03:16:21.000Z
2021-05-19T03:16:21.000Z
android/src/main/java/com/oblador/shimmer/RNShimmeringView.java
chaseholland/react-native-shimmer
fbc83807cb8f88b65e8d437e29765303b877cff8
[ "MIT" ]
null
null
null
android/src/main/java/com/oblador/shimmer/RNShimmeringView.java
chaseholland/react-native-shimmer
fbc83807cb8f88b65e8d437e29765303b877cff8
[ "MIT" ]
null
null
null
26.964286
88
0.562252
10,024
package com.oblador.shimmer; import android.content.Context; import android.util.AttributeSet; import com.facebook.shimmer.ShimmerFrameLayout; public class RNShimmeringView extends ShimmerFrameLayout { public RNShimmeringView(Context context) { super(context); } public RNShimmeringView(Context context, AttributeSet attrs) { super(context, attrs); } public RNShimmeringView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private float mSpeed = 0.0f; // The speed of shimmering, in points per second. public float getSpeed() { return mSpeed; } public void setSpeed(float speed) { mSpeed = speed; this.setDuration(this.getDuration()); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (mSpeed > 0) { int length = 0; switch (this.getAngle()) { case CW_90: case CW_270: length = bottom - top; break; case CW_0: case CW_180: default: length = right - left; break; } int duration = (int)(1000 * length / mSpeed); if (duration != this.getDuration()) { this.setDuration(duration); } } super.onLayout(changed, left, top, right, bottom); } }
3e178ba2523f2bce08bccd0caf0f09249956ee17
1,206
java
Java
runtime/impl/src/main/java/com/google/apphosting/runtime/anyrpc/EvaluationRuntimeServerInterface.java
isopov/appengine-java-standard
e9d2465c2def0a6710d96969b58006835cd792f2
[ "ECL-2.0", "Apache-2.0" ]
125
2020-11-12T16:59:49.000Z
2022-03-29T17:56:28.000Z
runtime/impl/src/main/java/com/google/apphosting/runtime/anyrpc/EvaluationRuntimeServerInterface.java
isopov/appengine-java-standard
e9d2465c2def0a6710d96969b58006835cd792f2
[ "ECL-2.0", "Apache-2.0" ]
4
2022-01-27T04:35:11.000Z
2022-03-22T05:54:50.000Z
runtime/impl/src/main/java/com/google/apphosting/runtime/anyrpc/EvaluationRuntimeServerInterface.java
isopov/appengine-java-standard
e9d2465c2def0a6710d96969b58006835cd792f2
[ "ECL-2.0", "Apache-2.0" ]
15
2020-11-12T17:00:02.000Z
2022-03-28T09:57:03.000Z
34.457143
79
0.770315
10,025
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.apphosting.runtime.anyrpc; import com.google.apphosting.base.protos.AppinfoPb.AppInfo; import com.google.apphosting.base.protos.RuntimePb.UPRequest; /** * RPC-agnostic version of EvaluationRuntime.ServerInterface. * * <p>If you add methods to EvaluationRuntime in apphosting/base/runtime.proto, * you need to remember to add them here too. */ public interface EvaluationRuntimeServerInterface { void handleRequest(AnyRpcServerContext ctx, UPRequest req); void addAppVersion(AnyRpcServerContext ctx, AppInfo req); void deleteAppVersion(AnyRpcServerContext ctx, AppInfo req); }
3e178c02f97014fa20ae7387b0217361c1b1f6ea
1,479
java
Java
hello-spring/src/test/java/hello/hellospring/repository/MemoryMemberRepositoryTest.java
Gummybearr/java-practice
4dfba0f78ed59bec31c64b2c58ab60faf1cd6b90
[ "MIT" ]
null
null
null
hello-spring/src/test/java/hello/hellospring/repository/MemoryMemberRepositoryTest.java
Gummybearr/java-practice
4dfba0f78ed59bec31c64b2c58ab60faf1cd6b90
[ "MIT" ]
null
null
null
hello-spring/src/test/java/hello/hellospring/repository/MemoryMemberRepositoryTest.java
Gummybearr/java-practice
4dfba0f78ed59bec31c64b2c58ab60faf1cd6b90
[ "MIT" ]
null
null
null
23.854839
69
0.647735
10,026
package hello.hellospring.repository; import hello.hellospring.domain.Member; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; class MemoryMemberRepositoryTest { MemoryMemberRepository repository = new MemoryMemberRepository(); @AfterEach public void afterEach(){ repository.clearStore(); } @Test public void save(){ Member member = new Member(); member.setName("spring"); repository.save(member); Member result = repository.findById(member.getId()).get(); Assertions.assertThat(member).isEqualTo(result); } @Test public void findByName(){ Member member1 = new Member(); member1.setName("spring1"); repository.save(member1); Member member2 = new Member(); member2.setName("spring2"); repository.save(member2); // Member result = repository.findByName("spring1").get(); Assertions.assertThat(result).isEqualTo(member1); } @Test public void findAll(){ Member member1 = new Member(); member1.setName("spring1"); repository.save(member1); Member member2 = new Member(); member2.setName("spring2"); repository.save(member2); List<Member> result = repository.findAll(); Assertions.assertThat(result.size()).isEqualTo(2); } }
3e178d4118103530fff972b0a36cc9fa1de6e621
352
java
Java
StaffWeb/src/com/lxl/servlet/model/ImageModel.java
aa5279aa/StaffManagerWeb
c3c74d1925554cc48eb107e8af765ef4e2b535d2
[ "Apache-2.0" ]
null
null
null
StaffWeb/src/com/lxl/servlet/model/ImageModel.java
aa5279aa/StaffManagerWeb
c3c74d1925554cc48eb107e8af765ef4e2b535d2
[ "Apache-2.0" ]
null
null
null
StaffWeb/src/com/lxl/servlet/model/ImageModel.java
aa5279aa/StaffManagerWeb
c3c74d1925554cc48eb107e8af765ef4e2b535d2
[ "Apache-2.0" ]
null
null
null
19.555556
56
0.678977
10,027
package com.lxl.servlet.model; import com.alibaba.fastjson.annotation.JSONField; import java.util.ArrayList; import java.util.List; /** * Created by xiangleiliu on 2017/5/25. */ public class ImageModel { @JSONField(serialize = false) public String name = "aaa"; public List<ImgFile> fileItems = new ArrayList<>(); }
3e178dd8d71227342e9134e5ed9c9fb2d5efa1a5
1,522
java
Java
jdk11/java.xml/com/sun/org/apache/xerces/internal/dom/AbortException.java
1446554749/jdk_11_src_read
b9c070d7232ee3cf5f2f6270e748ada74cbabb3f
[ "Apache-2.0" ]
543
2017-06-14T14:53:33.000Z
2022-03-23T14:18:09.000Z
jdk11/java.xml/com/sun/org/apache/xerces/internal/dom/AbortException.java
1446554749/jdk_11_src_read
b9c070d7232ee3cf5f2f6270e748ada74cbabb3f
[ "Apache-2.0" ]
381
2017-10-31T14:29:54.000Z
2022-03-25T15:27:27.000Z
jdk11/java.xml/com/sun/org/apache/xerces/internal/dom/AbortException.java
1446554749/jdk_11_src_read
b9c070d7232ee3cf5f2f6270e748ada74cbabb3f
[ "Apache-2.0" ]
50
2018-01-06T12:35:14.000Z
2022-03-13T14:54:33.000Z
41.135135
76
0.737845
10,028
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.org.apache.xerces.internal.dom; public class AbortException extends RuntimeException { private static final long serialVersionUID = 2608302175475740417L; /** * Constructor AbortException */ public AbortException() { super(null, null, false, false); } }
3e178e80a7bb16f41553ca52f70bf5fda4db4ce7
7,059
java
Java
core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
3,651
2015-01-02T23:58:10.000Z
2022-03-31T21:12:12.000Z
core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
6,890
2015-01-01T09:41:48.000Z
2022-03-29T08:39:49.000Z
core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
923
2015-01-01T20:40:08.000Z
2022-03-21T07:26:56.000Z
38.785714
109
0.710866
10,029
package com.orientechnologies.orient.core.serialization.serializer.binary.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializationDebug; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinaryDebug; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ORecordSerializerBinaryDebugTest { private ORecordSerializer previous; @Before public void before() { previous = ODatabaseDocumentTx.getDefaultSerializer(); ODatabaseDocumentTx.setDefaultSerializer(new ORecordSerializerBinary()); } @After public void after() { ODatabaseDocumentTx.setDefaultSerializer(previous); } @Test public void testSimpleDocumentDebug() { ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); db.create(); try { ODocument doc = new ODocument(); doc.field("test", "test"); doc.field("anInt", 2); doc.field("anDouble", 2D); byte[] bytes = doc.toStream(); ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); ORecordSerializationDebug debug = debugger.deserializeDebug(bytes, db); assertEquals(debug.properties.size(), 3); assertEquals(debug.properties.get(0).name, "test"); assertEquals(debug.properties.get(0).type, OType.STRING); assertEquals(debug.properties.get(0).value, "test"); assertEquals(debug.properties.get(1).name, "anInt"); assertEquals(debug.properties.get(1).type, OType.INTEGER); assertEquals(debug.properties.get(1).value, 2); assertEquals(debug.properties.get(2).name, "anDouble"); assertEquals(debug.properties.get(2).type, OType.DOUBLE); assertEquals(debug.properties.get(2).value, 2D); } finally { db.drop(); } } @Test public void testSchemaFullDocumentDebug() { ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); db.create(); try { OClass clazz = db.getMetadata().getSchema().createClass("some"); clazz.createProperty("testP", OType.STRING); clazz.createProperty("theInt", OType.INTEGER); ODocument doc = new ODocument("some"); doc.field("testP", "test"); doc.field("theInt", 2); doc.field("anDouble", 2D); byte[] bytes = doc.toStream(); ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); ORecordSerializationDebug debug = debugger.deserializeDebug(bytes, db); assertEquals(debug.properties.size(), 3); assertEquals(debug.properties.get(0).name, "testP"); assertEquals(debug.properties.get(0).type, OType.STRING); assertEquals(debug.properties.get(0).value, "test"); assertEquals(debug.properties.get(1).name, "theInt"); assertEquals(debug.properties.get(1).type, OType.INTEGER); assertEquals(debug.properties.get(1).value, 2); assertEquals(debug.properties.get(2).name, "anDouble"); assertEquals(debug.properties.get(2).type, OType.DOUBLE); assertEquals(debug.properties.get(2).value, 2D); } finally { db.drop(); } } @Test public void testSimpleBrokenDocumentDebug() { ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); db.create(); try { ODocument doc = new ODocument(); doc.field("test", "test"); doc.field("anInt", 2); doc.field("anDouble", 2D); byte[] bytes = doc.toStream(); byte[] brokenBytes = new byte[bytes.length - 10]; System.arraycopy(bytes, 0, brokenBytes, 0, bytes.length - 10); ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); ORecordSerializationDebug debug = debugger.deserializeDebug(brokenBytes, db); assertEquals(debug.properties.size(), 3); assertEquals(debug.properties.get(0).name, "test"); assertEquals(debug.properties.get(0).type, OType.STRING); assertEquals(debug.properties.get(0).faildToRead, true); assertNotNull(debug.properties.get(0).readingException); assertEquals(debug.properties.get(1).name, "anInt"); assertEquals(debug.properties.get(1).type, OType.INTEGER); assertEquals(debug.properties.get(1).faildToRead, true); assertNotNull(debug.properties.get(1).readingException); assertEquals(debug.properties.get(2).name, "anDouble"); assertEquals(debug.properties.get(2).type, OType.DOUBLE); assertEquals(debug.properties.get(2).faildToRead, true); assertNotNull(debug.properties.get(2).readingException); } finally { db.drop(); } } @Test public void testBrokenSchemaFullDocumentDebug() { ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); db.create(); try { OClass clazz = db.getMetadata().getSchema().createClass("some"); clazz.createProperty("testP", OType.STRING); clazz.createProperty("theInt", OType.INTEGER); ODocument doc = new ODocument("some"); doc.field("testP", "test"); doc.field("theInt", 2); doc.field("anDouble", 2D); byte[] bytes = doc.toStream(); byte[] brokenBytes = new byte[bytes.length - 10]; System.arraycopy(bytes, 0, brokenBytes, 0, bytes.length - 10); ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); ORecordSerializationDebug debug = debugger.deserializeDebug(brokenBytes, db); assertEquals(debug.properties.size(), 3); assertEquals(debug.properties.get(0).name, "testP"); assertEquals(debug.properties.get(0).type, OType.STRING); assertEquals(debug.properties.get(0).faildToRead, true); assertNotNull(debug.properties.get(0).readingException); assertEquals(debug.properties.get(1).name, "theInt"); assertEquals(debug.properties.get(1).type, OType.INTEGER); assertEquals(debug.properties.get(1).faildToRead, true); assertNotNull(debug.properties.get(1).readingException); assertEquals(debug.properties.get(2).name, "anDouble"); assertEquals(debug.properties.get(2).type, OType.DOUBLE); assertEquals(debug.properties.get(2).faildToRead, true); assertNotNull(debug.properties.get(2).readingException); } finally { db.drop(); } } }
3e178e84281364907550bb609f857b89c3b46384
6,417
java
Java
src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/item/FallingBlockEntityMixin_Tracker.java
astei/Sponge
c03c9572eabde4d79945770ecb2d25cf56e8a91d
[ "MIT" ]
334
2015-01-01T05:38:57.000Z
2022-03-28T06:35:23.000Z
src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/item/FallingBlockEntityMixin_Tracker.java
astei/Sponge
c03c9572eabde4d79945770ecb2d25cf56e8a91d
[ "MIT" ]
761
2015-01-01T22:40:49.000Z
2022-03-26T17:58:40.000Z
src/mixins/java/org/spongepowered/common/mixin/tracker/world/entity/item/FallingBlockEntityMixin_Tracker.java
LogicFan/Sponge
bd0aabe83d82e5deb22876130ed0f16230cb90e4
[ "MIT" ]
291
2015-01-01T12:48:30.000Z
2022-03-28T20:56:26.000Z
51.75
109
0.703132
10,030
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.mixin.tracker.world.entity.item; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.item.FallingBlockEntity; import net.minecraft.world.level.block.Blocks; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.world.level.LevelBridge; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.TrackingUtil; import org.spongepowered.common.event.tracking.phase.tick.EntityTickContext; import org.spongepowered.common.mixin.tracker.world.entity.EntityMixin_Tracker; @Mixin(FallingBlockEntity.class) public abstract class FallingBlockEntityMixin_Tracker extends EntityMixin_Tracker { @Override public void tracker$populateFrameInTickContext( final CauseStackManager.StackFrame frame, final EntityTickContext context ) { context.getCreator().ifPresent(frame::pushCause); super.tracker$populateFrameInTickContext(frame, context); } /** * @author gabizou - January 9th, 2018 - 1.12.2 * @author gabizou - May 21st, 2019 - 1.12.2 * @author gabizou - February 23rd, 2020 - 1.14.3 * * @reason Due to the need to fail fast and return out of this falling block * entity's update if the block change is cancelled, we need to inject after * the world.setBlockToAir is called and potentially tell the callback to * cancel. Unfortunately, there's no way to just blindly checking if the block * was changed, because the duality of bulk and single block tracking being * a possibility. So, we have to do the following: * - check if we're throwing the event that would otherwise trigger a block capture * - If the current phase state allows for bulk capturing, the block will be * in the capture supplier, and we can just blindly throw the processing * of that block(s) * - If the processing is cancelled, kill this entity * - If we're doing single capture throws, well, double check the block state * on the world, and if it's not air, well, it's been either replaced, or * cancelled. If it's replaced/cancelled, then don't allow this entity to * live. * * @param ci */ @Inject(method = "tick()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;removeBlock(Lnet/minecraft/core/BlockPos;Z)Z", shift = At.Shift.AFTER ), cancellable = true ) private void tracker$handleBlockCapture(final CallbackInfo ci) { final BlockPos pos = new BlockPos(this.shadow$getX(), this.shadow$getY(), this.shadow$getZ()); // So, there's two cases here: either the world is not cared for, or the // ChangeBlockEvent is not being listened to. If it's not being listened to, // we need to specifically just proceed as normal. if (((LevelBridge) this.level).bridge$isFake() || !ShouldFire.CHANGE_BLOCK_EVENT) { return; } // Ideally, at this point we should still be in the EntityTickState and only this block should // be changing. What we need to do here is throw the block event specifically for setting air // and THEN if this one cancels, we should kill this entity off, unless we want some duplication // of falling blocks, but, since the world already supposedly set the block to air, // we don't need to re-set the block state at the position, just need to check // if the processing succeeded or not. final PhaseContext<@NonNull ?> currentContext = PhaseTracker.getInstance().getPhaseContext(); // By this point, we should have some sort of captured block if (currentContext.doesBlockEventTracking()) { if (!TrackingUtil.processBlockCaptures(currentContext)) { // So, it's been cancelled, we want to absolutely remove this entity. // And we want to stop the entity update at this point. this.shadow$remove(); ci.cancel(); } // We have to check if the original set block state succeeded if we're doing // single captures. If we're not doing bulk capturing (for whatever reason), // we would simply check for the current block state on the world, if it's air, // then it's been captured/processed for single events. And if it's not air, // that means that single event was cancelled, so, the block needs to remain // and this entity needs to die. } else if (this.level.getBlockState(pos) != Blocks.AIR.defaultBlockState()) { this.shadow$remove(); ci.cancel(); } } }
3e178ece4a70b94e1150c4272787f7d91c33fa43
451
java
Java
src/jokrey/utilities/simple/data_structure/queue/Queue.java
jokrey/utility-algorithms-java
efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f
[ "MIT" ]
null
null
null
src/jokrey/utilities/simple/data_structure/queue/Queue.java
jokrey/utility-algorithms-java
efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f
[ "MIT" ]
null
null
null
src/jokrey/utilities/simple/data_structure/queue/Queue.java
jokrey/utility-algorithms-java
efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f
[ "MIT" ]
null
null
null
25.055556
71
0.634146
10,031
package jokrey.utilities.simple.data_structure.queue; /** * @author jokrey */ public interface Queue<E> { /**Add given element to queue, must not be null*/ void enqueue(E e); /**Return and Remove next elem in queue or null*/ E dequeue(); /**Return next elem in queue or null*/ E peek(); /**Calculate the size, might be done by iteration (can be costly)*/ int size(); /**Clears the contents*/ void clear(); }
3e178f9f1b09d0d5a327da7ad93265adadfd1a15
922
java
Java
sema4g-client/src/main/java/com/github/mvp4g/sema4g/client/exception/SeMa4gException.java
mvp4g/sema4g
540935a1ca3db7a8d3cd3960c03da06818c59636
[ "Apache-2.0" ]
2
2018-11-18T16:47:42.000Z
2019-01-05T05:32:17.000Z
sema4g-client/src/main/java/com/github/mvp4g/sema4g/client/exception/SeMa4gException.java
mvp4g/sema4g
540935a1ca3db7a8d3cd3960c03da06818c59636
[ "Apache-2.0" ]
4
2017-11-26T17:41:02.000Z
2018-06-21T14:47:42.000Z
sema4g-client/src/main/java/com/github/mvp4g/sema4g/client/exception/SeMa4gException.java
mvp4g/sema4g
540935a1ca3db7a8d3cd3960c03da06818c59636
[ "Apache-2.0" ]
null
null
null
28.8125
80
0.729935
10,032
/* * Copyright (c) 2017 - 2018 - Frank Hossfeld * * 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.github.mvp4g.sema4g.client.exception; /** * <p>This exception is thrown if something works not as expected</p> */ public class SeMa4gException extends Exception { @SuppressWarnings("unused") private SeMa4gException() { } public SeMa4gException(String message) { super(message); } }
3e17904ee2a83506e3d6d0fb996017a5a09ec042
3,587
java
Java
ssz/src/test/java/tech/pegasys/teku/ssz/SszListTest.java
bgravenorst/teku
ec682763f4ea262ee7debc6424e8ee3706f885e5
[ "Apache-2.0" ]
233
2020-10-26T23:40:37.000Z
2022-03-25T06:05:22.000Z
ssz/src/test/java/tech/pegasys/teku/ssz/SszListTest.java
MitchellTesla/teku
d133f21b75f2baa5314d43a8d036d4c4d2c9b939
[ "Apache-2.0" ]
930
2020-10-23T19:50:25.000Z
2022-03-31T23:48:55.000Z
ssz/src/test/java/tech/pegasys/teku/ssz/SszListTest.java
MitchellTesla/teku
d133f21b75f2baa5314d43a8d036d4c4d2c9b939
[ "Apache-2.0" ]
95
2020-10-26T07:39:33.000Z
2022-03-23T16:38:01.000Z
38.569892
118
0.744355
10,033
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.ssz; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; import org.junit.jupiter.api.Test; import tech.pegasys.teku.infrastructure.unsigned.UInt64; import tech.pegasys.teku.ssz.TestContainers.TestSubContainer; import tech.pegasys.teku.ssz.schema.SszListSchema; import tech.pegasys.teku.ssz.schema.collections.SszListSchemaTestBase; public class SszListTest implements SszListTestBase, SszMutableRefCompositeTestBase { private final RandomSszDataGenerator randomSsz = new RandomSszDataGenerator().withMaxListSize(256); @Override public Stream<SszList<?>> sszData() { return SszListSchemaTestBase.complexListSchemas() .flatMap( listSchema -> Stream.of(listSchema.getDefault(), randomSsz.randomData(listSchema))); } @Test void testMutableListReusable() { List<TestSubContainer> elements = IntStream.range(0, 5) .mapToObj(i -> new TestSubContainer(UInt64.valueOf(i), Bytes32.leftPad(Bytes.of(i)))) .collect(Collectors.toList()); SszListSchema<TestSubContainer, ?> type = SszListSchema.create(TestContainers.TestSubContainer.SSZ_SCHEMA, 100); SszList<TestSubContainer> lr1 = type.getDefault(); SszMutableList<TestSubContainer> lw1 = lr1.createWritableCopy(); assertThat(lw1.sszSerialize()).isEqualTo(lr1.sszSerialize()); assertThat(lw1.hashTreeRoot()).isEqualTo(lr1.hashTreeRoot()); lw1.append(elements.get(0)); SszMutableList<TestSubContainer> lw2 = type.getDefault().createWritableCopy(); lw2.append(elements.get(0)); SszList<TestSubContainer> lr2 = lw2.commitChanges(); assertThat(lw1.sszSerialize()).isEqualTo(lr2.sszSerialize()); assertThat(lw1.hashTreeRoot()).isEqualTo(lr2.hashTreeRoot()); lw1.appendAll(elements.subList(1, 5)); SszMutableList<TestSubContainer> lw3 = type.getDefault().createWritableCopy(); lw3.appendAll(elements); SszList<TestSubContainer> lr3 = lw3.commitChanges(); assertThat(lw1.sszSerialize()).isEqualTo(lr3.sszSerialize()); assertThat(lw1.hashTreeRoot()).isEqualTo(lr3.hashTreeRoot()); lw1.clear(); assertThat(lw1.sszSerialize()).isEqualTo(lr1.sszSerialize()); assertThat(lw1.hashTreeRoot()).isEqualTo(lr1.hashTreeRoot()); lw1.appendAll(elements.subList(0, 5)); SszMutableList<TestSubContainer> lw4 = type.getDefault().createWritableCopy(); lw4.appendAll(elements); SszList<TestSubContainer> lr4 = lw3.commitChanges(); assertThat(lw1.sszSerialize()).isEqualTo(lr4.sszSerialize()); assertThat(lw1.hashTreeRoot()).isEqualTo(lr4.hashTreeRoot()); lw1.clear(); lw1.append(elements.get(0)); assertThat(lw1.sszSerialize()).isEqualTo(lr2.sszSerialize()); assertThat(lw1.hashTreeRoot()).isEqualTo(lr2.hashTreeRoot()); } }
3e1790ed5bac83fccdc767fb0f4954a03d2f2ad3
1,622
java
Java
lib/devices/android/bootstrap/src/io/appium/android/bootstrap/utils/ElementHelpers.java
githubanly/appium
b5540de9229937cf0e92bb4a914d69c2b70c2097
[ "Apache-2.0" ]
null
null
null
lib/devices/android/bootstrap/src/io/appium/android/bootstrap/utils/ElementHelpers.java
githubanly/appium
b5540de9229937cf0e92bb4a914d69c2b70c2097
[ "Apache-2.0" ]
null
null
null
lib/devices/android/bootstrap/src/io/appium/android/bootstrap/utils/ElementHelpers.java
githubanly/appium
b5540de9229937cf0e92bb4a914d69c2b70c2097
[ "Apache-2.0" ]
null
null
null
30.037037
107
0.728113
10,034
package io.appium.android.bootstrap.utils; import android.view.accessibility.AccessibilityNodeInfo; import com.android.uiautomator.common.ReflectionUtils; import com.android.uiautomator.core.UiObject; import io.appium.android.bootstrap.AndroidElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public abstract class ElementHelpers { private static Method findAccessibilityNodeInfo; private static AccessibilityNodeInfo elementToNode(AndroidElement element) { AccessibilityNodeInfo result = null; try { result = (AccessibilityNodeInfo) findAccessibilityNodeInfo.invoke(element.getUiObject(), 5000L); } catch (Exception e) { e.printStackTrace(); } return result; } /** * Remove all duplicate elements from the provided list * * @param elements - elements to remove duplicates from * @return a new list with duplicates removed */ public static List<AndroidElement> dedupe(List<AndroidElement> elements) { try { ReflectionUtils utils = new ReflectionUtils(); findAccessibilityNodeInfo = utils.getMethod(UiObject.class, "findAccessibilityNodeInfo", long.class); } catch (Exception e) { e.printStackTrace(); } List<AndroidElement> result = new ArrayList<AndroidElement>(); List<AccessibilityNodeInfo> nodes = new ArrayList<AccessibilityNodeInfo>(); for (AndroidElement element : elements) { AccessibilityNodeInfo node = elementToNode(element); if (!nodes.contains(node)) { nodes.add(node); result.add(element); } } return result; } }
3e17915b77a175396d092c8cfe7f3a875e97d404
2,339
java
Java
src/cn/npt/fs/cache/SensorValuePool.java
Leonardo-YXH/CADB
943b4bc262e32b65e52f366f553e2a5df7249549
[ "Apache-2.0" ]
2
2016-08-09T01:19:22.000Z
2021-05-04T08:09:01.000Z
src/cn/npt/fs/cache/SensorValuePool.java
Leonardo-YXH/CADB
943b4bc262e32b65e52f366f553e2a5df7249549
[ "Apache-2.0" ]
null
null
null
src/cn/npt/fs/cache/SensorValuePool.java
Leonardo-YXH/CADB
943b4bc262e32b65e52f366f553e2a5df7249549
[ "Apache-2.0" ]
null
null
null
20.883929
94
0.688328
10,035
package cn.npt.fs.cache; import java.util.List; import com.alibaba.fastjson.JSONObject; import cn.npt.fs.config.CacheBlockCfg; import cn.npt.fs.event.FirstBSHandler; import cn.npt.fs.service.SensorValueFileService; import cn.npt.util.math.SensorFileKit; /** * 原始数据缓存池 * @author Leonardo * */ public class SensorValuePool extends CachePool<Double> { private long sensorId; private BSSensorPool bsp; private CacheBlockCfg cbCfg; private String dataDir; public SensorValuePool(long sensorId,CacheBlockCfg cbCfg,String dataDir) { super(cbCfg.size, cbCfg.blockInterval); this.sensorId=sensorId; this.cbCfg=cbCfg; this.dataDir=dataDir; } public long getSensorId() { return sensorId; } public void setSensorId(long sensorId) { this.sensorId = sensorId; } public BSSensorPool getBsp() { return bsp; } public void setBsp(BSSensorPool bsp) { this.bsp = bsp; FirstBSHandler handler=new FirstBSHandler(); this.addListener(handler); } public CacheBlockCfg getCbCfg() { return cbCfg; } public void setCbCfg(CacheBlockCfg cbCfg) { this.cbCfg = cbCfg; } public String getDataDir() { return dataDir; } public void setDataDir(String dataDir) { this.dataDir = dataDir; } /** * 从文件中读取恢复数据,大小为一个存储文件的大小 * @param time * @return */ public List<Double> preDataFromDB(long time){ String fileName=dataDir+SensorFileKit.getFileNameBySensorId(sensorId) +SensorFileKit.getFileNameByTime(time, cbCfg.getCapacity(),cbCfg.timeUnit) +"/sensor.dat"; return SensorFileKit.read(fileName); } /** * */ public void afterReStart(){ long previousTime=currentTime-this.blockInterval*this.size; List<Double> preValues=SensorValueFileService.getSensorValue(sensorId, previousTime, size); for(Double v:preValues){ if(this.index>=this.size){ this.index=0; } this.values.set(index, v); this.index++; } } @Override public void setCase2(Object paras) { } @Override public void setCase3(Object paras) { } @Override public void setCase4(Object paras) { } @Override public JSONObject currentV2JSON() { JSONObject obj=new JSONObject(); obj.put(String.valueOf(this.sensorId), this.getCurrentValue()); return obj; } }
3e1791c777e26c440063c247f6f108b37df222b6
1,102
java
Java
app/src/main/java/com/spryfieldsoftwaresolutions/android/connectthree/SingleFragmentActivity.java
adambaxter/ConnectThree
8a79a38f284c9bbb3b4b14ba9d1fff7546f31af6
[ "MIT" ]
null
null
null
app/src/main/java/com/spryfieldsoftwaresolutions/android/connectthree/SingleFragmentActivity.java
adambaxter/ConnectThree
8a79a38f284c9bbb3b4b14ba9d1fff7546f31af6
[ "MIT" ]
null
null
null
app/src/main/java/com/spryfieldsoftwaresolutions/android/connectthree/SingleFragmentActivity.java
adambaxter/ConnectThree
8a79a38f284c9bbb3b4b14ba9d1fff7546f31af6
[ "MIT" ]
null
null
null
26.878049
73
0.690563
10,036
package com.spryfieldsoftwaresolutions.android.connectthree; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; /** * Created by Adam Baxter on 02/02/18. * <p> * Abstract Activity to use for fragments */ public abstract class SingleFragmentActivity extends AppCompatActivity { protected abstract Fragment createFragment(); @LayoutRes protected int getLayoutResId() { return R.layout.activity_fragment; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutResId()); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment == null) { fragment = createFragment(); fm.beginTransaction() .add(R.id.fragment_container, fragment) .commit(); } } }
3e17927a112d8494486bae201a41b4df68c1e0e5
102
java
Java
core/src/main/java/com/narendra/app/core/exception/UserAlreadyExistException.java
narendracode/modular-app
9adcf0337082576ff05c2408d02815e3abcde5fe
[ "MIT" ]
null
null
null
core/src/main/java/com/narendra/app/core/exception/UserAlreadyExistException.java
narendracode/modular-app
9adcf0337082576ff05c2408d02815e3abcde5fe
[ "MIT" ]
null
null
null
core/src/main/java/com/narendra/app/core/exception/UserAlreadyExistException.java
narendracode/modular-app
9adcf0337082576ff05c2408d02815e3abcde5fe
[ "MIT" ]
null
null
null
20.4
57
0.843137
10,037
package com.narendra.app.core.exception; public class UserAlreadyExistException extends Exception{ }
3e1792f8c9522f3a946636234c78657db59f2162
625
java
Java
jxfw-reporting-xsl-fo/src/main/java/ru/croc/ctp/jxfw/reporting/xslfo/layouts/formatters/IReportFormatter.java
croc-code/jxfw
7af05aa6579a8dfd0e83c918b0e46195eb0802cf
[ "Apache-2.0" ]
12
2021-11-08T08:08:44.000Z
2022-02-21T15:42:25.000Z
jxfw-reporting-xsl-fo/src/main/java/ru/croc/ctp/jxfw/reporting/xslfo/layouts/formatters/IReportFormatter.java
crocinc/jxfw
da93ee21e4e586219eeefc8441e472f7136266d1
[ "Apache-2.0" ]
null
null
null
jxfw-reporting-xsl-fo/src/main/java/ru/croc/ctp/jxfw/reporting/xslfo/layouts/formatters/IReportFormatter.java
crocinc/jxfw
da93ee21e4e586219eeefc8441e472f7136266d1
[ "Apache-2.0" ]
1
2022-03-02T14:05:28.000Z
2022-03-02T14:05:28.000Z
34.722222
93
0.7632
10,038
package ru.croc.ctp.jxfw.reporting.xslfo.layouts.formatters; import ru.croc.ctp.jxfw.reporting.xslfo.types.AbstractFormatterClass; /** * Интерфейс объектов, реалзующих форматировние ячеек таблицы и их значений. * Created by vsavenkov on 25.04.2017. Import from Croc.XmlFramework.ReportService .Net.2.0 */ public interface IReportFormatter { /** * Производит форматирование ячейки таблицы. * @param formatterProfile - Профиль * @param formatterData - Набор исходных данных для форматировщика */ void execute(AbstractFormatterClass formatterProfile, ReportFormatterData formatterData); }