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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e05874a86745c48c61821a50c0534272676ff25
| 2,501 |
java
|
Java
|
src/main/java/uk/ac/manchester/libchebi/Comment.java
|
synbiochem/libChEBIj
|
110dc31b189702851dbad2737093a8057a38eb9f
|
[
"MIT"
] | 3 |
2015-11-24T04:19:06.000Z
|
2021-01-14T16:51:06.000Z
|
src/main/java/uk/ac/manchester/libchebi/Comment.java
|
synbiochem/libChEBIj
|
110dc31b189702851dbad2737093a8057a38eb9f
|
[
"MIT"
] | 4 |
2015-11-19T12:00:08.000Z
|
2020-01-27T11:08:26.000Z
|
src/main/java/uk/ac/manchester/libchebi/Comment.java
|
synbiochem/libChEBIj
|
110dc31b189702851dbad2737093a8057a38eb9f
|
[
"MIT"
] | 5 |
2016-10-21T09:07:58.000Z
|
2020-02-28T06:09:28.000Z
| 15.438272 | 113 | 0.608557 | 2,313 |
/*
* libChEBIj (c) University of Manchester 2015
*
* libChEBIj is licensed under the MIT License.
*
* To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
*/
package uk.ac.manchester.libchebi;
import java.util.*;
/**
* @author neilswainston
*/
public class Comment
{
/**
*
*/
private final String datatypeId;
/**
*
*/
private final String datatype;
/**
*
*/
private final String text;
/**
*
*/
private final Date createdOn;
/**
*
*/
Comment( final String datatypeId, final String datatype, final String text, final Date createdOn )
{
assert datatypeId != null;
assert datatype != null;
assert text != null;
assert createdOn != null;
this.datatypeId = datatypeId;
this.datatype = datatype;
this.text = text;
this.createdOn = createdOn;
}
/**
* @return datatype
*/
public String getDatatype()
{
return datatype;
}
/**
* @return text
*/
public String getText()
{
return text;
}
/**
* @return created on
*/
public Date getCreatedOn()
{
return createdOn;
}
/**
* Commonly, datatypeId is the same as datatype.
*
* Method has been made package private to "hide" this duplicate.
*
* @return datatype id
*/
String getDatatypeId()
{
return datatypeId;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return createdOn + "\t" + datatypeId + "\t" + datatype + "\t" + text; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
final int PRIME = 31;
int result = 1;
result = PRIME * result + datatype.hashCode();
result = PRIME * result + datatypeId.hashCode();
result = PRIME * result + text.hashCode();
result = PRIME * result + createdOn.hashCode();
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals( Object obj )
{
if( this == obj )
{
return true;
}
if( obj == null )
{
return false;
}
if( !( obj instanceof Comment ) )
{
return false;
}
final Comment other = (Comment)obj;
if( !datatype.equals( other.datatype ) )
{
return false;
}
if( !datatypeId.equals( other.datatypeId ) )
{
return false;
}
if( !text.equals( other.text ) )
{
return false;
}
if( !createdOn.equals( other.createdOn ) )
{
return false;
}
return true;
}
}
|
3e0587ae1059a84acc36804ea82d2892acdc6d74
| 1,939 |
java
|
Java
|
2017-Sum Algorithms/Algorithms01_BrandonHosley/FragranceBag.java
|
bhosley/Schoolwork
|
7c4eb909d2e6c65cd93b1c7fa744a183cebfc952
|
[
"Unlicense"
] | null | null | null |
2017-Sum Algorithms/Algorithms01_BrandonHosley/FragranceBag.java
|
bhosley/Schoolwork
|
7c4eb909d2e6c65cd93b1c7fa744a183cebfc952
|
[
"Unlicense"
] | null | null | null |
2017-Sum Algorithms/Algorithms01_BrandonHosley/FragranceBag.java
|
bhosley/Schoolwork
|
7c4eb909d2e6c65cd93b1c7fa744a183cebfc952
|
[
"Unlicense"
] | null | null | null | 16.86087 | 57 | 0.595152 | 2,314 |
public class FragranceBag<T> implements BagInterface<T> {
private final T[] bag;
private static final int DEFAULT_CAPACITY = 20;
private int numberOfEntries;
/*
* Constructors
*/
public FragranceBag() {
this(DEFAULT_CAPACITY);
}
public FragranceBag(int capacity) {
numberOfEntries = 0;
@SuppressWarnings("unchecked")
T[] tempBag = (T[])new Object[capacity];
bag = tempBag;
}
public boolean add(T newEntry) {
boolean result = true;
if (isFull())
{
result = false;
} else {
bag[numberOfEntries] = newEntry;
numberOfEntries++;
}
return result;
}
public T[] toArray() {
@SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) {
result[index] = bag[index];
}
return result;
}
public boolean isFull() {
return numberOfEntries == bag.length;
}
public T remove(int index) {
T trash = bag[index];
bag[index] = null;
return trash;
}
public boolean remove(T item) {
if (this.contains(item)) {
int i = this.getIndexOf(item);
this.remove(i);
return true;
} else {
return false;
}
}
public int getIndexOf(T item) {
int i = 0;
for(int j=0; j<bag.length; j++) {
if (bag[j] == item) {
i = j;
}
}
return i;
}
public void clear(){
for(int i=0;i<bag.length;i++) {
bag[i] = null;
}
}
public int getCurrentSize() {
int size = 0;
for(int i=0; i<bag.length; i++) {
if (bag[i] != null){
size++;
}
}
return size;
}
public boolean isEmpty() {
return !(numberOfEntries == bag.length);
}
public int getFrequencyOf(T item) {
int freq = 0;
for(int i=0; i<bag.length; i++) {
if (bag[i] != item){
freq++;
}
}
return freq;
}
public boolean contains(T item) {
boolean result = false;
for (int i=0; i<bag.length; i++) {
if(bag[i] == item) {
result = true;
}
}
return result;
}
}
|
3e0587fede73ef5ac0b3dc7ff277682157556449
| 411 |
java
|
Java
|
src/main/java/com/orient/netty/client/MainClass.java
|
fortunelee/fixdstock_dump
|
0fe012145cfa39e82ce558a64c0134df3a655174
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/orient/netty/client/MainClass.java
|
fortunelee/fixdstock_dump
|
0fe012145cfa39e82ce558a64c0134df3a655174
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/orient/netty/client/MainClass.java
|
fortunelee/fixdstock_dump
|
0fe012145cfa39e82ce558a64c0134df3a655174
|
[
"Apache-2.0"
] | null | null | null | 16.44 | 62 | 0.688564 | 2,315 |
package com.orient.netty.client;
import java.io.IOException;
import com.orient.constants.AppCommon;
public class MainClass {
public static void main(String[] args) throws IOException {
NettyClient client = new NettyClient(AppCommon.CONFIG_PATH);
client.connect();
while (true)
{
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
3e0588bf88662a6b44ddfeb370f788c70e542a4f
| 3,106 |
java
|
Java
|
app/src/main/java/com/hmw/mytoutiaoapp/photo/PhotoTabLayout.java
|
hanmingwang/MyToutiaoApp
|
a5fe4b0f22994da835c3ed70ee29e8c85eb674df
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/hmw/mytoutiaoapp/photo/PhotoTabLayout.java
|
hanmingwang/MyToutiaoApp
|
a5fe4b0f22994da835c3ed70ee29e8c85eb674df
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/hmw/mytoutiaoapp/photo/PhotoTabLayout.java
|
hanmingwang/MyToutiaoApp
|
a5fe4b0f22994da835c3ed70ee29e8c85eb674df
|
[
"Apache-2.0"
] | null | null | null | 33.042553 | 123 | 0.698648 | 2,316 |
package com.hmw.mytoutiaoapp.photo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hmw.mytoutiaoapp.InitApp;
import com.hmw.mytoutiaoapp.R;
import com.hmw.mytoutiaoapp.base.BaseListFragment;
import com.hmw.mytoutiaoapp.base.BasePagerAdapter;
import com.hmw.mytoutiaoapp.photo.artice.PhotoArticleView;
import com.hmw.mytoutiaoapp.util.SettingUtil;
import java.util.ArrayList;
import java.util.List;
/**
* Created by han on 2018/6/5.
*/
public class PhotoTabLayout extends Fragment {
private static final String TAG = "PhotoTabLayout";
private static PhotoTabLayout instance = null;
private static int pageSize = InitApp.AppContext.getResources().getStringArray(R.array.photo_id).length;
private String categoryId[] = InitApp.AppContext.getResources().getStringArray(R.array.photo_id);
private String categoryName[] = InitApp.AppContext.getResources().getStringArray(R.array.photo_name);
private TabLayout tabLayout;
private ViewPager viewPager;
private List<Fragment> fragmentList = new ArrayList<>();
private BasePagerAdapter adapter;
public static PhotoTabLayout getInstance() {
if (instance == null) {
instance = new PhotoTabLayout();
}
return instance;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo_tab, container, false);
initView(view);
initData();
return view;
}
@Override
public void onResume() {
super.onResume();
tabLayout.setBackgroundColor(SettingUtil.getInstance().getColor());
}
private void initView(View view) {
tabLayout = view.findViewById(R.id.tab_layout_photo);
viewPager = view.findViewById(R.id.view_pager_photo);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setBackgroundColor(SettingUtil.getInstance().getColor());
viewPager.setOffscreenPageLimit(pageSize);
}
private void initData() {
for (int i = 0; i < categoryId.length; i++) {
Fragment fragment = PhotoArticleView.newInstance(categoryId[i]);
fragmentList.add(fragment);
}
adapter = new BasePagerAdapter(getChildFragmentManager(), fragmentList, categoryName);
viewPager.setAdapter(adapter);
}
public void onDoubleClick() {
if (fragmentList != null && fragmentList.size() > 0) {
int item = viewPager.getCurrentItem();
((BaseListFragment) fragmentList.get(item)).onRefresh();
}
}
@Override
public void onDestroy() {
if (instance != null) {
instance = null;
}
super.onDestroy();
}
}
|
3e058999b780def3fa694c85cc33944d83a87ad0
| 243 |
java
|
Java
|
CoreJavaMuiltithreading/src/synchronization/demo/MyThread.java
|
Brajesh44/CoreJava
|
b2eb45797c097999ccdbf8a86c0511e66ce9c29f
|
[
"Apache-2.0"
] | null | null | null |
CoreJavaMuiltithreading/src/synchronization/demo/MyThread.java
|
Brajesh44/CoreJava
|
b2eb45797c097999ccdbf8a86c0511e66ce9c29f
|
[
"Apache-2.0"
] | null | null | null |
CoreJavaMuiltithreading/src/synchronization/demo/MyThread.java
|
Brajesh44/CoreJava
|
b2eb45797c097999ccdbf8a86c0511e66ce9c29f
|
[
"Apache-2.0"
] | null | null | null | 15.1875 | 43 | 0.641975 | 2,317 |
package synchronization.demo;
public class MyThread extends Thread{
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
@Override
public void run() {
d.wish(name);
}
}
|
3e0589a5d655a854c6152a59756f4d5d565f4833
| 49,314 |
java
|
Java
|
tests/qub/UPSClientTests.java
|
danschultequb/ups-java
|
6103ff418c0641306f934f8d11d7db41b3e7910a
|
[
"MIT"
] | null | null | null |
tests/qub/UPSClientTests.java
|
danschultequb/ups-java
|
6103ff418c0641306f934f8d11d7db41b3e7910a
|
[
"MIT"
] | null | null | null |
tests/qub/UPSClientTests.java
|
danschultequb/ups-java
|
6103ff418c0641306f934f8d11d7db41b3e7910a
|
[
"MIT"
] | null | null | null | 75.059361 | 194 | 0.305958 | 2,318 |
package qub;
public interface UPSClientTests
{
static void test(TestRunner runner)
{
runner.testGroup(UPSClient.class, () ->
{
runner.testGroup("create(Network)", () ->
{
runner.test("with null", (Test test) ->
{
test.assertThrows(() -> UPSClient.create((Network)null),
new PreConditionFailure("network cannot be null."));
});
runner.test("with non-null", (Test test) ->
{
final Network network = test.getNetwork();
final RealUPSClient upsClient = UPSClient.create(network);
test.assertNotNull(upsClient);
test.assertEqual(RealUPSClient.productionHost, upsClient.getHost());
test.assertNull(upsClient.getAccessLicenseNumber());
});
});
runner.testGroup("create(HttpClient)", () ->
{
runner.test("with null", (Test test) ->
{
test.assertThrows(() -> UPSClient.create((HttpClient)null),
new PreConditionFailure("httpClient cannot be null."));
});
runner.test("with non-null", (Test test) ->
{
final Network network = test.getNetwork();
final HttpClient httpClient = HttpClient.create(network);
final RealUPSClient upsClient = UPSClient.create(httpClient);
test.assertNotNull(upsClient);
test.assertEqual(RealUPSClient.productionHost, upsClient.getHost());
test.assertNull(upsClient.getAccessLicenseNumber());
});
});
});
}
static void test(TestRunner runner, Function1<Test,? extends UPSClient> creator)
{
UPSClientTests.test(runner, null, creator);
}
static void test(TestRunner runner, Skip skipRealTests, Function1<Test,? extends UPSClient> creator)
{
runner.testGroup(UPSClient.class, () ->
{
runner.testGroup("sendTrackRequest(UPSTrackRequest)", () ->
{
final Action2<UPSTrackRequest,Throwable> sendTrackRequestErrorTest = (UPSTrackRequest trackRequest, Throwable expected) ->
{
runner.test("with " + trackRequest, (Test test) ->
{
final UPSClient upsClient = creator.run(test);
test.assertThrows(() -> upsClient.sendTrackRequest(trackRequest),
expected);
});
};
sendTrackRequestErrorTest.run(
null,
new PreConditionFailure("trackRequest cannot be null."));
sendTrackRequestErrorTest.run(
UPSTrackRequest.create(),
new PreConditionFailure("!Strings.isNullOrEmpty(trackRequest.getAccessLicenseNumber()) || !Strings.isNullOrEmpty(this.getAccessLicenseNumber()) cannot be false."));
sendTrackRequestErrorTest.run(
UPSTrackRequest.create()
.setAccessLicenseNumber("a"),
new PreConditionFailure("trackRequest.getInquiryNumber() cannot be null."));
runner.testGroup("with real access license number", skipRealTests, () ->
{
final Action2<UPSTrackRequest,Action2<Test,UPSTrackResponse>> sendTrackRequestTest = (UPSTrackRequest trackRequest, Action2<Test,UPSTrackResponse> trackResponseValidation) ->
{
runner.test("with " + trackRequest, (Test test) ->
{
final UPSClient upsClient = creator.run(test);
final UPSTrackResponse trackResponse = upsClient.sendTrackRequest(trackRequest).await();
test.assertNotNull(trackResponse);
test.assertEqual(200, trackResponse.getStatusCode());
test.assertEqual("OK", trackResponse.getReasonPhrase());
test.assertEqual("HTTP/1.1", trackResponse.getHttpVersion());
trackResponseValidation.run(test, trackResponse);
});
};
sendTrackRequestTest.run(
UPSTrackRequest.create()
.setAccessLicenseNumber(RealUPSClientTests.accessLicenseNumber)
.setInquiryNumber("fakeinquirynumber"),
(Test test, UPSTrackResponse trackResponse) ->
{
test.assertEqual(
JSONObject.create()
.setObject("trackResponse", JSONObject.create()
.setArray("shipment", JSONArray.create()
.add(JSONObject.create()
.setArray("warnings", JSONArray.create()
.add(JSONObject.create()
.setString("code", "TW0001")
.setString("message", "Tracking Information Not Found")))))),
trackResponse.getBodyJson());
test.assertEqual(
Iterable.create(
UPSTrackResponseWarning.create()
.setCode("TW0001")
.setMessage("Tracking Information Not Found")),
trackResponse.getWarnings());
test.assertEqual(null, trackResponse.getTrackingNumber());
test.assertEqual(Iterable.create(), trackResponse.getDeliveryDates());
test.assertEqual(Iterable.create(), trackResponse.getActivities());
});
sendTrackRequestTest.run(
UPSTrackRequest.create()
.setAccessLicenseNumber(RealUPSClientTests.accessLicenseNumber)
.setInquiryNumber("1Z5338FF0107231059"),
(Test test, UPSTrackResponse trackResponse) ->
{
test.assertEqual(
JSONObject.create()
.setObject("trackResponse", JSONObject.create()
.setArray("shipment", JSONArray.create()
.add(JSONObject.create()
.setArray("package", JSONArray.create()
.add(JSONObject.create()
.setString("trackingNumber", "1Z5338FF0107231059")
.setArray("activity", JSONArray.create()
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "BALDWIN")
.setString("stateProvince", "MD")
.setString("postalCode", "")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "X")
.setString("description", "DeliveryAttempted")
.setString("code", "48"))
.setString("date", "20191121")
.setString("time", "140400"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Sparks")
.setString("stateProvince", "MD")
.setString("postalCode", "")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "X")
.setString("description", "Thereceiverwasnotavailablefordelivery.We'llmakeasecondattemptthenextbusinessday.")
.setString("code", "48"))
.setString("date", "20191121")
.setString("time", "135800"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "")
.setString("stateProvince", "")
.setString("postalCode", "")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "M")
.setString("description", "OrderProcessed:ReadyforUPS")
.setString("code", "MP"))
.setString("date", "20191119")
.setString("time", "132642"))
)
)
)
)
)
),
trackResponse.getBodyJson());
test.assertEqual(Iterable.create(), trackResponse.getWarnings());
test.assertEqual("1Z5338FF0107231059", trackResponse.getTrackingNumber());
test.assertEqual(
Iterable.create(),
trackResponse.getDeliveryDates());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageActivity.create()
.setCity("BALDWIN")
.setStateProvince("MD")
.setPostalCode("")
.setCountry("US")
.setType("X")
.setDescription("DeliveryAttempted")
.setCode("48")
.setDate("20191121")
.setTime("140400"),
UPSTrackResponsePackageActivity.create()
.setCity("Sparks")
.setStateProvince("MD")
.setPostalCode("")
.setCountry("US")
.setType("X")
.setDescription("Thereceiverwasnotavailablefordelivery.We'llmakeasecondattemptthenextbusinessday.")
.setCode("48")
.setDate("20191121")
.setTime("135800"),
UPSTrackResponsePackageActivity.create()
.setCity("")
.setStateProvince("")
.setPostalCode("")
.setCountry("US")
.setType("M")
.setDescription("OrderProcessed:ReadyforUPS")
.setCode("MP")
.setDate("20191119")
.setTime("132642")),
trackResponse.getActivities());
});
sendTrackRequestTest.run(
UPSTrackRequest.create()
.setAccessLicenseNumber(RealUPSClientTests.accessLicenseNumber)
.setInquiryNumber("92055900100111152280003029"),
(Test test, UPSTrackResponse trackResponse) ->
{
test.assertEqual(
JSONObject.create()
.setObject("trackResponse", JSONObject.create()
.setArray("shipment", JSONArray.create()
.add(JSONObject.create()
.setArray("package", JSONArray.create()
.add(JSONObject.create()
.setString("trackingNumber", "92055900100111152280003029")
.setArray("deliveryDate", JSONArray.create()
.add(JSONObject.create()
.setString("type", "SDD")
.setString("date", "20200123")))
.setArray("activity", JSONArray.create()
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Butner")
.setString("stateProvince", "NC")
.setString("postalCode", "27509")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "I")
.setString("description", "PostagePaid/Readyfordestinationpostofficeentry")
.setString("code", "ZW"))
.setString("date", "20200116")
.setString("time", "103700"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Butner")
.setString("stateProvince", "NC")
.setString("postalCode", "27509")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "I")
.setString("description", "PackagedepartedUPSMailInnovationsfacilityenroutetoUSPSforinduction")
.setString("code", "ZR"))
.setString("date", "20200116")
.setString("time", "103700"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Butner")
.setString("stateProvince", "NC")
.setString("postalCode", "27509")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "I")
.setString("description", "PackageprocessedbyUPSMailInnovationsoriginfacility")
.setString("code", "ZT"))
.setString("date", "20200116")
.setString("time", "103400"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Butner")
.setString("stateProvince", "NC")
.setString("postalCode", "27509")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "I")
.setString("description", "PackagereceivedforprocessingbyUPSMailInnovations")
.setString("code", "ZS"))
.setString("date", "20200116")
.setString("time", "095500"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "DURHAM")
.setString("stateProvince", "NC")
.setString("postalCode", "27713")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "P")
.setString("description", "ShipmenttenderedtoUPSMailInnovations")
.setString("code", "VS"))
.setString("date", "20200116")
.setString("time", "020200")))))))),
trackResponse.getBodyJson());
test.assertEqual(Iterable.create(), trackResponse.getWarnings());
test.assertEqual("92055900100111152280003029", trackResponse.getTrackingNumber());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageDeliveryDate.create()
.setType("SDD")
.setDate("20200123")),
trackResponse.getDeliveryDates());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageActivity.create()
.setCity("Butner")
.setStateProvince("NC")
.setPostalCode("27509")
.setCountry("US")
.setType("I")
.setDescription("PostagePaid/Readyfordestinationpostofficeentry")
.setCode("ZW")
.setDate("20200116")
.setTime("103700"),
UPSTrackResponsePackageActivity.create()
.setCity("Butner")
.setStateProvince("NC")
.setPostalCode("27509")
.setCountry("US")
.setType("I")
.setDescription("PackagedepartedUPSMailInnovationsfacilityenroutetoUSPSforinduction")
.setCode("ZR")
.setDate("20200116")
.setTime("103700"),
UPSTrackResponsePackageActivity.create()
.setCity("Butner")
.setStateProvince("NC")
.setPostalCode("27509")
.setCountry("US")
.setType("I")
.setDescription("PackageprocessedbyUPSMailInnovationsoriginfacility")
.setCode("ZT")
.setDate("20200116")
.setTime("103400"),
UPSTrackResponsePackageActivity.create()
.setCity("Butner")
.setStateProvince("NC")
.setPostalCode("27509")
.setCountry("US")
.setType("I")
.setDescription("PackagereceivedforprocessingbyUPSMailInnovations")
.setCode("ZS")
.setDate("20200116")
.setTime("095500"),
UPSTrackResponsePackageActivity.create()
.setCity("DURHAM")
.setStateProvince("NC")
.setPostalCode("27713")
.setCountry("US")
.setType("P")
.setDescription("ShipmenttenderedtoUPSMailInnovations")
.setCode("VS")
.setDate("20200116")
.setTime("020200")),
trackResponse.getActivities());
});
sendTrackRequestTest.run(
UPSTrackRequest.create()
.setAccessLicenseNumber(RealUPSClientTests.accessLicenseNumber)
.setInquiryNumber("7798339175"),
(Test test, UPSTrackResponse trackResponse) ->
{
test.assertEqual(
JSONObject.create()
.setObject("trackResponse", JSONObject.create()
.setArray("shipment", JSONArray.create()
.add(JSONObject.create()
.setArray("package", JSONArray.create()
.add(JSONObject.create()
.setString("trackingNumber", "7798339175")
.setArray("deliveryDate", JSONArray.create()
.add(JSONObject.create()
.setString("type", "SDD")
.setString("date", "20200721")))
.setArray("activity", JSONArray.create()
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Vancouver")
.setString("stateProvince", "BC")
.setString("country", "CA")))
.setObject("status", JSONObject.create()
.setString("type", "I")
.setString("description", "ETA at Port of Discharge")
.setString("code", "006"))
.setString("date", "20200706")
.setString("time", "000100"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Tokyo")
.setString("stateProvince", "13")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "Documents received from shipper")
.setString("code", "045"))
.setString("date", "20200615")
.setString("time", "102702"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Tokyo")
.setString("stateProvince", "13")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "Date Available to Ship")
.setString("code", "003"))
.setString("date", "20200615")
.setString("time", "102702"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Kobe")
.setString("stateProvince", "28")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "ETD from Load Port")
.setString("code", "004"))
.setString("date", "20200614")
.setString("time", "141800"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Kobe")
.setString("stateProvince", "28")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "Departure")
.setString("code", "005"))
.setString("date", "20200614")
.setString("time", "141800"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Osaka")
.setString("stateProvince", "27")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "Planned pickup date")
.setString("code", "072"))
.setString("date", "20200611")
.setString("time", "100000"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Tokyo")
.setString("stateProvince", "13")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "Received into UPS possession")
.setString("code", "002"))
.setString("date", "20200611")
.setString("time", "100000"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Tokyo")
.setString("stateProvince", "13")
.setString("country", "JP")))
.setObject("status", JSONObject.create()
.setString("type", "")
.setString("description", "Booking Received from Client")
.setString("code", "037"))
.setString("date", "20200604")
.setString("time", "023812")))))))),
trackResponse.getBodyJson());
test.assertEqual(Iterable.create(), trackResponse.getWarnings());
test.assertEqual("7798339175", trackResponse.getTrackingNumber());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageDeliveryDate.create()
.setType("SDD")
.setDate("20200721")),
trackResponse.getDeliveryDates());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageActivity.create()
.setCity("Vancouver")
.setStateProvince("BC")
.setCountry("CA")
.setType("I")
.setDescription("ETA at Port of Discharge")
.setCode("006")
.setDate("20200706")
.setTime("000100"),
UPSTrackResponsePackageActivity.create()
.setCity("Tokyo")
.setStateProvince("13")
.setCountry("JP")
.setType("")
.setDescription("Documents received from shipper")
.setCode("045")
.setDate("20200615")
.setTime("102702"),
UPSTrackResponsePackageActivity.create()
.setCity("Tokyo")
.setStateProvince("13")
.setCountry("JP")
.setType("")
.setDescription("Date Available to Ship")
.setCode("003")
.setDate("20200615")
.setTime("102702"),
UPSTrackResponsePackageActivity.create()
.setCity("Kobe")
.setStateProvince("28")
.setCountry("JP")
.setType("")
.setDescription("ETD from Load Port")
.setCode("004")
.setDate("20200614")
.setTime("141800"),
UPSTrackResponsePackageActivity.create()
.setCity("Kobe")
.setStateProvince("28")
.setCountry("JP")
.setType("")
.setDescription("Departure")
.setCode("005")
.setDate("20200614")
.setTime("141800"),
UPSTrackResponsePackageActivity.create()
.setCity("Osaka")
.setStateProvince("27")
.setCountry("JP")
.setType("")
.setDescription("Planned pickup date")
.setCode("072")
.setDate("20200611")
.setTime("100000"),
UPSTrackResponsePackageActivity.create()
.setCity("Tokyo")
.setStateProvince("13")
.setCountry("JP")
.setType("")
.setDescription("Received into UPS possession")
.setCode("002")
.setDate("20200611")
.setTime("100000"),
UPSTrackResponsePackageActivity.create()
.setCity("Tokyo")
.setStateProvince("13")
.setCountry("JP")
.setType("")
.setDescription("Booking Received from Client")
.setCode("037")
.setDate("20200604")
.setTime("023812")),
trackResponse.getActivities());
});
sendTrackRequestTest.run(
UPSTrackRequest.create()
.setAccessLicenseNumber(RealUPSClientTests.accessLicenseNumber)
.setInquiryNumber("572254454"),
(Test test, UPSTrackResponse trackResponse) ->
{
test.assertEqual(
JSONObject.create()
.setObject("trackResponse", JSONObject.create()
.setArray("shipment", JSONArray.create()
.add(JSONObject.create()
.setArray("package", JSONArray.create()
.add(JSONObject.create()
.setString("trackingNumber", "572254454")
.setArray("deliveryDate", JSONArray.create()
.add(JSONObject.create()
.setString("type", "DEL")
.setString("date", "20191207"))
.add(JSONObject.create()
.setString("type", "SDD")
.setString("date", "20191210")))
.setObject("deliveryTime", JSONObject.create()
.setString("startTime", "")
.setString("endTime", "")
.setString("type", "EOD"))
.setArray("activity", JSONArray.create()
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Truckload")
.setString("stateProvince", "VA")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "D")
.setString("description", "Shipmenthasbeendeliveredtoconsignee"))
.setString("date", "20191207")
.setString("time", "104500"))
.add(JSONObject.create()
.setObject("location", JSONObject.create()
.setObject("address", JSONObject.create()
.setString("city", "Truckload")
.setString("stateProvince", "VA")
.setString("country", "US")))
.setObject("status", JSONObject.create()
.setString("type", "I")
.setString("description", "Shipmenthasbeenpickedup"))
.setString("date", "20191207")
.setString("time", "080000")))))))),
trackResponse.getBodyJson());
test.assertEqual(Iterable.create(), trackResponse.getWarnings());
test.assertEqual("572254454", trackResponse.getTrackingNumber());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageDeliveryDate.create()
.setType("DEL")
.setDate("20191207"),
UPSTrackResponsePackageDeliveryDate.create()
.setType("SDD")
.setDate("20191210")),
trackResponse.getDeliveryDates());
test.assertEqual(
Iterable.create(
UPSTrackResponsePackageActivity.create()
.setCity("Truckload")
.setStateProvince("VA")
.setCountry("US")
.setType("D")
.setDescription("Shipmenthasbeendeliveredtoconsignee")
.setDate("20191207")
.setTime("104500"),
UPSTrackResponsePackageActivity.create()
.setCity("Truckload")
.setStateProvince("VA")
.setCountry("US")
.setType("I")
.setDescription("Shipmenthasbeenpickedup")
.setDate("20191207")
.setTime("080000")),
trackResponse.getActivities());
});
});
});
});
}
}
|
3e058a510174c41fd4c29afa8f92105c0bf06d74
| 679 |
java
|
Java
|
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/ix.java
|
vietnux/CodeEditorMobile
|
acd29a6a647342276eb557f3af579535092ab377
|
[
"Apache-2.0"
] | null | null | null |
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/ix.java
|
vietnux/CodeEditorMobile
|
acd29a6a647342276eb557f3af579535092ab377
|
[
"Apache-2.0"
] | null | null | null |
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/ix.java
|
vietnux/CodeEditorMobile
|
acd29a6a647342276eb557f3af579535092ab377
|
[
"Apache-2.0"
] | null | null | null | 29.521739 | 92 | 0.714286 | 2,319 |
package com.google.android.gms.internal.ads;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
final class ix implements px {
private final /* synthetic */ Activity a;
/* renamed from: b reason: collision with root package name */
private final /* synthetic */ Bundle f4648b;
ix(hx hxVar, Activity activity, Bundle bundle) {
this.a = activity;
this.f4648b = bundle;
}
@Override // com.google.android.gms.internal.ads.px
public final void a(Application.ActivityLifecycleCallbacks activityLifecycleCallbacks) {
activityLifecycleCallbacks.onActivityCreated(this.a, this.f4648b);
}
}
|
3e058a7411bb97974cf3a369cb763c9c1f3cb7a2
| 508 |
java
|
Java
|
finalproject/src/main/java/canabarro/fraga/finalproject/service/ClientSaveService.java
|
luisfelipefraga/pipoquinha-filmes
|
64953b7841d2c0b9c09223c0337a3484d5504c80
|
[
"MIT"
] | null | null | null |
finalproject/src/main/java/canabarro/fraga/finalproject/service/ClientSaveService.java
|
luisfelipefraga/pipoquinha-filmes
|
64953b7841d2c0b9c09223c0337a3484d5504c80
|
[
"MIT"
] | null | null | null |
finalproject/src/main/java/canabarro/fraga/finalproject/service/ClientSaveService.java
|
luisfelipefraga/pipoquinha-filmes
|
64953b7841d2c0b9c09223c0337a3484d5504c80
|
[
"MIT"
] | 1 |
2020-07-01T13:48:45.000Z
|
2020-07-01T13:48:45.000Z
| 28.222222 | 64 | 0.814961 | 2,320 |
package canabarro.fraga.finalproject.service;
import canabarro.fraga.finalproject.model.ClientEntity;
import canabarro.fraga.finalproject.repository.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ClientSaveService {
@Autowired
private ClientRepository clientRepository;
public ClientEntity save(ClientEntity clientEntity) {
return this.clientRepository.save(clientEntity);
}
}
|
3e058aff55cdfb3e694fc0d53367a8005165f560
| 349 |
java
|
Java
|
JAVA/Projects/la fac/src/tp9/test.java
|
Zed-M/dzcode.talk
|
7da4e0e83aa58597f30a61384370c3ae41926894
|
[
"Unlicense"
] | 12 |
2019-04-22T10:16:54.000Z
|
2022-01-08T02:44:19.000Z
|
JAVA/Projects/la fac/src/tp9/test.java
|
Zed-M/dzcode.talk
|
7da4e0e83aa58597f30a61384370c3ae41926894
|
[
"Unlicense"
] | null | null | null |
JAVA/Projects/la fac/src/tp9/test.java
|
Zed-M/dzcode.talk
|
7da4e0e83aa58597f30a61384370c3ae41926894
|
[
"Unlicense"
] | 3 |
2019-05-14T11:24:42.000Z
|
2019-08-08T16:13:09.000Z
| 15.173913 | 45 | 0.524355 | 2,321 |
package tp9;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ticketameliore t []=new ticketameliore[500];
for (int i = 0; i < 5; i++) {
t[i]=new ticketameliore();
t[i].lire();
t[i].calculrecette();
}
ticketameliore.aficher();
}}
|
3e058b758d1e6171185abe2f302d9fb5e0e9be52
| 1,191 |
java
|
Java
|
Hexapawn/Pawns.java
|
RuddJohnson/Adversarial-Search
|
0427ea7586cafa2ea067fc61cb1475d5582a9378
|
[
"MIT"
] | null | null | null |
Hexapawn/Pawns.java
|
RuddJohnson/Adversarial-Search
|
0427ea7586cafa2ea067fc61cb1475d5582a9378
|
[
"MIT"
] | null | null | null |
Hexapawn/Pawns.java
|
RuddJohnson/Adversarial-Search
|
0427ea7586cafa2ea067fc61cb1475d5582a9378
|
[
"MIT"
] | null | null | null | 36.090909 | 167 | 0.562552 | 2,322 |
/**
* Rudd Johnson
* 4/21/17
*/
public class Pawns extends Piece { //inherits piece, store information about pawns on the board, where they are at any point and where their next move will be
private Piece location; //pointer to location on board
private int x; //current x-axis
private int y; //current y-axis
private int nextX; //next x-axis location for move
private int nextY; //next y-axis location for move
Pawns(char type, Piece loc, int X, int Y, int newX, int newY){ //initialize variables
super(type); //call parent constructor
this.x = X;
this.y =Y;
this.location = loc;
this.nextX = newX;
this.nextY = newY;
}
public Piece getLocation() {return location;} //getters and setters for variables
public void setLocation(Piece location) {this.location = location;}
public int getX() {return x;}
public int getY() {return y;}
public int getNextX(){ return nextX;}
public int getNextY(){return nextY;}
}
|
3e058bdf6df590c53f9ffdde3cc735714e2f2319
| 178 |
java
|
Java
|
Chapter 11 Bridge/homework/XMLGenerator.java
|
zclhit/design-pattern-java-source-code
|
299d232edca15ca6298bc07f449215c9f6d3fdef
|
[
"Apache-2.0"
] | null | null | null |
Chapter 11 Bridge/homework/XMLGenerator.java
|
zclhit/design-pattern-java-source-code
|
299d232edca15ca6298bc07f449215c9f6d3fdef
|
[
"Apache-2.0"
] | null | null | null |
Chapter 11 Bridge/homework/XMLGenerator.java
|
zclhit/design-pattern-java-source-code
|
299d232edca15ca6298bc07f449215c9f6d3fdef
|
[
"Apache-2.0"
] | null | null | null | 22.25 | 49 | 0.640449 | 2,323 |
public class XMLGenerator extends Generator {
@Override
void exportFile() {
this.connector.connectDB();
System.out.println("generate xml file.");
}
}
|
3e058c0863073d96042f763d0c58a2ce167d09b0
| 829 |
java
|
Java
|
modules/foxbpm-kernel/src/main/java/org/foxbpm/kernel/process/KernelDefinitions.java
|
FoxBPM/FoxBPM
|
f7b502807ec2cb65b5ebcab7123ff2cf545c81dc
|
[
"Apache-2.0"
] | 120 |
2015-01-02T09:35:36.000Z
|
2022-02-09T03:33:31.000Z
|
modules/foxbpm-kernel/src/main/java/org/foxbpm/kernel/process/KernelDefinitions.java
|
yangchenhui/FoxBPM
|
f7b502807ec2cb65b5ebcab7123ff2cf545c81dc
|
[
"Apache-2.0"
] | 14 |
2015-01-05T08:14:27.000Z
|
2019-09-04T04:21:46.000Z
|
modules/foxbpm-kernel/src/main/java/org/foxbpm/kernel/process/KernelDefinitions.java
|
yangchenhui/FoxBPM
|
f7b502807ec2cb65b5ebcab7123ff2cf545c81dc
|
[
"Apache-2.0"
] | 78 |
2015-01-04T08:49:53.000Z
|
2022-02-17T06:52:38.000Z
| 26.741935 | 75 | 0.732207 | 2,324 |
/**
* Copyright 1996-2014 FoxBPM 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.
*
* @author kenshin
*/
package org.foxbpm.kernel.process;
import java.util.List;
/**
* @author kenshin
*
*/
public interface KernelDefinitions extends KernelBaseElement {
List<KernelRootElement> getRootElements();
}
|
3e058c0f73975635f2921668bb9af286c794e9b9
| 1,956 |
java
|
Java
|
structr-core/src/main/java/org/structr/schema/importer/FileBasedHashLongMap.java
|
dlaske/structr
|
e829a57d42c1b82774ef4d61b816fef6f1950846
|
[
"IJG",
"ADSL"
] | null | null | null |
structr-core/src/main/java/org/structr/schema/importer/FileBasedHashLongMap.java
|
dlaske/structr
|
e829a57d42c1b82774ef4d61b816fef6f1950846
|
[
"IJG",
"ADSL"
] | null | null | null |
structr-core/src/main/java/org/structr/schema/importer/FileBasedHashLongMap.java
|
dlaske/structr
|
e829a57d42c1b82774ef4d61b816fef6f1950846
|
[
"IJG",
"ADSL"
] | null | null | null | 29.636364 | 114 | 0.712168 | 2,325 |
/**
* Copyright (C) 2010-2015 Morgner UG (haftungsbeschränkt)
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.schema.importer;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
*
* @author Christian Morgner
*/
public class FileBasedHashLongMap<K> {
private final Map<K, LazyFileBasedLongCollection> hashFiles = new LinkedHashMap<>();
private boolean clearOnOpen = true;
private String basePath = null;
public FileBasedHashLongMap(final String basePath) {
this(basePath, true);
}
public FileBasedHashLongMap(final String basePath, final boolean clearOnOpen) {
this.basePath = basePath;
}
public void add(final K key, final Long value) {
getCollectionForKey(key).add(value);
}
public Collection<Long> get(final K key) {
return getCollectionForKey(key);
}
// ----- private methods -----
private LazyFileBasedLongCollection getCollectionForKey(final K key) {
LazyFileBasedLongCollection collection = hashFiles.get(key);
if (collection == null) {
collection = new LazyFileBasedLongCollection(basePath + File.separator + key.hashCode() + ".lfc", clearOnOpen);
hashFiles.put(key, collection);
}
return collection;
}
}
|
3e058c14e15ded7c2c21d5840b4c9914fd8fac60
| 1,933 |
java
|
Java
|
zebra-client/src/main/java/com/dianping/zebra/shard/router/rule/dimension/AbstractDimensionRule.java
|
stancycowen/Zebra
|
33d74b831abe7e8e2d29f8c4e145e46ba17432dc
|
[
"Apache-2.0"
] | 1,837 |
2018-11-28T03:16:41.000Z
|
2022-03-28T16:46:30.000Z
|
zebra-client/src/main/java/com/dianping/zebra/shard/router/rule/dimension/AbstractDimensionRule.java
|
jiayangchen/Zebra
|
3bba3b6e1a424f69662d0123d383830deaac3888
|
[
"Apache-2.0"
] | 51 |
2018-12-13T09:52:41.000Z
|
2022-03-09T06:13:52.000Z
|
zebra-client/src/main/java/com/dianping/zebra/shard/router/rule/dimension/AbstractDimensionRule.java
|
jiayangchen/Zebra
|
3bba3b6e1a424f69662d0123d383830deaac3888
|
[
"Apache-2.0"
] | 459 |
2018-11-27T08:01:54.000Z
|
2022-03-31T11:29:10.000Z
| 28.014493 | 76 | 0.707191 | 2,326 |
/*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.zebra.shard.router.rule.dimension;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
/**
* @author hao.zhu
*
*/
public abstract class AbstractDimensionRule implements DimensionRule {
protected Set<String> shardColumns = new HashSet<String>();
protected boolean isMaster;
protected boolean isRange;
public void initShardColumn(String dbRule, String tbRule) {
Matcher matcher = RULE_COLUMN_PATTERN.matcher(dbRule);
while (matcher.find()) {
shardColumns.add(matcher.group(1));
}
if(tbRule != null && tbRule.trim().length() > 0) {
matcher = RULE_COLUMN_PATTERN.matcher(tbRule);
while (matcher.find()) {
shardColumns.add(matcher.group(1));
}
}
}
@Override
public boolean isMaster() {
return isMaster;
}
public void setMaster(boolean isMaster) {
this.isMaster = isMaster;
}
@Override
public boolean isRange() {
return isRange;
}
public void setRange(boolean range) {
isRange = range;
}
}
|
3e058c395d3d9d4e7702a7accb4efff4f36dc03e
| 3,419 |
java
|
Java
|
bkc-api/src/main/java/cn/bitflash/entity/UserInfoEntity.java
|
mrchen210282/Mid-Autumn-Festival
|
27e1bfafbc0ee527014a4ca00a7cac1a9b55c5fb
|
[
"Apache-2.0"
] | null | null | null |
bkc-api/src/main/java/cn/bitflash/entity/UserInfoEntity.java
|
mrchen210282/Mid-Autumn-Festival
|
27e1bfafbc0ee527014a4ca00a7cac1a9b55c5fb
|
[
"Apache-2.0"
] | null | null | null |
bkc-api/src/main/java/cn/bitflash/entity/UserInfoEntity.java
|
mrchen210282/Mid-Autumn-Festival
|
27e1bfafbc0ee527014a4ca00a7cac1a9b55c5fb
|
[
"Apache-2.0"
] | 1 |
2020-12-29T08:25:02.000Z
|
2020-12-29T08:25:02.000Z
| 18.68306 | 70 | 0.629131 | 2,327 |
package cn.bitflash.entity;
import java.io.Serializable;
import java.util.Date;
public class UserInfoEntity implements Serializable {
private static final long serialVersionUID = 4282111755160371079L;
private String uid;
private String realname;
private String mobile;
private String nickname;
private String idNumber;
private String isInvited;
private String invitationCode;
private String isAuth;
//头像
private String avatar;
private Integer upgradeNum;
private Integer vipLevel;
private Float currentPower;
private String area;
private String nicklock;
//npc释放比率
private Integer npcRelease;
//hlb释放比率
private Integer hlbRelease;
private String isAvailable;
public Float getCurrentPower() {
return currentPower;
}
public void setCurrentPower(Float currentPower) {
this.currentPower = currentPower;
}
public String getNicklock() {
return nicklock;
}
public void setNicklock(String nicklock) {
this.nicklock = nicklock;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getIsInvited() {
return isInvited;
}
public void setIsInvited(String isInvited) {
this.isInvited = isInvited;
}
public String getInvitationCode() {
return invitationCode;
}
public void setInvitationCode(String invitationCode) {
this.invitationCode = invitationCode;
}
public String getIsAuth() {
return isAuth;
}
public void setIsAuth(String isAuth) {
this.isAuth = isAuth;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Integer getUpgradeNum() {
return upgradeNum;
}
public void setUpgradeNum(Integer upgradeNum) {
this.upgradeNum = upgradeNum;
}
public Integer getVipLevel() {
return vipLevel;
}
public void setVipLevel(Integer vipLevel) {
this.vipLevel = vipLevel;
}
public Integer getNpcRelease() {
return npcRelease;
}
public void setNpcRelease(Integer npcRelease) {
this.npcRelease = npcRelease;
}
public Integer getHlbRelease() {
return hlbRelease;
}
public void setHlbRelease(Integer hlbRelease) {
this.hlbRelease = hlbRelease;
}
public String getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(String isAvailable) {
this.isAvailable = isAvailable;
}
}
|
3e058c47f584c14985efe4cf0251fc72e607c31d
| 2,911 |
java
|
Java
|
jms-light/src/main/java/com/google/pubsub/jms/light/message/AbstractPropertyMessage.java
|
kingcontext/pubsub
|
0fb66807aad2dd47d9df8d6027ed5eefaf254ea1
|
[
"Apache-2.0"
] | 1 |
2019-02-19T02:23:26.000Z
|
2019-02-19T02:23:26.000Z
|
jms-light/src/main/java/com/google/pubsub/jms/light/message/AbstractPropertyMessage.java
|
kingcontext/pubsub
|
0fb66807aad2dd47d9df8d6027ed5eefaf254ea1
|
[
"Apache-2.0"
] | null | null | null |
jms-light/src/main/java/com/google/pubsub/jms/light/message/AbstractPropertyMessage.java
|
kingcontext/pubsub
|
0fb66807aad2dd47d9df8d6027ed5eefaf254ea1
|
[
"Apache-2.0"
] | 1 |
2019-03-27T17:02:20.000Z
|
2019-03-27T17:02:20.000Z
| 22.742188 | 94 | 0.747166 | 2,328 |
package com.google.pubsub.jms.light.message;
import com.google.common.collect.Maps;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Message;
/**
* Default implementation of property handling methods from {@link javax.jms.Message}.
*
* @author Maksym Prokhorenko
*/
public abstract class AbstractPropertyMessage implements Message, Serializable {
private final Map<String, Object> properties = Maps.newHashMap();
@Override
public void clearProperties() throws JMSException {
properties.clear();
}
@Override
public boolean propertyExists(final String name) throws JMSException {
return properties.containsKey(name);
}
@Override
public boolean getBooleanProperty(final String name) throws JMSException {
return false;
}
@Override
public byte getByteProperty(final String name) throws JMSException {
return 0;
}
// short forced by protocol
@SuppressWarnings("PMD.AvoidUsingShortType")
@Override
public short getShortProperty(final String name) throws JMSException {
return 0;
}
@Override
public int getIntProperty(final String name) throws JMSException {
return 0;
}
@Override
public long getLongProperty(final String name) throws JMSException {
return 0;
}
@Override
public float getFloatProperty(final String name) throws JMSException {
return 0;
}
@Override
public double getDoubleProperty(final String name) throws JMSException {
return 0;
}
@Override
public String getStringProperty(final String name) throws JMSException {
return null;
}
@Override
public Object getObjectProperty(final String name) throws JMSException {
return null;
}
@Override
public Enumeration getPropertyNames() throws JMSException {
return null;
}
@Override
public void setBooleanProperty(final String name, final boolean value) throws JMSException {
}
@Override
public void setByteProperty(final String name, final byte value) throws JMSException {
}
// short forced by protocol
@SuppressWarnings("PMD.AvoidUsingShortType")
@Override
public void setShortProperty(final String name, final short value) throws JMSException {
}
@Override
public void setIntProperty(final String name, final int value) throws JMSException {
}
@Override
public void setLongProperty(final String name, final long value) throws JMSException {
}
@Override
public void setFloatProperty(final String name, final float value) throws JMSException {
}
@Override
public void setDoubleProperty(final String name, final double value) throws JMSException {
}
@Override
public void setStringProperty(final String name, final String value) throws JMSException {
}
@Override
public void setObjectProperty(final String name, final Object value) throws JMSException {
}
}
|
3e058c655322403abda84f2619480700b5543785
| 2,145 |
java
|
Java
|
src/main/java/qasino/simulation/qasino/pipeline/SymmetricHashJoin.java
|
folkvir/snob-v2-simulation
|
2412d505381334b52048aefd44752109a6b0dc73
|
[
"MIT"
] | null | null | null |
src/main/java/qasino/simulation/qasino/pipeline/SymmetricHashJoin.java
|
folkvir/snob-v2-simulation
|
2412d505381334b52048aefd44752109a6b0dc73
|
[
"MIT"
] | null | null | null |
src/main/java/qasino/simulation/qasino/pipeline/SymmetricHashJoin.java
|
folkvir/snob-v2-simulation
|
2412d505381334b52048aefd44752109a6b0dc73
|
[
"MIT"
] | null | null | null | 27.5 | 114 | 0.682051 | 2,329 |
package qasino.simulation.qasino.pipeline;
import org.apache.jena.atlas.io.IndentedWriter;
import org.apache.jena.shared.PrefixMapping;
import org.apache.jena.sparql.core.Var;
import org.apache.jena.sparql.engine.ExecutionContext;
import org.apache.jena.sparql.engine.QueryIterator;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.serializer.SerializationContext;
import java.util.ArrayList;
import java.util.List;
public class SymmetricHashJoin implements QueryIteratorPlus {
private Var joinKey;
private UnionIterator source;
private HashJoinTable leftTable;
private HashJoinTable rightTable;
private List<Var> vars;
public SymmetricHashJoin(Var joinKey, QueryIteratorPlus left, QueryIteratorPlus right, ExecutionContext cxt) {
this.joinKey = joinKey;
leftTable = new HashJoinTable();
rightTable = new HashJoinTable();
QueryIterator leftOp = new HalfHashJoin(joinKey, left, leftTable, rightTable, cxt);
QueryIterator rightOp = new HalfHashJoin(joinKey, right, rightTable, leftTable, cxt);
source = new UnionIterator(leftOp, rightOp);
vars = new ArrayList<>();
vars.addAll(left.getVars());
vars.addAll(right.getVars());
}
@Override
public List<Var> getVars() {
return vars;
}
@Override
public void output(IndentedWriter out, SerializationContext sCxt) {
source.output(out, sCxt);
}
@Override
public String toString(PrefixMapping pmap) {
return "SymmetricHashJoin(" + source.toString(pmap) + ")";
}
@Override
public Binding nextBinding() {
return source.next();
}
@Override
public void cancel() {
// we cannot cancel a streaming pipeline
}
@Override
public boolean hasNext() {
return source.hasNext();
}
@Override
public Binding next() {
return this.nextBinding();
}
@Override
public void output(IndentedWriter out) {
source.output(out);
}
@Override
public void close() {
// we cannot close a streaming pipeline
}
}
|
3e058cc880244e3d4ebb88f4fd707d130d8cf3eb
| 9,644 |
java
|
Java
|
src/main/java/edu/unc/cs/robotics/math/GeomXf.java
|
jeffi/math
|
aae1e627ba37f70226159ce6bcc5cd65a4f2da58
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/edu/unc/cs/robotics/math/GeomXf.java
|
jeffi/math
|
aae1e627ba37f70226159ce6bcc5cd65a4f2da58
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/edu/unc/cs/robotics/math/GeomXf.java
|
jeffi/math
|
aae1e627ba37f70226159ce6bcc5cd65a4f2da58
|
[
"BSD-2-Clause"
] | null | null | null | 27.953623 | 102 | 0.369971 | 2,330 |
// Automatically generated from GeomXd.java, DO NOT EDIT!
package edu.unc.cs.robotics.math;
/**
* Geometry methods that work for arbitrary dimensions (or at least 2 and 3),
* and operate on float[]. This should be deprecated.
*/
public final class GeomXf {
public static final float EPSILON = 1e-6f;
private GeomXf() {
throw new AssertionError("no instances");
}
/**
* Compute the time of CPA for two "tracks"
*
* <p>source: http://geomalgorithms.com/a07-_distance.html</p>
*
* <p>Track 1 starts at p1 and has velocity v1</p>
* <p>Track 2 starts at p2 and has velocity v2</p>
*/
public static float cpaTime(float[] p1, float[] v1,
float[] p2, float[] v2)
{
// t_cpa = -w_0 * (u - v) / |u - v|^2
// w_0 = P_0 - Q_0
float dv2 = 0;
float dot = 0;
for (int i = p1.length ; --i >= 0 ; ) {
final float dvi = v1[i] - v2[i];
dv2 += dvi*dvi;
final float w0i = p2[i] - p1[i];
dot += w0i*dvi;
}
return dv2 < EPSILON ? 0 : dot/dv2;
}
static class DistSegmentSegment {
final int dim;
float[] u;
float[] v;
float[] w;
DistSegmentSegment(int dim) {
this.dim = dim;
u = new float[dim];
v = new float[dim];
w = new float[dim];
}
float compute(float[] s1p0, float[] s1p1,
float[] s2p0, float[] s2p1)
{
FloatArrays.sub(u, s1p1, s1p0);
FloatArrays.sub(v, s2p1, s2p0);
FloatArrays.sub(w, s1p0, s2p0);
float a = FloatArrays.dot(u, u);
float b = FloatArrays.dot(u, v);
float c = FloatArrays.dot(v, v);
float d = FloatArrays.dot(u, w);
float e = FloatArrays.dot(v, w);
float D = a*c - b*b;
float sD = D;
float tD = D;
float sN, tN;
if (D < 1e-9f) {
sN = 0.0f;
sD = 1.0f;
tN = e;
tD = c;
} else {
sN = (b*e - c*d);
tN = (a*e - b*d);
if (sN < 0) {
sN = 0;
tN = e;
tD = c;
} else if (sN > sD) {
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0) {
tN = 0;
if (-d < 0) {
sN = 0;
} else if (-d > a) {
sN = sD;
} else {
sN = -d;
sD = a;
}
} else if (tN > tD) {
tN = tD;
if ((-d + b) < 0.0f) {
sN = 0;
} else if ((-d + b) > a) {
sN = sD;
} else {
sN = (-d + b);
sD = a;
}
}
float sc = (Math.abs(sN) < 1e-9f ? 0.0f : sN / sD);
float tc = (Math.abs(tN) < 1e-9f ? 0.0f : tN / tD);
float sum = 0;
for (int i=0 ; i<dim ; ++i) {
float dPi = w[i] + sc * u[i] - tc * v[i];
sum += dPi*dPi;
}
return (float)Math.sqrt(sum);
}
}
public static float distPointSegment(float[] pt, float[] s0, float[] s1) {
final int dim = pt.length;
float[] v = new float[dim];
FloatArrays.sub(v, s1, s0);
float[] w = new float[dim];
FloatArrays.sub(w, pt, s0);
float c1 = FloatArrays.dot(w, v);
float c2;
if (c1 <= 0) {
return FloatArrays.length(w);
} else if ((c2 = FloatArrays.dot(v, v)) <= c1) {
return FloatArrays.dist(pt, s1);
} else {
float b = c1 / c2;
float sum = 0;
for (int i = dim; --i >= 0; ) {
float di = s0[i] + v[i] * b - pt[i];
sum += di * di;
}
return (float)Math.sqrt(sum);
}
}
/**
* Computes the distance between a point and a line segment.
*
* @param pt the point
* @param s0 endpoint of line segment
* @param s1 endpoint of line segment
* @param nearest on return contains the point on the segment nearest to pt.
* @return the distance between nearest and pt.
*/
public static float distPointSegmentSquared(float[] pt, float[] s0, float[] s1, float[] nearest) {
final int dim = pt.length;
float c1 = 0;
float c2 = 0;
// float ww = 0;
for (int i=dim ; --i >= 0 ; ) {
float vi = s1[i] - s0[i];
float wi = pt[i] - s0[i];
c1 += vi * wi;
c2 += vi * vi;
// ww += wi * wi;
// borrow nearest for temporary storage.
nearest[i] = vi;
}
if (c1 <= 0) {
System.arraycopy(s0, 0, nearest, 0, dim);
return FloatArrays.distSquared(pt, s0);
}
if (c2 <= c1) {
System.arraycopy(s1, 0, nearest, 0, dim);
return FloatArrays.distSquared(pt, s1);
}
float b = c1 / c2;
float sum = 0;
for (int i=dim ; --i >= 0 ; ) {
nearest[i] = s0[i] + nearest[i] * b;
float di = nearest[i] - pt[i];
sum += di*di;
}
return sum;
}
public static float distSegmentSegment(
float[] s1p0, float[] s1p1,
float[] s2p0, float[] s2p1)
{
final int dim = s1p0.length;
float[] u = new float[dim];
float[] v = new float[dim];
float[] w = new float[dim];
FloatArrays.sub(u, s1p1, s1p0);
FloatArrays.sub(v, s2p1, s2p0);
FloatArrays.sub(w, s1p0, s2p0);
float a = FloatArrays.dot(u, u);
float b = FloatArrays.dot(u, v);
float c = FloatArrays.dot(v, v);
float d = FloatArrays.dot(u, w);
float e = FloatArrays.dot(v, w);
float D = a*c - b*b;
float sD = D;
float tD = D;
float sN, tN;
if (D < 1e-9f) {
sN = 0.0f;
sD = 1.0f;
tN = e;
tD = c;
} else {
sN = (b*e - c*d);
tN = (a*e - b*d);
if (sN < 0) {
sN = 0;
tN = e;
tD = c;
} else if (sN > sD) {
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0) {
tN = 0;
if (-d < 0) {
sN = 0;
} else if (-d > a) {
sN = sD;
} else {
sN = -d;
sD = a;
}
} else if (tN > tD) {
tN = tD;
if ((-d + b) < 0.0f) {
sN = 0;
} else if ((-d + b) > a) {
sN = sD;
} else {
sN = (-d + b);
sD = a;
}
}
float sc = (Math.abs(sN) < 1e-9f ? 0.0f : sN / sD);
float tc = (Math.abs(tN) < 1e-9f ? 0.0f : tN / tD);
float sum = 0;
for (int i = 0; i< dim; ++i) {
float dPi = w[i] + sc * u[i] - tc * v[i];
sum += dPi*dPi;
}
return (float)Math.sqrt(sum);
}
// Prototype method, DO NOT DELETE
// This is the code before everything is inlined.
//
// public static float distSegmentSegment(
// Vec3f s1p0, Vec3f s1p1,
// Vec3f s2p0, Vec3f s2p1)
// {
// // http://geomalgorithms.com/a07-_distance.html
// Vec3f u = new Vec3f().sub(s1p1, s1p0);
// Vec3f v = new Vec3f().sub(s2p1, s2p0);
// Vec3f w = new Vec3f().sub(s1p0, s2p0);
//
// float a = u.dot(u);
// float b = u.dot(v);
// float c = v.dot(v);
// float d = u.dot(w);
// float e = v.dot(w);
// float D = a*c - b*b;
// float sD = D;
// float tD = D;
//
// float sN, tN;
//
// if (D < 1e-6ff) {
// sN = 0.0ff;
// sD = 1.0ff;
// tN = e;
// tD = c;
// } else {
// sN = (b*e - c*d);
// tN = (a*e - b*d);
// if (sN < 0f) {
// sN = 0f;
// tN = e;
// tD = c;
// } else if (sN > sD) {
// sN = sD;
// tN = e + b;
// tD = c;
// }
// }
//
// if (tN < 0f) {
// tN = 0f;
// if (-d < 0f) {
// sN = 0f;
// } else if (-d > a) {
// sN = sD;
// } else {
// sN = -d;
// sD = a;
// }
// } else if (tN > tD) {
// tN = tD;
// if ((-d + b) < 0.0ff) {
// sN = 0f;
// } else if ((-d + b) > a) {
// sN = sD;
// } else {
// sN = (-d + b);
// sD = a;
// }
// }
//
// float sc = (Math.abs(sN) < 1e-6ff ? 0.0ff : sN / sD);
// float tc = (Math.abs(tN) < 1e-6ff ? 0.0ff : tN / tD);
//
// // dP = w + (sc * u) - (tc * v);
// float dPx = w.x + sc * u.x - tc * v.x;
// float dPy = w.y + sc * u.y - tc * v.y;
// float dPz = w.z + sc * u.z - tc * v.z;
//
// return (float)(float)Math.sqrt(dPx*dPx + dPy*dPy + dPz*dPz);
// }
}
|
3e058d9aba71ce6231f19a07e5d5df2468bf8186
| 733 |
java
|
Java
|
src/main/java/tridios/gd/models/Foo.java
|
gdongus/tridios.github.io
|
97d9b22fcd8683b48972fd84db045208f88e7269
|
[
"MIT"
] | null | null | null |
src/main/java/tridios/gd/models/Foo.java
|
gdongus/tridios.github.io
|
97d9b22fcd8683b48972fd84db045208f88e7269
|
[
"MIT"
] | null | null | null |
src/main/java/tridios/gd/models/Foo.java
|
gdongus/tridios.github.io
|
97d9b22fcd8683b48972fd84db045208f88e7269
|
[
"MIT"
] | null | null | null | 17.046512 | 58 | 0.628922 | 2,331 |
package tridios.gd.models;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
@Entity
public class Foo {
@Id
@GeneratedValue
private Long id;
private String name;
@JsonBackReference
@OneToOne(cascade = CascadeType.PERSIST)
private BaseModel baseModel;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BaseModel getBaseModel() {
return baseModel;
}
public void setBaseModel(BaseModel baseModel) {
this.baseModel = baseModel;
}
}
|
3e058e2a515073baadda112d6da5a0a88e2513c6
| 2,186 |
java
|
Java
|
source/SS1/management/Student_Management.java
|
vuthanhtrung0504/CourseManApp
|
2fddcbf38a6513131a5a600c394c59f305ddb251
|
[
"MIT"
] | null | null | null |
source/SS1/management/Student_Management.java
|
vuthanhtrung0504/CourseManApp
|
2fddcbf38a6513131a5a600c394c59f305ddb251
|
[
"MIT"
] | null | null | null |
source/SS1/management/Student_Management.java
|
vuthanhtrung0504/CourseManApp
|
2fddcbf38a6513131a5a600c394c59f305ddb251
|
[
"MIT"
] | null | null | null | 33.630769 | 86 | 0.417658 | 2,332 |
package SS1.management;
import utils.TextIO;
public class Student_Management extends Management {
final String tableName="student";
final String fileName="students";
/**
* Student menu
*/
public void menuStudent(){
try {
int select;
while (true) {
TextIO.putln("---------------- STUDENTS MANAGE MENU ----------------");
TextIO.putln("1. Add a new student");
TextIO.putln("2. Edit information of an existing student");
TextIO.putln("3. Delete a student");
TextIO.putln("4. Display a list of all students to HTML");
TextIO.putln("5. Display a list of all students to console");
TextIO.putln("6. Display a list of all students to TXT");
TextIO.putln("7. Back to management menu");
TextIO.putln("0. Exit");
TextIO.put("Your choice is: ");
select = TextIO.getlnInt();
switch (select) {
case 1:
this.addRow(tableName);
break;
case 2:
this.editRow(tableName);
break;
case 3:
this.deleteRow(tableName);
break;
case 4:
this.writeToHTML(this.displayAll(tableName), fileName);
break;
case 5:
this.displayConsole(tableName);
break;
case 6:
this.writeToTXT(tableName);
break;
case 7:
this.menuManagement();
break;
case 0:
System.exit(0);
break;
default:
TextIO.putln("Invalid input. Please enter again.\n");
this.menuStudent();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e058e43687c36883437f1675ff93fd2c4fc6bc1
| 2,910 |
java
|
Java
|
org.jhotdraw8.draw/src/main/java/org.jhotdraw8.draw/org/jhotdraw8/draw/handle/PathIterableOutlineHandle.java
|
simplysuvi/jhotdraw8
|
8867b019b6cd408fb933f09008d89e5a43960c4a
|
[
"MIT"
] | null | null | null |
org.jhotdraw8.draw/src/main/java/org.jhotdraw8.draw/org/jhotdraw8/draw/handle/PathIterableOutlineHandle.java
|
simplysuvi/jhotdraw8
|
8867b019b6cd408fb933f09008d89e5a43960c4a
|
[
"MIT"
] | null | null | null |
org.jhotdraw8.draw/src/main/java/org.jhotdraw8.draw/org/jhotdraw8/draw/handle/PathIterableOutlineHandle.java
|
simplysuvi/jhotdraw8
|
8867b019b6cd408fb933f09008d89e5a43960c4a
|
[
"MIT"
] | 2 |
2022-02-28T02:16:35.000Z
|
2022-03-19T23:38:29.000Z
| 30 | 105 | 0.708591 | 2,333 |
/*
* @(#)PathIterableOutlineHandle.java
* Copyright © 2021 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.draw.handle;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Path;
import javafx.scene.shape.PathElement;
import javafx.scene.transform.Transform;
import org.jhotdraw8.annotation.NonNull;
import org.jhotdraw8.annotation.Nullable;
import org.jhotdraw8.css.CssColor;
import org.jhotdraw8.css.Paintable;
import org.jhotdraw8.draw.DrawingView;
import org.jhotdraw8.draw.figure.PathIterableFigure;
import org.jhotdraw8.geom.FXPathElementsBuilder;
import org.jhotdraw8.geom.FXShapes;
import org.jhotdraw8.geom.FXTransforms;
import org.jhotdraw8.geom.SvgPaths;
import java.util.ArrayList;
import java.util.List;
/**
* Draws an outline of the path of a {@link PathIterableFigure}.
*
* @author Werner Randelshofer
*/
public class PathIterableOutlineHandle extends AbstractHandle {
private final @NonNull Group node;
private final @NonNull Path path2;
private final @NonNull Path path1;
private final boolean selectable;
public PathIterableOutlineHandle(PathIterableFigure figure, boolean selectable) {
super(figure);
node = new Group();
path2 = new Path();
path1 = new Path();
node.getChildren().addAll(path1, path2);
this.selectable = selectable;
}
@Override
public boolean contains(DrawingView dv, double x, double y, double tolerance) {
return false;
}
@Override
public @Nullable Cursor getCursor() {
return null;
}
@Override
public @NonNull Node getNode(@NonNull DrawingView view) {
CssColor color = view.getEditor().getHandleColor();
path1.setStroke(Color.WHITE);
path2.setStroke(Paintable.getPaint(color));
double strokeWidth = view.getEditor().getHandleStrokeWidth();
path1.setStrokeWidth(strokeWidth + 2);
path2.setStrokeWidth(strokeWidth);
return node;
}
@Override
public boolean isEditable() {
return false;
}
@Override
public boolean isSelectable() {
return selectable;
}
@Override
public @NonNull PathIterableFigure getOwner() {
return (PathIterableFigure) super.getOwner();
}
@Override
public void updateNode(@NonNull DrawingView view) {
PathIterableFigure f = getOwner();
Transform t = FXTransforms.concat(view.getWorldToView(), f.getLocalToWorld());
List<PathElement> elements = new ArrayList<>();
FXPathElementsBuilder builder = new FXPathElementsBuilder(elements);
SvgPaths.buildFromPathIterator(builder, f.getPathIterator(view, FXShapes.awtTransformFromFX(t)));
path1.getElements().setAll(elements);
path2.getElements().setAll(elements);
}
}
|
3e058ebe825b6d127ef36ceca726c959a6def8fb
| 5,020 |
java
|
Java
|
src/main/java/frc/robot/subsystems/Shooter.java
|
robbiesylvia/Shooter-Prototype-Testing
|
a66044d547e5e6ba36ee9bf34e5af18e8bda6406
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/frc/robot/subsystems/Shooter.java
|
robbiesylvia/Shooter-Prototype-Testing
|
a66044d547e5e6ba36ee9bf34e5af18e8bda6406
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/frc/robot/subsystems/Shooter.java
|
robbiesylvia/Shooter-Prototype-Testing
|
a66044d547e5e6ba36ee9bf34e5af18e8bda6406
|
[
"BSD-3-Clause"
] | 1 |
2021-03-21T23:27:49.000Z
|
2021-03-21T23:27:49.000Z
| 34.62069 | 190 | 0.765936 | 2,334 |
package frc.robot.subsystems;
//import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import edu.wpi.first.wpilibj.AnalogPotentiometer;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.SupplyCurrentLimitConfiguration;
import com.ctre.phoenix.motorcontrol.TalonFXControlMode;
import com.ctre.phoenix.motorcontrol.can.TalonFX;
import com.ctre.phoenix.motorcontrol.TalonFXFeedbackDevice;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import com.revrobotics.ControlType;
import edu.wpi.first.wpilibj.controller.PIDController;
//manually change the targetVoltage in Constants.java
public class Shooter extends SubsystemBase {
public final TalonFX firstMotor;
public final TalonFX secondMotor;
public final CANSparkMax hoodMotor;
public PIDController hoodPIDController;
public Shooter(){
firstMotor = new TalonFX(Constants.talonFirstChannel);
secondMotor = new TalonFX(Constants.talonSecondChannel);
//configuring TalonFX motors
/* Factory Default all hardware to prevent unexpected behaviour */
firstMotor.configFactoryDefault();
/* Config neutral deadband to be the smallest possible */
firstMotor.configNeutralDeadband(0.001);
firstMotor.configSelectedFeedbackSensor(TalonFXFeedbackDevice.IntegratedSensor, Constants.kPIDLoopIdx, Constants.kTimeoutMs);
firstMotor.config_kF(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kF, Constants.kTimeoutMs);
firstMotor.config_kP(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kP, Constants.kTimeoutMs);
firstMotor.config_kI(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kI, Constants.kTimeoutMs);
firstMotor.config_kD(Constants.kPIDLoopIdx, Constants.kGains_Velocit.kD, Constants.kTimeoutMs);
firstMotor.configNominalOutputForward(0, 20);
firstMotor.configNominalOutputReverse(0, 20);
firstMotor.configPeakOutputForward(1, 20);
firstMotor.configPeakOutputReverse(-1, 20);
firstMotor.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration(true, 20, 10, 0.5));
secondMotor.follow(firstMotor);
secondMotor.setInverted(true);
// canSparkMAX for controlling hood angle
hoodMotor = new CANSparkMax(Constants.deviceIDCANSparkMax, CANSparkMaxLowLevel.MotorType.kBrushless);
//intializing + configuring hoodPIDController
hoodPIDController = new PIDController(Constants.kP, Constants.kI, Constants.kD);
}
public AnalogPotentiometer potentiometer = new AnalogPotentiometer(Constants.hoodAnglePotentiometerAnalogInputID, Constants.upperBoundPotentiometer - Constants.lowerBoundPotentiometer, 0);
public double getPotentiometerAngle(){
return potentiometer.get(); //* (Constants.upperBoundPotentiometer - Constants.lowerBoundPotentiometer) + Constants.lowerBoundPotentiometer;
}
//setAngle should be called periodically in order for PID control to occur
public void setAngle(double targetAngle){
hoodPIDController.setSetpoint(targetAngle);
double hoodMotorSpeed = hoodPIDController.calculate(getPotentiometerAngle());
//hoodMotor should not exceed 10% output, so this prevents it from exceeding 8% (to be safe)
if (hoodMotorSpeed > 0.08 || hoodMotorSpeed < -0.08) {
if(hoodMotorSpeed > 0) {
hoodMotorSpeed = 0.08;
}else{
hoodMotorSpeed = -0.08;
}
}
hoodMotor.set(hoodMotorSpeed);
if(calculateAngleError() < 1.5){
hoodMotor.disable();
}
}
public double calculateAngleError(){
return(Math.abs(hoodPIDController.getSetpoint() - getPotentiometerAngle()));
}
/*targetVelocity is in units/100ms and the integrated encoder is based on 2048 units/revolution, so to convert from targetRPM to targetVelocity,
*(targetRPM) / ((100ms per 1 second = 10) (sec per min = 60))
*/
//factor in gear ratio? (with wheels) ~*~
double currentSensorVelocity;
double currentSetPoint;
//targetVelocity is in pulses/100 ms (as opposed to 2048 pulses/revoluion)a
// cert statement could function as a failsafe if necessary
public void setRPM (double targetRPM){
double targetVelocity = (targetRPM * 2048) / 600;
currentSetPoint = targetRPM;
System.out.println("Target Velocity:" + targetVelocity);
firstMotor.set(TalonFXControlMode.Velocity, targetVelocity);
}
/* Configured for Velocity Closed Loop on Integrated Sensors' Sum and Arbitrary FeedForward on joyX */
/* Uncomment to view RPM in Driver Station */
// double actual_RPM = (_rightMaster.getSelectedSensorVelocity() / (double)Constants.kSensorUnitsPerRotation * 600f);
// System.out.println("Vel[RPM]: " + actual_RPM + " Pos: " + _rightMaster.getSelectedSensorPosition());
public void increaseRPM (int increment){
setRPM(currentSetPoint + increment);
}
public void decreaseRPM (int decrement){
setRPM(currentSetPoint - decrement);
}
}
|
3e058ed7593dc90f993174e478a8c4b3f44a2235
| 1,989 |
java
|
Java
|
java110-bean/src/main/java/com/java110/dto/product/ProductCategoryDto.java
|
2669430363/MicroCommunity
|
f7cdc8cc9b1d092403abf18239cdc88fa9c3522d
|
[
"Apache-2.0"
] | 711 |
2017-04-09T15:59:16.000Z
|
2022-03-27T07:19:02.000Z
|
java110-bean/src/main/java/com/java110/dto/product/ProductCategoryDto.java
|
yasudarui/MicroCommunity
|
1026aa5eaa86446aedfdefd092a3d6fcf0dfe470
|
[
"Apache-2.0"
] | 16 |
2017-04-09T16:13:09.000Z
|
2022-01-04T16:36:13.000Z
|
java110-bean/src/main/java/com/java110/dto/product/ProductCategoryDto.java
|
yasudarui/MicroCommunity
|
1026aa5eaa86446aedfdefd092a3d6fcf0dfe470
|
[
"Apache-2.0"
] | 334 |
2017-04-16T05:01:12.000Z
|
2022-03-30T00:49:37.000Z
| 21.857143 | 73 | 0.67823 | 2,335 |
package com.java110.dto.product;
import com.java110.dto.PageDto;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName FloorDto
* @Description 产品目录数据层封装
* @Author wuxw
* @Date 2019/4/24 8:52
* @Version 1.0
* add by wuxw 2019/4/24
**/
public class ProductCategoryDto extends PageDto implements Serializable {
private String categoryLevel;
private String parentCategoryId;
private String storeId;
private String categoryName;
private String categoryId;
private String seq;
private String isShow;
private Date createTime;
private String statusCd = "0";
public String getCategoryLevel() {
return categoryLevel;
}
public void setCategoryLevel(String categoryLevel) {
this.categoryLevel = categoryLevel;
}
public String getParentCategoryId() {
return parentCategoryId;
}
public void setParentCategoryId(String parentCategoryId) {
this.parentCategoryId = parentCategoryId;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getIsShow() {
return isShow;
}
public void setIsShow(String isShow) {
this.isShow = isShow;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatusCd() {
return statusCd;
}
public void setStatusCd(String statusCd) {
this.statusCd = statusCd;
}
}
|
3e058fbc7b424cc575a0e495eb507f3c09952a0b
| 316 |
java
|
Java
|
design-principles/src/main/java/com/nsc/designprinciples/openclosed/tax/FullTimeTaxCalculator.java
|
pratapgowda007/computer-fundamentals
|
d655483b352f2172a7eae7ee1edb19dbd4262e7f
|
[
"MIT"
] | null | null | null |
design-principles/src/main/java/com/nsc/designprinciples/openclosed/tax/FullTimeTaxCalculator.java
|
pratapgowda007/computer-fundamentals
|
d655483b352f2172a7eae7ee1edb19dbd4262e7f
|
[
"MIT"
] | null | null | null |
design-principles/src/main/java/com/nsc/designprinciples/openclosed/tax/FullTimeTaxCalculator.java
|
pratapgowda007/computer-fundamentals
|
d655483b352f2172a7eae7ee1edb19dbd4262e7f
|
[
"MIT"
] | null | null | null | 26.333333 | 62 | 0.753165 | 2,336 |
package com.nsc.designprinciples.openclosed.tax;
import com.nsc.designprinciples.singleresponsibility.Employee;
public class FullTimeTaxCalculator implements TaxCalculator {
@Override
public double calculate(Employee employee) {
System.out.println("calculating FTE tax");
return 0;
}
}
|
3e0590a845b14b703010edcc5f0b3a720560385d
| 2,843 |
java
|
Java
|
core/src/main/java/org/streameps/core/comparator/IAttributeValueEntry.java
|
fanhubgt/StreamEPS
|
ea8f9cd03755315e34301a50fdbfe9a30b59077f
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
core/src/main/java/org/streameps/core/comparator/IAttributeValueEntry.java
|
fanhubgt/StreamEPS
|
ea8f9cd03755315e34301a50fdbfe9a30b59077f
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
core/src/main/java/org/streameps/core/comparator/IAttributeValueEntry.java
|
fanhubgt/StreamEPS
|
ea8f9cd03755315e34301a50fdbfe9a30b59077f
|
[
"BSD-3-Clause-Clear"
] | null | null | null | 36.448718 | 86 | 0.672529 | 2,337 |
/*
* ====================================================================
* StreamEPS Platform
*
* (C) Copyright 2011.
*
* Distributed under the Modified BSD License.
* Copyright notice: The copyright for this software and a full listing
* of individual contributors are as shown in the packaged copyright.txt
* file.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the ORGANIZATION nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* =============================================================================
*/
package org.streameps.core.comparator;
/**
*
* @author Frank Appiah
*/
public interface IAttributeValueEntry<E> extends Comparable<IAttributeValueEntry<E>> {
/**
* It returns the event instance.
* @return An event instance.
*/
public E getEvent();
/**
* It returns the name of the attribute value entry.
* @return A name for the attribute value entry.
*/
public String getName();
/**
* It returns the value of an attribute from the event instance.
* @return value of the property.
*/
public Double getValue();
/**
* It sets the event instance.
* @param event event to set.
*/
public void setEvent(E event);
public void setName(String name);
/**
* It sets the value of the property.
* @param value value to set.
*/
public void setValue(Double value);
}
|
3e0590d679fcb10fb2667968c58fd2ed10045ace
| 235 |
java
|
Java
|
algoritmos-matematicos/Potenciacao.java
|
brunocampos01/introducao_a_POO_1_fase
|
df6637823dcf7c301eb363ff181c696ac019a3a4
|
[
"MIT"
] | 6 |
2018-09-20T02:41:49.000Z
|
2019-11-10T21:26:35.000Z
|
algoritmos-matematicos/Potenciacao.java
|
brunocampos01/introducao_a_POO_1_fase
|
df6637823dcf7c301eb363ff181c696ac019a3a4
|
[
"MIT"
] | null | null | null |
algoritmos-matematicos/Potenciacao.java
|
brunocampos01/introducao_a_POO_1_fase
|
df6637823dcf7c301eb363ff181c696ac019a3a4
|
[
"MIT"
] | 2 |
2019-11-10T21:30:56.000Z
|
2019-12-13T00:37:43.000Z
| 18.076923 | 45 | 0.493617 | 2,338 |
public class Potenciacao {
public static void main(String[] args) {
// atributos
int a = 2;
int b = 5;
int elevado = (int) Math.pow(a, b);
System.out.println(elevado);
}
}
|
3e05919e95baa51b8ee81d29898270db644d96d8
| 9,918 |
java
|
Java
|
src/testcases/org/apache/tools/ant/taskdefs/JavaTest.java
|
wardat/apache-ant-1.6.2
|
8c38f36fb822c6b3867a14c4cff9d0fae29e1eab
|
[
"W3C-19980720",
"Apache-2.0"
] | null | null | null |
src/testcases/org/apache/tools/ant/taskdefs/JavaTest.java
|
wardat/apache-ant-1.6.2
|
8c38f36fb822c6b3867a14c4cff9d0fae29e1eab
|
[
"W3C-19980720",
"Apache-2.0"
] | null | null | null |
src/testcases/org/apache/tools/ant/taskdefs/JavaTest.java
|
wardat/apache-ant-1.6.2
|
8c38f36fb822c6b3867a14c4cff9d0fae29e1eab
|
[
"W3C-19980720",
"Apache-2.0"
] | null | null | null | 30.801242 | 85 | 0.582275 | 2,339 |
/*
* Copyright 2001-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.taskdefs;
import junit.framework.*;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.TeeOutputStream;
/**
* stress out java task
* */
public class JavaTest extends BuildFileTest {
private static final int TIME_TO_WAIT = 1;
// wait 1 second extra to allow for java to start ...
// this time was OK on a Win NT machine and on nagoya
private static final int SECURITY_MARGIN = 2000;
private boolean runFatalTests=false;
public JavaTest(String name) {
super(name);
}
/**
* configure the project.
* if the property junit.run.fatal.tests is set we run
* the fatal tests
*/
public void setUp() {
configureProject("src/etc/testcases/taskdefs/java.xml");
//final String propname="tests-classpath.value";
//String testClasspath=System.getProperty(propname);
//System.out.println("Test cp="+testClasspath);
String propname="tests-classpath.value";
String runFatal=System.getProperty("junit.run.fatal.tests");
if(runFatal!=null)
runFatalTests=true;
}
public void tearDown() {
// remove log file from testSpawn
project.executeTarget("cleanup");
}
public void testNoJarNoClassname(){
expectBuildExceptionContaining("testNoJarNoClassname",
"parameter validation",
"Classname must not be null.");
}
public void testJarNoFork() {
expectBuildExceptionContaining("testJarNoFork",
"parameter validation",
"Cannot execute a jar in non-forked mode. "
+ "Please set fork='true'. ");
}
public void testJarAndClassName() {
expectBuildException("testJarAndClassName",
"Should not be able to set both classname AND jar");
}
public void testClassnameAndJar() {
expectBuildException("testClassnameAndJar",
"Should not be able to set both classname AND jar");
}
public void testRun() {
executeTarget("testRun");
}
/** this test fails but we ignore the return value;
* we verify that failure only matters when failonerror is set
*/
public void testRunFail() {
if(runFatalTests) {
executeTarget("testRunFail");
}
}
public void testRunFailFoe() {
if(runFatalTests) {
expectBuildExceptionContaining("testRunFailFoe",
"java failures being propagated",
"Java returned:");
}
}
public void testRunFailFoeFork() {
expectBuildExceptionContaining("testRunFailFoeFork",
"java failures being propagated",
"Java returned:");
}
public void testExcepting() {
expectLogContaining("testExcepting",
"Exception raised inside called program");
}
public void testExceptingFork() {
expectLogContaining("testExceptingFork",
"Java Result:");
}
public void testExceptingFoe() {
expectBuildExceptionContaining("testExceptingFoe",
"passes exception through",
"Exception raised inside called program");
}
public void testExceptingFoeFork() {
expectBuildExceptionContaining("testExceptingFoeFork",
"exceptions turned into error codes",
"Java returned:");
}
public void testResultPropertyZero() {
executeTarget("testResultPropertyZero");
assertEquals("0",project.getProperty("exitcode"));
}
public void testResultPropertyNonZero() {
executeTarget("testResultPropertyNonZero");
assertEquals("2",project.getProperty("exitcode"));
}
public void testResultPropertyZeroNoFork() {
executeTarget("testResultPropertyZeroNoFork");
assertEquals("0",project.getProperty("exitcode"));
}
public void testResultPropertyNonZeroNoFork() {
executeTarget("testResultPropertyNonZeroNoFork");
assertEquals("-1",project.getProperty("exitcode"));
}
public void testRunFailWithFailOnError() {
expectBuildExceptionContaining("testRunFailWithFailOnError",
"non zero return code",
"Java returned:");
}
public void testRunSuccessWithFailOnError() {
executeTarget("testRunSuccessWithFailOnError");
}
public void testSpawn() {
FileUtils fileutils = FileUtils.newFileUtils();
File logFile = fileutils.createTempFile("spawn","log", project.getBaseDir());
// this is guaranteed by FileUtils#createTempFile
assertTrue("log file not existing", !logFile.exists());
project.setProperty("logFile", logFile.getAbsolutePath());
project.setProperty("timeToWait", Long.toString(TIME_TO_WAIT));
project.executeTarget("testSpawn");
try {
Thread.sleep(TIME_TO_WAIT * 1000 + SECURITY_MARGIN);
} catch (Exception ex) {
System.out.println("my sleep was interrupted");
}
// let's be nice with the next generation of developers
if (!logFile.exists()) {
System.out.println("suggestion: increase the constant"
+ " SECURITY_MARGIN to give more time for java to start.");
}
assertTrue("log file exists", logFile.exists());
}
public void testRedirect1() {
executeTarget("redirect1");
}
public void testRedirect2() {
executeTarget("redirect2");
}
public void testRedirect3() {
executeTarget("redirect3");
}
public void testRedirector1() {
executeTarget("redirector1");
}
public void testRedirector2() {
executeTarget("redirector2");
}
/**
* entry point class with no dependencies other
* than normal JRE runtime
*/
public static class EntryPoint {
/**
* this entry point is used by the java.xml tests to
* generate failure strings to handle
* argv[0] = exit code (optional)
* argv[1] = string to print to System.out (optional)
* argv[1] = string to print to System.err (optional)
*/
public static void main(String[] argv) {
int exitCode=0;
if(argv.length>0) {
try {
exitCode=Integer.parseInt(argv[0]);
} catch(NumberFormatException nfe) {
exitCode=-1;
}
}
if(argv.length>1) {
System.out.println(argv[1]);
}
if(argv.length>2) {
System.err.println(argv[2]);
}
if(exitCode!=0) {
System.exit(exitCode);
}
}
}
/**
* entry point class with no dependencies other
* than normal JRE runtime
*/
public static class ExceptingEntryPoint {
/**
* throw a run time exception which does not need
* to be in the signature of the entry point
*/
public static void main(String[] argv) {
throw new NullPointerException("Exception raised inside called program");
}
}
/**
* test class for spawn
*/
public static class SpawnEntryPoint {
public static void main(String [] argv) {
int sleepTime = 10;
String logFile = "spawn.log";
if (argv.length >= 1) {
sleepTime = Integer.parseInt(argv[0]);
}
if (argv.length >= 2)
{
logFile = argv[1];
}
OutputStreamWriter out = null;
try {
Thread.sleep(sleepTime * 1000);
} catch (InterruptedException ex) {
System.out.println("my sleep was interrupted");
}
try {
File dest = new File(logFile);
FileOutputStream fos = new FileOutputStream(dest);
out = new OutputStreamWriter(fos);
out.write("bye bye\n");
} catch (Exception ex) {}
finally {
try {out.close();} catch (IOException ioe) {}}
}
}
/**
* entry point class to pipe System.in to the specified stream:
* "out", "err", or "both". If none specified, swallow the input.
*/
public static class PipeEntryPoint {
/**
* pipe input to specified output
*/
public static void main(String[] args) {
OutputStream os = null;
if (args.length > 0) {
if ("out".equalsIgnoreCase(args[0])) {
os = System.out;
} else if ("err".equalsIgnoreCase(args[0])) {
os = System.err;
} else if ("both".equalsIgnoreCase(args[0])) {
os = new TeeOutputStream(System.out, System.err);
}
}
if (os != null) {
Thread t = new Thread(new StreamPumper(System.in, os, true));
t.start();
try {
t.join();
} catch (InterruptedException eyeEx) {
}
}
}
}
}
|
3e0591b303791f4a39ec76d61852a3919d767526
| 1,045 |
java
|
Java
|
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/core/authentication/PrincipalTransformationProperties.java
|
ConnCollege/CAS-5-FS
|
c1c6598c561f66548034d6e30bfc2e2127cdfb85
|
[
"Apache-2.0"
] | null | null | null |
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/core/authentication/PrincipalTransformationProperties.java
|
ConnCollege/CAS-5-FS
|
c1c6598c561f66548034d6e30bfc2e2127cdfb85
|
[
"Apache-2.0"
] | null | null | null |
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/core/authentication/PrincipalTransformationProperties.java
|
ConnCollege/CAS-5-FS
|
c1c6598c561f66548034d6e30bfc2e2127cdfb85
|
[
"Apache-2.0"
] | 1 |
2021-09-25T22:25:20.000Z
|
2021-09-25T22:25:20.000Z
| 21.770833 | 72 | 0.644019 | 2,340 |
package org.apereo.cas.configuration.model.core.authentication;
/**
* This is {@link PrincipalTransformationProperties}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class PrincipalTransformationProperties {
public enum CaseConversion {
/** No conversion. */
NONE,
/** Lowercase conversion. */
UPPERCASE,
/** Uppcase conversion. */
LOWERCASE,
}
private String prefix;
private String suffix;
private CaseConversion caseConversion = CaseConversion.NONE;
public String getPrefix() {
return prefix;
}
public void setPrefix(final String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(final String suffix) {
this.suffix = suffix;
}
public CaseConversion getCaseConversion() {
return caseConversion;
}
public void setCaseConversion(final CaseConversion caseConversion) {
this.caseConversion = caseConversion;
}
}
|
3e0591f90afccb5c4a74bdf40f07a0e8ffa0edc5
| 16,390 |
java
|
Java
|
server/src/test-fast/java/com/thoughtworks/go/config/update/UpdateTemplateConfigCommandTest.java
|
java-app-scans/gocd
|
9477487e74f86c4b54563d8ee7786a8205ebfc97
|
[
"Apache-2.0"
] | 5,865 |
2015-01-02T04:24:52.000Z
|
2022-03-31T11:00:46.000Z
|
server/src/test-fast/java/com/thoughtworks/go/config/update/UpdateTemplateConfigCommandTest.java
|
java-app-scans/gocd
|
9477487e74f86c4b54563d8ee7786a8205ebfc97
|
[
"Apache-2.0"
] | 5,972 |
2015-01-02T10:20:42.000Z
|
2022-03-31T20:17:09.000Z
|
server/src/test-fast/java/com/thoughtworks/go/config/update/UpdateTemplateConfigCommandTest.java
|
java-app-scans/gocd
|
9477487e74f86c4b54563d8ee7786a8205ebfc97
|
[
"Apache-2.0"
] | 998 |
2015-01-01T18:02:09.000Z
|
2022-03-28T21:20:50.000Z
| 58.120567 | 261 | 0.757535 | 2,341 |
/*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.config.update;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.exceptions.EntityType;
import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
import com.thoughtworks.go.helper.*;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.EntityHashingService;
import com.thoughtworks.go.server.service.ExternalArtifactsService;
import com.thoughtworks.go.server.service.SecurityService;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class UpdateTemplateConfigCommandTest {
@Mock
private EntityHashingService entityHashingService;
@Mock
private ExternalArtifactsService externalArtifactsService;
@Mock
private SecurityService securityService;
private HttpLocalizedOperationResult result;
private Username currentUser;
private BasicCruiseConfig cruiseConfig;
private PipelineTemplateConfig pipelineTemplateConfig;
private Authorization authorization;
@BeforeEach
void setup() {
currentUser = new Username(new CaseInsensitiveString("user"));
cruiseConfig = new GoConfigMother().defaultCruiseConfig();
result = new HttpLocalizedOperationResult();
pipelineTemplateConfig = new PipelineTemplateConfig(new CaseInsensitiveString("template"), StageConfigMother.oneBuildPlanWithResourcesAndMaterials("stage", "job"));
authorization = new Authorization(new AdminsConfig(new AdminUser(new CaseInsensitiveString("user"))));
pipelineTemplateConfig.setAuthorization(authorization);
}
@Test
void shouldUpdateExistingTemplate() {
PipelineTemplateConfig updatedTemplateConfig = new PipelineTemplateConfig(new CaseInsensitiveString("template"), StageConfigMother.oneBuildPlanWithResourcesAndMaterials("stage", "job"), StageConfigMother.oneBuildPlanWithResourcesAndMaterials("stage2"));
cruiseConfig.addTemplate(pipelineTemplateConfig);
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(updatedTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThat(cruiseConfig.getTemplates().contains(pipelineTemplateConfig)).isTrue();
command.update(cruiseConfig);
assertThat(cruiseConfig.getTemplates().contains(pipelineTemplateConfig)).isFalse();
assertThat(cruiseConfig.getTemplates().contains(updatedTemplateConfig)).isTrue();
}
@Test
void shouldAllowSubmittingInvalidElasticProfileId() {
PipelineTemplateConfig updatedTemplateConfig = new PipelineTemplateConfig(new CaseInsensitiveString("template"), StageConfigMother.stageConfig("stage", new JobConfigs(new JobConfig("job"))));
JobConfig jobConfig = updatedTemplateConfig.findBy(new CaseInsensitiveString("stage")).jobConfigByConfigName(new CaseInsensitiveString("job"));
jobConfig.addTask(new AntTask());
jobConfig.setElasticProfileId("invalidElasticProfileId");
cruiseConfig.addTemplate(pipelineTemplateConfig);
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(updatedTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThat(cruiseConfig.getTemplates().contains(pipelineTemplateConfig)).isTrue();
command.update(cruiseConfig);
assertThat(command.isValid(cruiseConfig)).isTrue();
assertThat(cruiseConfig.getTemplates().contains(pipelineTemplateConfig)).isFalse();
assertThat(cruiseConfig.getTemplates().contains(updatedTemplateConfig)).isTrue();
}
@Test
void shouldValidateElasticProfileIdWhenTemplateIsUsedInAPipeline() {
cruiseConfig.addTemplate(pipelineTemplateConfig);
PipelineConfig up42 = PipelineConfigMother.pipelineConfigWithTemplate("up42", pipelineTemplateConfig.name().toString());
cruiseConfig.addPipeline("first", up42);
PipelineTemplateConfig updatedTemplateConfig = new PipelineTemplateConfig(new CaseInsensitiveString("template"), StageConfigMother.stageConfig("stage", new JobConfigs(new JobConfig("job"))));
JobConfig jobConfig = updatedTemplateConfig.findBy(new CaseInsensitiveString("stage")).jobConfigByConfigName(new CaseInsensitiveString("job"));
jobConfig.addTask(new AntTask());
jobConfig.setElasticProfileId("invalidElasticProfileId");
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(updatedTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThat(cruiseConfig.getTemplates().contains(pipelineTemplateConfig)).isTrue();
command.update(cruiseConfig);
MagicalGoConfigXmlLoader.preprocess(cruiseConfig);
assertThat(command.isValid(cruiseConfig)).isFalse();
assertThat(updatedTemplateConfig.getAllErrors().size()).isEqualTo(1);
String message = "No profile defined corresponding to profile_id 'invalidElasticProfileId'";
assertThat(updatedTemplateConfig.getAllErrors().get(0).asString()).isEqualTo(message);
}
@Test
void shouldThrowAnExceptionIfTemplateConfigNotFound() {
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(pipelineTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThatThrownBy(() -> command.update(cruiseConfig))
.isInstanceOf(RecordNotFoundException.class)
.hasMessageContaining(EntityType.Template.notFoundMessage(pipelineTemplateConfig.name()));
}
@Test
void shouldCopyOverAuthorizationAsIsWhileUpdatingTemplateStageConfig() {
PipelineTemplateConfig updatedTemplateConfig = new PipelineTemplateConfig(new CaseInsensitiveString("template"), StageConfigMother.oneBuildPlanWithResourcesAndMaterials("stage", "job"), StageConfigMother.oneBuildPlanWithResourcesAndMaterials("stage2"));
;
cruiseConfig.addTemplate(pipelineTemplateConfig);
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(updatedTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
command.update(cruiseConfig);
assertThat(cruiseConfig.getTemplates().contains(pipelineTemplateConfig)).isFalse();
assertThat(cruiseConfig.getTemplates().contains(updatedTemplateConfig)).isTrue();
assertThat(cruiseConfig.getTemplateByName(updatedTemplateConfig.name()).getAuthorization()).isEqualTo(authorization);
}
@Test
void shouldNotContinueWithConfigSaveIfUserIsUnauthorized() {
CaseInsensitiveString templateName = new CaseInsensitiveString("template");
PipelineTemplateConfig oldTemplate = new PipelineTemplateConfig(templateName, StageConfigMother.manualStage("foo"));
cruiseConfig.addTemplate(oldTemplate);
when(entityHashingService.hashForEntity(oldTemplate)).thenReturn("digest");
when(securityService.isAuthorizedToEditTemplate(templateName, currentUser)).thenReturn(false);
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(pipelineTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThat(command.canContinue(cruiseConfig)).isFalse();
assertThat(result.message()).isEqualTo(EntityType.Template.forbiddenToEdit(pipelineTemplateConfig.name(), currentUser.getUsername()));
}
@Test
void shouldContinueWithConfigSaveifUserIsAuthorized() {
cruiseConfig.addTemplate(pipelineTemplateConfig);
when(securityService.isAuthorizedToEditTemplate(new CaseInsensitiveString("template"), currentUser)).thenReturn(true);
when(entityHashingService.hashForEntity(pipelineTemplateConfig)).thenReturn("digest");
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(pipelineTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThat(command.canContinue(cruiseConfig)).isTrue();
}
@Test
void shouldNotContinueWithConfigSaveIfRequestIsNotFresh() {
cruiseConfig.addTemplate(pipelineTemplateConfig);
when(entityHashingService.hashForEntity(pipelineTemplateConfig)).thenReturn("another-digest");
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(pipelineTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThat(command.canContinue(cruiseConfig)).isFalse();
assertThat(result.toString()).contains("Someone has modified the configuration for");
}
@Test
void shouldNotContinueWithConfigSaveIfObjectIsNotFound() {
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(pipelineTemplateConfig, currentUser, securityService, result, "digest", entityHashingService, externalArtifactsService);
assertThatThrownBy(() -> command.canContinue(cruiseConfig))
.hasMessageContaining(EntityType.Template.notFoundMessage(pipelineTemplateConfig.name()));
}
@Test
void shouldEncryptSecurePropertiesOfPipelineConfig() {
PipelineTemplateConfig pipelineTemplateConfig = mock(PipelineTemplateConfig.class);
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(pipelineTemplateConfig, null,
securityService, result, "stale_digest", entityHashingService, externalArtifactsService);
when(pipelineTemplateConfig.name()).thenReturn(new CaseInsensitiveString("p1"));
CruiseConfig preprocessedConfig = mock(CruiseConfig.class);
when(preprocessedConfig.findTemplate(new CaseInsensitiveString("p1"))).thenReturn(pipelineTemplateConfig);
command.encrypt(preprocessedConfig);
verify(pipelineTemplateConfig).encryptSecureProperties(eq(preprocessedConfig), any(PipelineTemplateConfig.class));
}
@Nested
class isValid {
@Test
void updateTemplateConfigShouldValidateAllExternalArtifacts() {
PluggableArtifactConfig s3 = new PluggableArtifactConfig("id1", "id");
PluggableArtifactConfig docker = new PluggableArtifactConfig("id2", "id");
JobConfig job1 = JobConfigMother.jobWithNoResourceRequirement();
JobConfig job2 = JobConfigMother.jobWithNoResourceRequirement();
job1.artifactTypeConfigs().add(s3);
job2.artifactTypeConfigs().add(docker);
PipelineTemplateConfig template = PipelineTemplateConfigMother.createTemplate("P1", new StageConfig(new CaseInsensitiveString("S1"), new JobConfigs(job1)),
new StageConfig(new CaseInsensitiveString("S2"), new JobConfigs(job2)));
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(template, null,
securityService, result, "stale_digest", entityHashingService, externalArtifactsService);
BasicCruiseConfig preprocessedConfig = GoConfigMother.defaultCruiseConfig();
preprocessedConfig.addTemplate(template);
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfigWithTemplate("pipeline", "P1");
preprocessedConfig.addPipelineWithoutValidation("group", pipelineConfig);
preprocessedConfig.setArtifactStores(new ArtifactStores(new ArtifactStore("id", "pluginId")));
new TemplateExpansionPreprocessor().process(preprocessedConfig);
command.isValid(preprocessedConfig);
verify(externalArtifactsService, times(2)).validateExternalArtifactConfig(any(PluggableArtifactConfig.class),
eq(new ArtifactStore("id", "pluginId")), eq(true));
}
@Test
void updateTemplateConfigShouldValidateAllFetchExternalArtifactTasks() {
JobConfig job1 = JobConfigMother.jobWithNoResourceRequirement();
JobConfig job2 = JobConfigMother.jobWithNoResourceRequirement();
FetchPluggableArtifactTask fetchS3Task = new FetchPluggableArtifactTask(new CaseInsensitiveString("p0"), new CaseInsensitiveString("s0"), new CaseInsensitiveString("j0"), "s3");
FetchPluggableArtifactTask fetchDockerTask = new FetchPluggableArtifactTask(new CaseInsensitiveString("p0"), new CaseInsensitiveString("s0"), new CaseInsensitiveString("j0"), "docker");
job1.addTask(fetchS3Task);
job2.addTask(fetchDockerTask);
PipelineTemplateConfig template = PipelineTemplateConfigMother.createTemplate("P1", new StageConfig(new CaseInsensitiveString("S1"), new JobConfigs(job1)),
new StageConfig(new CaseInsensitiveString("S2"), new JobConfigs(job2)));
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(template, null,
securityService, result, "stale_digest", entityHashingService, externalArtifactsService);
BasicCruiseConfig preprocessedConfig = GoConfigMother.defaultCruiseConfig();
preprocessedConfig.addTemplate(template);
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfigWithTemplate("pipeline", "P1");
preprocessedConfig.addPipelineWithoutValidation("group", pipelineConfig);
new TemplateExpansionPreprocessor().process(preprocessedConfig);
command.isValid(preprocessedConfig);
verify(externalArtifactsService, times(2)).validateFetchExternalArtifactTask(any(FetchPluggableArtifactTask.class), any(PipelineTemplateConfig.class), eq(preprocessedConfig));
}
/* During config save if a template is used by a pipeline, the pipeline is preprocessed and parameters are resolved. If there are any errors
during parameter resolution, the errors are added on the pipeline and not the template, hence earlier the update used to go through.
This test ensures that a template is invalid if there are errors in the preprocessed config.
*/
@Test
void shouldNotBeValidIfPreProcessedConfigHasErrors() {
BasicCruiseConfig preprocessedConfig = GoConfigMother.defaultCruiseConfig();
PipelineTemplateConfig template = PipelineTemplateConfigMother.createTemplate("temp1",
new StageConfig(new CaseInsensitiveString("S2"), new JobConfigs()));
preprocessedConfig.addTemplate(template);
preprocessedConfig.addError("name", "Error when processing params for 'a#' used in field 'name'," +
" # must be followed by a parameter pattern or escaped by another #");
UpdateTemplateConfigCommand command = new UpdateTemplateConfigCommand(template, null,
securityService, result, "stale_digest", entityHashingService, externalArtifactsService);
assertThat(command.isValid(preprocessedConfig)).isFalse();
assertThat(template.errors().isEmpty()).isFalse();
assertThat(template.errors().on("name")).isEqualTo("Error when processing params for 'a#' used in field 'name'," +
" # must be followed by a parameter pattern or escaped by another #");
}
}
}
|
3e0594ec925891394a59bd824aed5c10e7ce64b7
| 761 |
java
|
Java
|
MidtermReview/src/midtermreview/Flower.java
|
EricCharnesky/CIS1500-Fall2021
|
eb046620f424a15eab355a9f1a50428eff1d5af5
|
[
"MIT"
] | null | null | null |
MidtermReview/src/midtermreview/Flower.java
|
EricCharnesky/CIS1500-Fall2021
|
eb046620f424a15eab355a9f1a50428eff1d5af5
|
[
"MIT"
] | null | null | null |
MidtermReview/src/midtermreview/Flower.java
|
EricCharnesky/CIS1500-Fall2021
|
eb046620f424a15eab355a9f1a50428eff1d5af5
|
[
"MIT"
] | 1 |
2021-10-09T01:06:21.000Z
|
2021-10-09T01:06:21.000Z
| 18.119048 | 80 | 0.571616 | 2,342 |
package midtermreview;
public class Flower {
private String name;
private String color;
private String smell;
private int numberOfPetals;
public Flower(String name, String color, String smell, int numberOfPetals) {
this.name = name;
this.color = color;
this.smell = smell;
this.numberOfPetals = numberOfPetals;
}
public void pickAPetal(){
if (numberOfPetals > 0 ){
numberOfPetals--;
}
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public String getSmell() {
return smell;
}
public int getNumberOfPetals() {
return numberOfPetals;
}
}
|
3e0595d4f014c685ecfa13b15bc2ba7da7031726
| 5,125 |
java
|
Java
|
flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/IncrSumAggFunction.java
|
Shih-Wei-Hsu/flink
|
3fed93d62d8f79627d4ded2dd1fae6fae91b36e8
|
[
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | 41 |
2018-11-14T04:05:42.000Z
|
2022-02-09T10:39:23.000Z
|
flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/IncrSumAggFunction.java
|
Shih-Wei-Hsu/flink
|
3fed93d62d8f79627d4ded2dd1fae6fae91b36e8
|
[
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | 15 |
2021-06-13T18:06:12.000Z
|
2022-02-09T22:40:04.000Z
|
flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/IncrSumAggFunction.java
|
houmaozheng/flink
|
ef692d0967daf8f532d9011122e1d3104a07fb39
|
[
"Apache-2.0"
] | 16 |
2019-01-04T09:19:03.000Z
|
2022-01-10T14:34:31.000Z
| 29.624277 | 114 | 0.757268 | 2,343 |
/*
* 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.table.planner.functions.aggfunctions;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.expressions.UnresolvedReferenceExpression;
import org.apache.flink.table.planner.calcite.FlinkTypeSystem;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.DecimalType;
import static org.apache.flink.table.expressions.ApiExpressionUtils.unresolvedRef;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.ifThenElse;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.isNull;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.lessThan;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.literal;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.nullOf;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.or;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.plus;
/**
* built-in IncrSum aggregate function,
* negative number is discarded to ensure the monotonicity.
*/
public abstract class IncrSumAggFunction extends DeclarativeAggregateFunction {
private UnresolvedReferenceExpression sum = unresolvedRef("sum");
@Override
public int operandCount() {
return 1;
}
@Override
public UnresolvedReferenceExpression[] aggBufferAttributes() {
return new UnresolvedReferenceExpression[] { sum };
}
@Override
public DataType[] getAggBufferTypes() {
return new DataType[] { getResultType() };
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {
/* sum = */ nullOf(getResultType())
};
}
@Override
public Expression[] accumulateExpressions() {
return new Expression[] {
/* sum = */
ifThenElse(or(isNull(operand(0)), lessThan(operand(0), literal(0L))), sum,
ifThenElse(isNull(sum), operand(0), plus(sum, operand(0))))
};
}
@Override
public Expression[] retractExpressions() {
throw new TableException("This function does not support retraction, Please choose SumWithRetractAggFunction.");
}
@Override
public Expression[] mergeExpressions() {
return new Expression[] {
/* sum = */
ifThenElse(isNull(mergeOperand(sum)), sum,
ifThenElse(isNull(sum), mergeOperand(sum), plus(sum, mergeOperand(sum))))
};
}
@Override
public Expression getValueExpression() {
return sum;
}
/**
* Built-in Int IncrSum aggregate function.
*/
public static class IntIncrSumAggFunction extends IncrSumAggFunction {
@Override
public DataType getResultType() {
return DataTypes.INT();
}
}
/**
* Built-in Byte IncrSum aggregate function.
*/
public static class ByteIncrSumAggFunction extends IncrSumAggFunction {
@Override
public DataType getResultType() {
return DataTypes.TINYINT();
}
}
/**
* Built-in Short IncrSum aggregate function.
*/
public static class ShortIncrSumAggFunction extends IncrSumAggFunction {
@Override
public DataType getResultType() {
return DataTypes.SMALLINT();
}
}
/**
* Built-in Long IncrSum aggregate function.
*/
public static class LongIncrSumAggFunction extends IncrSumAggFunction {
@Override
public DataType getResultType() {
return DataTypes.BIGINT();
}
}
/**
* Built-in Float IncrSum aggregate function.
*/
public static class FloatIncrSumAggFunction extends IncrSumAggFunction {
@Override
public DataType getResultType() {
return DataTypes.FLOAT();
}
}
/**
* Built-in Double IncrSum aggregate function.
*/
public static class DoubleIncrSumAggFunction extends IncrSumAggFunction {
@Override
public DataType getResultType() {
return DataTypes.DOUBLE();
}
}
/**
* Built-in Decimal IncrSum aggregate function.
*/
public static class DecimalIncrSumAggFunction extends IncrSumAggFunction {
private DecimalType decimalType;
public DecimalIncrSumAggFunction(DecimalType decimalType) {
this.decimalType = decimalType;
}
@Override
public DataType getResultType() {
DecimalType sumType = FlinkTypeSystem.inferAggSumType(decimalType.getScale());
return DataTypes.DECIMAL(sumType.getPrecision(), sumType.getScale());
}
}
}
|
3e0595ffdba9c882bc681be7651753704d4f7fca
| 1,800 |
java
|
Java
|
abstract_data_structure/Stack.java
|
cnLawrie/Algorithm
|
6f1b8c99dc69b756212ed81d649e5bcdcb861de3
|
[
"MIT"
] | null | null | null |
abstract_data_structure/Stack.java
|
cnLawrie/Algorithm
|
6f1b8c99dc69b756212ed81d649e5bcdcb861de3
|
[
"MIT"
] | null | null | null |
abstract_data_structure/Stack.java
|
cnLawrie/Algorithm
|
6f1b8c99dc69b756212ed81d649e5bcdcb861de3
|
[
"MIT"
] | null | null | null | 24.324324 | 79 | 0.55 | 2,344 |
package ADT;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class Stack<E> implements Iterable<E>{
private int N;
private Node first;
private class Node{
E elem;
Node next;
}
public boolean isEmpty(){return first == null;}
public int size(){return N;}
public void push(E elem){
Node oldfirst = first;
first = new Node();
first.elem = elem;
first.next = oldfirst;
N++;
}
public E pop(){
E elem = first.elem;
first = first.next;
N--;
return elem;
}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<E>{
private Node current = first;
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
*
* @return {@code true} if the iteration has more elements
*/
@Override
public boolean hasNext() {
return current != null;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration
* @throws NoSuchElementException if the iteration has no more elements
*/
@Override
public E next() {
if(!hasNext())
throw new NoSuchElementException();
E elem = current.elem;
current = current.next;
return elem;
}
}
}
|
3e059653447344bfca35199248c2cbf8bd208615
| 1,462 |
java
|
Java
|
src/main/gen/com/bloxbean/algodea/idea/language/psi/impl/TEALGtxnsasOperationImpl.java
|
bloxbean/algorand-idea-plugin
|
773d2fb00ad2c59dd14697fb7e0cc622c16d0bdf
|
[
"MIT"
] | null | null | null |
src/main/gen/com/bloxbean/algodea/idea/language/psi/impl/TEALGtxnsasOperationImpl.java
|
bloxbean/algorand-idea-plugin
|
773d2fb00ad2c59dd14697fb7e0cc622c16d0bdf
|
[
"MIT"
] | null | null | null |
src/main/gen/com/bloxbean/algodea/idea/language/psi/impl/TEALGtxnsasOperationImpl.java
|
bloxbean/algorand-idea-plugin
|
773d2fb00ad2c59dd14697fb7e0cc622c16d0bdf
|
[
"MIT"
] | null | null | null | 26.581818 | 100 | 0.77565 | 2,345 |
// This is a generated file. Not intended for manual editing.
package com.bloxbean.algodea.idea.language.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.bloxbean.algodea.idea.language.psi.TEALTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.bloxbean.algodea.idea.language.psi.*;
public class TEALGtxnsasOperationImpl extends ASTWrapperPsiElement implements TEALGtxnsasOperation {
public TEALGtxnsasOperationImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull TEALVisitor visitor) {
visitor.visitGtxnsasOperation(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof TEALVisitor) accept((TEALVisitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public TEALGtxnsasOpcode getGtxnsasOpcode() {
return findNotNullChildByClass(TEALGtxnsasOpcode.class);
}
@Override
@Nullable
public TEALTxnFieldArg getTxnFieldArg() {
return findChildByClass(TEALTxnFieldArg.class);
}
@Override
@Nullable
public TEALUnsignedInteger getUnsignedInteger() {
return findChildByClass(TEALUnsignedInteger.class);
}
@Override
@Nullable
public PsiElement getVarTmpl() {
return findChildByType(VAR_TMPL);
}
}
|
3e0596f7c6e18703a2269e81509dca285bfaabbf
| 5,334 |
java
|
Java
|
build/generated/source/apt/main/com/intersysconsulting/derive4jexamples/PersonNames.java
|
oscarvarto/learning-java
|
9057a3388792568e042bcefd6ab263892805ca0a
|
[
"BSD-3-Clause"
] | null | null | null |
build/generated/source/apt/main/com/intersysconsulting/derive4jexamples/PersonNames.java
|
oscarvarto/learning-java
|
9057a3388792568e042bcefd6ab263892805ca0a
|
[
"BSD-3-Clause"
] | null | null | null |
build/generated/source/apt/main/com/intersysconsulting/derive4jexamples/PersonNames.java
|
oscarvarto/learning-java
|
9057a3388792568e042bcefd6ab263892805ca0a
|
[
"BSD-3-Clause"
] | null | null | null | 27.78125 | 118 | 0.658043 | 2,346 |
package com.intersysconsulting.derive4jexamples;
import fj.Equal;
import fj.Hash;
import fj.Ord;
import fj.Ordering;
import fj.Show;
import fj.data.Option;
import fj.data.Stream;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.function.Function;
import java.util.function.Supplier;
import lombok.NonNull;
public final class PersonNames {
@SuppressWarnings("rawtypes")
private static Show personNameShow;
@SuppressWarnings("rawtypes")
private static Ord personNameOrd;
@SuppressWarnings("rawtypes")
private static Equal personNameEqual;
@SuppressWarnings("rawtypes")
private static Hash personNameHash;
private PersonNames() {
}
/**
* This method is reexported with public modifier as
* {@link PersonNames#parseName(String)}. Also the javadoc is copied over.
*
* @param value unparse string
* @return a valid {@link PersonName}, maybe.
*/
public static Option<PersonName> parseName(@NonNull String value) {
return com.intersysconsulting.derive4jexamples.PersonName.parseName(value);
}
static PersonName Name0(String value) {
return new Name(value);
}
public static PersonName lazy(Supplier<PersonName> personName) {
return new Lazy(personName);
}
public static CasesMatchers.TotalMatcher_Name cases() {
return CasesMatchers.totalMatcher_Name;
}
public static String getValue(PersonName personName) {
return personName.match((value) -> value);
}
static Function<PersonName, PersonName> setValue0(String newValue) {
return modValue0(__ -> newValue);
}
static Function<PersonName, PersonName> modValue0(Function<String, String> valueMod) {
return personName -> personName.match((value) -> Name0(valueMod.apply(value)));
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Show<PersonName> personNameShow() {
Show<PersonName> _personNameShow = personNameShow;
if (_personNameShow == null) {
personNameShow = _personNameShow = Show.show(personName -> personName.match(
(value) -> Stream.fromString("Name(").append(() -> Show.stringShow.show(value)).append(Stream.fromString(")"))
));
}
return _personNameShow;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Ord<PersonName> personNameOrd() {
Ord<PersonName> _personNameOrd = personNameOrd;
if (_personNameOrd == null) {
personNameOrd = _personNameOrd = Ord.ordDef(personName1 -> personName1.match(
(value1) -> personName2 -> personName2.match(
(value2) -> {
Ordering o = Ordering.EQ;
o = Ord.stringOrd.compare(value1, value2);
if (o != Ordering.EQ) return o;
return o;
}
)
));
}
return _personNameOrd;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Equal<PersonName> personNameEqual() {
Equal<PersonName> _personNameEqual = personNameEqual;
if (_personNameEqual == null) {
personNameEqual = _personNameEqual = Equal.equalDef(personName1 -> personName1.match(
(value1) -> personName2 -> personName2.match(
(value2) -> Equal.stringEqual.eq(value1, value2)
)
));
}
return _personNameEqual;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Hash<PersonName> personNameHash() {
Hash<PersonName> _personNameHash = personNameHash;
if (_personNameHash == null) {
personNameHash = _personNameHash = Hash.hash(personName -> personName.match(
(value) -> 23 + Hash.stringHash.hash(value)
));
}
return _personNameHash;
}
private static final class Name extends PersonName {
private final String value;
Name(String value) {
this.value = value;
}
@Override
public <R> R match(Function<String, R> Name) {
return Name.apply(this.value);
}
}
private static final class Lazy extends PersonName {
private volatile Supplier<PersonName> expression;
private PersonName evaluation;
Lazy(Supplier<PersonName> personName) {
this.expression = personName;
}
private synchronized PersonName _evaluate() {
Lazy lazy = this;
while (true) {
Supplier<PersonName> expr = lazy.expression;
if (expr == null) {
evaluation = lazy.evaluation;
break;
}
else {
PersonName eval = expr.get();
if (eval instanceof Lazy) {
lazy = (Lazy) eval;
}
else {
evaluation = eval;
break;
}
}
}
expression = null;
return evaluation;
}
@Override
public <R> R match(Function<String, R> Name) {
return (this.expression == null ? this.evaluation : _evaluate()).match(Name);
}
}
public static class CasesMatchers {
private static final TotalMatcher_Name totalMatcher_Name = new TotalMatcher_Name();
private CasesMatchers() {
}
public static final class TotalMatcher_Name {
TotalMatcher_Name() {
}
public final <R> Function<PersonName, R> Name(Function<String, R> Name) {
return personName -> personName.match(Name);
}
public final <R> Function<PersonName, R> Name_(R r) {
return this.Name((value) -> r);
}
}
}
}
|
3e0598c33bbe52076c6d07efbc67f5420f6b2142
| 3,645 |
java
|
Java
|
bmc-announcementsservice/src/main/java/com/oracle/bmc/announcementsservice/requests/UpdateAnnouncementUserStatusRequest.java
|
Mattlk13/oci-java-sdk
|
3e9a65b05844c5cbbe626d45e0a89b16fece065b
|
[
"UPL-1.0",
"Apache-2.0"
] | null | null | null |
bmc-announcementsservice/src/main/java/com/oracle/bmc/announcementsservice/requests/UpdateAnnouncementUserStatusRequest.java
|
Mattlk13/oci-java-sdk
|
3e9a65b05844c5cbbe626d45e0a89b16fece065b
|
[
"UPL-1.0",
"Apache-2.0"
] | 1 |
2020-11-10T21:43:28.000Z
|
2020-11-10T21:43:28.000Z
|
bmc-announcementsservice/src/main/java/com/oracle/bmc/announcementsservice/requests/UpdateAnnouncementUserStatusRequest.java
|
Mattlk13/oci-java-sdk
|
3e9a65b05844c5cbbe626d45e0a89b16fece065b
|
[
"UPL-1.0",
"Apache-2.0"
] | null | null | null | 38.368421 | 135 | 0.662551 | 2,348 |
/**
* Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
*/
package com.oracle.bmc.announcementsservice.requests;
import com.oracle.bmc.announcementsservice.model.*;
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 0.0.1")
@lombok.Builder(builderClassName = "Builder", buildMethodName = "buildWithoutInvocationCallback")
@lombok.Getter
public class UpdateAnnouncementUserStatusRequest extends com.oracle.bmc.requests.BmcRequest {
/**
* The OCID of the announcement.
*/
private String announcementId;
/**
* The information to use to update the announcement's read status.
*/
private AnnouncementUserStatusDetails statusDetails;
/**
* The locking version, used for optimistic concurrency control.
*/
private String ifMatch;
/**
* The unique Oracle-assigned identifier for the request. If you need to contact Oracle about
* a particular request, please provide the complete request ID.
*
*/
private String opcRequestId;
public static class Builder {
private com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder>
invocationCallback = null;
private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;
/**
* Set the invocation callback for the request to be built.
* @param invocationCallback the invocation callback to be set for the request
* @return this builder instance
*/
public Builder invocationCallback(
com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder>
invocationCallback) {
this.invocationCallback = invocationCallback;
return this;
}
/**
* Set the retry configuration for the request to be built.
* @param retryConfiguration the retry configuration to be used for the request
* @return this builder instance
*/
public Builder retryConfiguration(
com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {
this.retryConfiguration = retryConfiguration;
return this;
}
/**
* Copy method to populate the builder with values from the given instance.
* @return this builder instance
*/
public Builder copy(UpdateAnnouncementUserStatusRequest o) {
announcementId(o.getAnnouncementId());
statusDetails(o.getStatusDetails());
ifMatch(o.getIfMatch());
opcRequestId(o.getOpcRequestId());
invocationCallback(o.getInvocationCallback());
retryConfiguration(o.getRetryConfiguration());
return this;
}
/**
* Build the instance of UpdateAnnouncementUserStatusRequest as configured by this builder
*
* Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,
* while the method {@link Builder#buildWithoutInvocationCallback} does not.
*
* This is the preferred method to build an instance.
*
* @return instance of UpdateAnnouncementUserStatusRequest
*/
public UpdateAnnouncementUserStatusRequest build() {
UpdateAnnouncementUserStatusRequest request = buildWithoutInvocationCallback();
request.setInvocationCallback(invocationCallback);
request.setRetryConfiguration(retryConfiguration);
return request;
}
}
}
|
3e059912c2fd15517c555801be90e84e06680cce
| 3,003 |
java
|
Java
|
core/src/main/java/flex/messaging/security/LoginCommand.java
|
ShangwenWang/flex-blazeds
|
4db3bc764e1842b03afa0bcc6302db8aefc28436
|
[
"Apache-2.0"
] | 49 |
2015-02-05T10:28:05.000Z
|
2021-11-10T23:11:17.000Z
|
core/src/main/java/flex/messaging/security/LoginCommand.java
|
ShangwenWang/flex-blazeds
|
4db3bc764e1842b03afa0bcc6302db8aefc28436
|
[
"Apache-2.0"
] | 4 |
2015-07-02T12:49:26.000Z
|
2021-02-03T13:03:03.000Z
|
core/src/main/java/flex/messaging/security/LoginCommand.java
|
ShangwenWang/flex-blazeds
|
4db3bc764e1842b03afa0bcc6302db8aefc28436
|
[
"Apache-2.0"
] | 51 |
2015-03-18T22:18:54.000Z
|
2021-11-10T23:11:11.000Z
| 38.012658 | 103 | 0.71362 | 2,349 |
/*
* 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 flex.messaging.security;
import javax.servlet.ServletConfig;
import java.security.Principal;
import java.util.List;
/**
* The class name of the implementation of this interface is configured in the
* gateway configuration's security section and is instantiated using reflection
* on servlet initialization.
*/
public interface LoginCommand
{
/**
* Called to initialize a login command prior to authentication/authorization requests.
*
* @param config The servlet configuration for MessageBrokerServlet.
*/
void start(ServletConfig config);
/**
* Called to free up resources used by the login command.
*/
void stop();
/**
* The gateway calls this method to perform programmatic, custom authentication.
* <p>
* The credentials are passed as a Map to allow for extra properties to be
* passed in the future. For now, only a "password" property is sent.
* </p>
*
* @param username The principal being authenticated
* @param credentials A map, typically with string keys and values - holds, for example, a password
* @return principal for the authenticated user when authentication is successful; null otherwise
*/
Principal doAuthentication(String username, Object credentials);
/**
* The gateway calls this method to perform programmatic authorization.
* <p>
* A typical implementation would simply iterate over the supplied roles and
* check that at least one of the roles returned true from a call to
* HttpServletRequest.isUserInRole(String role).
* </p>
*
* @param principal The principal being checked for authorization
* @param roles A List of role names to check, all members should be strings
* @return true if the principal is authorized given the list of roles
*/
boolean doAuthorization(Principal principal, List roles);
/**
* Attempts to log a user out from their session.
*
* NOTE: May not be possible on all application servers.
* @param principal The principal to logout.
* @return true when logout is successful
*/
boolean logout(Principal principal);
}
|
3e059a02f305c0e1b20003f69ffc6b3a21053800
| 1,014 |
java
|
Java
|
rest-client/src/main/java/org/jboss/pnc/restclient/websocket/ListenerUnsubscriber.java
|
DnsZhou/pnc
|
26d7cbecc9cf4494e29aca3482dbb4a96ec47f93
|
[
"Apache-2.0"
] | 41 |
2015-02-02T14:44:34.000Z
|
2022-03-01T16:12:34.000Z
|
rest-client/src/main/java/org/jboss/pnc/restclient/websocket/ListenerUnsubscriber.java
|
DnsZhou/pnc
|
26d7cbecc9cf4494e29aca3482dbb4a96ec47f93
|
[
"Apache-2.0"
] | 1,502 |
2015-01-04T19:57:43.000Z
|
2022-03-30T08:55:17.000Z
|
rest-client/src/main/java/org/jboss/pnc/restclient/websocket/ListenerUnsubscriber.java
|
DnsZhou/pnc
|
26d7cbecc9cf4494e29aca3482dbb4a96ec47f93
|
[
"Apache-2.0"
] | 52 |
2015-02-02T13:32:57.000Z
|
2022-03-04T11:05:07.000Z
| 35.034483 | 75 | 0.74311 | 2,350 |
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.restclient.websocket;
/**
* It's labeled Runnable which is used to remove WebSocket listeners.
*
* Should be used after listener is no longer needed.
*
* @author <a href="mailto:[email protected]">Jan Michalov</a>
*/
public interface ListenerUnsubscriber extends Runnable {
}
|
3e059a5b65513b4019d3ee465be5d596b82b7356
| 506 |
java
|
Java
|
src.save/test/java/g0801_0900/s0823_binary_trees_with_factors/SolutionTest.java
|
jscrdev/LeetCode-in-Java
|
cb2ec473a6e728e0eafb534518fde41910488d85
|
[
"MIT"
] | 2 |
2021-12-21T11:30:12.000Z
|
2022-03-04T09:30:33.000Z
|
src.save/test/java/g0801_0900/s0823_binary_trees_with_factors/SolutionTest.java
|
ThanhNIT/LeetCode-in-Java
|
d1c1eab40db8ef15d69d78dcc55ebb410b4bb5f5
|
[
"MIT"
] | null | null | null |
src.save/test/java/g0801_0900/s0823_binary_trees_with_factors/SolutionTest.java
|
ThanhNIT/LeetCode-in-Java
|
d1c1eab40db8ef15d69d78dcc55ebb410b4bb5f5
|
[
"MIT"
] | null | null | null | 26.631579 | 95 | 0.717391 | 2,351 |
package g0801_0900.s0823_binary_trees_with_factors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void numFactoredBinaryTrees() {
assertThat(new Solution().numFactoredBinaryTrees(new int[] {2, 4}), equalTo(3));
}
@Test
void numFactoredBinaryTrees2() {
assertThat(new Solution().numFactoredBinaryTrees(new int[] {2, 4, 5, 10}), equalTo(7));
}
}
|
3e059b19511deb46bcc5188d63c3eb7df02ca7b3
| 3,365 |
java
|
Java
|
app/src/main/java/edu/cnm/deepdive/cardcombat/service/UserRepository.java
|
Dominguez1st/card-combat
|
c5d1cb5b860dcec25edc05f78b358cb39e19dbcc
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/edu/cnm/deepdive/cardcombat/service/UserRepository.java
|
Dominguez1st/card-combat
|
c5d1cb5b860dcec25edc05f78b358cb39e19dbcc
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/edu/cnm/deepdive/cardcombat/service/UserRepository.java
|
Dominguez1st/card-combat
|
c5d1cb5b860dcec25edc05f78b358cb39e19dbcc
|
[
"Apache-2.0"
] | null | null | null | 32.047619 | 97 | 0.677563 | 2,352 |
package edu.cnm.deepdive.cardcombat.service;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import edu.cnm.deepdive.cardcombat.model.dao.DeckDao;
import edu.cnm.deepdive.cardcombat.model.dao.GameDao;
import edu.cnm.deepdive.cardcombat.model.dao.UserDao;
import edu.cnm.deepdive.cardcombat.model.entity.Deck;
import edu.cnm.deepdive.cardcombat.model.entity.User;
import io.reactivex.Completable;
import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
import java.util.Date;
/**
* {@code UserRepository} contains methods that provide a layer of abstraction above the {@link
* UserDao}, and allows for creation, reading, updating, and deleting of attempts.
*/
public class UserRepository {
private final Context context;
private final DeckDao deckDao;
private final UserDao userDao;
private final GameDao gameDao;
private final GoogleSignInService signInService;
/**
* The constructor initializes the context, the database, the dao, and the GoogleSignInService.
*
* @param context The application context.
*/
public UserRepository(Context context) {
this.context = context;
CardCombatDatabase database = CardCombatDatabase.getInstance();
deckDao = database.getDeckDao();
userDao = database.getUserDao();
gameDao = database.getGameDao();
signInService = GoogleSignInService.getInstance();
}
/**
* Creates a player record in the database given a Google Sign In account.
*
* @param account A GoogleSignInAccount that will be associated with the player.
* @return A {@code Single} {@link User} that has been created.
*/
@SuppressWarnings("ConstantConditions")
public Single<User> getOrCreate(@NonNull GoogleSignInAccount account) {
return userDao.findByOauthKey(account.getId())
.switchIfEmpty(
Single.fromCallable(() -> {
User user = new User();
user.setOauthKey(account.getId());
userDao.insert(user)
.doAfterSuccess(user::setId)
.subscribe();
return user;
})
)
.subscribeOn(Schedulers.io());
}
/**
* Creates or updates a player record in the database.
*
* @param user The {@code User} entity.
* @return A {@code Completable} indicating the success or failure of the creation/update.
*/
public Completable save(User user) {
return ((user.getId() == 0)
? userDao.insert(user)
.doAfterSuccess(user::setId)
.ignoreElement()
: userDao.update(user)
.ignoreElement())
.subscribeOn(Schedulers.io());
}
/**
* Deletes a user record in the database.
*
* @param user The {@code Player} entity.
* @return A {@code Completable} indicating the success or failure of the deletion.
*/
public Completable delete(User user) {
return ((user.getId() == 0)
? Completable.complete()
: userDao.delete(user)
.ignoreElement())
.subscribeOn(Schedulers.io());
}
/**
* Returns LiveData on a user, given their id.
*
* @param id The user's id.
* @return {@code LiveData} of a {@code User}.
*/
public LiveData<User> get(long id) {
return userDao.findByUserId(id);
}
}
|
3e059b5d0a95d51fb567a1069048b51e106beaf5
| 1,639 |
java
|
Java
|
vividus-plugin-web-app/src/main/java/org/vividus/selenium/screenshot/strategies/AdjustingCutStrategy.java
|
draker94/vividus
|
46545b6555c29f21b5d9b29a70ef8679ce42e119
|
[
"Apache-2.0"
] | 335 |
2019-06-24T06:43:45.000Z
|
2022-03-26T08:26:23.000Z
|
vividus-plugin-web-app/src/main/java/org/vividus/selenium/screenshot/strategies/AdjustingCutStrategy.java
|
draker94/vividus
|
46545b6555c29f21b5d9b29a70ef8679ce42e119
|
[
"Apache-2.0"
] | 2,414 |
2019-08-15T15:24:31.000Z
|
2022-03-31T14:38:26.000Z
|
vividus-plugin-web-app/src/main/java/org/vividus/selenium/screenshot/strategies/AdjustingCutStrategy.java
|
Yauhenda/vividus
|
583df23b34dfc48d3911ed1b300a273c2fd1777c
|
[
"Apache-2.0"
] | 64 |
2019-08-16T11:32:48.000Z
|
2022-03-12T06:15:18.000Z
| 29.267857 | 75 | 0.720561 | 2,353 |
/*
* Copyright 2019-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vividus.selenium.screenshot.strategies;
import org.openqa.selenium.WebDriver;
import ru.yandex.qatools.ashot.shooting.cutter.CutStrategy;
class AdjustingCutStrategy implements CutStrategy
{
private static final long serialVersionUID = 2124902370489242441L;
private final CutStrategy cutStrategy;
private final int headerAdjustment;
private boolean beforeScrolling = true;
AdjustingCutStrategy(CutStrategy cutStrategy, int headerAdjustment)
{
this.cutStrategy = cutStrategy;
this.headerAdjustment = headerAdjustment;
}
@Override
public int getHeaderHeight(WebDriver driver)
{
int headerHeight = cutStrategy.getHeaderHeight(driver);
if (beforeScrolling)
{
beforeScrolling = false;
return headerHeight;
}
return headerHeight + headerAdjustment;
}
@Override
public int getFooterHeight(WebDriver driver)
{
return cutStrategy.getFooterHeight(driver);
}
}
|
3e059c23fc17c8200a7fde39748a0685afd98527
| 1,511 |
java
|
Java
|
model/src/test/java/org/example/playground/model/util/MemoryAppender.java
|
bytemania/playground-java-akka
|
bf68c77db47dd70212f6a8341db35a7997cce403
|
[
"MIT"
] | 1 |
2020-12-09T12:15:18.000Z
|
2020-12-09T12:15:18.000Z
|
model/src/test/java/org/example/playground/model/util/MemoryAppender.java
|
bytemania/playground-java-akka
|
bf68c77db47dd70212f6a8341db35a7997cce403
|
[
"MIT"
] | null | null | null |
model/src/test/java/org/example/playground/model/util/MemoryAppender.java
|
bytemania/playground-java-akka
|
bf68c77db47dd70212f6a8341db35a7997cce403
|
[
"MIT"
] | null | null | null | 29.627451 | 76 | 0.626737 | 2,354 |
package org.example.playground.model.util;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class MemoryAppender extends ListAppender<ILoggingEvent> {
public void reset() {
this.list.clear();
}
public boolean contains(String string, Level level) {
return this.list.stream()
.anyMatch(event -> event.getMessage().contains(string)
&& event.getLevel().equals(level));
}
public int countEventsForLogger(String loggerName) {
return (int) this.list.stream()
.filter(event -> event.getLoggerName().contains(loggerName))
.count();
}
public List<ILoggingEvent> search(String string) {
return this.list.stream()
.filter(event -> event.getMessage().contains(string))
.collect(Collectors.toList());
}
public List<ILoggingEvent> search(String string, Level level) {
return this.list.stream()
.filter(event -> event.getMessage().contains(string)
&& event.getLevel().equals(level))
.collect(Collectors.toList());
}
public int getSize() {
return this.list.size();
}
public List<ILoggingEvent> getLoggedEvents() {
return Collections.unmodifiableList(this.list);
}
}
|
3e059c3c54681fc57dccc4e13be225e79b91f571
| 332 |
java
|
Java
|
src/com/score/dao/inter/ExamDaoInter.java
|
cy486/StudentInformationManagementSystem
|
9a0f005e22385911fb9b1f3193fb7e695baa7e3a
|
[
"Apache-2.0"
] | null | null | null |
src/com/score/dao/inter/ExamDaoInter.java
|
cy486/StudentInformationManagementSystem
|
9a0f005e22385911fb9b1f3193fb7e695baa7e3a
|
[
"Apache-2.0"
] | null | null | null |
src/com/score/dao/inter/ExamDaoInter.java
|
cy486/StudentInformationManagementSystem
|
9a0f005e22385911fb9b1f3193fb7e695baa7e3a
|
[
"Apache-2.0"
] | 1 |
2019-12-08T09:34:42.000Z
|
2019-12-08T09:34:42.000Z
| 14.434783 | 63 | 0.680723 | 2,355 |
package com.score.dao.inter;
import java.util.List;
import com.score.bean.Exam;
/**
* 操作学生的数据层接口
* @author bojiangzhou
*
*/
public interface ExamDaoInter extends BaseDaoInter {
/**
* 获取考试信息
* @param sql 要执行的sql语句
* @param param 参数
* @return
*/
public List<Exam> getExamList(String sql, List<Object> param);
}
|
3e059ca1d0f461db474591cd9786061a165f4751
| 2,176 |
java
|
Java
|
cpython/src/gen/java/org/bytedeco/cpython/_mod.java
|
StuffNoOneCaresAbout/javacpp-presets
|
4967c4cb8c2a1f6f0d97e4d6e838bd46775bdcd7
|
[
"Apache-2.0"
] | 1 |
2021-01-21T03:46:40.000Z
|
2021-01-21T03:46:40.000Z
|
cpython/src/gen/java/org/bytedeco/cpython/_mod.java
|
StuffNoOneCaresAbout/javacpp-presets
|
4967c4cb8c2a1f6f0d97e4d6e838bd46775bdcd7
|
[
"Apache-2.0"
] | null | null | null |
cpython/src/gen/java/org/bytedeco/cpython/_mod.java
|
StuffNoOneCaresAbout/javacpp-presets
|
4967c4cb8c2a1f6f0d97e4d6e838bd46775bdcd7
|
[
"Apache-2.0"
] | null | null | null | 49.454545 | 155 | 0.721048 | 2,356 |
// Targeted by JavaCPP version 1.5.5-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.cpython;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.cpython.global.python.*;
@Properties(inherit = org.bytedeco.cpython.presets.python.class)
public class _mod extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public _mod() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public _mod(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public _mod(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public _mod position(long position) {
return (_mod)super.position(position);
}
@Override public _mod getPointer(long i) {
return new _mod((Pointer)this).position(position + i);
}
public native @Cast("_mod_kind") int kind(); public native _mod kind(int setter);
@Name("v.Module.body") public native asdl_seq v_Module_body(); public native _mod v_Module_body(asdl_seq setter);
@Name("v.Module.type_ignores") public native asdl_seq v_Module_type_ignores(); public native _mod v_Module_type_ignores(asdl_seq setter);
@Name("v.Interactive.body") public native asdl_seq v_Interactive_body(); public native _mod v_Interactive_body(asdl_seq setter);
@Name("v.Expression.body") public native _expr v_Expression_body(); public native _mod v_Expression_body(_expr setter);
@Name("v.FunctionType.argtypes") public native asdl_seq v_FunctionType_argtypes(); public native _mod v_FunctionType_argtypes(asdl_seq setter);
@Name("v.FunctionType.returns") public native _expr v_FunctionType_returns(); public native _mod v_FunctionType_returns(_expr setter);
@Name("v.Suite.body") public native asdl_seq v_Suite_body(); public native _mod v_Suite_body(asdl_seq setter);
}
|
3e059ce7f2f2694a658382a2aa3e776cc7366300
| 1,350 |
java
|
Java
|
src/main/java/dev/cheerfun/pixivic/biz/dns/config/JDDNSConfig.java
|
CrazyForks/Pixiv-Illustration-Collection-Backend
|
315cc4fbe002481edd32de2df34709ffc27a1a95
|
[
"Apache-2.0"
] | 607 |
2020-01-23T17:06:22.000Z
|
2022-03-29T09:47:23.000Z
|
src/main/java/dev/cheerfun/pixivic/biz/dns/config/JDDNSConfig.java
|
CrazyForks/Pixiv-Illustration-Collection-Backend
|
315cc4fbe002481edd32de2df34709ffc27a1a95
|
[
"Apache-2.0"
] | 18 |
2020-04-22T14:05:00.000Z
|
2022-02-17T09:36:53.000Z
|
src/main/java/dev/cheerfun/pixivic/biz/dns/config/JDDNSConfig.java
|
CrazyForks/Pixiv-Illustration-Collection-Backend
|
315cc4fbe002481edd32de2df34709ffc27a1a95
|
[
"Apache-2.0"
] | 89 |
2020-01-24T13:49:15.000Z
|
2022-03-25T13:06:37.000Z
| 40.909091 | 119 | 0.702222 | 2,357 |
package dev.cheerfun.pixivic.biz.dns.config;
import com.jdcloud.sdk.auth.CredentialsProvider;
import com.jdcloud.sdk.auth.StaticCredentialsProvider;
import com.jdcloud.sdk.http.HttpRequestConfig;
import com.jdcloud.sdk.http.Protocol;
import com.jdcloud.sdk.service.clouddnsservice.client.ClouddnsserviceClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author OysterQAQ
* @version 1.0
* @date 2021/5/31 11:19 PM
* @description JDDNSConfig
*/
@AllArgsConstructor
@Configuration
public class JDDNSConfig {
@Bean
public ClouddnsserviceClient clouddnsserviceClient(@Value("${jdcloud.accessKeyId}")
String accessKeyId, @Value("${jdcloud.secretAccessKey}")
String secretAccessKey) {
CredentialsProvider credentialsProvider = new StaticCredentialsProvider(accessKeyId, secretAccessKey);
return ClouddnsserviceClient.builder()
.credentialsProvider(credentialsProvider)
.httpRequestConfig(new HttpRequestConfig.Builder().protocol(Protocol.HTTP).build()) //默认为HTTPS
.build();
}
}
|
3e059d28ab1115d02a530f05ddeb1ee166274f1a
| 1,477 |
java
|
Java
|
_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/NBTTagLong.java
|
MarioMatschgi/Minecraft-Plugins
|
b1363d06b6d741337dc0c6c7e1c1231778356be4
|
[
"MIT"
] | 1 |
2021-03-24T12:20:04.000Z
|
2021-03-24T12:20:04.000Z
|
_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/NBTTagLong.java
|
MarioMatschgi/Minecraft-Plugins
|
b1363d06b6d741337dc0c6c7e1c1231778356be4
|
[
"MIT"
] | null | null | null |
_Eclipse/_SpigotDecompiled/work/decompile-cf6b1333/net/minecraft/server/NBTTagLong.java
|
MarioMatschgi/Minecraft-Plugins
|
b1363d06b6d741337dc0c6c7e1c1231778356be4
|
[
"MIT"
] | 2 |
2021-03-27T15:43:42.000Z
|
2021-03-27T15:50:42.000Z
| 19.959459 | 93 | 0.577522 | 2,358 |
package net.minecraft.server;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class NBTTagLong extends NBTNumber {
private long data;
NBTTagLong() {}
public NBTTagLong(long i) {
this.data = i;
}
void write(DataOutput dataoutput) throws IOException {
dataoutput.writeLong(this.data);
}
void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException {
nbtreadlimiter.a(128L);
this.data = datainput.readLong();
}
public byte getTypeId() {
return (byte) 4;
}
public String toString() {
return this.data + "L";
}
public NBTTagLong c() {
return new NBTTagLong(this.data);
}
public boolean equals(Object object) {
return super.equals(object) && this.data == ((NBTTagLong) object).data;
}
public int hashCode() {
return super.hashCode() ^ (int) (this.data ^ this.data >>> 32);
}
public long d() {
return this.data;
}
public int e() {
return (int) (this.data & -1L);
}
public short f() {
return (short) ((int) (this.data & 65535L));
}
public byte g() {
return (byte) ((int) (this.data & 255L));
}
public double asDouble() {
return (double) this.data;
}
public float i() {
return (float) this.data;
}
public NBTBase clone() {
return this.c();
}
}
|
3e059e12f11b9fbfd479d1b238be16aab58d5828
| 2,223 |
java
|
Java
|
maven-checkstyle-plugin/src/main/java/org/apache/maven/plugin/checkstyle/ReportResource.java
|
NunoEdgarGFlowHub/maven-plugins
|
91f90b8075a363e4c592da285cf8324c63a66ffa
|
[
"Apache-2.0"
] | 1 |
2018-06-06T13:56:44.000Z
|
2018-06-06T13:56:44.000Z
|
maven-checkstyle-plugin/src/main/java/org/apache/maven/plugin/checkstyle/ReportResource.java
|
NunoEdgarGFlowHub/maven-plugins
|
91f90b8075a363e4c592da285cf8324c63a66ffa
|
[
"Apache-2.0"
] | 3 |
2021-05-18T20:53:35.000Z
|
2022-02-01T01:12:21.000Z
|
maven-checkstyle-plugin/src/main/java/org/apache/maven/plugin/checkstyle/ReportResource.java
|
NunoEdgarGFlowHub/maven-plugins
|
91f90b8075a363e4c592da285cf8324c63a66ffa
|
[
"Apache-2.0"
] | 1 |
2017-09-26T14:37:06.000Z
|
2017-09-26T14:37:06.000Z
| 28.883117 | 116 | 0.694245 | 2,359 |
package org.apache.maven.plugin.checkstyle;
/*
* 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.
*/
import org.codehaus.plexus.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* Generic Report Resource management.
*
* @author <a href="mailto:[email protected]">Joakim Erdfelt</a>
* @version $Id$
*/
public class ReportResource
{
private String resourcePathBase;
private File outputDirectory;
public ReportResource( String resourcePathBase, File outputDirectory )
{
this.resourcePathBase = resourcePathBase;
this.outputDirectory = outputDirectory;
}
public void copy( String resourceName ) throws IOException
{
File resource = new File( outputDirectory, resourceName );
if ( ( resource != null ) && ( !resource.exists() ) )
{
URL url =
Thread.currentThread().getContextClassLoader().getResource( resourcePathBase + "/" + resourceName );
FileUtils.copyURLToFile( url, resource );
}
}
public File getOutputDirectory()
{
return outputDirectory;
}
public void setOutputDirectory( File outputDirectory )
{
this.outputDirectory = outputDirectory;
}
public String getResourcePathBase()
{
return resourcePathBase;
}
public void setResourcePathBase( String resourcePathBase )
{
this.resourcePathBase = resourcePathBase;
}
}
|
3e059e248f8427eac008c299d9c6bdcd655925ae
| 2,804 |
java
|
Java
|
modules/global/src/com/haulmont/cuba/security/entity/FilterEntity.java
|
cuba-platform/cuba-thesis
|
09ae6b584537f89e458a6a70c9344b3f47d9a8c4
|
[
"Apache-2.0"
] | 2 |
2020-02-21T08:17:10.000Z
|
2020-07-27T08:24:47.000Z
|
modules/global/src/com/haulmont/cuba/security/entity/FilterEntity.java
|
cuba-platform/cuba-thesis
|
09ae6b584537f89e458a6a70c9344b3f47d9a8c4
|
[
"Apache-2.0"
] | null | null | null |
modules/global/src/com/haulmont/cuba/security/entity/FilterEntity.java
|
cuba-platform/cuba-thesis
|
09ae6b584537f89e458a6a70c9344b3f47d9a8c4
|
[
"Apache-2.0"
] | 2 |
2020-02-21T08:17:12.000Z
|
2020-09-22T20:02:02.000Z
| 21.90625 | 90 | 0.623039 | 2,360 |
/*
* Copyright (c) 2008-2013 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/license for details.
*/
package com.haulmont.cuba.security.entity;
import com.haulmont.chile.core.annotations.NamePattern;
import com.haulmont.cuba.core.entity.AbstractSearchFolder;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.cuba.core.entity.annotation.EnableRestore;
import com.haulmont.cuba.core.entity.annotation.SystemLevel;
import javax.persistence.*;
/**
* A filter component settings.
*
* @author krivopustov
* @version $Id$
*/
@Entity(name = "sec$Filter")
@Table(name = "SEC_FILTER")
@NamePattern("%s|name")
@SystemLevel
@EnableRestore
public class FilterEntity extends StandardEntity {
@Column(name = "COMPONENT")
protected String componentId;
@Column(name = "NAME", length = 255)
protected String name;
@Column(name = "CODE", length = 200)
protected String code;
@Column(name = "XML")
@Lob
protected String xml;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
protected User user;
@Transient
protected Boolean isDefault = false;
@Transient
protected Boolean applyDefault = false;
@Transient
protected AbstractSearchFolder folder;
@Transient
protected Boolean isSet = false;
public String getComponentId() {
return componentId;
}
public void setComponentId(String componentId) {
this.componentId = componentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getXml() {
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
public Boolean getIsDefault() {
return isDefault;
}
public void setIsDefault(Boolean aDefault) {
isDefault = aDefault;
}
public Boolean getApplyDefault(){
return applyDefault;
}
public void setApplyDefault(Boolean applyDefault){
this.applyDefault=applyDefault;
}
public AbstractSearchFolder getFolder() {
return folder;
}
public void setFolder(AbstractSearchFolder folder) {
this.folder = folder;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Boolean getIsSet(){
return isSet;
}
public void setIsSet(Boolean isSet){
this.isSet=isSet;
}
}
|
3e059ea918051e396d4ff771d8addbfb7be70fa6
| 739 |
java
|
Java
|
src/visao/UIAtualizaCurso.java
|
phcayres/java_DAO
|
3981565f1c18b8fb7d5245fed59350c09db5f5ee
|
[
"MIT"
] | null | null | null |
src/visao/UIAtualizaCurso.java
|
phcayres/java_DAO
|
3981565f1c18b8fb7d5245fed59350c09db5f5ee
|
[
"MIT"
] | null | null | null |
src/visao/UIAtualizaCurso.java
|
phcayres/java_DAO
|
3981565f1c18b8fb7d5245fed59350c09db5f5ee
|
[
"MIT"
] | null | null | null | 23.09375 | 96 | 0.634641 | 2,361 |
package visao;
import controle.CursoDAO;
import javax.swing.JOptionPane;
import modelo.Curso;
/**
*
* @author Paulo Henrique Cayres
*/
public class UIAtualizaCurso {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Curso c = new Curso(Integer.parseInt(JOptionPane.showInputDialog("Código para alteração: ")),
JOptionPane.showInputDialog("Digite o novo nome: "));
try {
CursoDAO dao = new CursoDAO();
dao.atualizarCurso(c);
JOptionPane.showMessageDialog(null, "Registro alterado com sucesso!!!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
3e05a06d0ebd62742b13a04ef2f9d3bb6589af8d
| 3,579 |
java
|
Java
|
src/main/java/frc/robot/Util/Swerve.java
|
Team-2960/PreseasonCode2022
|
1e86d020fe04bd11a7d586a12f93866efc121f31
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/frc/robot/Util/Swerve.java
|
Team-2960/PreseasonCode2022
|
1e86d020fe04bd11a7d586a12f93866efc121f31
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/frc/robot/Util/Swerve.java
|
Team-2960/PreseasonCode2022
|
1e86d020fe04bd11a7d586a12f93866efc121f31
|
[
"BSD-3-Clause"
] | null | null | null | 33.448598 | 142 | 0.68874 | 2,362 |
package frc.robot.Util;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
//MOTORS
import com.revrobotics.CANDigitalInput;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
//PID
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.geometry.Pose2d;
import edu.wpi.first.wpilibj.geometry.Rotation2d;
import edu.wpi.first.wpilibj.geometry.Translation2d;
//SENSORS
import edu.wpi.first.wpilibj.kinematics.SwerveModuleState;
import com.ctre.phoenix.CANifier;
import com.ctre.phoenix.sensors.CANCoder;
import frc.robot.Constants;
public class Swerve {
private CANSparkMax driveMotor;
private CANSparkMax angleMotor;
private PIDController anglePID;
private PIDController drivePID;
private CANCoder angleEncoder;
private Translation2d translation2d;
private Rotation2d rotation2d;
private Pose2d pose2d;
public Swerve(int motorIdDrive,int motorIdAngle,int encoderID, PIDController pidA, PIDController pidD, double offSet){
//TODO ADD OFFSET OF THE MOTOR SO ITS NOT ANNOYING
angleEncoder = new CANCoder(encoderID);
angleEncoder.configMagnetOffset(offSet);
drivePID = pidA;
anglePID = pidD;
driveMotor = new CANSparkMax(motorIdDrive, MotorType.kBrushless);
angleMotor = new CANSparkMax(motorIdAngle, MotorType.kBrushless);
}
public void setSpeed(double driveSpeed, double angleSpeed){
driveMotor.set(driveSpeed);
angleMotor.set(angleSpeed);
}
public void setAngleSpeed(double angleSpeed){
angleMotor.set(angleSpeed);
}
public void setDriveSpeed(double driveSpeed){
driveMotor.set(driveSpeed);
}
public double drivePIDCalc(double rate){
double calcDriveSpeed = 0;
//angle
return calcDriveSpeed;
}
public double angleOffsetAnglePID(double angle, double offSet){
return anglePIDCalcABS(angle);
}
public double angleOffsetDrivePID(double angle, double offSet){
return anglePIDCalcABS(angle);
}
public double anglePIDCalc(double angle){
double calcAngleSpeed = 0;
anglePID.calculate(angleEncoder.getPosition(), angle);
return calcAngleSpeed;
}
public double anglePIDCalcABS(double angle){
double calcAngleSpeed = 0;
if(angle != 42069) {
double curPos = angleEncoder.getAbsolutePosition();
double posAngle = angle + 360;
double negAngle = angle - 360;
double curError = Math.abs(curPos - angle);
double posError = Math.abs(curPos - posAngle);
double negError = Math.abs(curPos - negAngle);
if(curError < posError && curError < negError) {
calcAngleSpeed = anglePID.calculate(angleEncoder.getAbsolutePosition(), angle);
} else if(posError < curError && posError < negError) {
calcAngleSpeed = anglePID.calculate(angleEncoder.getAbsolutePosition(), posAngle);
} else {
calcAngleSpeed = anglePID.calculate(angleEncoder.getAbsolutePosition(), negAngle);
}
}
return calcAngleSpeed;
}
public void resetEncoder(){
angleEncoder.setPosition(0);
}
public double getEncoder(){
return angleEncoder.getAbsolutePosition();
}
public SwerveModuleState getState(){
return new SwerveModuleState(driveMotor.getEncoder().getVelocity()*0.31918645197/(60*6.86), new Rotation2d(getEncoder()*Math.PI/180));
}
}
|
3e05a22577715256c621f48583c9bb5c8d118bce
| 2,921 |
java
|
Java
|
VendingMachine/java/src/main/java/VendingMachine.java
|
tgdraugr/CodingKatas
|
c9caf7b8cde0ccb50fe74b4dbef3d1b8b8698a8e
|
[
"MIT"
] | null | null | null |
VendingMachine/java/src/main/java/VendingMachine.java
|
tgdraugr/CodingKatas
|
c9caf7b8cde0ccb50fe74b4dbef3d1b8b8698a8e
|
[
"MIT"
] | null | null | null |
VendingMachine/java/src/main/java/VendingMachine.java
|
tgdraugr/CodingKatas
|
c9caf7b8cde0ccb50fe74b4dbef3d1b8b8698a8e
|
[
"MIT"
] | null | null | null | 28.359223 | 113 | 0.607326 | 2,363 |
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class VendingMachine {
private final List<Money> insertedMoney;
private List<Money> availableChange;
private List<Item> availableItems;
public VendingMachine(List<Money> availableChange, List<Item> availableItems) {
this(availableChange, availableItems, new ArrayList<>());
}
protected VendingMachine(List<Money> availableChange, List<Item> availableItems, List<Money> insertedMoney) {
setup(availableChange, availableItems);
this.insertedMoney = insertedMoney;
}
public Map<Money, Long> availableChange() {
return Grouped(this.availableChange);
}
public Map<Item, Long> availableItems() {
return Grouped(this.availableItems);
}
public void setup(List<Money> availableChange, List<Item> availableItems) {
this.availableChange = new ArrayList<>(availableChange);
this.availableItems = new ArrayList<>(availableItems);
}
public void insert(Money money) {
this.insertedMoney.add(money);
}
public Amount currentAmount() {
return new Amount(this.insertedMoney);
}
public Amount refund() {
var amount = new Amount(new ArrayList<>(this.insertedMoney));
this.insertedMoney.clear();
return amount;
}
public Item selectItem(String selector) {
var selectedItem = item(selector);
selectedItem.ifPresent(item -> {
this.availableChange.addAll(item.price.money());
this.availableItems.remove(item);
});
return selectedItem.orElse(null);
}
private Optional<Item> item(String selector) {
for (var item : this.availableItems) {
if (item.selector.equals(selector)) {
return Optional.of(item);
}
}
return Optional.empty();
}
private <E> Map<E, Long> Grouped(List<E> elements) {
return elements
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
public static class Item {
private final String selector;
private final Price price;
public Item(String selector, Price price) {
this.selector = selector;
this.price = price;
}
public double value() {
return this.price.value();
}
public String selector() {
return this.selector;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return Objects.equals(selector, item.selector);
}
@Override
public int hashCode() {
return Objects.hash(selector);
}
}
}
|
3e05a31419f398e9e3b46f1b2cb1c256492d0072
| 752 |
java
|
Java
|
code/mancala-backend/src/main/java/com/halilayyildiz/game/data/dto/GameJoinResponse.java
|
halilayyildiz/mancala-game
|
80bc08c18be745a50780dcc8a46e1bf6bcd6ea89
|
[
"MIT"
] | null | null | null |
code/mancala-backend/src/main/java/com/halilayyildiz/game/data/dto/GameJoinResponse.java
|
halilayyildiz/mancala-game
|
80bc08c18be745a50780dcc8a46e1bf6bcd6ea89
|
[
"MIT"
] | null | null | null |
code/mancala-backend/src/main/java/com/halilayyildiz/game/data/dto/GameJoinResponse.java
|
halilayyildiz/mancala-game
|
80bc08c18be745a50780dcc8a46e1bf6bcd6ea89
|
[
"MIT"
] | 2 |
2019-09-16T06:38:58.000Z
|
2020-01-21T09:47:32.000Z
| 20.324324 | 51 | 0.654255 | 2,364 |
package com.halilayyildiz.game.data.dto;
import com.halilayyildiz.game.model.IPlayer;
import lombok.Data;
@Data
public class GameJoinResponse
{
private Result result;
private String gameId;
private String playerId;
private String playerName;
private Integer playerIndex;
public GameJoinResponse(IPlayer player)
{
this.gameId = player.getGame().getId();
this.playerId = player.getId();
this.playerName = player.getName();
this.playerIndex = player.getPlayerIndex();
}
public GameJoinResponse success()
{
this.result = Result.SUCCESS;
return this;
}
public GameJoinResponse fail()
{
this.result = Result.FAIL;
return this;
}
}
|
3e05a4382c8ce3ad535d464c1cecb01f60d2b8de
| 5,358 |
java
|
Java
|
src/test/java/nyla/solutions/core/patterns/iteration/PageCriteriaTest.java
|
nyla-solutions/nyla
|
2eb67055d2285e9b62ca881efb02f065d5010225
|
[
"Apache-2.0"
] | 6 |
2016-03-20T23:20:07.000Z
|
2021-09-20T13:20:21.000Z
|
src/test/java/nyla/solutions/core/patterns/iteration/PageCriteriaTest.java
|
nyla-solutions/nyla
|
2eb67055d2285e9b62ca881efb02f065d5010225
|
[
"Apache-2.0"
] | 4 |
2016-03-02T16:48:18.000Z
|
2018-11-16T17:00:24.000Z
|
src/test/java/nyla/solutions/core/patterns/iteration/PageCriteriaTest.java
|
nyla-solutions/nyla
|
2eb67055d2285e9b62ca881efb02f065d5010225
|
[
"Apache-2.0"
] | 1 |
2019-09-05T16:08:46.000Z
|
2019-09-05T16:08:46.000Z
| 26.656716 | 76 | 0.620007 | 2,365 |
package nyla.solutions.core.patterns.iteration;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class PageCriteriaTest
{
@Test
void getId()
{
String expected ="expected";
assertEquals(expected,new PageCriteria(expected).getId());
}
@Test
void constructor_BeginIndex_Size()
{
int beginIndex = 4;
int size = 5;
PageCriteria subject = new PageCriteria(beginIndex,size);
assertEquals(size,subject.getSize());
assertEquals(beginIndex,subject.getBeginIndex());
}
@Test
void constructor_ID()
{
String id ="hello";
PageCriteria subject = new PageCriteria(id);
assertEquals(id,subject.getId());
}
@Test
void constructor_BeginIndex_LessThan_1_ThrowsException()
{
assertThrows(Exception.class, () -> new PageCriteria(0,1));
assertDoesNotThrow( () -> new PageCriteria(1,1));
}
@Test
void hasIdentifier()
{
PageCriteria subject = new PageCriteria();
assertFalse(subject.hasIdentifier());
subject.setId("id");
assertTrue(subject.hasIdentifier());
subject.setId("");
assertFalse(subject.hasIdentifier());
subject.setId("hello");
assertTrue(subject.hasIdentifier());
subject.setId(null);
assertFalse(subject.hasIdentifier());
}
@Test
void incrementPage()
{
int beginIndex = 4;
int size = 5;
PageCriteria subject = new PageCriteria(beginIndex,size);
subject.incrementPage();
assertEquals(9,subject.getBeginIndex());
assertEquals(size,subject.getSize());
}
@Test
void incrementPage_PageCriteria()
{
int beginIndex = 4;
int size = 5;
PageCriteria subject = new PageCriteria(beginIndex,size);
PageCriteria.incrementPage(subject);
assertEquals(9,subject.getBeginIndex());
assertEquals(size,subject.getSize());
}
@Test
void constructor_Size_LessThan_1_ThrowsException()
{
assertThrows(Exception.class, () -> new PageCriteria(0,0));
assertThrows(Exception.class, () -> new PageCriteria(0,-1));
}
@Test
void first()
{
int beginIndex =4;
int size = 1;
PageCriteria subject = new PageCriteria(beginIndex,size);
subject.first();
assertEquals(1,subject.getBeginIndex());
assertEquals(size,subject.getSize());
}
@Test
void className()
{
PageCriteria subject = new PageCriteria();
String expected = "hello";
subject.setClassName(expected);
assertEquals(expected,subject.getClassName());
}
@Test
void getEndIndex()
{
assertEquals(6,new PageCriteria(1,5).getEndIndex());
}
@Test
void id()
{
PageCriteria subject = new PageCriteria();
String expected ="id";
subject.setId(expected);
assertEquals(expected,subject.getId());
}
@Test
void size()
{
PageCriteria subject = new PageCriteria();
assertEquals(0,subject.getSize());
int expected = 3;
subject.setSize(expected);
assertEquals(expected,subject.getSize());
}
@Test
void savePagination()
{
PageCriteria subject = new PageCriteria();
assertFalse(subject.isSavePagination());
subject.setSavePagination(true);
assertTrue(subject.isSavePagination());
subject.setSavePagination(false);
assertFalse(subject.isSavePagination());
}
@Test
void testToString()
{
int beginIndex =2;
int size = 3;
PageCriteria subject = new PageCriteria(beginIndex,size);
assertThat(subject.toString()).contains(String.valueOf(beginIndex));
assertThat(subject.toString()).contains(String.valueOf(size));
String id ="myId";
subject.setId(id);
assertThat(subject.toString()).contains(subject.getId());
subject.setClassName("theClassName");
assertThat(subject.toString()).contains(subject.getClassName());
}
@Test
void testEquals()
{
int beginIndex =2;
int size = 3;
PageCriteria subject1 = new PageCriteria(beginIndex,size);
PageCriteria subject2 = new PageCriteria(beginIndex,size);
assertTrue(subject1.equals(subject2));
String id ="myId";
subject1.setId(id);
assertFalse(subject1.equals(subject2));
subject2.setId(id);
assertTrue(subject1.equals(subject2));
subject1.setClassName(id);
assertFalse(subject1.equals(subject2));
subject2.setClassName(id);
assertTrue(subject1.equals(subject2));
}
@Test
void testHashCode()
{
int beginIndex =2;
int size = 3;
PageCriteria subject1 = new PageCriteria(beginIndex,size);
PageCriteria subject2 = new PageCriteria(beginIndex,size);
assertEquals(subject1.hashCode(),subject2.hashCode());
String id ="myId";
subject1.setId(id);
assertNotEquals(subject1.hashCode(),subject2.hashCode());
subject2.setId(id);
assertEquals(subject1.hashCode(),subject2.hashCode());
}
}
|
3e05a4b25ac0602593ef3b7099d45bd3b913dbb3
| 351 |
java
|
Java
|
gulimall-product/src/main/java/com/li/gulimall/product/vo/BaseAttrs.java
|
kugga-no1/gulimail
|
cf0cc7df81643c5210fa52124ac14520df6f5899
|
[
"Apache-2.0"
] | null | null | null |
gulimall-product/src/main/java/com/li/gulimall/product/vo/BaseAttrs.java
|
kugga-no1/gulimail
|
cf0cc7df81643c5210fa52124ac14520df6f5899
|
[
"Apache-2.0"
] | 1 |
2021-08-23T06:45:23.000Z
|
2021-08-23T06:45:23.000Z
|
gulimall-product/src/main/java/com/li/gulimall/product/vo/BaseAttrs.java
|
kugga-no1/gulimall
|
cf0cc7df81643c5210fa52124ac14520df6f5899
|
[
"Apache-2.0"
] | null | null | null | 15.727273 | 44 | 0.67341 | 2,366 |
/**
* Copyright 2021 bejson.com
*/
package com.li.gulimall.product.vo;
import lombok.Data;
/**
* Auto-generated: 2021-08-20 11:15:30
*
* @author bejson.com ([email protected])
* @website http://www.bejson.com/java2pojo/
*/
@Data
public class BaseAttrs {
private Long attrId;
private String attrValues;
private int showDesc;
}
|
3e05a4cbbca3dfd838124920755e2a9cacfa752f
| 4,920 |
java
|
Java
|
src/main/java/org/dailywork/config/Options.java
|
piotr-sobczyk/daily-work
|
1d69c66ed4151c60733b30eef25cd75a34962c03
|
[
"Apache-2.0"
] | 1 |
2016-03-09T14:12:03.000Z
|
2016-03-09T14:12:03.000Z
|
src/main/java/org/dailywork/config/Options.java
|
piotr-sobczyk/daily-work
|
1d69c66ed4151c60733b30eef25cd75a34962c03
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/dailywork/config/Options.java
|
piotr-sobczyk/daily-work
|
1d69c66ed4151c60733b30eef25cd75a34962c03
|
[
"Apache-2.0"
] | null | null | null | 29.285714 | 95 | 0.630081 | 2,367 |
/*
* Copyright (c) 2010-2012 Célio Cidral Junior.
*
* 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.dailywork.config;
import java.io.File;
import javax.inject.Inject;
import com.google.common.eventbus.EventBus;
import org.dailywork.bus.messages.config.TimeOnTrayConfigChanged;
import org.dailywork.bus.messages.ui.LookChanged;
import org.dailywork.ui.theme.Theme;
import org.dailywork.ui.theme.themes.BrushedMetal;
public class Options {
private static final String TIME_POMODORO = "option.time.bursts";
private static final String TIME_BREAK = "option.time.break";
private static final String UI_THEME = "option.ui.theme";
private static final String UI_AUTOHIDE_WINDOW = "option.ui.window.autohide";
private static final String UI_DRAGGABLE_WINDOW = "option.ui.window.draggable";
private static final String UI_SHOW_TIME_ON_TRAY = "option.ui.showTimeOnTray";
private static final String SOUND_WIND = "option.sound.timer.wind";
private static final String SOUND_TICTAC = "option.sound.timer.tictac";
private static final String SOUND_DING = "option.sound.timer.ding";
@Inject
private Configuration config;
@Inject
private EventBus bus;
private UserInterfaceOptions ui = new UserInterfaceOptions();
private SoundOptions sound = new SoundOptions();
private TimeOptions time = new TimeOptions();
public UserInterfaceOptions ui() {
return ui;
}
public SoundOptions sound() {
return sound;
}
public TimeOptions time() {
return time;
}
public class TimeOptions {
public int pomodoro() {
return config.asInt(TIME_POMODORO, 25);
}
public void pomodoro(int minutes) {
config.set(TIME_POMODORO, minutes);
}
public int breakTime() {
return config.asInt(TIME_BREAK, 5);
}
public void breakTime(int minutes) {
config.set(TIME_BREAK, minutes);
}
}
public class UserInterfaceOptions {
public boolean autoHideWindow() {
return config.asBoolean(UI_AUTOHIDE_WINDOW, true);
}
public void autoHide(boolean autoHide) {
config.set(UI_AUTOHIDE_WINDOW, autoHide);
}
public Theme theme() {
return config.asObject(UI_THEME, BrushedMetal.class);
}
public void theme(Class<? extends Theme> clazz) {
Class<? extends Theme> currentClass = config.asClass(UI_THEME, BrushedMetal.class);
if (!clazz.equals(currentClass)) {
config.set(UI_THEME, clazz);
bus.post(new LookChanged());
}
}
public boolean showTimeOnTray() {
return config.asBoolean(UI_SHOW_TIME_ON_TRAY, true);
}
public void showTimeOnTray(boolean show) {
if (show != showTimeOnTray()) {
config.set(UI_SHOW_TIME_ON_TRAY, show);
bus.post(new TimeOnTrayConfigChanged(show));
}
}
public boolean draggableWindow() {
return config.asBoolean(UI_DRAGGABLE_WINDOW, false);
}
public void draggableWindow(boolean draggable) {
config.set(UI_DRAGGABLE_WINDOW, draggable);
}
}
public class SoundOptions {
private SoundConfig wind = new SoundConfig(SOUND_WIND);
private SoundConfig tictac = new SoundConfig(SOUND_TICTAC);
private SoundConfig ding = new SoundConfig(SOUND_DING);
public SoundConfig wind() {
return wind;
}
public SoundConfig tictac() {
return tictac;
}
public SoundConfig ding() {
return ding;
}
}
public class SoundConfig {
private String enabledKey;
private String fileKey;
public SoundConfig(String key) {
this.enabledKey = key + ".enabled";
this.fileKey = key + ".file";
}
public boolean enabled() {
return config.asBoolean(enabledKey, true);
}
public void enable(boolean enable) {
config.set(enabledKey, enable);
}
public File file() {
return config.asFile(fileKey);
}
public void file(File file) {
config.set(fileKey, file);
}
}
}
|
3e05a528953151049b62a3f68f82f2320ec4e02f
| 3,367 |
java
|
Java
|
android-godeye-monitor/src/main/java/cn/hikyson/godeye/monitor/server/Router.java
|
dodola/AndroidGodEye
|
5b8854610bbc8af41b452a1bcb9f7fc3f99bec93
|
[
"Apache-2.0"
] | 8 |
2018-02-01T01:01:47.000Z
|
2021-06-01T16:59:22.000Z
|
android-godeye-monitor/src/main/java/cn/hikyson/godeye/monitor/server/Router.java
|
hongyangAndroid/AndroidGodEye
|
5b8854610bbc8af41b452a1bcb9f7fc3f99bec93
|
[
"Apache-2.0"
] | null | null | null |
android-godeye-monitor/src/main/java/cn/hikyson/godeye/monitor/server/Router.java
|
hongyangAndroid/AndroidGodEye
|
5b8854610bbc8af41b452a1bcb9f7fc3f99bec93
|
[
"Apache-2.0"
] | 2 |
2018-06-30T02:19:41.000Z
|
2019-04-23T15:08:48.000Z
| 39.151163 | 79 | 0.71488 | 2,368 |
package cn.hikyson.godeye.monitor.server;
import android.content.Context;
import android.net.Uri;
import android.support.v4.util.ArrayMap;
import java.util.Map;
import cn.hikyson.godeye.monitor.modules.AppInfoModule;
import cn.hikyson.godeye.monitor.modules.AssetsModule;
import cn.hikyson.godeye.monitor.modules.BatteryModule;
import cn.hikyson.godeye.monitor.modules.BlockModule;
import cn.hikyson.godeye.monitor.modules.CpuModule;
import cn.hikyson.godeye.monitor.modules.CrashModule;
import cn.hikyson.godeye.monitor.modules.FpsModule;
import cn.hikyson.godeye.monitor.modules.HeapModule;
import cn.hikyson.godeye.monitor.modules.LeakMemoryModule;
import cn.hikyson.godeye.monitor.modules.Module;
import cn.hikyson.godeye.monitor.modules.NetworkModule;
import cn.hikyson.godeye.monitor.modules.PssModule;
import cn.hikyson.godeye.monitor.modules.RamModule;
import cn.hikyson.godeye.monitor.modules.StartUpModule;
import cn.hikyson.godeye.monitor.modules.ThreadModule;
import cn.hikyson.godeye.monitor.modules.TrafficModule;
/**
* Created by kysonchao on 2017/9/3.
*/
public class Router {
private Map<String, Module> mRouteModules;
private Router() {
}
private static class InstanceHolder {
private static Router sInstance = new Router();
}
public static Router get() {
return InstanceHolder.sInstance;
}
public void init(Context context) {
mRouteModules = new ArrayMap<>();
AssetsModule assetsModule = new AssetsModule(context, "androidgodeye");
mRouteModules.put("assets", assetsModule);
AppInfoModule appInfoModule = new AppInfoModule();
mRouteModules.put("appinfo", appInfoModule);
BatteryModule batteryModule = new BatteryModule();
mRouteModules.put("battery", batteryModule);
BlockModule blockModule = new BlockModule();
mRouteModules.put("block", blockModule);
CpuModule cpuModule = new CpuModule();
mRouteModules.put("cpu", cpuModule);
FpsModule fpsModule = new FpsModule();
mRouteModules.put("fps", fpsModule);
HeapModule heapModule = new HeapModule();
mRouteModules.put("heap", heapModule);
LeakMemoryModule LeakMemoryModule = new LeakMemoryModule();
mRouteModules.put("leakMemory", LeakMemoryModule);
NetworkModule networkModule = new NetworkModule();
mRouteModules.put("network", networkModule);
PssModule pssModule = new PssModule();
mRouteModules.put("pss", pssModule);
RamModule ramModule = new RamModule();
mRouteModules.put("ram", ramModule);
StartUpModule startUpModule = new StartUpModule();
mRouteModules.put("startup", startUpModule);
TrafficModule trafficModule = new TrafficModule();
mRouteModules.put("traffic", trafficModule);
ThreadModule threadModule = new ThreadModule();
mRouteModules.put("thread", threadModule);
CrashModule crashModule = new CrashModule();
mRouteModules.put("crash", crashModule);
}
public byte[] process(Uri uri) throws Throwable {
String moduleName = uri.getPath();
Module module = mRouteModules.get(moduleName);
if (module == null) {
return mRouteModules.get("assets").process(moduleName, uri);
}
return module.process(moduleName, uri);
}
}
|
3e05a5347ba0f1fdc503cedb59712193d014b6f4
| 679 |
java
|
Java
|
addressbook-web-test/src/test/java/ru/sqrt/ptf/addressbook/tests/CreateNewContactTest.java
|
mugurel3000/java_ook
|
7f09fef8d22bcd6b2491bcf80b25cc3dfadd623f
|
[
"Apache-2.0"
] | null | null | null |
addressbook-web-test/src/test/java/ru/sqrt/ptf/addressbook/tests/CreateNewContactTest.java
|
mugurel3000/java_ook
|
7f09fef8d22bcd6b2491bcf80b25cc3dfadd623f
|
[
"Apache-2.0"
] | null | null | null |
addressbook-web-test/src/test/java/ru/sqrt/ptf/addressbook/tests/CreateNewContactTest.java
|
mugurel3000/java_ook
|
7f09fef8d22bcd6b2491bcf80b25cc3dfadd623f
|
[
"Apache-2.0"
] | null | null | null | 28.291667 | 71 | 0.755523 | 2,369 |
package ru.sqrt.ptf.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.sqrt.ptf.addressbook.model.ContactData;
import java.util.List;
public class CreateNewContactTest extends TestBase {
@Test
public void testCreateNewContact() {
List<ContactData> before = app.getContactHelper().getContactList();
app.getNavigationHelper().gotoNewContactPage();
app.getContactHelper().fillFieldNewContact(true);
app.getContactHelper().addNewContact();
app.getContactHelper().gotoHomePage();
List<ContactData> after = app.getContactHelper().getContactList();
Assert.assertEquals(after.size(), before.size() +1);
}
}
|
3e05a60531c44de6f5d2e3dc99b2c91b526e8d14
| 393 |
java
|
Java
|
src/main/java/com/github/joostvdg/demo/springboot2/repository/ProductRepository.java
|
joostvdg/spring-boot-2-demo
|
0e23d3b94be74ef605637f1f7eeb0f14c44315e4
|
[
"MIT"
] | null | null | null |
src/main/java/com/github/joostvdg/demo/springboot2/repository/ProductRepository.java
|
joostvdg/spring-boot-2-demo
|
0e23d3b94be74ef605637f1f7eeb0f14c44315e4
|
[
"MIT"
] | null | null | null |
src/main/java/com/github/joostvdg/demo/springboot2/repository/ProductRepository.java
|
joostvdg/spring-boot-2-demo
|
0e23d3b94be74ef605637f1f7eeb0f14c44315e4
|
[
"MIT"
] | null | null | null | 28.071429 | 76 | 0.788804 | 2,370 |
package com.github.joostvdg.demo.springboot2.repository;
import com.github.joostvdg.demo.springboot2.model.Product;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface ProductRepository extends CrudRepository<Product, String> {
// @Override
// Optional<Product> findById(String id);
@Override
void delete(Product deleted);
}
|
3e05a606f0b5058299fd54e3c7a71f4269ececfa
| 6,034 |
java
|
Java
|
servers/store/src/test/java/org/projectnessie/server/store/TestStoreWorker.java
|
omarsmak/nessie
|
bd008262cb708c8de2cb90d9e4f23bc0910ce6e6
|
[
"Apache-2.0"
] | null | null | null |
servers/store/src/test/java/org/projectnessie/server/store/TestStoreWorker.java
|
omarsmak/nessie
|
bd008262cb708c8de2cb90d9e4f23bc0910ce6e6
|
[
"Apache-2.0"
] | null | null | null |
servers/store/src/test/java/org/projectnessie/server/store/TestStoreWorker.java
|
omarsmak/nessie
|
bd008262cb708c8de2cb90d9e4f23bc0910ce6e6
|
[
"Apache-2.0"
] | null | null | null | 40.77027 | 99 | 0.716274 | 2,371 |
/*
* Copyright (C) 2020 Dremio
*
* 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.projectnessie.server.store;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.protobuf.ByteString;
import java.time.Instant;
import java.util.AbstractMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.projectnessie.model.CommitMeta;
import org.projectnessie.model.Contents;
import org.projectnessie.model.ImmutableCommitMeta;
import org.projectnessie.model.ImmutableDeltaLakeTable;
import org.projectnessie.model.ImmutableIcebergTable;
import org.projectnessie.model.ImmutableSqlView;
import org.projectnessie.model.SqlView;
import org.projectnessie.store.ObjectTypes;
class TestStoreWorker {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ID = "x";
private final TableCommitMetaStoreWorker worker = new TableCommitMetaStoreWorker();
@ParameterizedTest
@MethodSource("provideDeserialization")
void testDeserialization(Map.Entry<ByteString, Contents> entry) {
Contents actual = worker.getValueSerializer().fromBytes(entry.getKey());
Assertions.assertEquals(entry.getValue(), actual);
}
@ParameterizedTest
@MethodSource("provideDeserialization")
void testSerialization(Map.Entry<ByteString, Contents> entry) {
ByteString actual = worker.getValueSerializer().toBytes(entry.getValue());
Assertions.assertEquals(entry.getKey(), actual);
}
@ParameterizedTest
@MethodSource("provideDeserialization")
void testSerde(Map.Entry<ByteString, Contents> entry) {
ByteString actualBytes = worker.getValueSerializer().toBytes(entry.getValue());
Assertions.assertEquals(entry.getValue(), worker.getValueSerializer().fromBytes(actualBytes));
Contents actualContents = worker.getValueSerializer().fromBytes(entry.getKey());
Assertions.assertEquals(entry.getKey(), worker.getValueSerializer().toBytes(actualContents));
}
@Test
void testCommitSerde() throws JsonProcessingException {
CommitMeta expectedCommit =
ImmutableCommitMeta.builder()
.commitTime(Instant.now())
.authorTime(Instant.now())
.author("bill")
.committer("ted")
.hash("xyz")
.message("commit msg")
.build();
ByteString expectedBytes = ByteString.copyFrom(MAPPER.writeValueAsBytes(expectedCommit));
CommitMeta actualCommit = worker.getMetadataSerializer().fromBytes(expectedBytes);
Assertions.assertEquals(expectedCommit, actualCommit);
ByteString actualBytes = worker.getMetadataSerializer().toBytes(expectedCommit);
Assertions.assertEquals(expectedBytes, actualBytes);
actualBytes = worker.getMetadataSerializer().toBytes(expectedCommit);
Assertions.assertEquals(expectedCommit, worker.getMetadataSerializer().fromBytes(actualBytes));
actualCommit = worker.getMetadataSerializer().fromBytes(expectedBytes);
Assertions.assertEquals(expectedBytes, worker.getMetadataSerializer().toBytes(actualCommit));
}
private static Stream<Map.Entry<ByteString, Contents>> provideDeserialization() {
return Stream.of(getIceberg(), getDelta(), getView());
}
private static Map.Entry<ByteString, Contents> getIceberg() {
String path = "foo/bar";
Contents contents = ImmutableIcebergTable.builder().metadataLocation(path).id(ID).build();
ByteString bytes =
ObjectTypes.Contents.newBuilder()
.setId(ID)
.setIcebergTable(ObjectTypes.IcebergTable.newBuilder().setMetadataLocation(path))
.build()
.toByteString();
return new AbstractMap.SimpleImmutableEntry<>(bytes, contents);
}
private static Map.Entry<ByteString, Contents> getDelta() {
String path = "foo/bar";
String cl1 = "xyz";
String cl2 = "abc";
String ml1 = "efg";
String ml2 = "hij";
Contents contents =
ImmutableDeltaLakeTable.builder()
.lastCheckpoint(path)
.addCheckpointLocationHistory(cl1)
.addCheckpointLocationHistory(cl2)
.addMetadataLocationHistory(ml1)
.addMetadataLocationHistory(ml2)
.id(ID)
.build();
ByteString bytes =
ObjectTypes.Contents.newBuilder()
.setId(ID)
.setDeltaLakeTable(
ObjectTypes.DeltaLakeTable.newBuilder()
.setLastCheckpoint(path)
.addCheckpointLocationHistory(cl1)
.addCheckpointLocationHistory(cl2)
.addMetadataLocationHistory(ml1)
.addMetadataLocationHistory(ml2))
.build()
.toByteString();
return new AbstractMap.SimpleImmutableEntry<>(bytes, contents);
}
private static Map.Entry<ByteString, Contents> getView() {
String path = "SELECT * FROM foo.bar,";
Contents contents =
ImmutableSqlView.builder().dialect(SqlView.Dialect.DREMIO).sqlText(path).id(ID).build();
ByteString bytes =
ObjectTypes.Contents.newBuilder()
.setId(ID)
.setSqlView(ObjectTypes.SqlView.newBuilder().setSqlText(path).setDialect("DREMIO"))
.build()
.toByteString();
return new AbstractMap.SimpleImmutableEntry<>(bytes, contents);
}
}
|
3e05a804237831c09be3d9eedacaaaa4a3a9e8bb
| 1,497 |
java
|
Java
|
build/tmp/expandedArchives/forge-1.16.5-36.0.46_mapped_snapshot_20201028-1.16.3-sources.jar_d86e7e7643b801f3a450d94fefd63481/net/minecraft/entity/monster/AbstractIllagerEntity.java
|
JoppeGames1/TvStudio-1_16
|
181f67939b6c67e410e7881b20e10508b74e306b
|
[
"Apache-2.0"
] | 2 |
2020-11-28T06:31:55.000Z
|
2020-11-29T22:15:39.000Z
|
build/tmp/expandedArchives/forge-1.16.5-36.0.46_mapped_snapshot_20201028-1.16.3-sources.jar_d86e7e7643b801f3a450d94fefd63481/net/minecraft/entity/monster/AbstractIllagerEntity.java
|
JoppeGames1/TvStudio-1_16
|
181f67939b6c67e410e7881b20e10508b74e306b
|
[
"Apache-2.0"
] | 1 |
2020-12-05T14:47:34.000Z
|
2020-12-05T14:47:34.000Z
|
build/tmp/expandedArchives/forge-1.16.5-36.0.46_mapped_snapshot_20201028-1.16.3-sources.jar_d86e7e7643b801f3a450d94fefd63481/net/minecraft/entity/monster/AbstractIllagerEntity.java
|
JoppeGames1/TvStudio-1_16
|
181f67939b6c67e410e7881b20e10508b74e306b
|
[
"Apache-2.0"
] | 3 |
2020-11-28T20:19:58.000Z
|
2020-11-29T22:16:03.000Z
| 27.722222 | 118 | 0.714763 | 2,372 |
package net.minecraft.entity.monster;
import net.minecraft.entity.CreatureAttribute;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.ai.goal.OpenDoorGoal;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public abstract class AbstractIllagerEntity extends AbstractRaiderEntity {
protected AbstractIllagerEntity(EntityType<? extends AbstractIllagerEntity> type, World worldIn) {
super(type, worldIn);
}
protected void registerGoals() {
super.registerGoals();
}
public CreatureAttribute getCreatureAttribute() {
return CreatureAttribute.ILLAGER;
}
@OnlyIn(Dist.CLIENT)
public AbstractIllagerEntity.ArmPose getArmPose() {
return AbstractIllagerEntity.ArmPose.CROSSED;
}
@OnlyIn(Dist.CLIENT)
public static enum ArmPose {
CROSSED,
ATTACKING,
SPELLCASTING,
BOW_AND_ARROW,
CROSSBOW_HOLD,
CROSSBOW_CHARGE,
CELEBRATING,
NEUTRAL;
}
public class RaidOpenDoorGoal extends OpenDoorGoal {
public RaidOpenDoorGoal(AbstractRaiderEntity raider) {
super(raider, false);
}
/**
* Returns whether execution should begin. You can also read and cache any state necessary for execution in this
* method as well.
*/
public boolean shouldExecute() {
return super.shouldExecute() && AbstractIllagerEntity.this.isRaidActive();
}
}
}
|
3e05a845237ae2ff640da7786ca3ce158ad19656
| 1,115 |
java
|
Java
|
Bungee/src/main/java/com/github/jolice/bungee/ProxyChannelDeclaration.java
|
TrashToggled/MinecraftNetwork
|
3e2dd390e3fbcf72b908afb03fc144dfaee3a5a7
|
[
"MIT"
] | 41 |
2020-06-13T19:25:06.000Z
|
2022-03-08T00:03:09.000Z
|
Bungee/src/main/java/com/github/jolice/bungee/ProxyChannelDeclaration.java
|
TrashToggled/MinecraftNetwork
|
3e2dd390e3fbcf72b908afb03fc144dfaee3a5a7
|
[
"MIT"
] | 1 |
2020-12-23T14:47:50.000Z
|
2020-12-23T14:47:50.000Z
|
Bungee/src/main/java/com/github/jolice/bungee/ProxyChannelDeclaration.java
|
TrashToggled/MinecraftNetwork
|
3e2dd390e3fbcf72b908afb03fc144dfaee3a5a7
|
[
"MIT"
] | 5 |
2020-06-30T10:03:07.000Z
|
2022-03-06T19:54:06.000Z
| 30.972222 | 85 | 0.735426 | 2,373 |
package io.riguron.bungee;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import lombok.RequiredArgsConstructor;
import io.riguron.server.ServerName;
import io.riguron.system.task.startup.PostLoadTask;
import io.riguron.messaging.MessagingChannels;
import io.riguron.messaging.amqp.AMQPException;
import java.io.IOException;
/**
* Task responsible for declaring AMQP channel for BungeeCord
*/
@RequiredArgsConstructor
public class ProxyChannelDeclaration implements PostLoadTask {
private final DefaultConsumer messageListener;
private final ServerName serverName;
private final Channel channel;
@Override
public void run() {
try {
channel.queueDeclare(MessagingChannels.PROXY, false, false, false, null);
channel.queueDeclare(serverName.get(), false, false, false, null);
channel.basicConsume(MessagingChannels.PROXY, true, messageListener);
channel.basicConsume(serverName.get(), true, messageListener);
} catch (IOException e) {
throw new AMQPException(e);
}
}
}
|
3e05aa3ff30fe63eeb7899f79d9bbdfab794e3b0
| 1,178 |
java
|
Java
|
apm-collector/apm-collector-analysis/analysis-register/register-define/src/main/java/org/apache/skywalking/apm/collector/analysis/register/define/service/IApplicationIDService.java
|
CaiShiJun/incubator-skywalking
|
64981f938d7fa8c968310ad5d138a9f668100831
|
[
"Apache-2.0"
] | 12 |
2018-01-28T03:32:37.000Z
|
2022-03-02T07:10:39.000Z
|
apm-collector/apm-collector-analysis/analysis-register/register-define/src/main/java/org/apache/skywalking/apm/collector/analysis/register/define/service/IApplicationIDService.java
|
piaoyingfeimeng/incubator-skywalking
|
dbc0f8b9d2d7b6e18eb98d718709b04e205b1d7f
|
[
"Apache-2.0"
] | 5 |
2020-12-02T18:39:39.000Z
|
2022-01-21T23:38:17.000Z
|
apm-collector/apm-collector-analysis/analysis-register/register-define/src/main/java/org/apache/skywalking/apm/collector/analysis/register/define/service/IApplicationIDService.java
|
piaoyingfeimeng/incubator-skywalking
|
dbc0f8b9d2d7b6e18eb98d718709b04e205b1d7f
|
[
"Apache-2.0"
] | 4 |
2018-01-18T07:52:37.000Z
|
2019-02-14T16:10:51.000Z
| 38 | 77 | 0.770798 | 2,375 |
/*
* 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.skywalking.apm.collector.analysis.register.define.service;
import org.apache.skywalking.apm.collector.core.module.Service;
/**
* @author peng-yongsheng
*/
public interface IApplicationIDService extends Service {
int getOrCreateForApplicationCode(String applicationCode);
int getOrCreateForAddressId(int addressId, String networkAddress);
}
|
3e05aaa9a2b67237334dc7cb0f94a81eed89ba66
| 9,197 |
java
|
Java
|
server/Group/src/main/java/com/Xjournal/Group/DBGenerator.java
|
RomanPanshin/X-Class
|
b75344b71fc8fc887004c5643f339fc47d9c74d7
|
[
"BSD-3-Clause"
] | 1 |
2021-01-07T11:41:11.000Z
|
2021-01-07T11:41:11.000Z
|
Group/src/main/java/com/Xjournal/Group/DBGenerator.java
|
RomanPanshin/XClassBack
|
6bb8bb5458fd991bcb22ed8c315d10cc5cea9d38
|
[
"BSD-2-Clause"
] | null | null | null |
Group/src/main/java/com/Xjournal/Group/DBGenerator.java
|
RomanPanshin/XClassBack
|
6bb8bb5458fd991bcb22ed8c315d10cc5cea9d38
|
[
"BSD-2-Clause"
] | null | null | null | 33.443636 | 178 | 0.54757 | 2,376 |
package com.Xjournal.Group;
import com.Xjournal.Group.Entity.*;
import com.Xjournal.Group.Entity.GroupDate;
import com.Xjournal.Group.Repo.*;
import com.google.firebase.auth.FirebaseAuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
@Component
public class DBGenerator {
@Autowired
private UserRepository userRepository;
@Autowired
private LessonRepository lessonRepository;
@Autowired
private ClassInfoRepository classInfoRepository;
@Autowired
private AdditionalLessonRepository additionalLessonRepository;
@Autowired
private VideoLessonRepository videoLessonRepository;
private ArrayList<String> teachers = new ArrayList<>();
private ArrayList<ClassInfo> classes = new ArrayList<>();
private static final int classCount= 11;
private static final int teacherCount= 22;
private static final String[] classNames= {"А", "Б"};
private HashMap<String,Boolean > teachersOccupy = new HashMap<String, Boolean>();
private String[] lessonNames = {
"Русский язык",
"Иностранный язык",
"Литература",
"Информатика",
"История древнего мира",
"Математика",
"Обществознание",
"Музыка",
"ОДНКНР",
"Труд",
"Природоведение",
"Основы безопасности жизнедеятельности",
"География",
"ИЗО (рисование)",
"Физическая культура"
};
public void generateAdditionalLessons(){
int k = 0;
for(String ch : classNames){
for(int i = 1; i != 12; i++){
for(String ln : lessonNames){
additionalLessonRepository.sendALessonToDB(new AdditionalLesson(ln, i + ch));
k++;
}
System.out.println(k + " " + i + ch);
k = 0;
}
}
}
private String[] names = {
" Михаил Александрович",
" Сергей Сергеевич",
" Ахед Гаджимурадович",
" Джорджо",
" Сабетказы",
" Лариса Анатольевна",
" Виктор Петрович",
" Нина Георгиевна",
" Рафаэль",
" Сен Суренович",
" Асеф Мехманович",
" Муслим Бахтиярович",
" Ильдар Анвярович",
" Василий Олегович",
" Ирина Анатольевна",
" Николай Викторович",
" Валерий Абрамович",
" Юрий Петрович",
" Хож-Ахмед Ахмадович",
" Леонид Давидович",
" Платон Сергеевич",
" Филипп Денисович",
" Евгений Николаевич",
" Владимир Осипович",
" Роман Сергеевич",
" Владимир Генрихович",
" Ахмет Хамиевич",
" Владимир Алексеевич",
" Андрей Олегович",
" Игорь Михайлович",
" Александр Викторович",
" Олег Николаеви",
" Линор",
" Владимир Иванович",
" Андрей Николаевич",
" Алексей Андреевич",
" Дмитрий Степанович",
" Дмитрий Анатольевич",
" Леонид Григорьевич",
" Игорь Борисович",
" Василий Фёдорович",
" Евгений Валерьевич",
" Александр Николаевич",
" Андрей Вадимович",
" Дмитрий Сергеевич",
" Валерий Дмитриевич",
" Алексей Андреевич",
" Дмитрий Степанович",
" Дмитрий Анатольевич",
" Леонид Григорьевич",
" Игорь Борисович",
" Василий Фёдорович",
" Евгений Валерьевич",
" Александр Николаевич",
" Андрей Вадимович",
" Дмитрий Сергеевич",
" Валерий Дмитриевич"
};
private String[] studentsSurNames = {
"Смирнов" ,
"Иванов" ,
"Кузнецов" ,
"Соколов" ,
"Попов" ,
"Лебедев" ,
"Козлов" ,
"Новиков" ,
"Морозов" ,
"Петров" ,
"Волков" ,
"Соловьёв" ,
"Васильев" ,
"Зайцев" ,
"Павлов" ,
"Семёнов" ,
"Голубев" ,
"Виноградов" ,
"Богданов" ,
"Воробьёв" ,
"Фёдоров" ,
"Михайлов" ,
"Беляев" ,
"Тарасов" ,
"Белов" ,
"Комаров" ,
"Орлов" ,
"Киселёв" ,
"Макаров"
};
String[] Names = {"Михаил"," Максим"," Артем"," Лев"," Марк"," Дмитрий"," Иван"," Матвей","Даниил"};
private void generateStudents() {
int i = 0;
Random r= new Random();
for (ClassInfo c : classes) {
String name = names[r.nextInt(names.length)] + " " + studentsSurNames[r.nextInt(studentsSurNames.length)];
String id = userRepository.createUser("students"+i+"@school.ru","roma123",name,UserRepository.STUDENT,classes.get(i).getId());
i++;
}
}
private void generateTeachers() {
Random r= new Random();
for (int i = 0; i < teacherCount; i++) {
String name = names[r.nextInt(names.length)] + " " + studentsSurNames[r.nextInt(studentsSurNames.length)];
String id = userRepository.createUser("teachers"+i+"@school.ru","roma123",name,UserRepository.TEACHER,null);
teachers.add(id);
}
}
private void generateClasses() throws ExecutionException, InterruptedException {
for (int i = 0; i < classCount; i++) {
for (int j = 0; j < classNames.length; j++) {
ClassInfo classInfo = new ClassInfo(Integer.toString(i + 1),classNames[j]);
classInfoRepository.addClassInfo(classInfo);
classes.add(classInfo);
}
}
}
private String getLessonForTeacher(String id) {
int hash = Math.abs(id.hashCode());
int num = hash % lessonNames.length;
return lessonNames[num];
}
private void generateScheduleForClass(String classId) throws ExecutionException, InterruptedException {
Random r = new Random(100);
for (GroupDate.DayOfWeek d: GroupDate.DayOfWeek.values()) {
int count = r.nextInt(4)+4;
for (int i = 0; i < count; i++) {
String teacher = teachers.get(r.nextInt(teacherCount));
String lessonName = getLessonForTeacher(teacher);
Lesson lesson = new Lesson(lessonName,teacher,classId,new GroupDate(d,i+1));
lessonRepository.addLessonDetails(lesson);
}
}
}
private void generateScheduleForClass2(String classId) throws ExecutionException, InterruptedException {
Random r = new Random(100);
for (GroupDate.DayOfWeek d: GroupDate.DayOfWeek.values()) {
int count = 6;
for (int i = 0; i < count; i++) {
String teacherIndex = "";
String teacher = "";
do {
teacher = teachers.get(r.nextInt(teacherCount));
teacherIndex = teacher+"-"+d+"-"+i+1;
} while (teachersOccupy.getOrDefault(teacherIndex,false));
teachersOccupy.put(teacherIndex,true);
String lessonName = getLessonForTeacher(teacher);
Lesson lesson = new Lesson(lessonName,teacher,classId,new GroupDate(d,i+1));
System.out.println("lesson "+lesson.getIdclass() +" "+ lessonName + " " +(i+1));
lessonRepository.addLessonDetails(lesson);
}
}
}
public void Generate() {
try {
userRepository.DeleteUsers();
generateTeachers();
generateClasses();
generateStudents();
generateAdditionalLessons();
for (ClassInfo c: classes) {
generateScheduleForClass2(c.getId());
}
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (FirebaseAuthException e) {
e.printStackTrace();
}
}
public void createUU(){
String id = userRepository.createUser("admins"+"@school.ru","roma123","Роман Паньшин",UserRepository.ADMIN,null);
}
public void uploadVideoLesson(){
HashMap<String, Boolean> presentStudents = new HashMap<>();
presentStudents.put("1UsH8az6tpb2jnkBhLrlpscS0k33", true);
presentStudents.put("brsoxtbmr3cneJp3iQFVQzETrmc2", false);
VideoLesson result = new VideoLesson(UUID.randomUUID().toString(), "38eb3cbc-ec5e-4cbc-92db-4733fa16a525", presentStudents, "18.02.2021", "0AczFiV5UdQhf3EYJBM6R2b5V3h2");
videoLessonRepository.sendFileToDB(result);
}
public void Clear(){
}
}
|
3e05aaddc1212b46f8d174513b4a1d503b8891af
| 967 |
java
|
Java
|
app/src/androidTest/java/com/prashanth/newsapp/runner/TestRunner.java
|
prashanthramakrishnan/NewsApp
|
21fbc3bf6e9fcf0a2f1dc8d747c6968f28593e95
|
[
"Apache-2.0"
] | 1 |
2019-03-13T15:45:56.000Z
|
2019-03-13T15:45:56.000Z
|
app/src/androidTest/java/com/prashanth/newsapp/runner/TestRunner.java
|
prashanthramakrishnan/NewsApp
|
21fbc3bf6e9fcf0a2f1dc8d747c6968f28593e95
|
[
"Apache-2.0"
] | null | null | null |
app/src/androidTest/java/com/prashanth/newsapp/runner/TestRunner.java
|
prashanthramakrishnan/NewsApp
|
21fbc3bf6e9fcf0a2f1dc8d747c6968f28593e95
|
[
"Apache-2.0"
] | null | null | null | 33.344828 | 94 | 0.788004 | 2,377 |
package com.prashanth.newsapp.runner;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import androidx.annotation.NonNull;
import androidx.test.runner.AndroidJUnitRunner;
import com.prashanth.newsapp.NewsApplication;
import com.prashanth.newsapp.NewsBaseApplication;
import com.prashanth.newsapp.NewsTestApplication;
public class TestRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
super.onCreate(arguments);
}
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, NewsTestApplication.class.getName(), context);
}
}
|
3e05ab729ac3f5d726fd51a1d174d5669a5f3c2d
| 560 |
java
|
Java
|
business/trade/trade-api/src/main/java/study/daydayup/wolf/business/trade/api/domain/vo/buy/Installment.java
|
wolforest/wolf
|
207c61cd473d1433bf3e4fc5a591aaf3a5964418
|
[
"MIT"
] | 18 |
2019-10-05T06:00:36.000Z
|
2021-12-14T10:20:58.000Z
|
business/trade/trade-api/src/main/java/study/daydayup/wolf/business/trade/api/domain/vo/buy/Installment.java
|
wolforest/wolf
|
207c61cd473d1433bf3e4fc5a591aaf3a5964418
|
[
"MIT"
] | 1 |
2020-02-06T15:50:36.000Z
|
2020-02-06T15:50:39.000Z
|
business/trade/trade-api/src/main/java/study/daydayup/wolf/business/trade/api/domain/vo/buy/Installment.java
|
wolforest/wolf
|
207c61cd473d1433bf3e4fc5a591aaf3a5964418
|
[
"MIT"
] | 12 |
2020-01-14T01:04:12.000Z
|
2022-02-22T07:21:37.000Z
| 21.538462 | 61 | 0.764286 | 2,378 |
package study.daydayup.wolf.business.trade.api.domain.vo.buy;
import lombok.Data;
import lombok.NoArgsConstructor;
import study.daydayup.wolf.framework.layer.domain.VO;
import java.math.BigDecimal;
/**
* study.daydayup.wolf.business.trade.api.domain.vo.buy
*
* @author Wingle
* @since 2019/12/18 10:57 上午
**/
@Data
@NoArgsConstructor
public class Installment implements VO {
private Integer installmentNo;
private Integer period;
private BigDecimal percentage;
private BigDecimal feePercentage;
private Integer installmentType;
}
|
3e05ac7a315c90d653f0ed47ea235fca90139777
| 10,652 |
java
|
Java
|
app/src/main/java/com/codearms/maoqiqi/one/data/source/OneRepository.java
|
codearms/One
|
222273e9d9e360745231ce14ab3da23acdb9565a
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/codearms/maoqiqi/one/data/source/OneRepository.java
|
codearms/One
|
222273e9d9e360745231ce14ab3da23acdb9565a
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/codearms/maoqiqi/one/data/source/OneRepository.java
|
codearms/One
|
222273e9d9e360745231ce14ab3da23acdb9565a
|
[
"Apache-2.0"
] | 3 |
2019-06-03T12:11:29.000Z
|
2019-09-16T01:59:02.000Z
| 39.746269 | 153 | 0.728971 | 2,379 |
package com.codearms.maoqiqi.one.data.source;
import com.codearms.maoqiqi.one.App;
import com.codearms.maoqiqi.one.data.bean.ArticleBean;
import com.codearms.maoqiqi.one.data.bean.ArticleBeans;
import com.codearms.maoqiqi.one.data.bean.BannerBean;
import com.codearms.maoqiqi.one.data.bean.BookDetailBean;
import com.codearms.maoqiqi.one.data.bean.BookListBean;
import com.codearms.maoqiqi.one.data.bean.ChildClassifyBean;
import com.codearms.maoqiqi.one.data.bean.DataBean;
import com.codearms.maoqiqi.one.data.bean.HotKeyBean;
import com.codearms.maoqiqi.one.data.bean.MovieDetailBean;
import com.codearms.maoqiqi.one.data.bean.MovieListBean;
import com.codearms.maoqiqi.one.data.bean.MusicAlbumBean;
import com.codearms.maoqiqi.one.data.bean.MusicArtistBean;
import com.codearms.maoqiqi.one.data.bean.MusicSongBean;
import com.codearms.maoqiqi.one.data.bean.NavigationBean;
import com.codearms.maoqiqi.one.data.bean.NewsBean;
import com.codearms.maoqiqi.one.data.bean.NewsDetailBean;
import com.codearms.maoqiqi.one.data.bean.ParentClassifyBean;
import com.codearms.maoqiqi.one.data.bean.UsefulSitesBean;
import com.codearms.maoqiqi.one.data.bean.UserBean;
import com.codearms.maoqiqi.one.data.net.DouBanApi;
import com.codearms.maoqiqi.one.data.net.GankApi;
import com.codearms.maoqiqi.one.data.net.NewsAPI;
import com.codearms.maoqiqi.one.data.net.RetrofitManager;
import com.codearms.maoqiqi.one.data.net.ServerApi;
import com.codearms.maoqiqi.one.utils.MediaLoader;
import com.codearms.maoqiqi.utils.RxUtils;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
public class OneRepository implements OneDataSource {
private static volatile OneRepository INSTANCE = null;
private static final String apiKey = "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7";
private ServerApi api;
private NewsAPI newsAPI;
private DouBanApi douBanApi;
private GankApi gankApi;
private OneRepository() {
api = RetrofitManager.getInstance().getServerApi();
newsAPI = RetrofitManager.getInstance().getNewsAPI();
douBanApi = RetrofitManager.getInstance().getDouBanApi();
gankApi = RetrofitManager.getInstance().getGankApi();
}
public static OneRepository getInstance() {
if (INSTANCE == null) {
synchronized (OneRepository.class) {
if (INSTANCE == null) {
INSTANCE = new OneRepository();
}
}
}
return INSTANCE;
}
@Override
public Observable<List<BannerBean>> getBanner() {
return api.getBanner().delay(3000, TimeUnit.MILLISECONDS).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<UsefulSitesBean>> getUsefulSites() {
return api.getUsefulSites().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<HotKeyBean>> getHotKey() {
return api.getHotKey().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<ArticleBean>> getTopArticles() {
return api.getTopArticles().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBeans> getArticles(int page) {
return api.getArticles(page).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<NavigationBean>> getNavigation() {
return api.getNavigation().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<ChildClassifyBean>> getWxList() {
return api.getWxList().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBeans> getWxArticles(int id, int page) {
return api.getWxArticles(id, page).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> getWxSearchArticles(int id, int page, String k) {
return api.getWxSearchArticles(id, page, k).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<ParentClassifyBean>> getKnowledge() {
return api.getKnowledge().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBeans> getKnowledgeArticles(int page, int cid) {
return api.getKnowledgeArticles(page, cid).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<List<ChildClassifyBean>> getProject() {
return api.getProject().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBeans> getProjectArticles(int page, int cid) {
return api.getProjectArticles(page, cid).delay(3000, TimeUnit.MILLISECONDS).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<UserBean> login(String username, String password) {
return api.login(username, password).delay(8000, TimeUnit.MILLISECONDS).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<UserBean> register(String username, String password, String repassword) {
return api.register(username, password, repassword).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> logout() {
return api.logout().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBeans> getCollect(int page) {
return api.getCollect(page).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> collect(int id) {
return api.collect(id).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBean> collect(String title, String author, String link) {
return api.collect(title, author, link).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> unCollect(int id) {
return api.unCollect(id).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> unCollect(int id, int originId) {
return api.unCollect(id, originId).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> getCollectUrl() {
return api.getCollectUrl().compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> collectUrl(String name, String link) {
return api.collectUrl(name, link).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> collectUrl(int id, String name, String link) {
return api.collectUrl(id, name, link).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<Object> unCollectUrl(int id) {
return api.unCollectUrl(id).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<ArticleBeans> query(int page, String k) {
return api.query(page, k).compose(RxUtils.rxSchedulerHelper()).compose(RxUtils.handleResult());
}
@Override
public Observable<NewsBean> getLatestNews() {
return newsAPI.getLatestNews().compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<NewsDetailBean> getNewsDetail(int id) {
return newsAPI.getNewsDetail(id).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<BookListBean> getBook(String q, String tag, int start, int count) {
return douBanApi.getBook(apiKey, q, tag, start, count).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<BookDetailBean> getBookDetail(String id) {
return douBanApi.getBookDetail(id, apiKey).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<MovieListBean> inTheatersMovies(String city, int start, int count) {
return douBanApi.inTheatersMovies(apiKey, city, start, count).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<MovieListBean> comingSoonMovies(int start, int count) {
return douBanApi.comingSoonMovies(apiKey, start, count).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<MovieDetailBean> getMovieDetail(String id) {
return douBanApi.getMovieDetail(id, apiKey).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<String> getCelebrity(String id, int start, int count) {
return douBanApi.getCelebrity(id, apiKey, start, count).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<MovieListBean> searchMovie(String q, int start, int count) {
return douBanApi.searchMovie(q, start, count).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<List<MusicSongBean>> getSongList(Long artistId, long albumId, String folderPath, String sortOrder) {
return RxUtils.createData(MediaLoader.getSongBeanList(artistId, albumId, folderPath, sortOrder)).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<List<MusicArtistBean>> getArtistList(String sortOrder) {
return RxUtils.createData(MediaLoader.getArtistBeanList(sortOrder)).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<List<MusicAlbumBean>> getAlbumList(String sortOrder) {
return RxUtils.createData(MediaLoader.getAlbumBeanList(sortOrder)).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<List<String>> getFolderList() {
return RxUtils.createData(MediaLoader.getFolderList(App.getInstance())).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<DataBean> getData(String type, int pageIndex, int pageCount) {
return gankApi.getData(type, pageIndex, pageCount).compose(RxUtils.rxSchedulerHelper());
}
@Override
public Observable<DataBean> getRandomData(String type, int number) {
return gankApi.getRandomData(type, number).compose(RxUtils.rxSchedulerHelper());
}
}
|
3e05acb09016fecc806ebd091cd7cdf42c59e4dc
| 3,822 |
java
|
Java
|
src/com/abyat/mvp/util/AbyatUtility.java
|
tauqir295/abyat-mvp
|
40650b45d55870be9ba8129efa4af7ec5dcb3f9d
|
[
"Apache-2.0"
] | null | null | null |
src/com/abyat/mvp/util/AbyatUtility.java
|
tauqir295/abyat-mvp
|
40650b45d55870be9ba8129efa4af7ec5dcb3f9d
|
[
"Apache-2.0"
] | null | null | null |
src/com/abyat/mvp/util/AbyatUtility.java
|
tauqir295/abyat-mvp
|
40650b45d55870be9ba8129efa4af7ec5dcb3f9d
|
[
"Apache-2.0"
] | null | null | null | 30.822581 | 151 | 0.749346 | 2,380 |
package com.abyat.mvp.util;
import com.abyat.mvp.AbyatMain;
import com.abyat.mvp.interfaces.IPlayerMatchStats;
import com.abyat.mvp.interfaces.IGame;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility class.
*
* @author Mohammad Tauqir
*/
public class AbyatUtility {
/**
* Get MVP nickname based on the player's statistics.
*
* @param playerMatchStatsList Player's statistics .
* @return MVP nickname
* @throws Exception :
*/
public static String getMVPNickName(List<IPlayerMatchStats> playerMatchStatsList) throws Exception {
Map<String, Integer> playerRatingsMap = new HashMap<>();
// calculate ratings for each player(assuming that nicknames are unique)
for (IPlayerMatchStats playerMatchStats : playerMatchStatsList) {
int rating = playerRatingsMap.getOrDefault(playerMatchStats.getPlayerNickName(), 0);
rating += playerMatchStats.getPlayerRating();
playerRatingsMap.put(playerMatchStats.getPlayerNickName(), rating);
}
// get MVP entry this the highest rating
Map.Entry<String, Integer> mvpEntry = playerRatingsMap.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(1).findFirst().get();
return mvpEntry.getKey();
}
/**
* match statistics from the via input stream.
*
* @param inputStream Input stream to read statistics from.
* @return players statistics
* @throws Exception for unsupported game, incorrect format, or i/o error.
*/
public static List<IPlayerMatchStats> readMatchStats(InputStream inputStream) throws Exception {
List<IPlayerMatchStats> IPlayerMatchStatsList = new ArrayList<>();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
String gameName = bf.readLine();
if (gameName.equals("") || ! AbyatMain.GAMES.containsKey(gameName)) {
throw new IllegalArgumentException(
"Invalid game name" + gameName);
}
// instantiate selected game class
Class<IGame> gameClass = AbyatMain.GAMES.get(gameName);
IGame IGame = gameClass.newInstance();
Class<IPlayerMatchStats> playerMatchStatsClass = IGame.getPlayerMatchStatisticsClass();
String inputString;
List<String> nicknames = new ArrayList<>();
// read players stats line by line, checking nicks uniqueness
while ((inputString = bf.readLine()) != null) {
IPlayerMatchStats IPlayerMatchStats =
playerMatchStatsClass.getConstructor(
String.class, Boolean.class).newInstance(
inputString, false);
if (nicknames.contains(IPlayerMatchStats.getPlayerNickName())) {
throw new IllegalStateException(
"Player's nickname should be unique");
}
nicknames.add(IPlayerMatchStats.getPlayerNickName());
IPlayerMatchStatsList.add(IPlayerMatchStats);
}
Map<String, Integer> teamPointsMap = new HashMap<>();
// calculate teams scores to know which team won the match
for (IPlayerMatchStats IPlayerMatchStats : IPlayerMatchStatsList) {
if (teamPointsMap.containsKey(IPlayerMatchStats.getPlayerTeamName())) {
continue;
}
teamPointsMap.put(IPlayerMatchStats.getPlayerTeamName(),IGame.calculateEachTeamScore(IPlayerMatchStats.getPlayerTeamName(), IPlayerMatchStatsList));
}
// get the winner team and assign corresponding player's property
Map.Entry<String, Integer> teamWonEntry = teamPointsMap.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(1).findFirst().get();
for (IPlayerMatchStats IPlayerMatchStats : IPlayerMatchStatsList) {
if (teamWonEntry.getValue().equals(IPlayerMatchStats.getPlayerTeamName())) {
IPlayerMatchStats.setWinningTeam(true);
}
}
return IPlayerMatchStatsList;
}
}
|
3e05ad0974b54763722544f256a34532274c3641
| 582 |
java
|
Java
|
src/main/java/com/ticodev/action/ActionForward.java
|
ticod/simplog
|
75cd8df7054d09d5b65d33c1e9084e780a185924
|
[
"MIT"
] | null | null | null |
src/main/java/com/ticodev/action/ActionForward.java
|
ticod/simplog
|
75cd8df7054d09d5b65d33c1e9084e780a185924
|
[
"MIT"
] | null | null | null |
src/main/java/com/ticodev/action/ActionForward.java
|
ticod/simplog
|
75cd8df7054d09d5b65d33c1e9084e780a185924
|
[
"MIT"
] | null | null | null | 18.1875 | 57 | 0.608247 | 2,381 |
package com.ticodev.action;
public class ActionForward {
private boolean redirect;
private String view;
public ActionForward() {}
public ActionForward(boolean redirect, String view) {
this.redirect = redirect;
this.view = view;
}
/* setter, getter */
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
public String getView() {
return view;
}
public void setView(String view) {
this.view = view;
}
}
|
3e05ad865bb45628508bfbbf551e669ee98a4cac
| 2,825 |
java
|
Java
|
src/rtf/com/lowagie/text/rtf/parser/properties/RtfCtrlWordPropertyType.java
|
j5int/itext
|
336fe79e83f404b0965746e8ad3e3680599ae423
|
[
"Condor-1.1"
] | null | null | null |
src/rtf/com/lowagie/text/rtf/parser/properties/RtfCtrlWordPropertyType.java
|
j5int/itext
|
336fe79e83f404b0965746e8ad3e3680599ae423
|
[
"Condor-1.1"
] | null | null | null |
src/rtf/com/lowagie/text/rtf/parser/properties/RtfCtrlWordPropertyType.java
|
j5int/itext
|
336fe79e83f404b0965746e8ad3e3680599ae423
|
[
"Condor-1.1"
] | null | null | null | 47.083333 | 84 | 0.75292 | 2,382 |
/* $Id: RtfCtrlWordPropertyType.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2007 by Howard Shank ([email protected])
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999-2006 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2006 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the ?GNU LIBRARY GENERAL PUBLIC LICENSE?), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.rtf.parser.properties;
/**
* @since 2.1.0
*/
public class RtfCtrlWordPropertyType {
public static final int UNIDENTIFIED = -1;
public static final int PROPERTY = 0;
public static final int CHARACTER = 1;
public static final int SPECIAL = 2;
public static final int DESTINATION = 3;
}
|
3e05aee3d0047c86e5f917db08538f5ede740a12
| 3,140 |
java
|
Java
|
osgp/platform/osgp-adapter-domain-publiclighting/src/main/java/org/opensmartgridplatform/adapter/domain/publiclighting/application/config/messaging/InboundOsgpCoreResponsesMessagingConfig.java
|
ekmixon/open-smart-grid-platform
|
ca095718390ce8b33db399722e86fc43f252057a
|
[
"Apache-2.0"
] | 77 |
2018-10-25T12:05:06.000Z
|
2022-02-03T12:49:56.000Z
|
osgp/platform/osgp-adapter-domain-publiclighting/src/main/java/org/opensmartgridplatform/adapter/domain/publiclighting/application/config/messaging/InboundOsgpCoreResponsesMessagingConfig.java
|
OSGP/open-smart-grid-platform
|
f431e30820fe79dbde7da963f51b087a8a0c91d0
|
[
"Apache-2.0"
] | 526 |
2018-10-24T15:58:01.000Z
|
2022-03-31T20:06:59.000Z
|
osgp/platform/osgp-adapter-domain-publiclighting/src/main/java/org/opensmartgridplatform/adapter/domain/publiclighting/application/config/messaging/InboundOsgpCoreResponsesMessagingConfig.java
|
ekmixon/open-smart-grid-platform
|
ca095718390ce8b33db399722e86fc43f252057a
|
[
"Apache-2.0"
] | 30 |
2018-12-27T07:11:35.000Z
|
2021-09-09T06:57:44.000Z
| 45.507246 | 110 | 0.823248 | 2,383 |
/*
* Copyright 2019 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.adapter.domain.publiclighting.application.config.messaging;
import javax.jms.ConnectionFactory;
import javax.net.ssl.SSLException;
import org.opensmartgridplatform.adapter.domain.publiclighting.infra.jms.core.OsgpCoreResponseMessageListener;
import org.opensmartgridplatform.shared.application.config.messaging.DefaultJmsConfiguration;
import org.opensmartgridplatform.shared.application.config.messaging.JmsConfigurationFactory;
import org.opensmartgridplatform.shared.application.config.messaging.JmsConfigurationNames;
import org.opensmartgridplatform.shared.infra.jms.BaseMessageProcessorMap;
import org.opensmartgridplatform.shared.infra.jms.MessageProcessorMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
/** Configuration class for inbound responses from OSGP Core. */
@Configuration
public class InboundOsgpCoreResponsesMessagingConfig {
private static final Logger LOGGER =
LoggerFactory.getLogger(InboundOsgpCoreResponsesMessagingConfig.class);
private JmsConfigurationFactory jmsConfigurationFactory;
public InboundOsgpCoreResponsesMessagingConfig(
final Environment environment, final DefaultJmsConfiguration defaultJmsConfiguration)
throws SSLException {
this.jmsConfigurationFactory =
new JmsConfigurationFactory(
environment,
defaultJmsConfiguration,
JmsConfigurationNames.JMS_INCOMING_OSGP_CORE_RESPONSES);
}
@Bean(
destroyMethod = "stop",
name = "domainPublicLightingInboundOsgpCoreResponsesConnectionFactory")
public ConnectionFactory connectionFactory() {
LOGGER.info("Initializing domainPublicLightingInboundOsgpCoreResponsesConnectionFactory bean.");
return this.jmsConfigurationFactory.getPooledConnectionFactory();
}
@Bean(name = "domainPublicLightingInboundOsgpCoreResponsesMessageListenerContainer")
public DefaultMessageListenerContainer messageListenerContainer(
@Qualifier("domainPublicLightingInboundOsgpCoreResponsesMessageListener")
final OsgpCoreResponseMessageListener messageListener) {
LOGGER.info(
"Initializing domainPublicLightingInboundOsgpCoreResponsesMessageListenerContainer bean.");
return this.jmsConfigurationFactory.initMessageListenerContainer(messageListener);
}
@Bean(name = "domainPublicLightingInboundOsgpCoreResponsesMessageProcessorMap")
public MessageProcessorMap messageProcessorMap() {
return new BaseMessageProcessorMap(
"domainPublicLightingInboundOsgpCoreResponsesMessageProcessorMap");
}
}
|
3e05af6285e3c605aa29320278b54555a0d5bef8
| 2,898 |
java
|
Java
|
metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/CpuProfileServlet.java
|
Mu-L/metrics
|
55ed37589c1a6717c1b059e4f6c15e44dad9442c
|
[
"Apache-2.0"
] | 5,439 |
2015-01-01T17:11:35.000Z
|
2022-03-31T07:54:16.000Z
|
metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/CpuProfileServlet.java
|
Mu-L/metrics
|
55ed37589c1a6717c1b059e4f6c15e44dad9442c
|
[
"Apache-2.0"
] | 1,489 |
2015-01-06T13:11:24.000Z
|
2022-03-31T19:46:24.000Z
|
metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/CpuProfileServlet.java
|
Mu-L/metrics
|
55ed37589c1a6717c1b059e4f6c15e44dad9442c
|
[
"Apache-2.0"
] | 1,536 |
2015-01-02T15:51:50.000Z
|
2022-03-29T09:20:22.000Z
| 36.225 | 116 | 0.623188 | 2,384 |
package io.dropwizard.metrics.servlets;
import com.papertrail.profiler.CpuProfile;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Duration;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* An HTTP servlets which outputs a <a href="https://github.com/gperftools/gperftools">pprof</a> parseable response.
*/
public class CpuProfileServlet extends HttpServlet {
private static final long serialVersionUID = -668666696530287501L;
private static final String CONTENT_TYPE = "pprof/raw";
private static final String CACHE_CONTROL = "Cache-Control";
private static final String NO_CACHE = "must-revalidate,no-cache,no-store";
private final Lock lock = new ReentrantLock();
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
int duration = 10;
if (req.getParameter("duration") != null) {
try {
duration = Integer.parseInt(req.getParameter("duration"));
} catch (NumberFormatException e) {
duration = 10;
}
}
int frequency = 100;
if (req.getParameter("frequency") != null) {
try {
frequency = Integer.parseInt(req.getParameter("frequency"));
frequency = Math.min(Math.max(frequency, 1), 1000);
} catch (NumberFormatException e) {
frequency = 100;
}
}
final Thread.State state;
if ("blocked".equalsIgnoreCase(req.getParameter("state"))) {
state = Thread.State.BLOCKED;
} else {
state = Thread.State.RUNNABLE;
}
resp.setStatus(HttpServletResponse.SC_OK);
resp.setHeader(CACHE_CONTROL, NO_CACHE);
resp.setContentType(CONTENT_TYPE);
try (OutputStream output = resp.getOutputStream()) {
doProfile(output, duration, frequency, state);
}
}
protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) throws IOException {
if (lock.tryLock()) {
try {
CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration),
frequency, state);
if (profile == null) {
throw new RuntimeException("could not create CpuProfile");
}
profile.writeGoogleProfile(out);
return;
} finally {
lock.unlock();
}
}
throw new RuntimeException("Only one profile request may be active at a time");
}
}
|
3e05af7909947b38001b8d8b23d24f7a38a02ea9
| 766 |
java
|
Java
|
domain/Utensil.java
|
POEI2018/Parseur_CSV
|
eb5c47efb7f1549f412c91657582701e9555598f
|
[
"Apache-2.0"
] | null | null | null |
domain/Utensil.java
|
POEI2018/Parseur_CSV
|
eb5c47efb7f1549f412c91657582701e9555598f
|
[
"Apache-2.0"
] | null | null | null |
domain/Utensil.java
|
POEI2018/Parseur_CSV
|
eb5c47efb7f1549f412c91657582701e9555598f
|
[
"Apache-2.0"
] | null | null | null | 18.238095 | 74 | 0.68799 | 2,385 |
package fr.gtm.tp.exo11.domain;
import java.time.LocalDate;
/**
* @author Adminl
*
*/
public abstract class Utensil {
private LocalDate creation ;
public abstract void setScore(Object obj) ;
/**
* @param current la date a partir de laquelle calculer l'année en cours.
* @return int la valeur calculée
*/
public int calcValue(LocalDate current) {
return current.getYear() - this.creation.getYear() - 50 ;
}
public LocalDate getCreation() {
return creation;
}
public void setCreation(LocalDate creation) {
this.creation = creation;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Ustensile[") ;
sb.append("Fabrication->") ;
sb.append(this.creation);
return sb.toString() ;
}
}
|
3e05afa7b78a183a960d1fab9808058fcca61678
| 9,133 |
java
|
Java
|
openweb/src/main/java/cc/solart/openweb/base/BaseWebFragment.java
|
Solartisan/OpenWeb
|
a00215df6de513956a934594c9cd7033d1ffc98d
|
[
"Apache-2.0"
] | 47 |
2016-04-11T08:47:34.000Z
|
2021-08-12T03:27:01.000Z
|
openweb/src/main/java/cc/solart/openweb/base/BaseWebFragment.java
|
Solartisan/OpenWeb
|
a00215df6de513956a934594c9cd7033d1ffc98d
|
[
"Apache-2.0"
] | 3 |
2016-12-06T05:21:31.000Z
|
2016-12-14T10:35:02.000Z
|
openweb/src/main/java/cc/solart/openweb/base/BaseWebFragment.java
|
Solartisan/OpenWeb
|
a00215df6de513956a934594c9cd7033d1ffc98d
|
[
"Apache-2.0"
] | 16 |
2016-05-08T06:02:21.000Z
|
2018-11-25T08:48:23.000Z
| 29.085987 | 131 | 0.616993 | 2,386 |
package cc.solart.openweb.base;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import cc.solart.openweb.utils.Logger;
import cc.solart.openweb.utils.NetworkUtil;
import cc.solart.openweb.utils.ObjEnsureUtil;
import cc.solart.openweb.utils.WebSettingsUtil;
import cc.solart.openweb.widget.OpenWebLayout;
/**
* Created by imilk on 15/6/8.
*/
public abstract class BaseWebFragment extends Fragment {
protected static final String TAG = "BaseWebFragment";
protected static final String BLANK_SCREEN_URL = "about:blank";
protected BaseWebEvent mWebEvent;
protected WebView mWebView;
protected ProgressBar mProgressBar;
protected boolean mNetworkConnected;
private NetworkConnectivityReceiver mNetworkConnectivityReceiver;
/**
* TargetApi{@link Build.VERSION_CODES.KITKAT}
*/
static {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
}
protected Activity mActivity;
@Override
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
}
protected abstract int loadLayoutRes();
protected abstract int getWebViewId();
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
registerConnectivityReceiver();
mNetworkConnected = NetworkUtil.isNetConnected(mActivity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int i = loadLayoutRes();
if (i <= 0)
throw new IllegalArgumentException("You must provide a valid category_more");
View view = inflater.inflate(i, container, false);
OpenWebLayout openWebLayout = (OpenWebLayout) view.findViewById(getWebViewId());
if (openWebLayout == null)
throw new IllegalArgumentException("As a web view fragment, you must provide a OpenWebLayout");
mWebView = openWebLayout.getWebView();
mProgressBar = openWebLayout.getProgressBar();
onInitWebViewSettings();
return view;
}
public void onResume() {
super.onResume();
if (mWebView != null) {
mWebView.onResume();
}
}
@Override
public void onPause() {
super.onPause();
if (mWebView != null) {
mWebView.onPause();
}
}
@Override
public void onDetach() {
super.onDetach();
unregisterConnectivityReceiver();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mWebView != null) {
((ViewGroup) mWebView.getParent()).removeView(mWebView);
mWebView.destroy();
}
}
protected void onInitWebViewSettings() {
WebSettingsUtil.initSettings(this.mActivity, this.mWebView);
WebChromeClient webChromeClient = onCreateWebChromeClient();
if (webChromeClient != null) {
mWebView.setWebChromeClient(webChromeClient);
}
WebViewClient webViewClient = onCreateWebViewClient();
if (webViewClient != null) {
mWebView.setWebViewClient(webViewClient);
}
mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
mWebView.requestFocus();
mWebView.setDownloadListener(new WebDownloadListener(this));
}
private boolean ensureNonNull() {
return ObjEnsureUtil.ensureNonNull(new Object[]{this.mActivity, this.mWebView, this.mWebEvent});
}
public void loadUrl(String url) {
if (!ensureNonNull())
return;
if (TextUtils.isEmpty(url)) {
Logger.e(TAG, "The url should not be null, load nothing");
return;
}
Logger.d(TAG, "loadUrl: " + url);
this.mWebView.loadUrl(url);
}
/**
* webview reload
*/
public void reload() {
if (!ensureNonNull())
return;
Logger.d("BaseWebFragment", "webview reload");
this.mWebView.reload();
}
protected void onNetworkConnected() {
reload();
}
protected WebChromeClient onCreateWebChromeClient() {
return new BaseWebChromeClient(this);
}
protected WebViewClient onCreateWebViewClient() {
return new BaseWebViewClient(this);
}
private int stepsToGoBack() {
int j = 1;
WebBackForwardList webBackForwardList = mWebView.copyBackForwardList();
int k = webBackForwardList.getCurrentIndex();
Logger.d(TAG, "k = " + k);
for (int i = 0; i <= k; i++) {
String url = webBackForwardList.getItemAtIndex(k - i).getUrl();
if ((!BLANK_SCREEN_URL.equalsIgnoreCase(url)) && (TextUtils.equals(mWebView.getUrl(), url)))
break;
j += 1;
Logger.d(TAG, "j = " + j);
}
return j;
}
/**
* 回退H5
*
* @return
*/
protected boolean goBack() {
int i;
int j;
if (mWebView.canGoBack()) {
WebBackForwardList backForwardList = mWebView.copyBackForwardList();
i = stepsToGoBack();
j = backForwardList.getCurrentIndex();
Logger.d(TAG, "i = " + i);
Logger.d(TAG, "j = " + j);
if (i <= j) {
String title = backForwardList.getItemAtIndex(j - i).getTitle();
if (!TextUtils.isEmpty(title)) {
mActivity.setTitle(title);
}
mWebView.goBackOrForward(-i);
return true;
}
}
return false;
}
/**
* 前进H5页面
*
* @return
*/
protected boolean goForward() {
int i;
int j;
if (mWebView.canGoForward()) {
WebBackForwardList backForwardList = mWebView.copyBackForwardList();
i = 1;
j = backForwardList.getCurrentIndex();
if (backForwardList.getSize() > j) {
String title = backForwardList.getItemAtIndex(j + i).getTitle();
if (!TextUtils.isEmpty(title)) {
mActivity.setTitle(title);
}
mWebView.goBackOrForward(i);
return true;
}
}
return false;
}
/**
* ActionBar返回监听处理,子类应该覆写该方法
* @return
*/
public boolean onMenuHome(){
return false;
}
public boolean onBackPressed() {
if (!ensureNonNull())
return false;
return goBack();
}
public boolean onForwardPressed() {
if (!ensureNonNull())
return false;
return goForward();
}
private void registerConnectivityReceiver() {
Logger.d(TAG, "Register network connectivity changed receiver");
if (mNetworkConnectivityReceiver == null) {
mNetworkConnectivityReceiver = new NetworkConnectivityReceiver();
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mActivity.registerReceiver(mNetworkConnectivityReceiver, intentFilter);
}
private void unregisterConnectivityReceiver() {
Logger.d(TAG, "Unregister network connectivity changed receiver");
mActivity.unregisterReceiver(mNetworkConnectivityReceiver);
}
/**
* DownloadListener
*/
class WebDownloadListener implements DownloadListener {
private BaseWebFragment mWebFragment;
private WebDownloadListener(BaseWebFragment mWebFragment) {
this.mWebFragment = mWebFragment;
}
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
mWebFragment.startActivity(intent);
}catch (Exception e){
e.printStackTrace();
}
}
}
class NetworkConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean bool = NetworkUtil.isNetConnected(mActivity);
if ((!mNetworkConnected) && (bool)) {
onNetworkConnected();
}
mNetworkConnected = bool;
}
}
}
|
3e05b06e62d931a4f9a748344bf0f81bd33a35c4
| 8,455 |
java
|
Java
|
app/src/main/java/com/morihacky/android/rxjava/fragments/TimingDemoFragment.java
|
DoggyZhang/RxJava-Android-Samples
|
d938197dea5636ea8e61d4de71397ce56d53a71d
|
[
"Apache-2.0"
] | 2 |
2016-08-18T18:46:30.000Z
|
2016-12-20T00:52:44.000Z
|
app/src/main/java/com/morihacky/android/rxjava/fragments/TimingDemoFragment.java
|
abdelrhman/RxJava-Android-Samples
|
d938197dea5636ea8e61d4de71397ce56d53a71d
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/morihacky/android/rxjava/fragments/TimingDemoFragment.java
|
abdelrhman/RxJava-Android-Samples
|
d938197dea5636ea8e61d4de71397ce56d53a71d
|
[
"Apache-2.0"
] | 1 |
2016-10-11T14:44:32.000Z
|
2016-10-11T14:44:32.000Z
| 34.230769 | 110 | 0.5411 | 2,387 |
package com.morihacky.android.rxjava.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.morihacky.android.rxjava.R;
import com.morihacky.android.rxjava.RxUtils;
import com.morihacky.android.rxjava.wiring.LogAdapter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action1;
import timber.log.Timber;
import static android.os.Looper.getMainLooper;
import static android.os.Looper.myLooper;
public class TimingDemoFragment
extends BaseFragment {
@Bind(R.id.list_threading_log) ListView _logsList;
private LogAdapter _adapter;
private List<String> _logs;
private Subscription _subscription1 = null;
private Subscription _subscription2 = null;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
_setupLogger();
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_demo_timing, container, false);
ButterKnife.bind(this, layout);
return layout;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
RxUtils.unsubscribeIfNotNull(_subscription1);
RxUtils.unsubscribeIfNotNull(_subscription2);
}
// -----------------------------------------------------------------------------------
@OnClick(R.id.btn_demo_timing_1)
public void btn1_RunSingleTaskAfter2s() {
_log(String.format("A1 [%s] --- BTN click", _getCurrentTimestamp()));
Observable.timer(2, TimeUnit.SECONDS)//
//.just(1).delay(2, TimeUnit.SECONDS)//
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
_log(String.format("A1 [%s] XXX COMPLETE", _getCurrentTimestamp()));
}
@Override
public void onError(Throwable e) {
Timber.e(e, "something went wrong in TimingDemoFragment example");
}
@Override
public void onNext(Long number) {
_log(String.format("A1 [%s] NEXT", _getCurrentTimestamp()));
}
});
}
@OnClick(R.id.btn_demo_timing_2)
public void btn2_RunTask_IntervalOf1s() {
if (_subscription1 != null && !_subscription1.isUnsubscribed()) {
_subscription1.unsubscribe();
_log(String.format("B2 [%s] XXX BTN KILLED", _getCurrentTimestamp()));
return;
}
_log(String.format("B2 [%s] --- BTN click", _getCurrentTimestamp()));
_subscription1 = Observable//
.interval(1, TimeUnit.SECONDS)//
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
_log(String.format("B2 [%s] XXXX COMPLETE", _getCurrentTimestamp()));
}
@Override
public void onError(Throwable e) {
Timber.e(e, "something went wrong in TimingDemoFragment example");
}
@Override
public void onNext(Long number) {
_log(String.format("B2 [%s] NEXT", _getCurrentTimestamp()));
}
});
}
@OnClick(R.id.btn_demo_timing_3)
public void btn3_RunTask_IntervalOf1s_StartImmediately() {
if (_subscription2 != null && !_subscription2.isUnsubscribed()) {
_subscription2.unsubscribe();
_log(String.format("C3 [%s] XXX BTN KILLED", _getCurrentTimestamp()));
return;
}
_log(String.format("C3 [%s] --- BTN click", _getCurrentTimestamp()));
_subscription2 = Observable//
.interval(0, 1, TimeUnit.SECONDS)//
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
_log(String.format("C3 [%s] XXXX COMPLETE", _getCurrentTimestamp()));
}
@Override
public void onError(Throwable e) {
Timber.e(e, "something went wrong in TimingDemoFragment example");
}
@Override
public void onNext(Long number) {
_log(String.format("C3 [%s] NEXT", _getCurrentTimestamp()));
}
});
}
@OnClick(R.id.btn_demo_timing_4)
public void btn4_RunTask5Times_IntervalOf3s() {
_log(String.format("D4 [%s] --- BTN click", _getCurrentTimestamp()));
Observable//
.interval(3, TimeUnit.SECONDS).take(5)//
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
_log(String.format("D4 [%s] XXX COMPLETE", _getCurrentTimestamp()));
}
@Override
public void onError(Throwable e) {
Timber.e(e, "something went wrong in TimingDemoFragment example");
}
@Override
public void onNext(Long number) {
_log(String.format("D4 [%s] NEXT", _getCurrentTimestamp()));
}
});
}
@OnClick(R.id.btn_demo_timing_5)
public void btn5_RunTask5Times_IntervalOf3s() {
_log(String.format("D5 [%s] --- BTN click", _getCurrentTimestamp()));
Observable.just("Do task A right away")
.doOnNext(new Action1<String>() {
@Override
public void call(String input) {
_log(String.format("D5 %s [%s]", input, _getCurrentTimestamp()));
}
})
.delay(1, TimeUnit.SECONDS)
.doOnNext(new Action1<String>() {
@Override
public void call(String oldInput) {
_log(String.format("D5 %s [%s]", "Doing Task B after a delay", _getCurrentTimestamp()));
}
})
.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
_log(String.format("D5 [%s] XXX COMPLETE", _getCurrentTimestamp()));
}
@Override
public void onError(Throwable e) {
Timber.e(e, "something went wrong in TimingDemoFragment example");
}
@Override
public void onNext(String number) {
_log(String.format("D5 [%s] NEXT", _getCurrentTimestamp()));
}
});
}
// -----------------------------------------------------------------------------------
// Method that help wiring up the example (irrelevant to RxJava)
@OnClick(R.id.btn_clr)
public void OnClearLog() {
_logs = new ArrayList<>();
_adapter.clear();
}
private void _setupLogger() {
_logs = new ArrayList<>();
_adapter = new LogAdapter(getActivity(), new ArrayList<String>());
_logsList.setAdapter(_adapter);
}
private void _log(String logMsg) {
_logs.add(0, String.format(logMsg + " [MainThread: %b]", getMainLooper() == myLooper()));
// You can only do below stuff on main thread.
new Handler(getMainLooper()).post(new Runnable() {
@Override
public void run() {
_adapter.clear();
_adapter.addAll(_logs);
}
});
}
private String _getCurrentTimestamp() {
return new SimpleDateFormat("k:m:s:S a").format(new Date());
}
}
|
3e05b18b13412b44d762f4c82de54ccb92bb7420
| 3,267 |
java
|
Java
|
src/main/java/de/otto/edison/jobtrigger/trigger/TriggerRunnablesService.java
|
bennetschulz1309/edison-jobtrigger
|
c7e39f55099e3293a8335c9126b14d2d23e95b11
|
[
"Apache-2.0"
] | 6 |
2015-09-28T10:45:19.000Z
|
2019-09-23T07:30:06.000Z
|
src/main/java/de/otto/edison/jobtrigger/trigger/TriggerRunnablesService.java
|
bennetschulz1309/edison-jobtrigger
|
c7e39f55099e3293a8335c9126b14d2d23e95b11
|
[
"Apache-2.0"
] | 8 |
2016-05-16T05:25:52.000Z
|
2022-03-11T09:24:35.000Z
|
src/main/java/de/otto/edison/jobtrigger/trigger/TriggerRunnablesService.java
|
bennetschulz1309/edison-jobtrigger
|
c7e39f55099e3293a8335c9126b14d2d23e95b11
|
[
"Apache-2.0"
] | 14 |
2015-11-10T10:24:30.000Z
|
2022-03-06T14:04:48.000Z
| 42.986842 | 149 | 0.557698 | 2,388 |
package de.otto.edison.jobtrigger.trigger;
import de.otto.edison.jobtrigger.definition.JobDefinition;
import de.otto.edison.jobtrigger.security.AuthProvider;
import org.asynchttpclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.time.Duration;
import static de.otto.edison.jobtrigger.security.BasicAuthCredentials.AUTHORIZATION_HEADER;
import static java.lang.Thread.sleep;
/**
* @author Guido Steinacker
* @since 05.09.15
*/
@Service
class TriggerRunnablesService {
private final AuthProvider authHeaderProvider;
private final AsyncHttpClient httpClient;
TriggerRunnablesService(AuthProvider authHeaderProvider, AsyncHttpClient httpClient) {
this.authHeaderProvider = authHeaderProvider;
this.httpClient = httpClient;
}
public Runnable httpTriggerRunnable(
final JobDefinition jobDefinition,
final TriggerResponseConsumer consumer) {
return () -> {
final Logger LOG = LoggerFactory.getLogger("de.otto.edison.jobtrigger.trigger.HttpTriggerRunnable");
final String triggerUrl = jobDefinition.getTriggerUrl();
try {
for (int i = 0, n = jobDefinition.getRetries() + 1; i < n; ++i) {
BoundRequestBuilder boundRequestBuilder = httpClient.preparePost(triggerUrl);
authHeaderProvider.setAuthHeader(boundRequestBuilder);
final ListenableFuture<Response> futureResponse = boundRequestBuilder.execute(new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(final Response response) throws Exception {
final String location = response.getHeader("Location");
final int status = response.getStatusCode();
consumer.consume(response);
return response;
}
@Override
public void onThrowable(Throwable t) {
consumer.consume(t);
}
});
if (futureResponse.get().getStatusCode() < 300) {
return;
} else {
if (i < (jobDefinition).getRetries()) {
if (jobDefinition.getRetryDelay().isPresent()) {
final Duration duration = jobDefinition.getRetryDelay().get();
LOG.info("Retrying trigger in " + duration.getSeconds() + "s");
sleep(duration.toMillis());
}
LOG.info("Trigger failed. Retry " + jobDefinition.getJobType() + "[" + (i + 1) + "/" + jobDefinition.getRetries() + "]");
} else {
LOG.info("Trigger failed. No more retries.");
}
}
}
} catch (final Exception e) {
LOG.error("Exception caught when trying to trigger '{}': {}", triggerUrl, e.getMessage());
}
};
}
}
|
3e05b193e63fe308048bb95f1992863c5406fc3e
| 831 |
java
|
Java
|
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/VMwareDvsLacpLoadBalanceAlgorithm.java
|
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
|
504cbeec6fce27a4b6b23887b28d6a4e85393f4b
|
[
"Apache-2.0"
] | null | null | null |
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/VMwareDvsLacpLoadBalanceAlgorithm.java
|
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
|
504cbeec6fce27a4b6b23887b28d6a4e85393f4b
|
[
"Apache-2.0"
] | null | null | null |
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/VMwareDvsLacpLoadBalanceAlgorithm.java
|
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
|
504cbeec6fce27a4b6b23887b28d6a4e85393f4b
|
[
"Apache-2.0"
] | 1 |
2018-10-03T16:53:11.000Z
|
2018-10-03T16:53:11.000Z
| 20.775 | 110 | 0.659446 | 2,389 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.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: 2019.06.12 at 09:16:35 AM EDT
//
package com.vmware.vim25;
/**
*
*/
public enum VMwareDvsLacpLoadBalanceAlgorithm {
srcMac,
destMac,
srcDestMac,
destIpVlan,
srcIpVlan,
srcDestIpVlan,
destTcpUdpPort,
srcTcpUdpPort,
srcDestTcpUdpPort,
destIpTcpUdpPort,
srcIpTcpUdpPort,
srcDestIpTcpUdpPort,
destIpTcpUdpPortVlan,
srcIpTcpUdpPortVlan,
srcDestIpTcpUdpPortVlan,
destIp,
srcIp,
srcDestIp,
vlan,
srcPortId;
}
|
3e05b22da1c98c728038191def721220865b1686
| 2,875 |
java
|
Java
|
evosuite/master/src/test/java/com/examples/with/different/packagename/jee/injection/wildfly/TransactionServlet.java
|
racoq/TESRAC
|
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
|
[
"Apache-2.0"
] | null | null | null |
evosuite/master/src/test/java/com/examples/with/different/packagename/jee/injection/wildfly/TransactionServlet.java
|
racoq/TESRAC
|
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
|
[
"Apache-2.0"
] | null | null | null |
evosuite/master/src/test/java/com/examples/with/different/packagename/jee/injection/wildfly/TransactionServlet.java
|
racoq/TESRAC
|
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
|
[
"Apache-2.0"
] | null | null | null | 36.392405 | 124 | 0.672348 | 2,390 |
/**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* From JBoss, Apache License Apache License, Version 2.0
*/
package com.examples.with.different.packagename.jee.injection.wildfly;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/BMT")
public class TransactionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static String PAGE_HEADER = "<html><head><title>bmt</title></head><body>";
static String PAGE_CONTENT = "<h1>Stepping Outside the Container (with JPA and JTA)</h1>"
+ "<form>"
+ "<input checked type=\"checkbox\" name=\"strategy\" value=\"managed\" /> Use bean managed Entity Managers <br />"
+ "Key: <input type=\"text\" name=\"key\" /><br />"
+ "Value: <input type=\"text\" name=\"value\" /><br />"
+ "<input type=\"submit\" value=\"Submit\" /><br />"
+ "</form>";
static String PAGE_FOOTER = "</body></html>";
@Inject
ManagedComponent managedBean;
@Inject
UnManagedComponent unManagedBean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
String responseText;
String key = req.getParameter("key");
String value = req.getParameter("value");
String txStrategy = req.getParameter("strategy");
if ("managed".equalsIgnoreCase(txStrategy))
responseText = managedBean.updateKeyValueDatabase(key, value);
else
responseText = unManagedBean.updateKeyValueDatabase(key, value);
writer.println(PAGE_HEADER);
writer.println(PAGE_CONTENT);
writer.println("<p>" + responseText + "</p>");
writer.println(PAGE_FOOTER);
writer.close();
}
}
|
3e05b4279aa0b42df834e7f80295f7f18930b73e
| 151 |
java
|
Java
|
cultivar-servlets/src/main/java/com/readytalk/cultivar/servlets/package-info.java
|
ReadyTalk/cultivar
|
a51678dd35600ce43b97f975d3d15269d4b14d90
|
[
"Apache-2.0"
] | 1 |
2015-03-10T00:31:44.000Z
|
2015-03-10T00:31:44.000Z
|
cultivar-servlets/src/main/java/com/readytalk/cultivar/servlets/package-info.java
|
ReadyTalk/cultivar
|
a51678dd35600ce43b97f975d3d15269d4b14d90
|
[
"Apache-2.0"
] | 21 |
2015-02-23T19:50:01.000Z
|
2015-06-04T16:27:04.000Z
|
cultivar-servlets/src/main/java/com/readytalk/cultivar/servlets/package-info.java
|
ReadyTalk/cultivar
|
a51678dd35600ce43b97f975d3d15269d4b14d90
|
[
"Apache-2.0"
] | 1 |
2022-03-27T06:52:58.000Z
|
2022-03-27T06:52:58.000Z
| 25.166667 | 53 | 0.801325 | 2,391 |
/**
* Tools for using Cultivar in a Servlet environment.
*/
@javax.annotation.ParametersAreNonnullByDefault
package com.readytalk.cultivar.servlets;
|
3e05b54b7b50832f5e1dbf6f22cdd2a7f1f4c89a
| 11,967 |
java
|
Java
|
src/main/java/NotaQLGraph/model/predicate/RelationalPredicate.java
|
notaql/notaql_graph
|
6fa64b06934542dc9df122048534cb9f5903bbea
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/NotaQLGraph/model/predicate/RelationalPredicate.java
|
notaql/notaql_graph
|
6fa64b06934542dc9df122048534cb9f5903bbea
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/NotaQLGraph/model/predicate/RelationalPredicate.java
|
notaql/notaql_graph
|
6fa64b06934542dc9df122048534cb9f5903bbea
|
[
"Apache-2.0"
] | null | null | null | 42.892473 | 203 | 0.536141 | 2,392 |
package NotaQLGraph.model.predicate;
import NotaQLGraph.Evaluation.Filter;
import NotaQLGraph.Evaluation.VertexToCheck;
import com.tinkerpop.blueprints.Vertex;
import NotaQLGraph.model.vdata.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Klasse für Relationale Predikate
* also z.b. "10<gehalt
* Created by yannick on 25.11.15.
*/
public class RelationalPredicate implements Predicate {
private VData left;
private VData right;
private Operator operator;
public RelationalPredicate(VData left, VData right, Operator operator) {
this.left = left;
this.right = right;
this.operator = operator;
}
public boolean evaluate(VertexToCheck vtc) {
Vertex v = vtc.getVertex();
VData l = left.evaluate(vtc);
VData r = right.evaluate(vtc);
// System.out.println(l+" " +r);
if (l instanceof CollectionVData&&!(r instanceof CollectionVData)){//Links = mehrere Ergebnisse
boolean result = false;
for (int i =0; i < ((CollectionVData)l).size();i++){
boolean zwischenergebnis = operatorAnwenden(((CollectionVData) l).get(i), r, operator);
if (vtc.isGetEdges()==true){
if (zwischenergebnis){
result = true;
vtc.addEdgetoList(((CollectionVData) l).getEdge(i));
}
}else {
if (zwischenergebnis) {
return true;
}
}
}
return result;
}
else if (!(l instanceof CollectionVData) && r instanceof CollectionVData){//Rechts = mehrere Ergebnisse
boolean result = false;
for (int i =0; i < ((CollectionVData)r).size();i++){
boolean zwischenergebnis= operatorAnwenden(l,((CollectionVData) r).get(i),operator);
if (vtc.isGetEdges()==true){
if (zwischenergebnis){
result = true;
vtc.addEdgetoList(((CollectionVData) r).getEdge(i));
}
}else {
if (zwischenergebnis) {
return true;
}
}
}
return result;
}
else if (l instanceof CollectionVData && r instanceof CollectionVData){//Links&&Rects = mehrere Ergebnisse
boolean result = false;
for (int i =0; i < ((CollectionVData)l).size();i++){
for (int j =0; j < ((CollectionVData)r).size();j++){
boolean zwischenergebnis= operatorAnwenden(((CollectionVData) l).get(i),((CollectionVData) r).get(i),operator);
//Hier wurde der Fall mit vtc.addEdge weggelassen, da so eine Anfrage nicht vorkommen sollte bei dem vergleich (_id = IN._e?(_incoming)_.id <- EDGE (_outgoing, _l <-IN._e[@]_l
if (zwischenergebnis) {
return true;
}
}
}
return result;
}
else{//Links && Rechts jeweils nur ein Erbebnis
// System.out.println("bla") ;
// System.out.println(left.getClass()+""+right.getClass());
// System.out.println(operatorAnwenden(l,r,operator));
return operatorAnwenden(l,r,operator);
}
}
private boolean operatorAnwenden(VData l, VData r, RelationalPredicate.Operator o){
//wenn ich die nächsten zeilen nicht mache, wird die Rückgabe true, wenn ich Number 33.0 mit String 33 vergleichen möchte
if (l instanceof StringValue){
try {
l =new NumberValue(Double.parseDouble(l.toString()));
}
catch (Exception e) {
}}
if (r instanceof StringValue){
try {
r =new NumberValue(Double.parseDouble(r.toString()));
}
catch (Exception e) {
}}
switch (o) {
case LT:
return lowerThan(l,r);
case LTEQ:
return lowerThan(l,r)||equal(l,r);
case GT:
return greaterThan(l,r)||equal(l,r);
case GTEQ:
return greaterThan(l,r);
case EQ:
return equal(l,r);
case NEQ:
return !equal(l,r);
}
throw new RuntimeException("RelationPredicate Runtimeexeption"+o);
}
private boolean lowerThan (VData l, VData r) {
if (l instanceof NumberValue && r instanceof NumberValue) {
return (((NumberValue) l).compareTo((NumberValue) r)<0); //1 kommt raus, wenn der Wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof StringValue && r instanceof StringValue) {
return (((StringValue) l).compareTo((StringValue) r)<0); //1 kommt raus, wenn der wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof NumberValue && r instanceof StringValue) {
return l.toString().compareTo(((StringValue) r).getValue())<0; //1 kommt raus, wenn der wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof StringValue && r instanceof NumberValue) {
return((((StringValue) l).getValue()).compareTo(r.toString())<0); //1 kommt raus, wenn der wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof NoVData || r instanceof NoVData){
return false;
}
throw new RuntimeException(l.toString() + "Boolean kann nicht mit Lower than verglichen werden"+r.toString());
}
private boolean greaterThan (VData l, VData r) {//wegen VDATA fall brauch ich auch greater than, weil bei novdata zählt umkehrung nicht [novadta < novdata = false; novadta > novdata = true ==> error)
if (l instanceof NumberValue && r instanceof NumberValue) {
return (((NumberValue) l).compareTo((NumberValue) r)>0); //1 kommt raus, wenn der Wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof StringValue && r instanceof StringValue) {
return (((StringValue) l).compareTo((StringValue) r)>0); //1 kommt raus, wenn der wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof NumberValue && r instanceof StringValue) {
return l.toString().compareTo(((StringValue) r).getValue())>0; //1 kommt raus, wenn der wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof StringValue && r instanceof NumberValue) {
return((((StringValue) l).getValue()).compareTo(r.toString())>0); //1 kommt raus, wenn der wert größer ist, 0 wenn gleich -1 wenn kleiner
}
if (l instanceof NoVData || r instanceof NoVData){
return false;
}
throw new RuntimeException(l.toString() + "Boolean kann nicht mit greaterthan verglichen werden"+r.toString());
}
private boolean equal (VData l, VData r) {
if (l instanceof NumberValue && r instanceof NumberValue) {
return (((NumberValue) l).compareTo((NumberValue) r)==0);
}
if (l instanceof StringValue && r instanceof StringValue) {
return (((StringValue) l).compareTo((StringValue) r)==0);
}
if (l instanceof BooleanValue && r instanceof BooleanValue) {
return ((BooleanValue) l).getValue().equals(((BooleanValue) r).getValue());
}
if (l instanceof NumberValue && r instanceof StringValue) {
return l.toString().compareTo(((StringValue) r).getValue())==0;
}
if (l instanceof StringValue && r instanceof NumberValue) {
return((((StringValue) l).getValue()).compareTo(r.toString())==0);
}
if (l instanceof NoVData || r instanceof NoVData){
return false;
}
throw new RuntimeException(l.toString() + "Fehler beim Equals vergleich"+r.toString());
}
public String[] getLabel() {
return null;
}
public String getDirection() {
return null;
}
public LinkedList<Filter> getAttribute(Vertex v) {
try {
if (operator == Operator.EQ) {
LinkedList<Filter> result = new LinkedList<Filter>();
if (left instanceof InputDataVData && ((InputDataVData) left).getMode() == InputDataVData.Mode.Name && right instanceof BaseAtomValue) {
Filter f = new Filter(((InputDataVData) left).getFilterKey(),((BaseAtomValue) right).getValue());
result.add(f);
return result;
}
else if (right instanceof InputDataVData && ((InputDataVData) right).getMode() == InputDataVData.Mode.Name && left instanceof BaseAtomValue) {
Filter f = new Filter(((InputDataVData) right).getFilterKey(),((BaseAtomValue) left).getValue());
result.add(f);
return result;
} else {
// System.out.println(left.getClass()+", "+right.getClass());
if (v!=null) {
VertexToCheck vtc = new VertexToCheck(null, null);
vtc.setRootvertex(v);
VData leftClass = null;
VData rightClass=null;
try {leftClass = left.evaluate(vtc);}catch(Exception e){}
try {rightClass= right.evaluate(vtc);} catch (Exception e){}
if (leftClass==null&&rightClass instanceof CollectionVData&&left instanceof InputDataVData){
HashSet<StringValue> list = new HashSet<StringValue>();//Um Duplikate zu löschen
// System.out.println(((CollectionVData) rightClass).size()+"rightclassize");
for (int i=0;i<((CollectionVData) rightClass).size();i++){
if (((CollectionVData) rightClass).get(i) instanceof StringValue) {
list.add((StringValue)((CollectionVData) rightClass).get(i));
}
// System.out.println(((CollectionVData) rightClass).get(i).hashCode());
}
LinkedList<Object> list2 = new LinkedList<Object>();
Iterator<StringValue> it =list.iterator();
while (it.hasNext()){
// Object a = it.next();
// System.out.println(a);
list2.add(it.next());
}
Filter f = new Filter( list2, ((InputDataVData) left).getFilterKey());
result.add(f);
return result;
}
else if (leftClass==null&&rightClass instanceof NoVData&&left instanceof InputDataVData){
//Der Fall, dass die Liste leer war
Filter f = new Filter(true);
result.add(f);
return result;
}
// System.err.println(rightClass.getClass());
return null;
//System.out.println(((InputDataVData) left).getFilterKey()+"Filterkey");
//System.out.println(((CollectionVData)right.evaluate(vtc)).size()+"Listsize");
}
return null;
}
} else {
return null;
}
}catch(RuntimeException e){
e.printStackTrace();
return null;
}
}
public enum Operator {
LT, LTEQ, GT, GTEQ, EQ, NEQ
}
}
|
3e05b56a3b0565d51659d2f7d9c720f9eb644dd7
| 1,109 |
java
|
Java
|
lubanlou-master/lubanlou-provider/lubanlou-provider-gsexam/src/main/java/net/gvsun/gsexam/utils/Util.java
|
osgvsun/lubanlou
|
16d87a30edcb677bb399e001a2020e8527ba26f2
|
[
"BSD-3-Clause"
] | 1 |
2022-01-20T04:42:37.000Z
|
2022-01-20T04:42:37.000Z
|
lubanlou-master/lubanlou-provider/lubanlou-provider-gsexam/src/main/java/net/gvsun/gsexam/utils/Util.java
|
osgvsun/lubanlou
|
16d87a30edcb677bb399e001a2020e8527ba26f2
|
[
"BSD-3-Clause"
] | null | null | null |
lubanlou-master/lubanlou-provider/lubanlou-provider-gsexam/src/main/java/net/gvsun/gsexam/utils/Util.java
|
osgvsun/lubanlou
|
16d87a30edcb677bb399e001a2020e8527ba26f2
|
[
"BSD-3-Clause"
] | null | null | null | 30.805556 | 80 | 0.434626 | 2,393 |
package net.gvsun.gsexam.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Util {
private static final String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";
/**************************************************************************
* @Description: 判断字符串是否为空对象或空字符串
* @Author: 罗璇
* @Date: 2017/10/8 15:06
**************************************************************************/
public static boolean isEmpty(String src){
return src == null || src.trim().length() == 0;
}
/**************************************************************************
* @Description: 转换到时间类型
* @Author: 罗璇
* @Date: 2017/10/8 16:14
**************************************************************************/
public static Date parseToDate(String src){
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATETIME);
Date rs = null;
try {
rs = sdf.parse(src);
} catch (ParseException e) {
e.printStackTrace();
}
return rs;
}
}
|
3e05b62f39fb1af09e75a6008d4266b0c48fe3e3
| 432 |
java
|
Java
|
NLPCCd/Hadoop/10040_1.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null |
NLPCCd/Hadoop/10040_1.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null |
NLPCCd/Hadoop/10040_1.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null | 27 | 134 | 0.766204 | 2,394 |
//,temp,sample_1033.java,2,12,temp,sample_8821.java,2,9
//,3
public class xxx {
private COMMIT_STATUS handleSpecialWait(boolean fromRead, long commitOffset, Channel channel, int xid, Nfs3FileAttributes preOpAttr) {
if (!fromRead) {
CommitCtx commitCtx = new CommitCtx(commitOffset, channel, xid, preOpAttr);
pendingCommits.put(commitOffset, commitCtx);
}
if (LOG.isDebugEnabled()) {
log.info("return commit special wait");
}
}
};
|
3e05b674b765f64de670f2b508f259e36aded087
| 2,297 |
java
|
Java
|
Mage.Sets/src/mage/cards/m/MalakirSoothsayer.java
|
zeffirojoe/mage
|
71260c382a4e3afef5cdf79adaa00855b963c166
|
[
"MIT"
] | 1,444 |
2015-01-02T00:25:38.000Z
|
2022-03-31T13:57:18.000Z
|
Mage.Sets/src/mage/cards/m/MalakirSoothsayer.java
|
zeffirojoe/mage
|
71260c382a4e3afef5cdf79adaa00855b963c166
|
[
"MIT"
] | 6,180 |
2015-01-02T19:10:09.000Z
|
2022-03-31T21:10:44.000Z
|
Mage.Sets/src/mage/cards/m/MalakirSoothsayer.java
|
zeffirojoe/mage
|
71260c382a4e3afef5cdf79adaa00855b963c166
|
[
"MIT"
] | 1,001 |
2015-01-01T01:15:20.000Z
|
2022-03-30T20:23:04.000Z
| 35.338462 | 135 | 0.735307 | 2,395 |
package mage.cards.m;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.common.TapTargetCost;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.LoseLifeSourceControllerEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.AbilityWord;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.common.FilterControlledCreaturePermanent;
import mage.filter.predicate.permanent.TappedPredicate;
import mage.target.common.TargetControlledCreaturePermanent;
/**
*
* @author LevelX2
*/
public final class MalakirSoothsayer extends CardImpl {
private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("untapped Ally you control");
static {
filter.add(SubType.ALLY.getPredicate());
filter.add(TappedPredicate.UNTAPPED);
}
public MalakirSoothsayer(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{B}");
this.subtype.add(SubType.VAMPIRE);
this.subtype.add(SubType.SHAMAN);
this.subtype.add(SubType.ALLY);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// <i>Cohort</i> — {T}, Tap an untapped Ally you control: You draw a card and you lose a life.
SimpleActivatedAbility ability = new SimpleActivatedAbility(Zone.BATTLEFIELD,
new DrawCardSourceControllerEffect(1).setText("you draw a card"),
new TapSourceCost());
ability.setAbilityWord(AbilityWord.COHORT);
ability.addCost(new TapTargetCost(new TargetControlledCreaturePermanent(1, 1, filter, false)));
Effect effect = new LoseLifeSourceControllerEffect(1);
effect.setText("and you lose a life");
ability.addEffect(effect);
this.addAbility(ability);
}
private MalakirSoothsayer(final MalakirSoothsayer card) {
super(card);
}
@Override
public MalakirSoothsayer copy() {
return new MalakirSoothsayer(this);
}
}
|
3e05b790437c6e5b52f7b751d0fc6313ec9791c7
| 35 |
java
|
Java
|
test/files/neg/t10260/A.java
|
jjudd/scala
|
7247dfe341807dfa1f97d64b0119f610342fc6cf
|
[
"Apache-2.0"
] | 12,824 |
2015-01-01T14:47:08.000Z
|
2022-03-31T17:25:33.000Z
|
test/files/neg/t10260/A.java
|
Code-distancing/scala
|
99de4622e8e81e0adc4d4ea60f81bc42d40f84b9
|
[
"Apache-2.0"
] | 4,594 |
2015-01-02T02:47:39.000Z
|
2022-03-31T15:51:59.000Z
|
test/files/neg/t10260/A.java
|
Code-distancing/scala
|
99de4622e8e81e0adc4d4ea60f81bc42d40f84b9
|
[
"Apache-2.0"
] | 3,253 |
2015-01-02T07:53:20.000Z
|
2022-03-31T14:18:46.000Z
| 11.666667 | 33 | 0.628571 | 2,396 |
public class A<T extends A<T>> {}
|
3e05b7cd9d8a98a94fbc46d5f58a266e7718f175
| 1,923 |
java
|
Java
|
src/day13/MultiBracketValidation.java
|
louiethe17th/data-structures-and-algorithms
|
9ac6a3286cb291297eff9e7c76ab8f26f084af53
|
[
"MIT"
] | null | null | null |
src/day13/MultiBracketValidation.java
|
louiethe17th/data-structures-and-algorithms
|
9ac6a3286cb291297eff9e7c76ab8f26f084af53
|
[
"MIT"
] | null | null | null |
src/day13/MultiBracketValidation.java
|
louiethe17th/data-structures-and-algorithms
|
9ac6a3286cb291297eff9e7c76ab8f26f084af53
|
[
"MIT"
] | null | null | null | 23.740741 | 69 | 0.401456 | 2,397 |
package day13;
public class MultiBracketValidation {
static class stack {
int top=-1;
char items[] = new char[100];
void push(char x) {
if (top == 99) {
System.out.println("Stack full");
} else {
items[++top] = x;
}
}
char pop() {
if (top == -1) {
System.out.println("Underflow error");
return '\0';
} else {
char element = items[top];
top--;
return element;
}
}
boolean isEmpty() {
return (top == -1) ? true : false;
}
}
static boolean isMatchingPair(char character1, char character2) {
if (character1 == '(' && character2 == ')')
return true;
else if (character1 == '{' && character2 == '}')
return true;
else if (character1 == '[' && character2 == ']')
return true;
else
return false;
}
static boolean areParenthesisBalanced(char exp[]) {
stack st=new stack();
for(int i=0;i<exp.length;i++) {
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
st.push(exp[i]);
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') {
if (st.isEmpty()) {
return false; }
else if ( !isMatchingPair(st.pop(), exp[i]) ) {
return false;
}
}
}
if (st.isEmpty())
return true;
else {
return false;
}
}
public static void main(String[] args) {
char exp[] = {'{','(',')','}','[',']'};
if (areParenthesisBalanced(exp))
System.out.println("Balanced ");
else
System.out.println("Not Balanced ");
}
}
|
3e05b853a60d8c6d50513f66e5645404ba221f4d
| 4,794 |
java
|
Java
|
spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java
|
KyeongMoon/spring-integration
|
fa060900b0434627c4a520a2ae84a7a20dae735f
|
[
"Apache-2.0"
] | 1,093 |
2015-01-01T15:28:50.000Z
|
2022-03-29T18:30:56.000Z
|
spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java
|
KyeongMoon/spring-integration
|
fa060900b0434627c4a520a2ae84a7a20dae735f
|
[
"Apache-2.0"
] | 1,920 |
2015-01-05T12:16:48.000Z
|
2022-03-31T16:58:41.000Z
|
spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java
|
KyeongMoon/spring-integration
|
fa060900b0434627c4a520a2ae84a7a20dae735f
|
[
"Apache-2.0"
] | 922 |
2015-01-05T05:10:05.000Z
|
2022-03-30T21:06:32.000Z
| 34 | 109 | 0.748227 | 2,398 |
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.integration.transformer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import java.util.Date;
import java.util.UUID;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
/**
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.0
*/
public class HeaderFilterTests {
@Test
public void testFilterDirectly() {
Message<String> message = MessageBuilder.withPayload("test")
.setHeader("x", 1).setHeader("y", 2).setHeader("z", 3)
.build();
HeaderFilter filter = new HeaderFilter("x", "z");
Message<?> result = filter.transform(message);
assertThat(result).isNotNull();
assertThat(result.getHeaders().get("y")).isNotNull();
assertThat(result.getHeaders().get("x")).isNull();
assertThat(result.getHeaders().get("z")).isNull();
}
@Test
public void testFilterWithinHandler() {
UUID correlationId = UUID.randomUUID();
QueueChannel replyChannel = new QueueChannel();
Message<String> message = MessageBuilder.withPayload("test")
.setHeader("x", 1).setHeader("y", 2).setHeader("z", 3)
.setCorrelationId(correlationId)
.setReplyChannel(replyChannel)
.setErrorChannelName("testErrorChannel")
.build();
HeaderFilter filter = new HeaderFilter("x", "z");
MessageTransformingHandler handler = new MessageTransformingHandler(filter);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
handler.handleMessage(message);
Message<?> result = replyChannel.receive(0);
assertThat(result).isNotNull();
assertThat(result.getHeaders().get("y")).isNotNull();
assertThat(result.getHeaders().get("x")).isNull();
assertThat(result.getHeaders().get("z")).isNull();
assertThat(result.getHeaders().getErrorChannel()).isEqualTo("testErrorChannel");
assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel);
assertThat(new IntegrationMessageHeaderAccessor(result).getCorrelationId()).isEqualTo(correlationId);
}
@Test
public void testIdHeaderRemoval() {
HeaderFilter filter = new HeaderFilter("foo", MessageHeaders.ID);
try {
filter.afterPropertiesSet();
fail("BeanInitializationException expected");
}
catch (Exception e) {
assertThat(e).isInstanceOf(BeanInitializationException.class);
assertThat(e.getMessage()).contains("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers.");
}
}
@Test
public void testTimestampHeaderRemoval() {
HeaderFilter filter = new HeaderFilter(MessageHeaders.TIMESTAMP);
try {
filter.afterPropertiesSet();
fail("BeanInitializationException expected");
}
catch (Exception e) {
assertThat(e).isInstanceOf(BeanInitializationException.class);
assertThat(e.getMessage()).contains("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers.");
}
}
@Test
public void testIdPatternRemoval() {
HeaderFilter filter = new HeaderFilter("*", MessageHeaders.ID);
filter.setPatternMatch(true);
try {
filter.afterPropertiesSet();
fail("BeanInitializationException expected");
}
catch (Exception e) {
assertThat(e).isInstanceOf(BeanInitializationException.class);
assertThat(e.getMessage()).contains("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers.");
}
}
@Test
public void testPatternRemoval() {
HeaderFilter filter = new HeaderFilter("time*");
filter.setPatternMatch(true);
filter.afterPropertiesSet();
Message<String> message = MessageBuilder.withPayload("test")
.setHeader("time", new Date())
.build();
Message<?> result = filter.transform(message);
assertThat(result.getHeaders())
.containsKey(MessageHeaders.TIMESTAMP)
.doesNotContainKey("time");
}
}
|
3e05b8b180eac7a795d71e8cf8e0525b1365c9cd
| 752 |
java
|
Java
|
EarthQuakes_Cprovider/app/src/main/java/com/mglezh/earthquakes/fragments/SettingFragment.java
|
mglezh/Android
|
16457037c853f6e0d3d4c5be1cf224ddd6705bf1
|
[
"MIT"
] | null | null | null |
EarthQuakes_Cprovider/app/src/main/java/com/mglezh/earthquakes/fragments/SettingFragment.java
|
mglezh/Android
|
16457037c853f6e0d3d4c5be1cf224ddd6705bf1
|
[
"MIT"
] | null | null | null |
EarthQuakes_Cprovider/app/src/main/java/com/mglezh/earthquakes/fragments/SettingFragment.java
|
mglezh/Android
|
16457037c853f6e0d3d4c5be1cf224ddd6705bf1
|
[
"MIT"
] | null | null | null | 26.857143 | 64 | 0.784574 | 2,399 |
package com.mglezh.earthquakes.fragments;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.app.Fragment;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mglezh.earthquakes.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link SettingFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SettingFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.userspreferences);
}
}
|
3e05b8dc0d3d5c533abfb1df12a1622192fd09fc
| 14,184 |
java
|
Java
|
IDE/src/main/java/org/jdesktop/swingx/JXTitledSeparator.java
|
martianworm17/SikuliX1
|
25d8a380871ceb07ab4f99e2cc56813606f91dbb
|
[
"MIT"
] | 1 |
2018-03-10T11:10:20.000Z
|
2018-03-10T11:10:20.000Z
|
IDE/src/main/java/org/jdesktop/swingx/JXTitledSeparator.java
|
martianworm17/SikuliX1
|
25d8a380871ceb07ab4f99e2cc56813606f91dbb
|
[
"MIT"
] | null | null | null |
IDE/src/main/java/org/jdesktop/swingx/JXTitledSeparator.java
|
martianworm17/SikuliX1
|
25d8a380871ceb07ab4f99e2cc56813606f91dbb
|
[
"MIT"
] | null | null | null | 36.556701 | 179 | 0.62634 | 2,400 |
/*
* Copyright (c) 2010-2017, sikuli.org, sikulix.com - MIT license
*/
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import org.jdesktop.beans.JavaBean;
/**
* <p>A simple horizontal separator that contains a title.<br/>
*
* <p>JXTitledSeparator allows you to specify the title via the {@link #setTitle} method.
* The title alignment may be specified by using the {@link #setHorizontalAlignment}
* method, and accepts all the same arguments as the {@link javax.swing.JLabel#setHorizontalAlignment}
* method.</p>
*
* <p>In addition, you may specify an Icon to use with this separator. The icon
* will appear "leading" the title (on the left in left-to-right languages,
* on the right in right-to-left languages). To change the position of the
* title with respect to the icon, call {@link #setHorizontalTextPosition}.</p>
*
* <p>The default font and color of the title comes from the <code>LookAndFeel</code>, mimicking
* the font and color of the {@link javax.swing.border.TitledBorder}</p>
*
* <p>Here are a few example code snippets:
* <pre><code>
* //create a plain separator
* JXTitledSeparator sep = new JXTitledSeparator();
* sep.setTitle("Customer Info");
*
* //create a separator with an icon
* sep = new JXTitledSeparator();
* sep.setTitle("Customer Info");
* sep.setIcon(new ImageIcon("myimage.png"));
*
* //create a separator with an icon to the right of the title,
* //center justified
* sep = new JXTitledSeparator();
* sep.setTitle("Customer Info");
* sep.setIcon(new ImageIcon("myimage.png"));
* sep.setHorizontalAlignment(SwingConstants.CENTER);
* sep.setHorizontalTextPosition(SwingConstants.TRAILING);
* </code></pre>
*
* @status REVIEWED
* @author rbair
*/
@JavaBean
public class JXTitledSeparator extends JXPanel {
/**
* Implementation detail: the label used to display the title
*/
private JLabel label;
/**
* Implementation detail: a separator to use on the left of the
* title if alignment is centered or right justified
*/
private JSeparator leftSeparator;
/**
* Implementation detail: a separator to use on the right of the
* title if alignment is centered or left justified
*/
private JSeparator rightSeparator;
/**
* Creates a new instance of <code>JXTitledSeparator</code>. The default title is simply
* an empty string. Default justification is <code>LEADING</code>, and the default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator() {
this("Untitled");
}
/**
* Creates a new instance of <code>JXTitledSeparator</code> with the specified
* title. Default horizontal alignment is <code>LEADING</code>, and the default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator(String title) {
this(title, SwingConstants.LEADING, null);
}
/**
* Creates a new instance of <code>JXTitledSeparator</code> with the specified
* title and horizontal alignment. The default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator(String title, int horizontalAlignment) {
this(title, horizontalAlignment, null);
}
/**
* Creates a new instance of <code>JXTitledSeparator</code> with the specified
* title, icon, and horizontal alignment. The default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator(String title, int horizontalAlignment, Icon icon) {
setLayout(new GridBagLayout());
label = new JLabel(title) {
@Override
public void updateUI(){
super.updateUI();
updateTitle();
}
};
label.setIcon(icon);
label.setHorizontalAlignment(horizontalAlignment);
leftSeparator = new JSeparator();
rightSeparator = new JSeparator();
layoutSeparator();
updateTitle();
setOpaque(false);
}
/**
* Implementation detail. Handles updates of title color and font on LAF change. For more
* details see swingx#451.
*/
//TODO remove this method in favor of UI delegate -- kgs
protected void updateTitle()
{
if (label == null) return;
Color c = label.getForeground();
if (c == null || c instanceof ColorUIResource)
setForeground(UIManager.getColor("TitledBorder.titleColor"));
Font f = label.getFont();
if (f == null || f instanceof FontUIResource)
setFont(UIManager.getFont("TitledBorder.font"));
}
/**
* Implementation detail. lays out this component, showing/hiding components
* as necessary. Actually changes the containment (removes and adds components).
* <code>JXTitledSeparator</code> is treated as a single component rather than
* a container.
*/
private void layoutSeparator() {
removeAll();
//SwingX #304 fix alignment issues
//this is really a hacky fix, but a fix nonetheless
//we need a better layout approach for this class
int alignment = getHorizontalAlignment();
if (!getComponentOrientation().isLeftToRight()) {
switch (alignment) {
case SwingConstants.LEFT:
alignment = SwingConstants.RIGHT;
break;
case SwingConstants.RIGHT:
alignment = SwingConstants.LEFT;
break;
case SwingConstants.EAST:
alignment = SwingConstants.WEST;
break;
case SwingConstants.WEST:
alignment = SwingConstants.EAST;
break;
default:
break;
}
}
switch (alignment) {
case SwingConstants.LEFT:
case SwingConstants.LEADING:
case SwingConstants.WEST:
add(label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(rightSeparator, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
break;
case SwingConstants.RIGHT:
case SwingConstants.TRAILING:
case SwingConstants.EAST:
add(rightSeparator, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
break;
case SwingConstants.CENTER:
default:
add(leftSeparator, new GridBagConstraints(0, 0, 1, 1, 0.5, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(rightSeparator, new GridBagConstraints(4, 0, 1, 1, 0.5, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
}
}
/**
* Sets the title for the separator. This may be simple html, or plain
* text.
*
* @param title the new title. Any string input is acceptable
*/
public void setTitle(String title) {
String old = getTitle();
label.setText(title);
firePropertyChange("title", old, getTitle());
}
/**
* Gets the title.
*
* @return the title being used for this <code>JXTitledSeparator</code>.
* This will be the raw title text, and so may include html tags etc
* if they were so specified in #setTitle.
*/
public String getTitle() {
return label.getText();
}
/**
* <p>Sets the alignment of the title along the X axis. If leading, then
* the title will lead the separator (in left-to-right languages,
* the title will be to the left and the separator to the right). If centered,
* then a separator will be to the left, followed by the title (centered),
* followed by a separator to the right. Trailing will have the title
* on the right with a separator to its left, in left-to-right languages.</p>
*
* <p>LEFT and RIGHT always position the text left or right of the separator,
* respectively, regardless of the language orientation.</p>
*
* @param alignment One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> (the default) or
* <code>TRAILING</code>.
*
* @throws IllegalArgumentException if the alignment does not match one of
* the accepted inputs.
* @see SwingConstants
* @see #getHorizontalAlignment
*/
public void setHorizontalAlignment(int alignment) {
int old = getHorizontalAlignment();
label.setHorizontalAlignment(alignment);
if (old != getHorizontalAlignment()) {
layoutSeparator();
}
firePropertyChange("horizontalAlignment", old, getHorizontalAlignment());
}
/**
* Returns the alignment of the title contents along the X axis.
*
* @return The value of the horizontalAlignment property, one of the
* following constants defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*
* @see #setHorizontalAlignment
* @see SwingConstants
*/
public int getHorizontalAlignment() {
return label.getHorizontalAlignment();
}
/**
* Sets the horizontal position of the title's text,
* relative to the icon.
*
* @param position One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code>, or
* <code>TRAILING</code> (the default).
* @throws IllegalArgumentException if the position does not match one of
* the accepted inputs.
*/
public void setHorizontalTextPosition(int position) {
int old = getHorizontalTextPosition();
label.setHorizontalTextPosition(position);
firePropertyChange("horizontalTextPosition", old, getHorizontalTextPosition());
}
/**
* Returns the horizontal position of the title's text,
* relative to the icon.
*
* @return One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*
* @see SwingConstants
*/
public int getHorizontalTextPosition() {
return label.getHorizontalTextPosition();
}
/**
* {@inheritDoc}
*/
@Override
public ComponentOrientation getComponentOrientation() {
return label.getComponentOrientation();
}
/**
* {@inheritDoc}
*/
@Override
public void setComponentOrientation(ComponentOrientation o) {
ComponentOrientation old = label.getComponentOrientation();
label.setComponentOrientation(o);
firePropertyChange("componentOrientation", old, label.getComponentOrientation());
}
/**
* Defines the icon this component will display. If
* the value of icon is null, nothing is displayed.
* <p>
* The default value of this property is null.
*
* @see #setHorizontalTextPosition
* @see #getIcon
*/
public void setIcon(Icon icon) {
Icon old = getIcon();
label.setIcon(icon);
firePropertyChange("icon", old, getIcon());
}
/**
* Returns the graphic image (glyph, icon) that the
* <code>JXTitledSeparator</code> displays.
*
* @return an Icon
* @see #setIcon
*/
public Icon getIcon() {
return label.getIcon();
}
/**
* {@inheritDoc}
*/
@Override
public void setForeground(Color foreground) {
if (label != null) {
label.setForeground(foreground);
}
super.setForeground(foreground);
}
/**
* {@inheritDoc}
*/
@Override
public void setFont(Font font) {
if (label != null) {
label.setFont(font);
}
super.setFont(font);
}
}
|
3e05b9366e79694b6c6a11fea079ecc964156d43
| 2,249 |
java
|
Java
|
drasyl-core/src/main/java/org/drasyl/crypto/sodium/DrasylSodium.java
|
drasyl-overlay/drasyl
|
3cfc1feddd9b7f3b308fda9b703863c17557c714
|
[
"MIT"
] | 10 |
2020-07-13T18:49:20.000Z
|
2022-03-30T11:36:53.000Z
|
drasyl-core/src/main/java/org/drasyl/crypto/sodium/DrasylSodium.java
|
drasyl-overlay/drasyl
|
3cfc1feddd9b7f3b308fda9b703863c17557c714
|
[
"MIT"
] | 131 |
2020-10-01T06:26:49.000Z
|
2022-03-27T21:05:12.000Z
|
drasyl-core/src/main/java/org/drasyl/crypto/sodium/DrasylSodium.java
|
drasyl-overlay/drasyl
|
3cfc1feddd9b7f3b308fda9b703863c17557c714
|
[
"MIT"
] | 2 |
2020-11-04T05:49:51.000Z
|
2021-10-31T09:55:11.000Z
| 38.775862 | 107 | 0.734549 | 2,401 |
/*
* Copyright (c) 2020-2021 Heiko Bornholdt and Kevin Röbert
*
* 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.drasyl.crypto.sodium;
import io.netty.util.internal.SystemPropertyUtil;
import org.drasyl.crypto.loader.LibraryLoader;
import org.drasyl.crypto.loader.NativeLoader;
import java.io.File;
import java.io.IOException;
import static org.drasyl.crypto.loader.LibraryLoader.PREFER_SYSTEM;
/**
* This class loads and binds the JNA {@link Sodium}.
*/
public class DrasylSodium extends Sodium {
private static final String DEFAULT_MODE = SystemPropertyUtil.get("drasyl.crypto.mode", PREFER_SYSTEM);
public DrasylSodium() throws IOException {
this(DEFAULT_MODE);
}
public DrasylSodium(final String loadingMode) throws IOException {
new LibraryLoader(Sodium.class).loadLibrary(loadingMode, "sodium");
register();
}
public DrasylSodium(final File libFile) throws IOException {
try {
NativeLoader.loadLibraryFromFileSystem(libFile.getAbsolutePath(), Sodium.class);
register();
}
catch (final Exception e) {
throw new IOException("Could not load local library due to: ", e);
}
}
}
|
3e05b93d08c6889fee8b9ddb6cdbd874e21fa40a
| 1,121 |
java
|
Java
|
Benchmarks_with_Functional_Bugs/Java/Bears-72/src/src/test/java/spoon/test/factory/ClassFactoryTest.java
|
kupl/starlab-benchmarks
|
1efc9efffad1b797f6a795da7e032041e230d900
|
[
"MIT"
] | null | null | null |
Benchmarks_with_Functional_Bugs/Java/Bears-72/src/src/test/java/spoon/test/factory/ClassFactoryTest.java
|
kupl/starlab-benchmarks
|
1efc9efffad1b797f6a795da7e032041e230d900
|
[
"MIT"
] | null | null | null |
Benchmarks_with_Functional_Bugs/Java/Bears-72/src/src/test/java/spoon/test/factory/ClassFactoryTest.java
|
kupl/starlab-benchmarks
|
1efc9efffad1b797f6a795da7e032041e230d900
|
[
"MIT"
] | 2 |
2020-11-26T13:27:14.000Z
|
2022-03-20T02:12:55.000Z
| 31.138889 | 80 | 0.775201 | 2,402 |
package spoon.test.factory;
import org.junit.Test;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtPackage;
import spoon.reflect.factory.Factory;
import static org.junit.Assert.assertEquals;
import static spoon.testing.utils.ModelUtils.createFactory;
public class ClassFactoryTest {
@Test
public void testDeclaringClass() throws Exception {
final Factory factory = createFactory();
final CtClass<Object> declaringClass = factory.Core().createClass();
declaringClass.setSimpleName("DeclaringClass");
final CtClass<Object> inner = factory.Class().create(declaringClass, "Inner");
assertEquals("Inner", inner.getSimpleName());
assertEquals(declaringClass, inner.getDeclaringType());
}
@Test
public void testTopLevelClass() throws Exception {
final Factory factory = createFactory();
final CtPackage aPackage = factory.Core().createPackage();
aPackage.setSimpleName("spoon");
final CtClass<Object> topLevel = factory.Class().create(aPackage, "TopLevel");
assertEquals("TopLevel", topLevel.getSimpleName());
assertEquals(aPackage, topLevel.getPackage());
}
}
|
3e05b9c836de6f765ce19519e515a46fec02d780
| 3,322 |
java
|
Java
|
app/src/main/java/com/mumet/abatidoda/curiousme/SampleApplication/utils/SampleApplication3DModel.java
|
DavideA/curiousme
|
0170c3cd8b8d4768679b7b31a3c6585b803287b7
|
[
"MIT"
] | 4 |
2016-06-20T11:03:23.000Z
|
2022-03-23T13:35:39.000Z
|
app/src/main/java/com/mumet/abatidoda/curiousme/SampleApplication/utils/SampleApplication3DModel.java
|
DavideA/curiousme
|
0170c3cd8b8d4768679b7b31a3c6585b803287b7
|
[
"MIT"
] | 2 |
2018-01-25T03:25:50.000Z
|
2021-08-17T05:02:07.000Z
|
app/src/main/java/com/mumet/abatidoda/curiousme/SampleApplication/utils/SampleApplication3DModel.java
|
DavideA/curiousme
|
0170c3cd8b8d4768679b7b31a3c6585b803287b7
|
[
"MIT"
] | 7 |
2016-06-20T10:35:47.000Z
|
2019-11-14T15:43:04.000Z
| 28.152542 | 82 | 0.527092 | 2,403 |
/*===============================================================================
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of QUALCOMM Incorporated, registered in the United States
and other countries. Trademarks of QUALCOMM Incorporated are used with permission.
===============================================================================*/
package com.mumet.abatidoda.curiousme.SampleApplication.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.content.res.AssetManager;
public class SampleApplication3DModel extends MeshObject
{
private ByteBuffer verts;
private ByteBuffer textCoords;
private ByteBuffer norms;
int numVerts = 0;
public void loadModel(AssetManager assetManager, String filename)
throws IOException
{
InputStream is = null;
try
{
is = assetManager.open(filename);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = reader.readLine();
int floatsToRead = Integer.parseInt(line);
numVerts = floatsToRead / 3;
verts = ByteBuffer.allocateDirect(floatsToRead * 4);
verts.order(ByteOrder.nativeOrder());
for (int i = 0; i < floatsToRead; i++)
{
verts.putFloat(Float.parseFloat(reader.readLine()));
}
verts.rewind();
line = reader.readLine();
floatsToRead = Integer.parseInt(line);
norms = ByteBuffer.allocateDirect(floatsToRead * 4);
norms.order(ByteOrder.nativeOrder());
for (int i = 0; i < floatsToRead; i++)
{
norms.putFloat(Float.parseFloat(reader.readLine()));
}
norms.rewind();
line = reader.readLine();
floatsToRead = Integer.parseInt(line);
textCoords = ByteBuffer.allocateDirect(floatsToRead * 4);
textCoords.order(ByteOrder.nativeOrder());
for (int i = 0; i < floatsToRead; i++)
{
textCoords.putFloat(Float.parseFloat(reader.readLine()));
}
textCoords.rewind();
} finally
{
if (is != null)
is.close();
}
}
@Override
public Buffer getBuffer(BUFFER_TYPE bufferType)
{
Buffer result = null;
switch (bufferType)
{
case BUFFER_TYPE_VERTEX:
result = verts;
break;
case BUFFER_TYPE_TEXTURE_COORD:
result = textCoords;
break;
case BUFFER_TYPE_NORMALS:
result = norms;
default:
break;
}
return result;
}
@Override
public int getNumObjectVertex()
{
return numVerts;
}
@Override
public int getNumObjectIndex()
{
return 0;
}
}
|
3e05ba9e7ee2d5cafe4692030f28a43415d012f4
| 1,837 |
java
|
Java
|
samplemapapp/src/main/java/com/joeracosta/simplefragments/view/stack/GreenStackFragment.java
|
JayyyR/SimpleFragments
|
4b9eee2a18268410256e126766688836ca4a4198
|
[
"MIT"
] | 4 |
2017-12-10T00:15:37.000Z
|
2017-12-15T05:08:48.000Z
|
samplemapapp/src/main/java/com/joeracosta/simplefragments/view/stack/GreenStackFragment.java
|
JayyyR/SimpleFragments
|
4b9eee2a18268410256e126766688836ca4a4198
|
[
"MIT"
] | 1 |
2017-10-11T20:11:12.000Z
|
2017-12-09T04:44:08.000Z
|
samplemapapp/src/main/java/com/joeracosta/simplefragments/view/stack/GreenStackFragment.java
|
JayyyR/SimpleFragments
|
4b9eee2a18268410256e126766688836ca4a4198
|
[
"MIT"
] | 1 |
2018-12-12T21:55:30.000Z
|
2018-12-12T21:55:30.000Z
| 31.672414 | 123 | 0.728361 | 2,404 |
package com.joeracosta.simplefragments.view.stack;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.joeracosta.library.activity.FragmentStackFragment;
import com.joeracosta.simplefragments.R;
import com.joeracosta.simplefragments.view.map.SampleMapActivity;
import com.joeracosta.simplefragments.view.simple.GreenFragment;
/**
* Created by Joe on 8/14/2017.
*/
public class GreenStackFragment extends FragmentStackFragment {
public static GreenStackFragment newInstance(int stackLevel){
Bundle args = new Bundle();
args.putInt(SampleMapActivity.STACK_LEVEL_KEY, stackLevel);
GreenStackFragment fragment = new GreenStackFragment();
fragment.setArguments(args);
return fragment;
}
private int stackLevel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null){
stackLevel = args.getInt(SampleMapActivity.STACK_LEVEL_KEY);
}
//if we haven't recreated a state that already had fragments, start at one green frag
if (!hasFragments()) {
addFragmentToStack(GreenFragment.newInstance(stackLevel), R.id.full_container, null, null);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(SampleMapActivity.STACK_LEVEL_KEY, stackLevel);
super.onSaveInstanceState(outState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.stack_fragment, container, false);
}
}
|
3e05bbe7d48e66402da1c498dd19aa59ed2d2575
| 1,730 |
java
|
Java
|
app/src/main/java/dev/ugwulo/lecturenote/adapter/MessageAdapter.java
|
ugwulo/LectureNote
|
572b1251d684a095c55b85b0fd104afd141bab67
|
[
"MIT"
] | 7 |
2020-10-01T02:18:31.000Z
|
2020-10-01T20:29:50.000Z
|
app/src/main/java/dev/ugwulo/lecturenote/adapter/MessageAdapter.java
|
ugwulo/LectureNote
|
572b1251d684a095c55b85b0fd104afd141bab67
|
[
"MIT"
] | 21 |
2020-10-01T01:59:38.000Z
|
2020-10-05T15:35:25.000Z
|
app/src/main/java/dev/ugwulo/lecturenote/adapter/MessageAdapter.java
|
ugwulo/LectureNote
|
572b1251d684a095c55b85b0fd104afd141bab67
|
[
"MIT"
] | 45 |
2020-10-01T02:03:39.000Z
|
2020-11-24T00:37:46.000Z
| 28.360656 | 145 | 0.760116 | 2,405 |
package dev.ugwulo.lecturenote.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import dev.ugwulo.lecturenote.databinding.FragmentCourseDetailsBinding;
import dev.ugwulo.lecturenote.model.Message;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {
FragmentCourseDetailsBinding mCourseDetailsBinding;
private DatabaseReference mReference;
private FirebaseAuth mAuth;
private List<Message> userMessageList;
public MessageAdapter(List<Message> userMessageList){
this.userMessageList = userMessageList;
}
@NonNull
@Override
public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
FragmentCourseDetailsBinding itemBinding = FragmentCourseDetailsBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(itemBinding);
}
@Override
public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
public MessageViewHolder(@NonNull FragmentCourseDetailsBinding itemView) {
super(itemView.getRoot());
}
public void bind(Message message){
}
}
}
|
3e05bbeead16fbcdf62e5893e506db19a80a6912
| 488 |
java
|
Java
|
nc-java/src/codefights/interview/dfsbfs/LongestPath.java
|
nhancv/nc-competition-code
|
456ee7f54adfeaf5dd0977e900e259014ce2b436
|
[
"MIT"
] | null | null | null |
nc-java/src/codefights/interview/dfsbfs/LongestPath.java
|
nhancv/nc-competition-code
|
456ee7f54adfeaf5dd0977e900e259014ce2b436
|
[
"MIT"
] | null | null | null |
nc-java/src/codefights/interview/dfsbfs/LongestPath.java
|
nhancv/nc-competition-code
|
456ee7f54adfeaf5dd0977e900e259014ce2b436
|
[
"MIT"
] | null | null | null | 16.827586 | 67 | 0.618852 | 2,406 |
package codefights.interview.dfsbfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* https://codefights.com/interview-practice/task/iXJRYae6TBqc4ymFg
*/
public class LongestPath {
int longestPath(String fileSystem) {
return 0;
}
class Node {
String word;
Node parent;
List<Node> nodes = new ArrayList<>();
public Node(String w) {
word = w;
}
}
}
|
3e05bc68f225833da45418417192db1d8f4ceccf
| 3,571 |
java
|
Java
|
main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/InitializeMojo.java
|
vishalbelsare/sarl
|
fe82d8fd5230872ae710084893092cb16f18d992
|
[
"Apache-2.0"
] | 131 |
2015-02-25T09:36:55.000Z
|
2022-02-04T03:38:56.000Z
|
main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/InitializeMojo.java
|
vishalbelsare/sarl
|
fe82d8fd5230872ae710084893092cb16f18d992
|
[
"Apache-2.0"
] | 849 |
2015-01-05T08:41:16.000Z
|
2022-03-09T07:51:16.000Z
|
main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/InitializeMojo.java
|
vishalbelsare/sarl
|
fe82d8fd5230872ae710084893092cb16f18d992
|
[
"Apache-2.0"
] | 50 |
2015-02-25T19:43:00.000Z
|
2022-03-08T19:14:54.000Z
| 31.60177 | 83 | 0.745729 | 2,407 |
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2021 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sarl.maven.docs;
import java.io.File;
import java.text.MessageFormat;
import java.util.List;
import com.google.common.base.Throwables;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
/** Initialization mojo for the SARL Maven compiler.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 0.6
*/
@Mojo(name = "initialize", defaultPhase = LifecyclePhase.INITIALIZE,
requiresDependencyResolution = ResolutionScope.COMPILE)
public class InitializeMojo extends AbstractDocumentationMojo {
@Override
protected String getSkippingMessage() {
return null;
}
@Override
protected String internalExecute() {
try {
for (final String sourceFolder : this.inferredSourceDirectories) {
addSourceFolder(sourceFolder);
}
addTestSourceFolder(this.testSourceDirectory);
} catch (Throwable exception) {
final String message = Throwables.getRootCause(exception).getLocalizedMessage();
getLog().error(message);
getLog().debug(exception);
return message;
}
return null;
}
/** Add a source folder in the current projecT.
*
* @param path the source folder path.
*/
protected void addSourceFolder(String path) {
final List<String> existingFolders1 = this.project.getCompileSourceRoots();
final List<String> existingFolders2 = this.project.getTestCompileSourceRoots();
if (!existingFolders1.contains(path) && !existingFolders2.contains(path)) {
getLog().info(MessageFormat.format(Messages.InitializeMojo_0, path));
this.session.getCurrentProject().addCompileSourceRoot(path);
} else {
getLog().info(MessageFormat.format(Messages.InitializeMojo_1, path));
}
}
/** Add a source folder in the current projecT.
*
* @param path the source folder path.
*/
protected void addSourceFolder(File path) {
addSourceFolder(path.getAbsolutePath());
}
/** Add a source folder in the current projecT.
*
* @param path the source folder path.
*/
protected void addTestSourceFolder(String path) {
final List<String> existingFolders1 = this.project.getCompileSourceRoots();
final List<String> existingFolders2 = this.project.getTestCompileSourceRoots();
if (!existingFolders1.contains(path) && !existingFolders2.contains(path)) {
getLog().info(MessageFormat.format(Messages.InitializeMojo_2, path));
this.session.getCurrentProject().addTestCompileSourceRoot(path);
} else {
getLog().info(MessageFormat.format(Messages.InitializeMojo_3, path));
}
}
/** Add a test source folder in the current projecT.
*
* @param path the source folder path.
*/
protected void addTestSourceFolder(File path) {
addTestSourceFolder(path.getAbsolutePath());
}
}
|
3e05bd282c9293613c36fea7e6fc2b0e6312038b
| 529 |
java
|
Java
|
MOC_WEB-07/src/main/java/com/maersk/line/web/WelcomeController.java
|
manishoctane/Manish
|
0e2d37f7a6b5bb318e907f52ab283e4dbeda09ad
|
[
"MIT"
] | null | null | null |
MOC_WEB-07/src/main/java/com/maersk/line/web/WelcomeController.java
|
manishoctane/Manish
|
0e2d37f7a6b5bb318e907f52ab283e4dbeda09ad
|
[
"MIT"
] | null | null | null |
MOC_WEB-07/src/main/java/com/maersk/line/web/WelcomeController.java
|
manishoctane/Manish
|
0e2d37f7a6b5bb318e907f52ab283e4dbeda09ad
|
[
"MIT"
] | null | null | null | 27.842105 | 104 | 0.79206 | 2,408 |
package com.maersk.line.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
return new ModelAndView("one").addObject("uname", "Chandu");
}
}
|
3e05bea2033cbe4acd116d6c42f5f6cd858afa13
| 4,737 |
java
|
Java
|
src/main/java/fluke/stygian/block/BlockEndCanopySapling.java
|
mcBegins2Snow/enderoni
|
26448a038b47a8190d375b082aaafb431716dae6
|
[
"MIT"
] | 4 |
2018-11-21T15:19:38.000Z
|
2021-12-05T20:15:30.000Z
|
src/main/java/fluke/stygian/block/BlockEndCanopySapling.java
|
mcBegins2Snow/enderoni
|
26448a038b47a8190d375b082aaafb431716dae6
|
[
"MIT"
] | 20 |
2018-10-15T12:46:25.000Z
|
2021-05-25T14:03:45.000Z
|
src/main/java/fluke/stygian/block/BlockEndCanopySapling.java
|
mcBegins2Snow/enderoni
|
26448a038b47a8190d375b082aaafb431716dae6
|
[
"MIT"
] | 5 |
2018-12-24T06:02:50.000Z
|
2022-01-21T22:35:26.000Z
| 33.595745 | 186 | 0.708043 | 2,409 |
package fluke.stygian.block;
import java.util.Random;
import fluke.stygian.util.Reference;
import fluke.stygian.world.feature.WorldGenEnderCanopy;
import net.minecraft.block.BlockBush;
import net.minecraft.block.IGrowable;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.IStateMapper;
import net.minecraft.client.renderer.block.statemap.StateMap;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockEndCanopySapling extends BlockBush implements IGrowable
{
public static final String REG_NAME = "endcanopysapling";
public static final PropertyInteger STAGE = PropertyInteger.create("stage", 0, 1);
protected static final AxisAlignedBB SAPLING_AABB = new AxisAlignedBB(0.09999999403953552D, 0.0D, 0.09999999403953552D, 0.8999999761581421D, 0.800000011920929D, 0.8999999761581421D);
public BlockEndCanopySapling()
{
this.setDefaultState(this.blockState.getBaseState().withProperty(STAGE, Integer.valueOf(0)));
this.setCreativeTab(CreativeTabs.DECORATIONS);
setUnlocalizedName(Reference.MOD_ID + ".endcanopysapling");
setRegistryName(REG_NAME);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
return SAPLING_AABB;
}
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (!worldIn.isRemote)
{
super.updateTick(worldIn, pos, state, rand);
if (!worldIn.isAreaLoaded(pos, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light
if (worldIn.getLightFromNeighbors(pos.up()) >= 9 && rand.nextInt(7) == 0)
{
this.grow(worldIn, pos, state, rand);
}
}
}
public void grow(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (((Integer)state.getValue(STAGE)).intValue() == 0)
{
worldIn.setBlockState(pos, state.cycleProperty(STAGE), 4);
}
else
{
this.generateTree(worldIn, pos, state, rand);
}
}
public void generateTree(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (!net.minecraftforge.event.terraingen.TerrainGen.saplingGrowTree(worldIn, rand, pos))
return;
WorldGenerator tree = new WorldGenEnderCanopy(true);
tree.generate(worldIn, rand, pos);
}
@Override
protected boolean canSustainBush(IBlockState state)
{
return state.getBlock() == ModBlocks.endGrass || state.getBlock() == Blocks.END_STONE;
}
/**
* Convert the given metadata into a BlockState for this Block
*/
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(STAGE, Integer.valueOf((meta & 8) >> 3));
}
/**
* Convert the BlockState into the correct metadata value
*/
@Override
public int getMetaFromState(IBlockState state)
{
int i = 0;
i = i | state.getValue(STAGE).intValue() << 3;
return i;
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] { STAGE });
}
public boolean canGrow(World worldIn, BlockPos pos, IBlockState state, boolean isClient)
{
return true;
}
public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state)
{
return (double)worldIn.rand.nextFloat() < 0.45D;
}
public void grow(World worldIn, Random rand, BlockPos pos, IBlockState state)
{
this.grow(worldIn, pos, state, rand);
}
@SideOnly(Side.CLIENT)
public void initModel()
{
IStateMapper mappy = (new StateMap.Builder()).ignore(new IProperty[] { STAGE }).build();
ModelLoader.setCustomStateMapper(this, mappy);
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
}
}
|
3e05bfd03cd086c7de2a7503105fa42b8dbc1517
| 1,257 |
java
|
Java
|
agent-tooling/src/main/java/io/opentelemetry/auto/typed/client/http/HttpClientTypedTracer.java
|
jeremy-lq/opentelemetry-auto-instr-java
|
336e73954003dbc637fe76272da4684521407cac
|
[
"Apache-2.0"
] | null | null | null |
agent-tooling/src/main/java/io/opentelemetry/auto/typed/client/http/HttpClientTypedTracer.java
|
jeremy-lq/opentelemetry-auto-instr-java
|
336e73954003dbc637fe76272da4684521407cac
|
[
"Apache-2.0"
] | null | null | null |
agent-tooling/src/main/java/io/opentelemetry/auto/typed/client/http/HttpClientTypedTracer.java
|
jeremy-lq/opentelemetry-auto-instr-java
|
336e73954003dbc637fe76272da4684521407cac
|
[
"Apache-2.0"
] | null | null | null | 35.914286 | 79 | 0.760541 | 2,410 |
/*
* Copyright 2020, OpenTelemetry 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 io.opentelemetry.auto.typed.client.http;
import io.opentelemetry.auto.typed.client.ClientTypedTracer;
import io.opentelemetry.context.propagation.HttpTextFormat;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public abstract class HttpClientTypedTracer<
T extends HttpClientTypedSpan<T, REQUEST, RESPONSE>, REQUEST, RESPONSE>
extends ClientTypedTracer<T, REQUEST, RESPONSE> {
@Override
protected T startSpan(REQUEST request, T span) {
tracer.getHttpTextFormat().inject(span.getContext(), request, getSetter());
return super.startSpan(request, span);
}
protected abstract HttpTextFormat.Setter<REQUEST> getSetter();
}
|
3e05c03cb175924331b54ccc0d39f37234b5dfaf
| 913 |
java
|
Java
|
Java-web/issueTracker/src/filter/IssueFilter.java
|
VasilPanovski/Java
|
4ae145680522424d8aaf7e7d41eb31a350d5e94e
|
[
"MIT"
] | null | null | null |
Java-web/issueTracker/src/filter/IssueFilter.java
|
VasilPanovski/Java
|
4ae145680522424d8aaf7e7d41eb31a350d5e94e
|
[
"MIT"
] | null | null | null |
Java-web/issueTracker/src/filter/IssueFilter.java
|
VasilPanovski/Java
|
4ae145680522424d8aaf7e7d41eb31a350d5e94e
|
[
"MIT"
] | null | null | null | 27.666667 | 124 | 0.713034 | 2,411 |
package com.issueTracker.filter;
import com.issueTracker.entities.user.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/issues/*")
public class IssueFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpSession session = ((HttpServletRequest) req).getSession();
User user = (User) session.getAttribute("currentUser");
if(user == null){
((HttpServletResponse) resp).sendRedirect("/login");
return;
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
|
3e05c0d382280cf14a664833035f74333dc69a42
| 3,656 |
java
|
Java
|
common/src/main/java/io/github/apace100/origins/mixin/PlayerEntityRendererMixin.java
|
GiantLuigi4/origins-architectury
|
8393e543233d2db8f9c9bf06530e5eed32724379
|
[
"MIT"
] | null | null | null |
common/src/main/java/io/github/apace100/origins/mixin/PlayerEntityRendererMixin.java
|
GiantLuigi4/origins-architectury
|
8393e543233d2db8f9c9bf06530e5eed32724379
|
[
"MIT"
] | null | null | null |
common/src/main/java/io/github/apace100/origins/mixin/PlayerEntityRendererMixin.java
|
GiantLuigi4/origins-architectury
|
8393e543233d2db8f9c9bf06530e5eed32724379
|
[
"MIT"
] | null | null | null | 68.981132 | 242 | 0.747538 | 2,412 |
package io.github.apace100.origins.mixin;
import io.github.apace100.origins.power.ModelColorPower;
import io.github.apace100.origins.registry.ModComponentsArchitectury;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.model.ModelPart;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.util.List;
@Mixin(PlayerEntityRenderer.class)
public class PlayerEntityRendererMixin {
@Environment(EnvType.CLIENT)
@Redirect(method = "renderArm", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelPart;render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumer;II)V", ordinal = 0))
private void makeArmTranslucent(ModelPart modelPart, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, MatrixStack matrices2, VertexConsumerProvider vertexConsumers, int light2, AbstractClientPlayerEntity player) {
List<ModelColorPower> modelColorPowers = ModComponentsArchitectury.getOriginComponent(player).getPowers(ModelColorPower.class);
if (modelColorPowers.size() > 0) {
float red = modelColorPowers.stream().map(ModelColorPower::getRed).reduce((a, b) -> a * b).get();
float green = modelColorPowers.stream().map(ModelColorPower::getGreen).reduce((a, b) -> a * b).get();
float blue = modelColorPowers.stream().map(ModelColorPower::getBlue).reduce((a, b) -> a * b).get();
float alpha = modelColorPowers.stream().map(ModelColorPower::getAlpha).min(Float::compare).get();
modelPart.render(matrices, vertexConsumers.getBuffer(RenderLayer.getEntityTranslucent(player.getSkinTexture())), light, overlay, red, green, blue, alpha);
return;
}
modelPart.render(matrices, vertices, light, overlay);
}
@Environment(EnvType.CLIENT)
@Redirect(method = "renderArm", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/ModelPart;render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumer;II)V", ordinal = 1))
private void makeSleeveTranslucent(ModelPart modelPart, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, MatrixStack matrices2, VertexConsumerProvider vertexConsumers, int light2, AbstractClientPlayerEntity player) {
List<ModelColorPower> modelColorPowers = ModComponentsArchitectury.getOriginComponent(player).getPowers(ModelColorPower.class);
if (modelColorPowers.size() > 0) {
float red = modelColorPowers.stream().map(ModelColorPower::getRed).reduce((a, b) -> a * b).get();
float green = modelColorPowers.stream().map(ModelColorPower::getGreen).reduce((a, b) -> a * b).get();
float blue = modelColorPowers.stream().map(ModelColorPower::getBlue).reduce((a, b) -> a * b).get();
float alpha = modelColorPowers.stream().map(ModelColorPower::getAlpha).min(Float::compare).get();
modelPart.render(matrices, vertexConsumers.getBuffer(RenderLayer.getEntityTranslucent(player.getSkinTexture())), light, overlay, red, green, blue, alpha);
return;
}
modelPart.render(matrices, vertices, light, overlay);
}
}
|
3e05c0edae0ee02e8ddfab2dab853155035cf218
| 4,604 |
java
|
Java
|
exec/java-exec/src/test/java/org/apache/drill/exec/fn/impl/TestCastEmptyStrings.java
|
vsowrirajan/drill
|
c54bd6acb81daa9e1c3ce358e9d3a4ce909f02aa
|
[
"Apache-2.0"
] | null | null | null |
exec/java-exec/src/test/java/org/apache/drill/exec/fn/impl/TestCastEmptyStrings.java
|
vsowrirajan/drill
|
c54bd6acb81daa9e1c3ce358e9d3a4ce909f02aa
|
[
"Apache-2.0"
] | null | null | null |
exec/java-exec/src/test/java/org/apache/drill/exec/fn/impl/TestCastEmptyStrings.java
|
vsowrirajan/drill
|
c54bd6acb81daa9e1c3ce358e9d3a4ce909f02aa
|
[
"Apache-2.0"
] | null | null | null | 52.318182 | 134 | 0.686794 | 2,413 |
/**
* 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.drill.exec.fn.impl;
import org.apache.drill.BaseTestQuery;
import org.apache.drill.common.util.FileUtils;
import org.junit.Test;
public class TestCastEmptyStrings extends BaseTestQuery {
@Test // see DRILL-1874
public void testCastInputTypeNullableVarCharToNumeric() throws Exception {
String root = FileUtils.getResourceAsFile("/emptyStrings.csv").toURI().toString();
// Enable the new cast functions (cast empty string "" to null)
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = true;");
// Test Optional VarChar
test(String.format("select cast(columns[0] as int) from dfs_test.`%s`;", root));
test(String.format("select cast(columns[0] as bigint) from dfs_test.`%s`;", root));
test(String.format("select cast(columns[0] as float) from dfs_test.`%s`;", root));
test(String.format("select cast(columns[0] as double) from dfs_test.`%s`;", root));
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = false;");
}
@Test // see DRILL-1874
public void testCastInputTypeNonNullableVarCharToNumeric() throws Exception {
String root = FileUtils.getResourceAsFile("/emptyStrings.csv").toURI().toString();
// Enable the new cast functions (cast empty string "" to null)
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = true;");
// Test Required VarChar
test(String.format("select cast('' as int) from dfs_test.`%s`;", root));
test(String.format("select cast('' as bigint) from dfs_test.`%s`;", root));
test(String.format("select cast('' as float) from dfs_test.`%s`;", root));
test(String.format("select cast('' as double) from dfs_test.`%s`;", root));
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = false;");
}
@Test // see DRILL-1874
public void testCastInputTypeNullableVarCharToDecimal() throws Exception {
String root = FileUtils.getResourceAsFile("/emptyStrings.csv").toURI().toString();
// Enable the new cast functions (cast empty string "" to null)
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = true;");
// Test Optional VarChar
test(String.format("select cast(columns[0] as decimal) from dfs_test.`%s` where cast(columns[0] as decimal) is null;", root));
test(String.format("select cast(columns[0] as decimal(9)) from dfs_test.`%s`;", root));
test(String.format("select cast(columns[0] as decimal(18)) from dfs_test.`%s`;", root));
test(String.format("select cast(columns[0] as decimal(28)) from dfs_test.`%s`;", root));
test(String.format("select cast(columns[0] as decimal(38)) from dfs_test.`%s`;", root));
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = false;");
}
@Test // see DRILL-1874
public void testCastInputTypeNonNullableVarCharToDecimal() throws Exception {
String root = FileUtils.getResourceAsFile("/emptyStrings.csv").toURI().toString();
// Enable the new cast functions (cast empty string "" to null)
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = true;");
// Test Required VarChar
test(String.format("select cast('' as decimal) from dfs_test.`%s` where cast('' as decimal) is null;", root));
test(String.format("select cast('' as decimal(18)) from dfs_test.`%s`;", root));
test(String.format("select cast('' as decimal(28)) from dfs_test.`%s`;", root));
test(String.format("select cast('' as decimal(38)) from dfs_test.`%s`;", root));
test("alter system set `drill.exec.functions.cast_empty_string_to_null` = false;");
}
}
|
3e05c18384a746657d42aaa83b3e1e12e8aceb74
| 1,855 |
java
|
Java
|
src/test/java/spark/examples/simple/SimpleExample.java
|
AutoscanForJava/com.sparkjava-spark-core
|
54079b0f95f0076dd3c440e1255a7d449d9489f1
|
[
"Apache-2.0"
] | 8,906 |
2015-01-02T12:29:01.000Z
|
2022-03-30T19:27:50.000Z
|
src/test/java/spark/examples/simple/SimpleExample.java
|
AutoscanForJava/com.sparkjava-spark-core
|
54079b0f95f0076dd3c440e1255a7d449d9489f1
|
[
"Apache-2.0"
] | 945 |
2015-01-12T13:50:47.000Z
|
2022-03-31T12:14:03.000Z
|
src/test/java/spark/examples/simple/SimpleExample.java
|
AutoscanForJava/com.sparkjava-spark-core
|
54079b0f95f0076dd3c440e1255a7d449d9489f1
|
[
"Apache-2.0"
] | 1,840 |
2015-01-01T10:55:31.000Z
|
2022-03-24T22:56:54.000Z
| 28.106061 | 110 | 0.59407 | 2,414 |
/*
* Copyright 2011- Per Wendel
*
* 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 spark.examples.simple;
import static spark.Spark.*;
/**
* A simple example just showing some basic functionality
*
* @author Per Wendel
*/
public class SimpleExample {
public static void main(String[] args) {
// port(5678); <- Uncomment this if you want spark to listen on a port different than 4567
get("/hello", (request, response) -> "Hello World!");
post("/hello", (request, response) -> "Hello World: " + request.body());
get("/private", (request, response) -> {
response.status(401);
return "Go Away!!!";
});
get("/users/:name", (request, response) -> "Selected user: " + request.params(":name"));
get("/news/:section", (request, response) -> {
response.type("text/xml");
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><news>" + request.params("section") + "</news>";
});
get("/protected", (request, response) -> {
halt(403, "I don't think so!!!");
return null;
});
get("/redirect", (request, response) -> {
response.redirect("/news/world");
return null;
});
get("/", (request, response) -> "root");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.