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
92305a018b983261e5b6be1a8519e4ad58e8c6d5
4,548
java
Java
src/main/java/seedu/address/logic/parser/StatsCommandParser.java
yeodonghan/main
c4322a3e68fca57147560909c2aaff44b2e373d0
[ "MIT" ]
null
null
null
src/main/java/seedu/address/logic/parser/StatsCommandParser.java
yeodonghan/main
c4322a3e68fca57147560909c2aaff44b2e373d0
[ "MIT" ]
154
2019-09-14T17:37:24.000Z
2019-11-14T05:45:06.000Z
src/main/java/seedu/address/logic/parser/StatsCommandParser.java
yeodonghan/main
c4322a3e68fca57147560909c2aaff44b2e373d0
[ "MIT" ]
5
2019-09-11T10:52:03.000Z
2019-09-14T16:23:18.000Z
47.375
113
0.680959
995,449
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_DATE_INPUT_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_ENDING_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_STARTING_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_STAT_TYPE; import java.util.Calendar; import java.util.Optional; import java.util.stream.Stream; import seedu.address.commons.core.Messages; import seedu.address.logic.commands.statisticcommand.StatisticType; import seedu.address.logic.commands.statisticcommand.StatsCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.statistic.StatsParseUtil; /** * Parses input arguments and creates a new StatsCommand object */ public class StatsCommandParser implements Parser<StatsCommand> { /** * Parses the given {@code String} of arguments in the context of the StatsCommand * and returns an StatsCommand object for execution. * @throws ParseException if the user input does not conform to the expected format. */ public StatsCommand parse(String args) throws ParseException { ArgumentMultimap argMultiMap = ArgumentTokenizer.tokenize(args, PREFIX_STAT_TYPE, PREFIX_STARTING_DATE, PREFIX_ENDING_DATE); //date arguments are optional if (!arePrefixesPresent(argMultiMap, PREFIX_STAT_TYPE)) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, StatsCommand.MESSAGE_USAGE)); } StatisticType type = ParserUtil.parseStatsType(argMultiMap.getValue(PREFIX_STAT_TYPE).get()); Optional<String> startingDateValue = argMultiMap.getValue(PREFIX_STARTING_DATE); Optional<String> endingDateValue = argMultiMap.getValue(PREFIX_ENDING_DATE); //if one date value is present and not the other if ((startingDateValue.isEmpty() && endingDateValue.isPresent()) | (startingDateValue.isPresent() && endingDateValue.isEmpty())) { throw new ParseException(String.format( Messages.OPTIONAL_DATE_MESSAGE_CONSTRAINTS, StatsCommand.NON_DEFAULT_MESSAGE_USAGE)); } if (startingDateValue.isPresent() && endingDateValue.isPresent()) { Calendar startingDate = ParserUtil.parseDateCalendar( argMultiMap.getValue(PREFIX_STARTING_DATE).get()); Calendar endingDate = ParserUtil.parseDateCalendar( argMultiMap.getValue(PREFIX_ENDING_DATE).get()); if (startingDate.compareTo(endingDate) > 0) { throw new ParseException(String.format(MESSAGE_INVALID_DATE_INPUT_FORMAT, StatsCommand.MESSAGE_USAGE)); } switch (type) { case COST: return new StatsCommand(startingDate, endingDate, StatisticType.COST); case PROFIT: return new StatsCommand(startingDate, endingDate, StatisticType.PROFIT); case REVENUE: return new StatsCommand(startingDate, endingDate, StatisticType.REVENUE); default: throw new ParseException("Wrong Statistic type for normal calculation mode, " + "types here only include:\n" + "profit, cost, revenue"); } } else { switch (type) { case COST: return new StatsCommand(StatsParseUtil.MIN_DATE, StatsParseUtil.MAX_DATE, StatisticType.COST); case PROFIT: return new StatsCommand(StatsParseUtil.MIN_DATE, StatsParseUtil.MAX_DATE, StatisticType.PROFIT); case REVENUE: return new StatsCommand(StatsParseUtil.MIN_DATE, StatsParseUtil.MAX_DATE, StatisticType.REVENUE); default: throw new ParseException("Wrong Statistic type for no date calculation mode, " + "default types here only include:\n" + "profit, cost, revenue"); } } } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
92305abc1df528f19599e9b31bd896e8c9ca4f5c
5,481
java
Java
core/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java
diendt/elasticsearch
60465d5e04b9722064aff63a3ceba177ceaefdae
[ "Apache-2.0" ]
4
2015-05-15T20:08:35.000Z
2021-04-02T02:19:07.000Z
core/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java
diendt/elasticsearch
60465d5e04b9722064aff63a3ceba177ceaefdae
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/elasticsearch/index/query/RegexpQueryParser.java
diendt/elasticsearch
60465d5e04b9722064aff63a3ceba177ceaefdae
[ "Apache-2.0" ]
15
2017-01-12T10:16:22.000Z
2019-04-18T21:18:41.000Z
47.25
154
0.631819
995,450
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.index.query; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; /** * Parser for regexp query */ public class RegexpQueryParser implements QueryParser<RegexpQueryBuilder> { public static final ParseField NAME_FIELD = new ParseField("_name").withAllDeprecated("query name is not supported in short version of regexp query"); public static final ParseField FLAGS_VALUE_FIELD = new ParseField("flags_value"); public static final ParseField MAX_DETERMINIZED_STATES_FIELD = new ParseField("max_determinized_states"); public static final ParseField FLAGS_FIELD = new ParseField("flags"); public static final ParseField REWRITE_FIELD = new ParseField("rewrite"); public static final ParseField VALUE_FIELD = new ParseField("value"); @Override public String[] names() { return new String[]{RegexpQueryBuilder.NAME}; } @Override public RegexpQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException { XContentParser parser = parseContext.parser(); String fieldName = parser.currentName(); String rewrite = null; String value = null; float boost = AbstractQueryBuilder.DEFAULT_BOOST; int flagsValue = RegexpQueryBuilder.DEFAULT_FLAGS_VALUE; int maxDeterminizedStates = RegexpQueryBuilder.DEFAULT_MAX_DETERMINIZED_STATES; String queryName = null; String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (parseContext.isDeprecatedSetting(currentFieldName)) { // skip } else if (token == XContentParser.Token.START_OBJECT) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if (parseContext.parseFieldMatcher().match(currentFieldName, VALUE_FIELD)) { value = parser.textOrNull(); } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) { boost = parser.floatValue(); } else if (parseContext.parseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) { rewrite = parser.textOrNull(); } else if (parseContext.parseFieldMatcher().match(currentFieldName, FLAGS_FIELD)) { String flags = parser.textOrNull(); flagsValue = RegexpFlag.resolveValue(flags); } else if (parseContext.parseFieldMatcher().match(currentFieldName, MAX_DETERMINIZED_STATES_FIELD)) { maxDeterminizedStates = parser.intValue(); } else if (parseContext.parseFieldMatcher().match(currentFieldName, FLAGS_VALUE_FIELD)) { flagsValue = parser.intValue(); } else if (parseContext.parseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) { queryName = parser.text(); } else { throw new ParsingException(parser.getTokenLocation(), "[regexp] query does not support [" + currentFieldName + "]"); } } } } else { if (parseContext.parseFieldMatcher().match(currentFieldName, NAME_FIELD)) { queryName = parser.text(); } else { fieldName = currentFieldName; value = parser.textOrNull(); } } } if (value == null) { throw new ParsingException(parser.getTokenLocation(), "No value specified for regexp query"); } return new RegexpQueryBuilder(fieldName, value) .flags(flagsValue) .maxDeterminizedStates(maxDeterminizedStates) .rewrite(rewrite) .boost(boost) .queryName(queryName); } @Override public RegexpQueryBuilder getBuilderPrototype() { return RegexpQueryBuilder.PROTOTYPE; } }
92305fbbd245a0b9e7f0fc21a8b0407f2985d6c7
1,581
java
Java
src/main/java/graphql/execution/nextgen/result/ExecutionResultNode.java
salewski/graphql-java
41d67d715947e3c33dcd355a980de8a53c9f5645
[ "MIT" ]
null
null
null
src/main/java/graphql/execution/nextgen/result/ExecutionResultNode.java
salewski/graphql-java
41d67d715947e3c33dcd355a980de8a53c9f5645
[ "MIT" ]
null
null
null
src/main/java/graphql/execution/nextgen/result/ExecutionResultNode.java
salewski/graphql-java
41d67d715947e3c33dcd355a980de8a53c9f5645
[ "MIT" ]
1
2020-09-03T20:18:21.000Z
2020-09-03T20:18:21.000Z
32.265306
145
0.803289
995,451
package graphql.execution.nextgen.result; import graphql.Internal; import graphql.execution.MergedField; import graphql.execution.NonNullableFieldWasNullException; import graphql.execution.nextgen.FetchedValueAnalysis; import graphql.util.NodeLocation; import java.util.List; import java.util.Map; @Internal public abstract class ExecutionResultNode { private final FetchedValueAnalysis fetchedValueAnalysis; private final NonNullableFieldWasNullException nonNullableFieldWasNullException; protected ExecutionResultNode(FetchedValueAnalysis fetchedValueAnalysis, NonNullableFieldWasNullException nonNullableFieldWasNullException) { this.fetchedValueAnalysis = fetchedValueAnalysis; this.nonNullableFieldWasNullException = nonNullableFieldWasNullException; } /* * can be null for the RootExecutionResultNode */ public FetchedValueAnalysis getFetchedValueAnalysis() { return fetchedValueAnalysis; } public MergedField getMergedField() { return fetchedValueAnalysis.getExecutionStepInfo().getField(); } public NonNullableFieldWasNullException getNonNullableFieldWasNullException() { return nonNullableFieldWasNullException; } public abstract List<ExecutionResultNode> getChildren(); public abstract Map<String, List<ExecutionResultNode>> getNamedChildren(); public abstract ExecutionResultNode withChild(ExecutionResultNode child, NodeLocation position); public abstract ExecutionResultNode withNewChildren(Map<NodeLocation, ExecutionResultNode> children); }
92305fea44a9fc0b221eced9145cccfdf94dfe82
1,341
java
Java
JavaFiles/JDBC_Console/src/JDBC3.java
hlimbo/Project1
aa1e414e6981ec6f297a86387686399fe9f8b490
[ "MIT" ]
null
null
null
JavaFiles/JDBC_Console/src/JDBC3.java
hlimbo/Project1
aa1e414e6981ec6f297a86387686399fe9f8b490
[ "MIT" ]
null
null
null
JavaFiles/JDBC_Console/src/JDBC3.java
hlimbo/Project1
aa1e414e6981ec6f297a86387686399fe9f8b490
[ "MIT" ]
null
null
null
39.441176
117
0.620433
995,452
//// JDBC Example - updating a DB via SQL template and value groups //// Coded by Chen Li/Kirill Petrov Winter, 2005 //// Slightly revised for ICS185 Spring 2005, by Norman Jacobson // //import java.sql.*; // Enable SQL processing // // public class JDBC3 //{ // public static void main(String[] arg) throws Exception // { // // Incorporate MySQL driver // Class.forName("com.mysql.jdbc.Driver").newInstance(); // // // Connect to the test database // Connection connection = // DriverManager.getConnection("jdbc:mysql:///moviedb?autoReconnect=true&useSSL=false", "mytestuser", "mypassword"); // // // prepare SQL statement template that's to be repeatedly excuted // String updateString = "update stars set first_name = ? where id = ?"; // PreparedStatement updateStars = connection.prepareStatement(updateString); // // // values for first and second "?" wildcard in statement template // int [] ids = {755011, 755017}; // String [] firstNames = {"New Arnold", "New Eddie"}; // // // for each record in table, update to new values given // for(int i = 0; i < ids.length; i++) // { // updateStars.setString(1, firstNames[i]); // updateStars.setInt(2, ids[i]); // updateStars.executeUpdate(); // } // } //}
9230606625f7cb8f4e3f05ae7f7c3fd93840b5f4
6,781
java
Java
src/main/java/com/umka/umka/fragments/profile/EditProfileFragment.java
UMKAman/UMKA-Android-demo
efe25dda846caa06da02fd98b28b9955a47f6d8e
[ "MIT" ]
null
null
null
src/main/java/com/umka/umka/fragments/profile/EditProfileFragment.java
UMKAman/UMKA-Android-demo
efe25dda846caa06da02fd98b28b9955a47f6d8e
[ "MIT" ]
null
null
null
src/main/java/com/umka/umka/fragments/profile/EditProfileFragment.java
UMKAman/UMKA-Android-demo
efe25dda846caa06da02fd98b28b9955a47f6d8e
[ "MIT" ]
null
null
null
35.502618
165
0.641351
995,453
package com.umka.umka.fragments.profile; import android.app.DialogFragment; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.umka.umka.MainActivity; import com.umka.umka.classes.BaseJsonHandler; import com.umka.umka.classes.HttpClient; import com.umka.umka.classes.InetCheackConection; import com.umka.umka.classes.UpdateProfileListener; import com.umka.umka.classes.Utils; import com.umka.umka.fragments.BaseFragment; import com.umka.umka.holders.EditProfileHolder; import com.umka.umka.model.Profile; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONException; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.entity.StringEntity; /** * Created by trablone on 12/11/16. */ public class EditProfileFragment extends BaseFragment { private EditProfileHolder holder; private Profile item; private FragmentAvatar fragmentAvatar; private boolean menu; private ProgressDialog progressDialog; private InetCheackConection inetCheack; public static EditProfileFragment getInstance(boolean menu){ EditProfileFragment fragment = new EditProfileFragment(); Bundle params = new Bundle(); params.putBoolean("menu", menu); fragment.setArguments(params); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(com.umka.umka.R.layout.fragment_edit_profile, container, false); holder = new EditProfileHolder(view); progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("Please wait..."); inetCheack = new InetCheackConection(getActivity()); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); menu = getArguments().getBoolean("menu"); setHasOptionsMenu(menu); fragmentAvatar = (FragmentAvatar)getChildFragmentManager().findFragmentById(com.umka.umka.R.id.fragment_avatar_edit); item = getBaseActivity().getUser(); fragmentAvatar.setImageUrl(item.avatar); holder.itemFirstName.setText(item.getName()); //holder.itemLastName.setText(item.lastname); holder.radioGroup.check(item.getGenderId()); holder.itemAbout.setText(item.getAbout()); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); fragmentAvatar.onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); fragmentAvatar.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.add(0, 1, 0, com.umka.umka.R.string.menu_save).setIcon(com.umka.umka.R.drawable.ic_toolbar_done).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case 1: if(inetCheack.isConnect()) updateProfile(null); return true; } return super.onOptionsItemSelected(item); } public boolean setProfile(){ String name = holder.itemFirstName.getText().toString(); String about = holder.itemAbout.getText().toString(); if (TextUtils.isEmpty(name)){ holder.itemFirstName.setError("Напишите имя"); return false; } if (TextUtils.isEmpty(about)){ holder.itemAbout.setError("Напишите несколько слов о себе"); return false; } item.name = name; item.setGender(holder.getGender()); item.about = about; return true; } public void updateProfile(final UpdateProfileListener listener){ if (setProfile()){ progressDialog.show(); JSONObject object = new JSONObject(); try { //object.put("firstname", item.firstname); object.put("name", item.name); object.put("gender", item.gender); object.put("about", item.about); String city = item.city; if (city != null){ if (!city.contains("неопределено")) object.put("city", item.city); } //object.put("phone", item.phone); } catch (JSONException e) { Log.e("tr", "e: " + e.getMessage()); } HttpClient.put(getBaseActivity(), "/user/" + item.id , new StringEntity(object.toString(), "UTF-8"), new BaseJsonHandler(getBaseActivity()){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); progressDialog.dismiss(); if (listener == null ) { startActivity((new Intent(getActivity(), MainActivity.class)).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); }else { listener.onSuccess(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); progressDialog.dismiss(); if (listener != null){ listener.onFailure(); } } }); }else { if (listener != null){ listener.onFailure(); } } } @Override public void onDestroy() { Utils.hideKeyboard(getBaseActivity()); super.onDestroy(); } }
923060f94ae970ff5cd0f638a100e8743c7c776b
601
java
Java
AP Computer Science/Labs/Unit 08/Triangle One/TriangleOne.java
mikozera/Computer-Science
52d2a317d95e2df2a82f54e837e43b6e6873a400
[ "MIT" ]
null
null
null
AP Computer Science/Labs/Unit 08/Triangle One/TriangleOne.java
mikozera/Computer-Science
52d2a317d95e2df2a82f54e837e43b6e6873a400
[ "MIT" ]
3
2020-05-01T01:36:59.000Z
2020-05-05T05:38:33.000Z
AP Computer Science/Labs/Unit 08/Triangle One/TriangleOne.java
mikozera/Computer-Science
52d2a317d95e2df2a82f54e837e43b6e6873a400
[ "MIT" ]
1
2019-11-26T09:02:51.000Z
2019-11-26T09:02:51.000Z
24.04
74
0.559068
995,454
// � A+ Computer Science - www.apluscompsci.com // Name - Sebastian Nunez // Date - 12/07/18 // Class - 10th // Lab - Triangle One public class TriangleOne { //this lab is setup with a single static method //there are no instance variables or additional methods / constructors public static String createTriangle(String let, int size) { String output = ""; for (int rows = 1; rows <= size; rows++) { for (int cols = 1; cols <= rows; cols++) { output += let; } output += "\n"; } return output; } }
9230614899f32f80517e39bb89cef347b511808f
370
java
Java
ufs-oss/ufs-oss-huawei/src/main/java/cc/ccoder/ufs/oss/huawei/factory/HuaweiObsClientFactory.java
ccoderJava/ccoder-ufs
6f5cba8a80c8c04198357a879d16f51c80fe4335
[ "Apache-2.0" ]
null
null
null
ufs-oss/ufs-oss-huawei/src/main/java/cc/ccoder/ufs/oss/huawei/factory/HuaweiObsClientFactory.java
ccoderJava/ccoder-ufs
6f5cba8a80c8c04198357a879d16f51c80fe4335
[ "Apache-2.0" ]
4
2021-11-02T06:56:49.000Z
2021-11-04T13:37:35.000Z
ufs-oss/ufs-oss-huawei/src/main/java/cc/ccoder/ufs/oss/huawei/factory/HuaweiObsClientFactory.java
ccoderJava/ccoder-ufs
6f5cba8a80c8c04198357a879d16f51c80fe4335
[ "Apache-2.0" ]
1
2022-01-21T10:17:26.000Z
2022-01-21T10:17:26.000Z
17
57
0.644385
995,455
package cc.ccoder.ufs.oss.huawei.factory; import com.obs.services.ObsClient; /** * <p> * </p> * * @author congcong * @email ychag@example.com * @date HuaweiObsClientFactory.java v1.0 2021/11/4 11:15 */ public interface HuaweiObsClientFactory { /** * create huawei obs service client * * @return obs client */ ObsClient create(); }
9230616e37135a3b5621e3cc0ebd4fdc711fc76d
849
java
Java
app/src/main/java/com/qq/googleplay/ui/adapter/recyclerview/OnItemClickListener.java
JackChen1999/GooglePlay
f050f5442e338278ed57bc380363820d2ef6b1fc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/qq/googleplay/ui/adapter/recyclerview/OnItemClickListener.java
JackChen1999/GooglePlay
f050f5442e338278ed57bc380363820d2ef6b1fc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/qq/googleplay/ui/adapter/recyclerview/OnItemClickListener.java
JackChen1999/GooglePlay
f050f5442e338278ed57bc380363820d2ef6b1fc
[ "Apache-2.0" ]
null
null
null
29.241379
76
0.599057
995,456
package com.qq.googleplay.ui.adapter.recyclerview; import android.view.View; import android.view.ViewGroup; /** * ============================================================ * Copyright:Google有限公司版权所有 (c) 2017 * Author: 陈冠杰 * Email: lyhxr@example.com * GitHub: https://github.com/JackChen1999 * 博客: http://blog.csdn.net/axi295309066 * 微博: AndroidDeveloper * <p> * Project_Name:GooglePlay * Package_Name:com.qq.googleplay * Version:1.0 * time:2016/2/16 13:33 * des :${TODO} * gitVersion:$Rev$ * updateAuthor:$Author$ * updateDate:$Date$ * updateDes:${TODO} * ============================================================ **/ public interface OnItemClickListener<T> { void onItemClick(ViewGroup parent, View view, T t, int position); boolean onItemLongClick(ViewGroup parent, View view, T t, int position); }
923062bf2469cfcebf2a18e69f4c5c92cb8e84b5
2,049
java
Java
src/main/java/com/popupmc/aprilfoolsday/packets/CorruptPositionAndRotation.java
alfonsoLeandro/AprilFoolsDay
80f963e7d038d52e970759b112aeb7e55997f2d1
[ "Apache-2.0" ]
2
2021-02-21T18:28:05.000Z
2021-03-23T00:17:20.000Z
src/main/java/com/popupmc/aprilfoolsday/packets/CorruptPositionAndRotation.java
alfonsoLeandro/AprilFoolsDay
80f963e7d038d52e970759b112aeb7e55997f2d1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/popupmc/aprilfoolsday/packets/CorruptPositionAndRotation.java
alfonsoLeandro/AprilFoolsDay
80f963e7d038d52e970759b112aeb7e55997f2d1
[ "Apache-2.0" ]
1
2021-02-14T00:34:25.000Z
2021-02-14T00:34:25.000Z
34.728814
101
0.638848
995,457
package com.popupmc.aprilfoolsday.packets; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.events.PacketEvent; import com.popupmc.aprilfoolsday.AprilFoolsDay; import com.popupmc.aprilfoolsday.commands.OnToggleJokeCommand; import org.bukkit.entity.Player; import java.util.Random; public class CorruptPositionAndRotation extends PacketAdapter { public CorruptPositionAndRotation(AprilFoolsDay plugin) { super(plugin, PacketType.Play.Server.REL_ENTITY_MOVE_LOOK); } @Override public void onPacketSending(PacketEvent event) { PacketContainer packet = event.getPacket(); Player player = event.getPlayer(); // If disabled for this player do nothing, stop here if(!OnToggleJokeCommand.getStatus(player)) return; // Exclude the player by comparing entity ids if(packet.getIntegers().read(0) == player.getEntityId()) return; // 10% chance of slightly corrupting y if(random.nextInt(100) <= CorruptPosition.yChance) { // Get Current Y Delta short curY = packet.getShorts().read(1); // Add or subtract noise if(random.nextBoolean()) packet.getShorts().write(1, (short) (curY + CorruptPosition.yNoise)); else packet.getShorts().write(1, (short) (curY - CorruptPosition.yNoise)); } // Generate Random Yaw & Pitch // Yaw is between -90 & 90 byte yaw = (byte)(random.nextInt(90 * 2) - 90); // I dont understand pitch, suppose to be -360 - 360 but is a byte which only goes up to 127 // I'm just doing a generic signed byte byte pitch = (byte)(random.nextInt(127 * 2) - 127); packet.getBytes().write(0, yaw); packet.getBytes().write(1, pitch); } Random random = new Random(); }
923062c886be07118b9bc972feaee38bc3b0c35f
1,794
java
Java
back/src/main/java/by/bestwork/domain/User.java
adultyoung/bestwork
6421ec1456dbc1f2639a661d3c18aaa85a75376c
[ "MIT" ]
null
null
null
back/src/main/java/by/bestwork/domain/User.java
adultyoung/bestwork
6421ec1456dbc1f2639a661d3c18aaa85a75376c
[ "MIT" ]
null
null
null
back/src/main/java/by/bestwork/domain/User.java
adultyoung/bestwork
6421ec1456dbc1f2639a661d3c18aaa85a75376c
[ "MIT" ]
null
null
null
22.425
86
0.692865
995,458
package by.bestwork.domain; import by.bestwork.dto.Role; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.Collection; import java.util.Set; @Entity @Data @NoArgsConstructor @Table(name = "usr") @EqualsAndHashCode(of = {"email"}) @ToString(of = {"email"}) public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String tel; private String email; private String lastName; private String firstName; private String otchestvo; private String referal; private String password; private String oplata; private double dolg; private double dolgPredPeriod; @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER) @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id")) @Enumerated(EnumType.STRING) @Column(columnDefinition = "varchar(255) default 'USER'") private Set<Role> roles; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return getRoles(); } @Override public String getPassword() { return password; } @Override public String getUsername() { return email; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
9230643ce888bad7729ff86bac165f8afd7d3a7f
10,703
java
Java
invoice/src/main/java/org/killbill/billing/invoice/model/DefaultInvoice.java
yutui1281461/killbill
7fd4145fcff4e2752f36058676bef9595fc60102
[ "Apache-2.0" ]
1
2018-08-06T10:45:05.000Z
2018-08-06T10:45:05.000Z
invoice/src/main/java/org/killbill/billing/invoice/model/DefaultInvoice.java
yutui1281461/killbill
7fd4145fcff4e2752f36058676bef9595fc60102
[ "Apache-2.0" ]
null
null
null
invoice/src/main/java/org/killbill/billing/invoice/model/DefaultInvoice.java
yutui1281461/killbill
7fd4145fcff4e2752f36058676bef9595fc60102
[ "Apache-2.0" ]
4
2019-01-03T09:48:55.000Z
2022-01-04T05:26:51.000Z
37.423077
288
0.699243
995,459
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.killbill.billing.invoice.model; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import javax.annotation.Nullable; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.entity.EntityBase; import org.killbill.billing.invoice.api.Invoice; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.api.InvoicePayment; import org.killbill.billing.invoice.api.InvoiceStatus; import org.killbill.billing.invoice.calculator.InvoiceCalculatorUtils; import org.killbill.billing.invoice.dao.InvoiceItemModelDao; import org.killbill.billing.invoice.dao.InvoiceModelDao; import org.killbill.billing.invoice.dao.InvoicePaymentModelDao; import org.killbill.billing.util.UUIDs; import com.google.common.base.Function; import com.google.common.collect.Collections2; public class DefaultInvoice extends EntityBase implements Invoice, Cloneable { private final List<InvoiceItem> invoiceItems; private final List<InvoicePayment> payments; private final UUID accountId; private final Integer invoiceNumber; private final LocalDate invoiceDate; private final LocalDate targetDate; private final Currency currency; private final boolean migrationInvoice; private final boolean isWrittenOff; private final Currency processedCurrency; private final InvoiceStatus status; private final boolean isParentInvoice; private final Invoice parentInvoice; // Used to create a new invoice public DefaultInvoice(final UUID accountId, final LocalDate invoiceDate, final LocalDate targetDate, final Currency currency) { this(UUIDs.randomUUID(), accountId, null, invoiceDate, targetDate, currency, false, InvoiceStatus.COMMITTED); } public DefaultInvoice(final UUID accountId, final LocalDate invoiceDate, final LocalDate targetDate, final Currency currency, final InvoiceStatus status) { this(UUIDs.randomUUID(), accountId, null, invoiceDate, targetDate, currency, false, status); } public DefaultInvoice(final UUID invoiceId, final UUID accountId, @Nullable final Integer invoiceNumber, final LocalDate invoiceDate, final LocalDate targetDate, final Currency currency, final boolean isMigrationInvoice, final InvoiceStatus status) { this(invoiceId, null, accountId, invoiceNumber, invoiceDate, targetDate, currency, currency, isMigrationInvoice, false, status, false, null); } // This CTOR is used to return an existing invoice and must include everything (items, payments, tags,..) public DefaultInvoice(final InvoiceModelDao invoiceModelDao) { this(invoiceModelDao.getId(), invoiceModelDao.getCreatedDate(), invoiceModelDao.getAccountId(), invoiceModelDao.getInvoiceNumber(), invoiceModelDao.getInvoiceDate(), invoiceModelDao.getTargetDate(), invoiceModelDao.getCurrency(), invoiceModelDao.getProcessedCurrency(), invoiceModelDao.isMigrated(), invoiceModelDao.isWrittenOff(), invoiceModelDao.getStatus(), invoiceModelDao.isParentInvoice(), invoiceModelDao.getParentInvoice()); addInvoiceItems(Collections2.transform(invoiceModelDao.getInvoiceItems(), new Function<InvoiceItemModelDao, InvoiceItem>() { @Override public InvoiceItem apply(final InvoiceItemModelDao input) { return InvoiceItemFactory.fromModelDao(input); } })); addPayments(Collections2.transform(invoiceModelDao.getInvoicePayments(), new Function<InvoicePaymentModelDao, InvoicePayment>() { @Override public InvoicePayment apply(final InvoicePaymentModelDao input) { return new DefaultInvoicePayment(input); } })); } public DefaultInvoice(final UUID accountId, final LocalDate invoiceDate, final Currency currency) { this(UUID.randomUUID(), null, accountId, null, invoiceDate, null, currency, currency, false, false, InvoiceStatus.DRAFT, true, null); } private DefaultInvoice(final UUID invoiceId, @Nullable final DateTime createdDate, final UUID accountId, @Nullable final Integer invoiceNumber, final LocalDate invoiceDate, @Nullable final LocalDate targetDate, final Currency currency, final Currency processedCurrency, final boolean isMigrationInvoice, final boolean isWrittenOff, final InvoiceStatus status, final boolean isParentInvoice, final InvoiceModelDao parentInvoice) { super(invoiceId, createdDate, createdDate); this.accountId = accountId; this.invoiceNumber = invoiceNumber; this.invoiceDate = invoiceDate; this.targetDate = targetDate; this.currency = currency; this.processedCurrency = processedCurrency; this.migrationInvoice = isMigrationInvoice; this.isWrittenOff = isWrittenOff; this.invoiceItems = new ArrayList<InvoiceItem>(); this.payments = new ArrayList<InvoicePayment>(); this.status = status; this.isParentInvoice = isParentInvoice; this.parentInvoice = (parentInvoice != null) ? new DefaultInvoice(parentInvoice) : null; } // Semi deep copy where we copy the lists but not the elements in the lists since they are immutables. @Override public Object clone() { InvoiceModelDao parentInvoiceModelDao = (parentInvoice != null) ? new InvoiceModelDao(parentInvoice) : null; final Invoice clonedInvoice = new DefaultInvoice(getId(), getCreatedDate(), getAccountId(), getInvoiceNumber(), getInvoiceDate(), getTargetDate(), getCurrency(), getProcessedCurrency(), isMigrationInvoice(), isWrittenOff(), getStatus(), isParentInvoice(), parentInvoiceModelDao); clonedInvoice.getInvoiceItems().addAll(getInvoiceItems()); clonedInvoice.getPayments().addAll(getPayments()); return clonedInvoice; } @Override public boolean addInvoiceItem(final InvoiceItem item) { return invoiceItems.add(item); } @Override public boolean addInvoiceItems(final Collection<InvoiceItem> items) { return this.invoiceItems.addAll(items); } @Override public List<InvoiceItem> getInvoiceItems() { return invoiceItems; } @Override public <T extends InvoiceItem> List<InvoiceItem> getInvoiceItems(final Class<T> clazz) { final List<InvoiceItem> results = new ArrayList<InvoiceItem>(); for (final InvoiceItem item : invoiceItems) { if (clazz.isInstance(item)) { results.add(item); } } return results; } @Override public int getNumberOfItems() { return invoiceItems.size(); } @Override public boolean addPayment(final InvoicePayment payment) { return payments.add(payment); } @Override public boolean addPayments(final Collection<InvoicePayment> payments) { return this.payments.addAll(payments); } @Override public List<InvoicePayment> getPayments() { return payments; } @Override public int getNumberOfPayments() { return payments.size(); } @Override public UUID getAccountId() { return accountId; } /** * null until retrieved from the database * * @return the invoice number */ @Override public Integer getInvoiceNumber() { return invoiceNumber; } @Override public LocalDate getInvoiceDate() { return invoiceDate; } @Override public LocalDate getTargetDate() { return targetDate; } @Override public Currency getCurrency() { return currency; } public Currency getProcessedCurrency() { return processedCurrency; } @Override public boolean isMigrationInvoice() { return migrationInvoice; } @Override public BigDecimal getPaidAmount() { return InvoiceCalculatorUtils.computeInvoiceAmountPaid(currency, payments); } @Override public BigDecimal getOriginalChargedAmount() { return InvoiceCalculatorUtils.computeInvoiceOriginalAmountCharged(createdDate, currency, invoiceItems); } @Override public BigDecimal getChargedAmount() { return InvoiceCalculatorUtils.computeInvoiceAmountCharged(currency, invoiceItems); } @Override public BigDecimal getCreditedAmount() { return InvoiceCalculatorUtils.computeInvoiceAmountCredited(currency, invoiceItems); } @Override public BigDecimal getRefundedAmount() { return InvoiceCalculatorUtils.computeInvoiceAmountRefunded(currency, payments); } @Override public BigDecimal getBalance() { if (isWrittenOff() || isMigrationInvoice() || getStatus() == InvoiceStatus.DRAFT || hasZeroParentBalance()) { return BigDecimal.ZERO; } else { return InvoiceCalculatorUtils.computeRawInvoiceBalance(currency, invoiceItems, payments); } } public boolean hasZeroParentBalance() { return (parentInvoice != null) && (parentInvoice.getBalance().compareTo(BigDecimal.ZERO) == 0); } public boolean isWrittenOff() { return isWrittenOff; } @Override public InvoiceStatus getStatus() { return status; } @Override public boolean isParentInvoice() { return isParentInvoice; } @Override public String toString() { return "DefaultInvoice [items=" + invoiceItems + ", payments=" + payments + ", id=" + id + ", accountId=" + accountId + ", invoiceDate=" + invoiceDate + ", targetDate=" + targetDate + ", currency=" + currency + ", amountPaid=" + getPaidAmount() + ", status=" + status + ", isParentInvoice=" + isParentInvoice + "]"; } }
92306487a669fdca3e5eeeb66031f0a6f58f33d3
571
java
Java
back-end/hospital-api/src/main/java/net/pladema/clinichistory/hospitalization/controller/generalstate/dto/SnomedResponseDto.java
eamanu/HistorialClinica-LaRioja
988cd5fae4b9b9bd3a17518b7e55585df5ef7218
[ "Apache-2.0" ]
null
null
null
back-end/hospital-api/src/main/java/net/pladema/clinichistory/hospitalization/controller/generalstate/dto/SnomedResponseDto.java
eamanu/HistorialClinica-LaRioja
988cd5fae4b9b9bd3a17518b7e55585df5ef7218
[ "Apache-2.0" ]
null
null
null
back-end/hospital-api/src/main/java/net/pladema/clinichistory/hospitalization/controller/generalstate/dto/SnomedResponseDto.java
eamanu/HistorialClinica-LaRioja
988cd5fae4b9b9bd3a17518b7e55585df5ef7218
[ "Apache-2.0" ]
1
2021-12-31T09:59:53.000Z
2021-12-31T09:59:53.000Z
19.689655
78
0.802102
995,460
package net.pladema.clinichistory.hospitalization.controller.generalstate.dto; import java.io.Serializable; import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @NoArgsConstructor public class SnomedResponseDto implements Serializable { /** * */ private static final long serialVersionUID = 4433983845725789933L; private Integer total; private List<SnomedDto> items; }
9230658a4e17d716df510918aa7a82c53150c965
316
java
Java
myshop-web-admin/src/main/java/com/sucifitz/myshop/web/admin/service/impl/TbContentCategoryServiceImpl.java
SuciFitz/myshop-pom
bda5e4b0c20a5886b4d27917109ef839871dac44
[ "MIT" ]
null
null
null
myshop-web-admin/src/main/java/com/sucifitz/myshop/web/admin/service/impl/TbContentCategoryServiceImpl.java
SuciFitz/myshop-pom
bda5e4b0c20a5886b4d27917109ef839871dac44
[ "MIT" ]
null
null
null
myshop-web-admin/src/main/java/com/sucifitz/myshop/web/admin/service/impl/TbContentCategoryServiceImpl.java
SuciFitz/myshop-pom
bda5e4b0c20a5886b4d27917109ef839871dac44
[ "MIT" ]
null
null
null
24.307692
79
0.806962
995,461
package com.sucifitz.myshop.web.admin.service.impl; import com.sucifitz.myshop.web.admin.service.TbContentCategoryService; import org.springframework.stereotype.Service; /** * @author Sucifitz * @date 2020/6/20 14:44 */ @Service public class TbContentCategoryServiceImpl implements TbContentCategoryService { }
92306634306e3993dc32b0f39f198e98a3b5597c
4,363
java
Java
control/src/main/java/org/syphr/mythtv/control/impl/Control0_25.java
syphr42/libmythtv-java
cc7a2012fbd4a4ba2562dda6b2614fb0548526ea
[ "Apache-2.0" ]
null
null
null
control/src/main/java/org/syphr/mythtv/control/impl/Control0_25.java
syphr42/libmythtv-java
cc7a2012fbd4a4ba2562dda6b2614fb0548526ea
[ "Apache-2.0" ]
null
null
null
control/src/main/java/org/syphr/mythtv/control/impl/Control0_25.java
syphr42/libmythtv-java
cc7a2012fbd4a4ba2562dda6b2614fb0548526ea
[ "Apache-2.0" ]
1
2018-10-04T06:40:21.000Z
2018-10-04T06:40:21.000Z
29.680272
110
0.699977
995,462
/* * Copyright 2011-2012 Gregory P. Moyer * * 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.syphr.mythtv.control.impl; import java.io.IOException; import java.net.URL; import java.util.Date; import java.util.List; import org.syphr.mythtv.commons.exception.CommandException; import org.syphr.mythtv.commons.translate.Translator; import org.syphr.mythtv.data.MusicInfo; import org.syphr.mythtv.data.Program; public class Control0_25 extends Control0_24 { @Override public List<Program> queryLiveTv() throws IOException { return new Command0_25QueryLiveTv(getTranslator()).send(getSocketManager()); } @Override public Program queryLiveTv(long channelId) throws IOException { return new Command0_25QueryLiveTvChannel(getTranslator(), channelId).send(getSocketManager()); } @Override public Program queryRecording(long channelId, Date recStartTs) throws IOException { return new Command0_25QueryRecording(getTranslator(), channelId, recStartTs).send(getSocketManager()); } @Override public List<Program> queryRecordings() throws IOException { return new Command0_25QueryRecordings(getTranslator()).send(getSocketManager()); } @Override public void playMusicPlay() throws IOException { new Command0_25PlayMusicPlay(getTranslator()).send(getSocketManager()); } @Override public void playMusicPause() throws IOException { new Command0_25PlayMusicPause(getTranslator()).send(getSocketManager()); } @Override public void playMusicStop() throws IOException { new Command0_25PlayMusicStop(getTranslator()).send(getSocketManager()); } @Override public void playMusicSetVolume(int percent) throws IOException { new Command0_25PlayMusicSetVolume(getTranslator(), percent).send(getSocketManager()); } @Override public int playMusicGetVolume() throws IOException { return new Command0_25PlayMusicGetVolume(getTranslator()).send(getSocketManager()); } @Override public MusicInfo playMusicGetMeta() throws IOException { return new Command0_25PlayMusicGetMeta(getTranslator()).send(getSocketManager()); } @Override public void playMusicFile(String filename) throws IOException { new Command0_25PlayMusicFile(getTranslator(), filename).send(getSocketManager()); } @Override public void playMusicTrack(int track) throws IOException { new Command0_25PlayMusicTrack(getTranslator(), track).send(getSocketManager()); } @Override public void playMusicUrl(URL url) throws IOException { new Command0_25PlayMusicUrl(getTranslator(), url).send(getSocketManager()); } @Override public void screenshot() throws IOException, CommandException { screenshot(0, 0); } @Override public void screenshot(int width, int height) throws IOException, CommandException { new Command0_25Screenshot(getTranslator(), width, height).send(getSocketManager()); } @Override public void screenshot(String filename) throws IOException, CommandException { handleUnsupported("screenshot with a filename"); screenshot(); } @Override public void screenshot(String filename, int width, int height) throws IOException, CommandException { handleUnsupported("screenshot with a filename"); screenshot(width, height); } @Override public void message(String text) throws IOException { new Command0_25Message(getTranslator(), text).send(getSocketManager()); } @Override protected Translator createTranslator() { return new Translator0_25(); } }
92306791d8729227b52babb7d2ce81bee2a90bd7
8,832
java
Java
my_test_apps/Rooommie777/app/src/main/java/com/example/yks93/rooommie777/test_searchroommate/SearchRoommateActivity.java
OptimistLabyrinth/Android
3539aa8f5804767c31081e8ef79a84e770dcdda6
[ "Apache-2.0" ]
null
null
null
my_test_apps/Rooommie777/app/src/main/java/com/example/yks93/rooommie777/test_searchroommate/SearchRoommateActivity.java
OptimistLabyrinth/Android
3539aa8f5804767c31081e8ef79a84e770dcdda6
[ "Apache-2.0" ]
null
null
null
my_test_apps/Rooommie777/app/src/main/java/com/example/yks93/rooommie777/test_searchroommate/SearchRoommateActivity.java
OptimistLabyrinth/Android
3539aa8f5804767c31081e8ef79a84e770dcdda6
[ "Apache-2.0" ]
null
null
null
30.350515
125
0.59375
995,463
package com.example.yks93.rooommie777.test_searchroommate; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.example.yks93.rooommie777.AfterTheFirstClickActivity; import com.example.yks93.rooommie777.using_mypage_menu.MyPageActivity; import com.example.yks93.rooommie777.R; import com.example.yks93.rooommie777.retrofit_package.RetrofitClientInstance; import com.example.yks93.rooommie777.signup_actions.SignupOneActivity; import com.example.yks93.rooommie777.static_storage.StaticVarMethods; import com.example.yks93.rooommie777.trylogin.LoginPageActivity; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /* * Depreciated */ //@Deprecated public class SearchRoommateActivity extends AppCompatActivity { @BindView(R.id.recyclerview_searchroommate) RecyclerView recyclerView; SearchRoommateAdapter adapter; RecyclerView.LayoutManager layoutManager; private List<RoommateItem> dataList = new ArrayList<>(); private List<RoommateData> dataFromServerList = new ArrayList<>(); // private int tryState = StaticVarMethods.TRY_ONCE_MORE; private final String TAG = "SearchRoommateActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { Log.d(TAG, "onCreate: "); super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_roommate); ButterKnife.bind(this); adapter = new SearchRoommateAdapter(dataList); Log.d(TAG, "onCreate: NEW Adapter"); layoutManager = new LinearLayoutManager(getApplicationContext()); Log.d(TAG, "onCreate: NEW LayoutManager"); recyclerView.setLayoutManager(layoutManager); Log.d(TAG, "onCreate: SET Layout Manager"); recyclerView.setAdapter(adapter); Log.d(TAG, "onCreate: SET Adapter"); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); Long tsLong = System.currentTimeMillis() / 1000; int tsNow = Integer.parseInt(tsLong.toString()); SharedPreferences sp = getSharedPreferences(StaticVarMethods.UserLoginPref, Context.MODE_PRIVATE); int tsSaved = Integer.parseInt(sp.getString(StaticVarMethods.LOGIN_TIME, "0")); if (sp.getString(StaticVarMethods.USER_ID, "--").equals("--") || tsNow - tsSaved > 27494400) { sp.edit().remove(StaticVarMethods.USER_ID) .remove(StaticVarMethods.USER_PWD) .remove(StaticVarMethods.LOGIN_TIME) .apply(); menuInflater.inflate(R.menu.menus_default, menu); } else { menuInflater.inflate(R.menu.menus_after_login, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.login_menu: onLoginMenuClicked(); break; case R.id.signup_menu: onSignupMenuClicked(); break; case R.id.menu_mypage: onMypageMenuClicked(); break; case R.id.menu_logout: onLogoutMenuClicked(); break; default: return super.onOptionsItemSelected(item); } return true; } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart: "); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume: "); prepareRoommateListPage(); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause: "); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop: "); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy: "); } private void prepareRoommateListPage() { Log.d(TAG, "prepareRoommateListPage: "); GetRoommateTableService service = RetrofitClientInstance.getRetrofitInstance().create(GetRoommateTableService.class); Call<List<RoommateData>> call = service.getMatchingData( "s", "i", "pwd", "n", "g", "phone", "", "m" ); Log.d(TAG, "prepareRoommateListPage: Call<T> initialization finished"); doBackgroundTask(call); } @NonNull private void doBackgroundTask(Call<List<RoommateData>> call) { Log.d(TAG, "doBackgroundTask: "); call.enqueue(new Callback<List<RoommateData>>() { @Override public void onResponse(Call<List<RoommateData>> call, Response<List<RoommateData>> response) { Log.d(TAG, "onResponse: "); int code = response.code(); Log.d(TAG, "onResponse: code = " + code); List<RoommateData> contents = response.body(); int i = 1; for (RoommateData rd : contents) { dataFromServerList.add(rd); Log.d(TAG, "onResponse: ADDED " + i + " rommmate data"); ++i; } passDataToSearchRoommateRecyclerAdapter(); adapter.notifyDataSetChanged(); call.cancel(); } @Override public void onFailure(Call<List<RoommateData>> call, Throwable t) { Log.d(TAG, "onFailure: "); } }); } private void passDataToSearchRoommateRecyclerAdapter() { Log.d(TAG, "passDataToSearchRoommateRecyclerAdapter: "); int i = 1; for (RoommateData rd : dataFromServerList) { Log.d(TAG, "passDataToSearchRoommateRecyclerAdapter: passing " + i); dataList.add( new RoommateItem( rd.getStud_id(), rd.getId(), rd.getPwd(), rd.getName(), rd.getGender(), rd.getPhone(), rd.getEmail(), rd.getMajor() ) ); ++i; } } void onLoginMenuClicked() { Intent intent = new Intent(this, LoginPageActivity.class); startActivity(intent); } void onSignupMenuClicked() { Intent intent = new Intent(this, SignupOneActivity.class); startActivity(intent); } void onMypageMenuClicked() { Intent intent = new Intent(this, MyPageActivity.class); startActivity(intent); } void onLogoutMenuClicked() { SharedPreferences.Editor editor = getSharedPreferences(StaticVarMethods.UserLoginPref, Context.MODE_PRIVATE).edit(); editor.remove(StaticVarMethods.USER_ID) .remove(StaticVarMethods.USER_PWD) .remove(StaticVarMethods.LOGIN_TIME) .apply(); Intent i = new Intent(this, AfterTheFirstClickActivity.class); startActivity(i); } } /* while (tryState != StaticVarMethods.FAILURE) { Call<List<RoommateData>> call2 = call.clone(); doBackgroundTask(call2); } switch (tryState) { case StaticVarMethods.FAILURE: Log.d(TAG, "prepareRoommateListPage: FAILURE"); break; case StaticVarMethods.SUCCESS: Log.d(TAG, "prepareRoommateListPage: SUCCESS"); passDataToSearchRoommateRecyclerAdapter(); break; } if (code != 200) { Log.d(TAG, "ERROR: Networking Task Failed"); if (StaticVarMethods.NETWORK_TASK_COUNT > 0) --StaticVarMethods.NETWORK_TASK_COUNT; } else { tryState = StaticVarMethods.SUCCESS; Log.d(TAG, "response size = " + response.body().size()); for (RoommateData rd : response.body()) { dataFromServerList.add(rd); } } */
9230682decc5891f3d3e8e0548a08b6fc73f5759
857
java
Java
app/src/main/java/com/sunnyweather/fsystem/activity/ui/notifications/ProjectListItemDecoration.java
feige011/StartApp
916fb8ec37c2c6418764c9b2b75a52319eae3819
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/sunnyweather/fsystem/activity/ui/notifications/ProjectListItemDecoration.java
feige011/StartApp
916fb8ec37c2c6418764c9b2b75a52319eae3819
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/sunnyweather/fsystem/activity/ui/notifications/ProjectListItemDecoration.java
feige011/StartApp
916fb8ec37c2c6418764c9b2b75a52319eae3819
[ "Apache-2.0" ]
null
null
null
26.78125
140
0.725788
995,464
package com.sunnyweather.fsystem.activity.ui.notifications; import android.content.res.Resources; import android.graphics.Rect; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class ProjectListItemDecoration extends RecyclerView.ItemDecoration { private int space; public ProjectListItemDecoration(int space){ this.space = space; } @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { outRect.bottom = space; if (parent.getChildLayoutPosition(view) == 0) outRect.top = space; } public static int px2dp(float dpValue) { return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density); } }
92306874afb6c2c7dde7f6513c39dcc4752a9f04
1,898
java
Java
core/src/main/java/org/solovyev/android/messenger/notifications/NotificationsViewBuilder.java
YunLemon/android-messengerpp
29a71dafe1d069fe3a9ab2d0c8a6ed26a3bc6d6c
[ "Apache-2.0" ]
54
2015-01-04T10:30:36.000Z
2022-03-05T10:31:24.000Z
core/src/main/java/org/solovyev/android/messenger/notifications/NotificationsViewBuilder.java
YunLemon/android-messengerpp
29a71dafe1d069fe3a9ab2d0c8a6ed26a3bc6d6c
[ "Apache-2.0" ]
7
2015-01-11T11:29:37.000Z
2020-10-31T00:11:22.000Z
core/src/main/java/org/solovyev/android/messenger/notifications/NotificationsViewBuilder.java
YunLemon/android-messengerpp
29a71dafe1d069fe3a9ab2d0c8a6ed26a3bc6d6c
[ "Apache-2.0" ]
21
2015-01-02T09:08:20.000Z
2022-03-19T00:47:06.000Z
31.633333
105
0.785564
995,465
/* * Copyright 2013 serso aka se.solovyev * * 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.solovyev.android.messenger.notifications; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import org.solovyev.android.list.ListItemAdapter; import org.solovyev.android.messenger.core.R; import org.solovyev.android.view.ViewBuilder; public final class NotificationsViewBuilder implements ViewBuilder<View> { @Nonnull private final List<Notification> notifications; public NotificationsViewBuilder(@Nonnull List<Notification> notifications) { this.notifications = notifications; } @Nonnull @Override public View build(@Nonnull Context context) { final LayoutInflater li = LayoutInflater.from(context); final View root = li.inflate(R.layout.mpp_popup_notifications, null); final ListView listView = (ListView) root.findViewById(android.R.id.list); final List<NotificationListItem> notificationListItems = new ArrayList<NotificationListItem>(); for (Notification notification : notifications) { notificationListItems.add(new NotificationListItem(notification)); } ListItemAdapter.attach(listView, ListItemAdapter.newInstance(context, notificationListItems), context); return root; } }
923068f99f0948b79d2ae530e0c6964f2da751cf
1,190
java
Java
niukit-ftpclient/src/main/java/com/woshidaniu/ftpclient/client/FTPPooledResourceClient.java
woshidaniu-com/niukit
b63ef035acc19f6868e2378a079b9c5c8d5bddc8
[ "Apache-2.0" ]
2
2020-10-16T01:08:36.000Z
2020-10-16T06:29:39.000Z
niukit-ftpclient/src/main/java/com/woshidaniu/ftpclient/client/FTPPooledResourceClient.java
woshidaniu-com/niukit
b63ef035acc19f6868e2378a079b9c5c8d5bddc8
[ "Apache-2.0" ]
4
2020-10-12T08:18:37.000Z
2020-10-12T08:18:37.000Z
niukit-ftpclient/src/main/java/com/woshidaniu/ftpclient/client/FTPPooledResourceClient.java
woshidaniu-com/niukit
b63ef035acc19f6868e2378a079b9c5c8d5bddc8
[ "Apache-2.0" ]
1
2022-02-10T03:07:03.000Z
2022-02-10T03:07:03.000Z
22.884615
65
0.773109
995,466
package com.woshidaniu.ftpclient.client; import com.woshidaniu.ftpclient.FTPClient; import com.woshidaniu.ftpclient.FTPClientConfig; import com.woshidaniu.ftpclient.pool.FTPClientManager; /** * * @className : FTPPooledResourceClient * @description : 基于 Apache Pool2的FTPClient资源服务客户端实现 * @author :kangzhidong * @date : Jan 12, 2016 9:07:53 AM */ public class FTPPooledResourceClient extends FTPResourceClient{ private FTPClientManager clientManager = null; public FTPPooledResourceClient(){ } public FTPPooledResourceClient(FTPClientManager clientManager){ this.clientManager = clientManager; } @Override public FTPClient getFTPClient() throws Exception { //从对象池获取FTPClient对象 return getClientManager().getClient(); } @Override public void releaseClient(FTPClient ftpClient) throws Exception{ //释放FTPClient到对象池 getClientManager().releaseClient(ftpClient); } public FTPClientConfig getClientConfig() { return getClientManager().getClientConfig(); } public FTPClientManager getClientManager() { return clientManager; } public void setClientManager(FTPClientManager clientManager) { this.clientManager = clientManager; } }
92306a6326fd08e0eb19fbf1f39f7951170d8222
3,117
java
Java
modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityManager.java
treelab/ignite
ec89c8586df89899ae56ebbc598639e0afea5901
[ "CC0-1.0" ]
4,339
2015-08-21T21:13:25.000Z
2022-03-30T09:56:44.000Z
modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityManager.java
treelab/ignite
ec89c8586df89899ae56ebbc598639e0afea5901
[ "CC0-1.0" ]
1,933
2015-08-24T11:37:40.000Z
2022-03-31T08:37:08.000Z
modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityManager.java
treelab/ignite
ec89c8586df89899ae56ebbc598639e0afea5901
[ "CC0-1.0" ]
2,140
2015-08-21T22:09:00.000Z
2022-03-25T07:57:34.000Z
39.455696
116
0.712865
995,467
/* * 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.ignite.internal.processors.platform.cache.affinity; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.binary.BinaryRawReaderEx; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.GridCacheAffinityManager; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.platform.PlatformAbstractTarget; import org.apache.ignite.internal.processors.platform.PlatformContext; /** * AffinityManager wrapper for platforms. */ public class PlatformAffinityManager extends PlatformAbstractTarget { /** */ public static final int OP_IS_ASSIGNMENT_VALID = 1; /** Affinity manager. */ private final GridCacheAffinityManager affMgr; /** * Constructor. * * @param platformCtx Context. */ public PlatformAffinityManager(PlatformContext platformCtx, int cacheId) { super(platformCtx); GridCacheContext<Object, Object> ctx = platformCtx.kernalContext().cache().context().cacheContext(cacheId); if (ctx == null) throw new IgniteException("Cache doesn't exist: " + cacheId); affMgr = ctx.affinity(); } /** {@inheritDoc} */ @Override public long processInStreamOutLong(int type, BinaryRawReaderEx reader) throws IgniteCheckedException { if (type == OP_IS_ASSIGNMENT_VALID) { AffinityTopologyVersion ver = new AffinityTopologyVersion(reader.readLong(), reader.readInt()); int part = reader.readInt(); AffinityTopologyVersion endVer = affMgr.affinityTopologyVersion(); if (!affMgr.primaryChanged(part, ver, endVer)) { return TRUE; } if (!affMgr.partitionLocalNode(part, endVer)) { return FALSE; } // Special case: late affinity assignment when primary changes to local node due to a node join. // Specified partition is local, and near cache entries are valid for primary keys. return ver.topologyVersion() == endVer.topologyVersion() ? TRUE : FALSE; } return super.processInStreamOutLong(type, reader); } }
92306a9f0850423f62bc35560819536b0f4ed615
480
java
Java
src/main/java/com/march/uikit/lifecycle/FragmentLifeCycle.java
Android-Modularity/uikit
94198455386f31b5150db961a16245ac9b2a2fc3
[ "MIT" ]
null
null
null
src/main/java/com/march/uikit/lifecycle/FragmentLifeCycle.java
Android-Modularity/uikit
94198455386f31b5150db961a16245ac9b2a2fc3
[ "MIT" ]
null
null
null
src/main/java/com/march/uikit/lifecycle/FragmentLifeCycle.java
Android-Modularity/uikit
94198455386f31b5150db961a16245ac9b2a2fc3
[ "MIT" ]
null
null
null
21.818182
95
0.772917
995,468
package com.march.uikit.lifecycle; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * CreateAt : 2017/12/20 * Describe : * * @author chendong */ public interface FragmentLifeCycle { void setUserVisibleHint(boolean isVisibleToUser); View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); void onViewCreated(View view, Bundle savedInstanceState); }
92306afaf219c1c941b10a660f2fd758c232e85b
1,013
java
Java
module-mall-pms/src/main/java/com/ruoyi/pms/domain/PmsAlbumPic.java
service-java/tpl-ruoyi-vue-20201217
44c6067d0249a315dc65e846ab6e5572477a93e7
[ "MIT" ]
5
2020-12-17T02:58:22.000Z
2022-02-17T01:21:38.000Z
module-mall-pms/src/main/java/com/ruoyi/pms/domain/PmsAlbumPic.java
service-java/tpl-ruoyi-vue-20201217
44c6067d0249a315dc65e846ab6e5572477a93e7
[ "MIT" ]
null
null
null
module-mall-pms/src/main/java/com/ruoyi/pms/domain/PmsAlbumPic.java
service-java/tpl-ruoyi-vue-20201217
44c6067d0249a315dc65e846ab6e5572477a93e7
[ "MIT" ]
2
2020-12-17T08:48:37.000Z
2021-06-02T11:49:33.000Z
24.707317
57
0.719645
995,469
package com.ruoyi.pms.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * Description: 模块功能描述 * * User: luo0412 * Date: 2020-12-22 16:32 */ /** * 画册图片表 */ @ApiModel(value="com-ruoyi-pms-domain-PmsAlbumPic") @Data @TableName(value = "pms_album_pic") public class PmsAlbumPic { @TableId(value = "id", type = IdType.AUTO) @ApiModelProperty(value="") private Long id; @TableField(value = "album_id") @ApiModelProperty(value="") private Long albumId; @TableField(value = "pic") @ApiModelProperty(value="") private String pic; public static final String COL_ID = "id"; public static final String COL_ALBUM_ID = "album_id"; public static final String COL_PIC = "pic"; }
92306b9d0efc6b04fb08b4871a189208daff277a
135
java
Java
api/src/main/java/io/tracee/spi/TraceeBackendProvider.java
SvenBunge/tracee
6a92c24c453f3b88ba7d2831e822c60902600bda
[ "BSD-3-Clause" ]
35
2015-01-27T08:08:42.000Z
2020-05-09T17:43:53.000Z
api/src/main/java/io/tracee/spi/TraceeBackendProvider.java
SvenBunge/tracee
6a92c24c453f3b88ba7d2831e822c60902600bda
[ "BSD-3-Clause" ]
89
2015-01-09T07:33:12.000Z
2018-01-26T16:02:41.000Z
api/src/main/java/io/tracee/spi/TraceeBackendProvider.java
SvenBunge/tracee
6a92c24c453f3b88ba7d2831e822c60902600bda
[ "BSD-3-Clause" ]
18
2015-01-03T14:41:19.000Z
2018-10-23T07:30:01.000Z
13.5
40
0.8
995,470
package io.tracee.spi; import io.tracee.TraceeBackend; public interface TraceeBackendProvider { TraceeBackend provideBackend(); }
92306b9fb848344fd6e1746cfc2a1f7399bfa927
4,494
java
Java
app/src/main/java/com/example/android/miwok/WordAdapter.java
atsang36/Miwok
b740fb82629dff61ac374ea9ffbeac570c49a499
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/WordAdapter.java
atsang36/Miwok
b740fb82629dff61ac374ea9ffbeac570c49a499
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/WordAdapter.java
atsang36/Miwok
b740fb82629dff61ac374ea9ffbeac570c49a499
[ "Apache-2.0" ]
1
2019-03-22T18:33:16.000Z
2019-03-22T18:33:16.000Z
42
101
0.684913
995,471
package com.example.android.miwok; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; /** * Created by AndyTsang on 2018-06-24. */ public class WordAdapter extends ArrayAdapter { private int background_color; /** * This is our own custom constructor (it doesn't mirror a superclass constructor). * The context is used to inflate the layout file, and the list is the data we want * to populate into the lists. * * @param context The current context. Used to inflate the layout file. * @param words A List of word objects to display in a list */ public WordAdapter(Activity context, ArrayList<Word> words, int colorId) { // Here, we initialize the ArrayAdapter's internal storage for the context and the list. // the second argument is used when the ArrayAdapter is populating a single TextView. // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not // going to use this second argument, so it can be any value. Here, we used 0. super(context, 0, words); background_color = colorId; } /** * Provides a view for an AdapterView (ListView, GridView, etc.) * * @param position The position in the list of data that should be displayed in the * list item view. * @param convertView The recycled view to populate. * @param parent The parent ViewGroup that is used for inflation. * @return The View for the position in the AdapterView. */ @Override public View getView(int position, View convertView, ViewGroup parent) { // Check if the existing view is being reused, otherwise inflate the view View listItemView = convertView; if(listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.list_item, parent, false); } // Get the {@link Word} object located at this position in the list Word word = (Word) getItem(position); // Find the TextView in the list_item.xml layout with the default translation TextView defaultTransTextView = (TextView) listItemView.findViewById(R.id.default_text_view); // Get the version name from the current Word object and // set this text on the name TextView defaultTransTextView.setText(word.getDefaultTranslation()); // Find the TextView in the list_item.xml layout with the ID version_number TextView miwokTransTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view); // Get the version number from the current Word object and // set this text on the number TextView miwokTransTextView.setText(word.getMiwokTranslation()); // Find the ImageView in the list_item.xml layout with the ID list_item_icon ImageView iconView = (ImageView) listItemView.findViewById(R.id.icon_view); //Check if image is present in Word instance if (word.hasImage()) { // Get the image resource ID from the current Word object and // set the image to iconView //make sure view is visible iconView.setImageResource(word.getmImageResourceId()); iconView.setVisibility(View.VISIBLE); //otherwise make view invisible }else{ iconView.setVisibility(View.GONE); } //Set the theme colour for the list item View textContainer = listItemView.findViewById(R.id.text_container); //find the colour that colorId maps to int color = ContextCompat.getColor(getContext(),background_color); //change the color of the background textContainer.setBackgroundColor(color); // Return the whole list item layout (containing 2 TextViews and an ImageView) // so that it can be shown in the ListView return listItemView; } // @Override // public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // return super.getView(position, convertView, parent); // } }
92306bfe6b9f62143195172e933a95ae7824ee29
5,689
java
Java
src/main/java/com/matt/forgehax/mods/ActiveModList.java
wwwg/ForgeHax
832bba75329bb8595ed3c4e682b2532d9c272f68
[ "MIT" ]
6
2020-01-12T16:39:17.000Z
2021-09-01T01:23:57.000Z
src/main/java/com/matt/forgehax/mods/ActiveModList.java
wwwg/ForgeHax
832bba75329bb8595ed3c4e682b2532d9c272f68
[ "MIT" ]
null
null
null
src/main/java/com/matt/forgehax/mods/ActiveModList.java
wwwg/ForgeHax
832bba75329bb8595ed3c4e682b2532d9c272f68
[ "MIT" ]
1
2020-03-07T00:16:57.000Z
2020-03-07T00:16:57.000Z
31.605556
101
0.621375
995,472
package com.matt.forgehax.mods; import static com.matt.forgehax.Helper.getModManager; import com.matt.forgehax.mods.services.TickRateService; import com.matt.forgehax.util.color.Colors; import com.matt.forgehax.util.command.Setting; import com.matt.forgehax.util.math.AlignHelper; import com.matt.forgehax.util.math.AlignHelper.Align; import com.matt.forgehax.util.draw.SurfaceHelper; import com.matt.forgehax.util.mod.BaseMod; import com.matt.forgehax.util.mod.Category; import com.matt.forgehax.util.mod.HudMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import net.minecraft.client.gui.GuiChat; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @RegisterMod public class ActiveModList extends HudMod { private final Setting<Boolean> tps_meter = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("tps-meter") .description("Shows the server tps") .defaultTo(true) .build(); private final Setting<Boolean> debug = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("debug") .description("Disables debug text on mods that have it") .defaultTo(false) .build(); private final Setting<Integer> factor = getCommandStub() .builders() .<Integer>newSettingBuilder() .name("factor") .description("Splitting up the tick rate data") .defaultTo(25) .min(1) .max(100) .build(); private final Setting<Boolean> showLag = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("showLag") .description("Shows lag time since last tick") .defaultTo(true) .build(); private final Setting<SortMode> sortMode = getCommandStub() .builders() .<SortMode>newSettingEnumBuilder() .name("sorting") .description("Sorting mode") .defaultTo(SortMode.ALPHABETICAL) .build(); @Override protected Align getDefaultAlignment() { return Align.TOPLEFT; } @Override protected int getDefaultOffsetX() { return 1; } @Override protected int getDefaultOffsetY() { return 1; } @Override protected double getDefaultScale() { return 1d; } public ActiveModList() { super(Category.RENDER, "ActiveMods", true, "Shows list of all active mods"); } @Override public boolean isHidden() { return true; } private String generateTickRateText() { StringBuilder builder = new StringBuilder("Tick-rate: "); TickRateService.TickRateData data = TickRateService.getTickData(); if (data.getSampleSize() <= 0) { builder.append("No tick data"); } else { int factor = this.factor.get(); int sections = data.getSampleSize() / factor; if ((sections * factor) < data.getSampleSize()) { TickRateService.TickRateData.CalculationData point = data.getPoint(); builder.append(String.format("%.2f", point.getAverage())); builder.append(" ("); builder.append(data.getSampleSize()); builder.append(")"); if (sections > 0) builder.append(", "); } if (sections > 0) { for (int i = sections; i > 0; i--) { int at = i * factor; TickRateService.TickRateData.CalculationData point = data.getPoint(at); builder.append(String.format("%.2f", point.getAverage())); builder.append(" ("); builder.append(at); builder.append(")"); if ((i - 1) != 0) builder.append(", "); } } } if (showLag.get()) { long lastTickMs = TickRateService.getInstance().getLastTimeDiff(); if (lastTickMs < 1000) { builder.append(", 0.0s"); } else { builder.append(String.format(", %01.1fs", ((float) (lastTickMs - 1000)) / 1000)); } } return builder.toString(); } @SubscribeEvent public void onRenderScreen(RenderGameOverlayEvent.Text event) { int align = alignment.get().ordinal(); List<String> text = new ArrayList<>(); if (tps_meter.get()) { text.add(generateTickRateText()); } if (MC.currentScreen instanceof GuiChat || MC.gameSettings.showDebugInfo) { long enabledMods = getModManager() .getMods() .stream() .filter(BaseMod::isEnabled) .filter(mod -> !mod.isHidden()) .count(); text.add(enabledMods + " mods enabled"); } else { getModManager() .getMods() .stream() .filter(BaseMod::isEnabled) .filter(mod -> !mod.isHidden()) .map(mod -> debug.get() ? mod.getDebugDisplayText() : mod.getDisplayText()) .sorted(sortMode.get().getComparator()) .forEach(name -> text.add(AlignHelper.getFlowDirX2(align) == 1 ? ">" + name : name + "<")); } SurfaceHelper.drawTextAlign(text, getPosX(0), getPosY(0), Colors.WHITE.toBuffer(), scale.get(), true, align); } private enum SortMode { ALPHABETICAL((o1, o2) -> 0), // mod list is already sorted alphabetically LENGTH(Comparator.<String>comparingInt(SurfaceHelper::getTextWidth).reversed()); private final Comparator<String> comparator; public Comparator<String> getComparator() { return this.comparator; } SortMode(Comparator<String> comparatorIn) { this.comparator = comparatorIn; } } }
92306d08f9de278c20162b3c7e050e60173d6d08
4,702
java
Java
excelium-core/src/test/java/excelium/core/screenshot/ScreenshotServiceTest.java
PhungDucKien/excelium
c7febe06209c212f8ad5c40bb53c9d0eeba3a8f1
[ "MIT" ]
5
2018-03-24T23:44:00.000Z
2018-04-27T15:12:35.000Z
excelium-core/src/test/java/excelium/core/screenshot/ScreenshotServiceTest.java
PhungDucKien/excelium
c7febe06209c212f8ad5c40bb53c9d0eeba3a8f1
[ "MIT" ]
22
2019-12-19T06:56:24.000Z
2022-02-27T00:24:56.000Z
excelium-core/src/test/java/excelium/core/screenshot/ScreenshotServiceTest.java
PhungDucKien/excelium
c7febe06209c212f8ad5c40bb53c9d0eeba3a8f1
[ "MIT" ]
null
null
null
35.089552
86
0.699277
995,473
/* * MIT License * * Copyright (c) 2018 Excelium * * 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 excelium.core.screenshot; import excelium.core.TestRunner; import excelium.core.driver.ContextAwareWebDriver; import excelium.model.enums.Browser; import excelium.model.project.Project; import excelium.model.test.TestFlow; import excelium.model.test.TestStep; import excelium.model.test.TestSuite; import excelium.model.test.config.Environment; import excelium.model.test.config.PcEnvironment; import mockit.Expectations; import mockit.Mocked; import mockit.Verifications; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.WebDriver; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static java.awt.image.BufferedImage.TYPE_INT_RGB; /** * Tests for {@link ScreenshotService}. * * @author PhungDucKien * @since 2018.05.25 */ public class ScreenshotServiceTest { @Mocked private TestRunner testRunner; @Mocked private AShot aShot; @Mocked private Screenshot screenshot; @Mocked private ContextAwareWebDriver webDriver; @Test public void testCaptureEntirePage() throws IOException { excelium.model.test.Test test = new excelium.model.test.Test(); test.setWorkbookName("Workbook1"); TestSuite testSuite = new TestSuite(); testSuite.setSheetName("Sheet1"); List<TestFlow> testFlows = new ArrayList<>(); TestFlow testFlow = new TestFlow(); testFlow.setNo(1); testFlows.add(testFlow); testFlow = new TestFlow(); testFlow.setNo(3); testFlows.add(testFlow); testFlow = new TestFlow(); testFlow.setNo(5); testFlows.add(testFlow); TestStep testStep = new TestStep(); testStep.setNo(10); Environment environment = new PcEnvironment(); ((PcEnvironment) environment).setBrowser(Browser.CHROME); Project project = new Project(); project.setBasePath(Paths.get(".")); project.setScreenshotPath(Paths.get("dump")); new Expectations() {{ testRunner.getTest(); result = test; testRunner.getTestSuite(); result = testSuite; testRunner.getTestFlows(); result = testFlows; testRunner.getTestStep(); result = testStep; testRunner.getEnvironment(); result = environment; testRunner.getProject(); result = project; aShot.takeScreenshot((WebDriver) any); result = screenshot; screenshot.getImage(); result = new BufferedImage(100, 100, TYPE_INT_RGB); webDriver.executeScript(anyString); result = 1; webDriver.isWebApp(); result = true; webDriver.isWebContext(); result = true; webDriver.isMobile(); result = false; }}; ScreenshotService screenshotService = new ScreenshotService(testRunner); screenshotService.captureEntirePage(webDriver); Path imagePath = Paths.get("dump/Chrome/Workbook1/Sheet1/1.3.5-10.png"); Assert.assertTrue(Files.exists(imagePath)); new Verifications() {{ aShot.takeScreenshot((WebDriver) any); }}; Files.delete(imagePath); Files.delete(Paths.get("dump/Chrome/Workbook1/Sheet1")); Files.delete(Paths.get("dump/Chrome/Workbook1")); Files.delete(Paths.get("dump/Chrome")); Files.delete(Paths.get("dump")); } }
92306d7bbd1de831340a1d1b8b5c19164742f9da
1,631
java
Java
flowgrid-android-legacy/src/main/java/org/flowgrid/android/classifier/VirtualOperationListAdapter.java
stefanhaustein/flowgrid
66e02b2b50c0fe4d5b05cd2459ea4b765d30b008
[ "Apache-2.0" ]
16
2017-06-04T23:39:19.000Z
2020-02-12T01:05:47.000Z
flowgrid-android-legacy/src/main/java/org/flowgrid/android/classifier/VirtualOperationListAdapter.java
stefanhaustein/flowgrid
66e02b2b50c0fe4d5b05cd2459ea4b765d30b008
[ "Apache-2.0" ]
1
2019-07-07T03:58:04.000Z
2019-07-08T03:40:15.000Z
flowgrid-android-legacy/src/main/java/org/flowgrid/android/classifier/VirtualOperationListAdapter.java
stefanhaustein/flowgrid
66e02b2b50c0fe4d5b05cd2459ea4b765d30b008
[ "Apache-2.0" ]
1
2018-05-20T13:26:03.000Z
2018-05-20T13:26:03.000Z
33.979167
129
0.745555
995,474
package org.flowgrid.android.classifier; import org.flowgrid.android.AbstractListAdapter; import org.flowgrid.model.VirtualOperation; import org.flowgrid.model.VirtualOperation.Parameter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class VirtualOperationListAdapter extends AbstractListAdapter<Parameter> { private final Context context; private final VirtualOperation operation; public VirtualOperationListAdapter(Context context, VirtualOperation operation) { this.context = context; this.operation = operation; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView tv = (TextView) ((convertView instanceof TextView) ? convertView : createViewFromResource(context, android.R.layout.simple_list_item_1, parent)); VirtualOperation.Parameter entry = getItem(position); boolean out = position >= operation.inputParameterCount(); int index = position - (out ? operation.inputParameterCount() : 0); tv.setText((out ? "Out " : "In ") + (index + 1) + ". " + entry.name + ": " + entry.type.toString()); return tv; } @Override public int getCount() { return operation.inputParameterCount() + operation.outputParameterCount(); } @Override public Parameter getItem(int position) { return position >= operation.inputParameterCount() ? operation.outputParameter(position - operation.inputParameterCount()) : operation.inputParameter(position); } public void notifyDataSetChanged() { super.notifyDataSetChanged(); } }
92306dbc42ba55608effe823b0d742d67c11a2f0
669
java
Java
class design/DogCat.java
dinhnhat0401/OCP
abcd89192e7fbcefbb37c5e8e0c74dbb58be9355
[ "MIT" ]
null
null
null
class design/DogCat.java
dinhnhat0401/OCP
abcd89192e7fbcefbb37c5e8e0c74dbb58be9355
[ "MIT" ]
null
null
null
class design/DogCat.java
dinhnhat0401/OCP
abcd89192e7fbcefbb37c5e8e0c74dbb58be9355
[ "MIT" ]
null
null
null
18.583333
60
0.518685
995,475
class Animal {} class Dog extends Animal {} class Cat extends Animal {} class A<T> { T t; void set(T t) { this.t = t; } T get() { return t; } } public class DogCat { public static <T> void print1(A<? extends Animal> obj) { obj.set(new Dog()); //Line 22 System.out.println(obj.get().getClass()); } public static <T> void print2(A<? super Dog> obj) { obj.set(new Dog()); //Line 27 System.out.println(obj.get().getClass()); } public static void main(String[] args) { A<Dog> obj = new A<>(); print1(obj); //Line 33 print2(obj); //Line 34 } }
92306f6e5be2c797394e8db86961ba91ca0540ab
1,046
java
Java
src/main/java/me/champeau/gradle/japicmp/filters/FilterConfiguration.java
cyberstormdotmu/japicmp-gradle-plugin
c6ae17606a803d0149f538de1b23ac40bd04b221
[ "Apache-2.0" ]
105
2015-03-25T23:55:29.000Z
2021-11-08T20:43:13.000Z
src/main/java/me/champeau/gradle/japicmp/filters/FilterConfiguration.java
cyberstormdotmu/japicmp-gradle-plugin
c6ae17606a803d0149f538de1b23ac40bd04b221
[ "Apache-2.0" ]
40
2015-06-05T21:45:31.000Z
2022-03-31T09:13:38.000Z
src/main/java/me/champeau/gradle/japicmp/filters/FilterConfiguration.java
cyberstormdotmu/japicmp-gradle-plugin
c6ae17606a803d0149f538de1b23ac40bd04b221
[ "Apache-2.0" ]
28
2015-05-20T17:44:31.000Z
2022-03-29T10:13:16.000Z
30.764706
75
0.737094
995,476
/* * Copyright 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 * * 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 me.champeau.gradle.japicmp.filters; import japicmp.filter.Filter; import java.io.Serializable; public class FilterConfiguration implements Serializable { protected final Class<? extends Filter> filterClass; public FilterConfiguration(Class<? extends Filter> filterClass) { this.filterClass = filterClass; } public Class<? extends Filter> getFilterClass() { return filterClass; } }
92306fa35b793a864ccffc795df12c914b1b3bc8
145
java
Java
src/main/com/beetle/framework/resource/mask/IPasswordMask.java
HeYuanFeng/BJAF3.x
c17eaee449dd0af19bf767ad2bc389e9755bec10
[ "Apache-2.0" ]
13
2016-05-06T13:19:43.000Z
2020-01-10T09:07:42.000Z
src/main/com/beetle/framework/resource/mask/IPasswordMask.java
HeYuanFeng/BJAF3.x
c17eaee449dd0af19bf767ad2bc389e9755bec10
[ "Apache-2.0" ]
2
2018-05-11T10:50:03.000Z
2018-06-09T12:47:38.000Z
src/main/com/beetle/framework/resource/mask/IPasswordMask.java
feishaozhang/BJAF3.x
a0e3931ab5c1dfac724f4b80bea003d43780af94
[ "Apache-2.0" ]
6
2017-03-13T09:18:53.000Z
2018-10-15T05:58:32.000Z
18.125
44
0.744828
995,477
package com.beetle.framework.resource.mask; public interface IPasswordMask { String decode(String src); String encode(String mask); }
9230705fffea15354df7486c6c67e0c4c78053da
8,763
java
Java
src/test/java/org/broadinstitute/hellbender/utils/config/ConfigIntegrationTest.java
slzhao/gatk
2e27f693bbea5b22eca809eb104a5df8a0a2d381
[ "Apache-2.0" ]
1,273
2015-10-13T18:11:50.000Z
2022-03-28T09:25:13.000Z
src/test/java/org/broadinstitute/hellbender/utils/config/ConfigIntegrationTest.java
slzhao/gatk
2e27f693bbea5b22eca809eb104a5df8a0a2d381
[ "Apache-2.0" ]
6,471
2015-10-08T02:31:06.000Z
2022-03-31T17:55:25.000Z
src/test/java/org/broadinstitute/hellbender/utils/config/ConfigIntegrationTest.java
slzhao/gatk
2e27f693bbea5b22eca809eb104a5df8a0a2d381
[ "Apache-2.0" ]
598
2015-10-14T19:16:14.000Z
2022-03-29T10:03:03.000Z
43.597015
132
0.621477
995,478
package org.broadinstitute.hellbender.utils.config; import org.broadinstitute.barclay.argparser.Argument; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import org.broadinstitute.hellbender.CommandLineProgramTest; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.cmdline.TestProgramGroup; import org.broadinstitute.hellbender.engine.GATKTool; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.testutils.ArgumentsBuilder; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; /** * Integration test * Created by jonn on 12/7/17. */ public class ConfigIntegrationTest extends CommandLineProgramTest { @CommandLineProgramProperties( summary = "Dummy empty command line that requires a reference .", oneLineSummary = "empty class", programGroup = TestProgramGroup.class ) public static class DummyGatkTool extends GATKTool { public static final String SYSTEM_VAR_ARG_LONG_NAME = "SystemVar"; public static final String SYSTEM_OUT_FILE_ARG_LONG_NAME = "SysOutFile"; @Argument( doc = "Output file with only the configuration settings in it.", fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME, shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME ) private File outputFilePath; @Argument( doc = "System properties to save to system properties output file.", fullName = SYSTEM_VAR_ARG_LONG_NAME ) private List<String> systemPropertiesToSave; @Argument( doc = "Output file with only the specified system properties in it.", fullName = SYSTEM_OUT_FILE_ARG_LONG_NAME ) private File systemPropertiesOutputFile; @Override public void traverse() { // Create our config and dump the config settings: final GATKConfig gatkConfig = ConfigFactory.getInstance().getGATKConfig(); ConfigFactory.dumpConfigSettings( gatkConfig, outputFilePath.toPath() ); final Properties systemProperties = new Properties(); for (final String propName : systemPropertiesToSave) { systemProperties.put( propName, System.getProperty(propName) ); } try ( final PrintStream systemOutPrintStream = new PrintStream(systemPropertiesOutputFile)) { systemProperties.store(systemOutPrintStream, ""); } catch ( final IOException ex ) { throw new GATKException("Could not open output file for system properties.", ex); } } } private void listProperties(final Properties props) { final List<String> propKeys = props.keySet().stream() .map(Object::toString) .sorted() .collect(Collectors.toCollection(ArrayList::new)); System.out.println("-- listing properties --"); for ( final String key : propKeys ) { System.out.print(key); System.out.print("="); System.out.println(props.get(key)); } } @Override public String getTestedClassName() { return DummyGatkTool.class.getSimpleName(); } @DataProvider private Object[][] provideForTestToolWithConfigValidation() { return new Object[][] { // Default config file (because nothing can be loaded): { getSafeNonExistentPath("nonExistentConfig.config") }, // Config file with overrides: { Paths.get(publicTestDir + "org/broadinstitute/hellbender/utils/config/" + "TestGATKConfigOverrides.properties") }, }; } @Test(dataProvider = "provideForTestToolWithConfigValidation", singleThreaded = true) public void testToolWithConfigValidation(final Path configFilePath) { // Grab the properties so we can reset them later: // NOTE: CLONE HERE IS ABSOLUTELY NECESSARY OR THIS WILL FAIL VERY VERY HARD! final Properties systemProperties = (Properties)System.getProperties().clone(); // System.out.println("================================================================================"); // listProperties(systemProperties); // System.out.println("================================================================================"); try { final File tmpConfigPropsFile = getSafeNonExistentFile("ConfigIntegrationTest.config.properties"); final File tmpSystemPropsFile = getSafeNonExistentFile("ConfigIntegrationTest.system.properties"); // Add in some system options. // None of these should be masked by the options of the same name in the config file. final Map<String, String> systemPropertiesToQuery = new HashMap<>(); systemPropertiesToQuery.put("gatk_stacktrace_on_user_exception", "true"); systemPropertiesToQuery.put("samjdk.compression_level", "7777"); for (final Map.Entry<String, String> entry : systemPropertiesToQuery.entrySet()) { System.setProperty(entry.getKey(), entry.getValue()); } // Create some arguments for our command: final ArgumentsBuilder args = new ArgumentsBuilder(); args.add(StandardArgumentDefinitions.GATK_CONFIG_FILE_OPTION, configFilePath.toUri().toString()); args.add(DummyGatkTool.SYSTEM_OUT_FILE_ARG_LONG_NAME, tmpSystemPropsFile.toString()); args.addOutput(tmpConfigPropsFile); // Add in our system properties to check: for ( final String sysProp : systemPropertiesToQuery.keySet() ) { args.add(DummyGatkTool.SYSTEM_VAR_ARG_LONG_NAME, sysProp); } // Run our command: runCommandLine(args); // ========================================================================================================= // Now we get to read in the file's contents and compare them to our config settings: final Properties configProperties = new Properties(); try ( final FileInputStream inputStream = new FileInputStream(tmpConfigPropsFile) ) { configProperties.load(inputStream); } catch ( final Exception ex ) { throw new GATKException("Test error!", ex); } final Properties systemPropertiesPostToolRun = new Properties(); try ( final FileInputStream inputStream = new FileInputStream(tmpSystemPropsFile) ) { systemPropertiesPostToolRun.load(inputStream); } catch ( final Exception ex ) { throw new GATKException("Test error!", ex); } // Create a config object to compare with the properties: final GATKConfig config = ConfigFactory.getInstance().createConfigFromFile(configFilePath.toString(), GATKConfig.class); // Get the config properties: final LinkedHashMap<String, Object> configMap = ConfigFactory.getConfigMap(config, false); // Compare the configuration properties and assert their equality: for ( final Map.Entry<String, Object> entry : configMap.entrySet() ) { Assert.assertEquals(configProperties.getProperty(entry.getKey()), String.valueOf(entry.getValue())); } // Compare the system properties and assert their equality: for ( final String sysPropKey : systemPropertiesToQuery.keySet() ) { Assert.assertEquals(systemPropertiesPostToolRun.getProperty(sysPropKey), systemPropertiesToQuery.get(sysPropKey)); } // Make sure they have the same size: Assert.assertEquals(configProperties.size(), configMap.size()); } // ========================================================================================================= // Now we have to reset our system options: finally { // Clear our system properties: final List<Object> keyList = new ArrayList<>(System.getProperties().keySet()); for ( final Object key : keyList ) { System.clearProperty(key.toString()); } // Set back the old System Properties: System.setProperties(systemProperties); } } }
9230706d89096a8278721aef79a8f7ce9e9a1f12
2,964
java
Java
src/main/java/fd/se/ooad_project/controller/usr/ExpertController.java
VigilGLC/ooad-project
736e6f20e761ba2a179261ea152a5efc1d68c16b
[ "Apache-2.0" ]
null
null
null
src/main/java/fd/se/ooad_project/controller/usr/ExpertController.java
VigilGLC/ooad-project
736e6f20e761ba2a179261ea152a5efc1d68c16b
[ "Apache-2.0" ]
null
null
null
src/main/java/fd/se/ooad_project/controller/usr/ExpertController.java
VigilGLC/ooad-project
736e6f20e761ba2a179261ea152a5efc1d68c16b
[ "Apache-2.0" ]
null
null
null
39
99
0.696356
995,479
package fd.se.ooad_project.controller.usr; import fd.se.ooad_project.entity.consts.Role; import fd.se.ooad_project.interceptor.Subject; import fd.se.ooad_project.interceptor.authorize.Authorized; import fd.se.ooad_project.pojo.request.MarketReportRequest; import fd.se.ooad_project.pojo.request.MereIdRequest; import fd.se.ooad_project.service.ReportService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user/expert") @AllArgsConstructor @Slf4j @Authorized(role = Role.ANY) public class ExpertController { private final Subject subject; private final ReportService reportService; @GetMapping("/expertReports") public ResponseEntity<?> allExpertReports() { log.info("Expert {} get all expert reports. ", subject); return ResponseEntity.ok(reportService.getExpertReports(subject.getUser())); } @GetMapping("/expertReport") public ResponseEntity<?> expertReport(@RequestParam int id) { log.info("Expert {} get expert report {}. ", subject, id); return ResponseEntity.ok(reportService.getExpertReportById(id)); } @PostMapping("/expertReport/submit") public ResponseEntity<?> submitExpertReport(@RequestBody MereIdRequest request) { final int id = request.getId(); final boolean result = reportService.submitExpertReportOfId(id); if (result) { log.info("Expert {} submit expert report {}. Success. ", subject, id); return ResponseEntity.ok().build(); } else { log.info("Expert {} submit expert report {}. Failed. ", subject, id); return ResponseEntity.badRequest().build(); } } @GetMapping("/expertReport/marketReports") public ResponseEntity<?> subMarketReports(@RequestParam int id) { log.info("Expert {} get all sub market reports of expert report {}. ", subject, id); return ResponseEntity.ok(reportService.getExpertReportSubMarketReports(id)); } @GetMapping("/expertReport/marketReport") public ResponseEntity<?> subMarketReport(@RequestParam int id) { log.info("Expert {} get sub market report {}. ", subject, id); return ResponseEntity.ok(reportService.getMarketReportById(id)); } @PostMapping("/expertReport/marketReport/submit") public ResponseEntity<?> submitSubMarketReport(@RequestBody MarketReportRequest request) { final boolean result = reportService.submitMarketReportFromRequest(request); if (result) { log.info("Expert {} submit sub market report {}. Success. ", subject, request.getId()); return ResponseEntity.ok().build(); } else { log.warn("Expert {} submit sub market report {}. Failed. ", subject, request.getId()); return ResponseEntity.badRequest().build(); } } }
923070b68feb9d9bdd1fac334dac5b1ffeb36931
2,323
java
Java
src/test/java/org/basex/test/query/expr/MixedTest.java
rostam/basex
6424d81435955289cc415efb7bf4e09afb29665c
[ "BSD-3-Clause" ]
1
2018-12-24T14:16:13.000Z
2018-12-24T14:16:13.000Z
src/test/java/org/basex/test/query/expr/MixedTest.java
rostam/basex
6424d81435955289cc415efb7bf4e09afb29665c
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/basex/test/query/expr/MixedTest.java
rostam/basex
6424d81435955289cc415efb7bf4e09afb29665c
[ "BSD-3-Clause" ]
null
null
null
27.987952
86
0.625915
995,480
package org.basex.test.query.expr; import static org.basex.query.func.Function.*; import org.basex.core.*; import org.basex.core.cmd.*; import org.basex.query.util.*; import org.basex.test.query.*; import org.junit.*; /** * Mixed XQuery tests. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public final class MixedTest extends AdvancedQueryTest { /** Test XQuery module file. */ private static final String XQMFILE = "src/test/resources/hello.xqm"; /** * Drops the collection. * @throws BaseXException exception */ @AfterClass public static void after() throws BaseXException { new DropDB(NAME).execute(context); } /** Catches duplicate module import. */ @Test public void duplImport() { error("import module namespace a='world' at '" + XQMFILE + "';" + "import module namespace a='world' at '" + XQMFILE + "'; 1", Err.DUPLMODULE); } /** Catches duplicate module import with different module uri. */ @Test public void duplImportDiffUri() { error("import module namespace a='world' at '" + XQMFILE + "';" + "import module namespace a='galaxy' at '" + XQMFILE + "'; 1", Err.WRONGMODULE); } /** * Overwrites an empty attribute value. * @throws BaseXException database exception */ @Test public void emptyAttValues() throws BaseXException { new CreateDB(NAME, "<A a='' b=''/>").execute(context); query("replace value of node /A/@a with 'A'"); query("/", "<A a=\"A\" b=\"\"/>"); } /** * Parse recursive queries. */ @Test public void parseRec() { // simple call query("declare function local:x() { if(<a/>) then 1 else local:x() }; local:x()"); // call from FLWOR expression query("declare function local:x() { if(<a/>) then 1 else local:x() }; " + "let $x := local:x() return $x", "1"); } /** * Performs count() on parts of a collection. * @throws BaseXException database exception */ @Test public void countCollection() throws BaseXException { new CreateDB(NAME).execute(context); new Add("a", "<a/>").execute(context); new Add("b", "<a/>").execute(context); new Optimize().execute(context); query(COUNT.args(_DB_OPEN.args(NAME, "a") + "/a"), "1"); query(COUNT.args(_DB_OPEN.args(NAME) + "/a"), "2"); } }
92307109670f96b7aef9362d9e00c4bb30f2e9d8
7,234
java
Java
yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/other/resource/src/main/java/com/lanking/uxb/rescon/teach/api/impl/handler/ResconTeachAssistElementPrepareGoalHandle.java
wangsikai/learn
af85f7c7db5c38b5009ebdfb8c8985032eca565c
[ "Apache-2.0" ]
1
2019-01-20T06:19:53.000Z
2019-01-20T06:19:53.000Z
yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/other/resource/src/main/java/com/lanking/uxb/rescon/teach/api/impl/handler/ResconTeachAssistElementPrepareGoalHandle.java
wangsikai/learn
af85f7c7db5c38b5009ebdfb8c8985032eca565c
[ "Apache-2.0" ]
null
null
null
yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/other/resource/src/main/java/com/lanking/uxb/rescon/teach/api/impl/handler/ResconTeachAssistElementPrepareGoalHandle.java
wangsikai/learn
af85f7c7db5c38b5009ebdfb8c8985032eca565c
[ "Apache-2.0" ]
2
2019-01-20T06:19:54.000Z
2021-07-21T14:13:44.000Z
30.782979
131
0.758087
995,481
package com.lanking.uxb.rescon.teach.api.impl.handler; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.lanking.cloud.component.db.support.hibernate.Repo; import com.lanking.cloud.domain.common.resource.teachAssist.AbstractTeachAssistElement; import com.lanking.cloud.domain.common.resource.teachAssist.TeachAssistCatalogElement; import com.lanking.cloud.domain.common.resource.teachAssist.TeachAssistElementPrepareGoal; import com.lanking.cloud.domain.common.resource.teachAssist.TeachAssistElementPrepareGoalContent; import com.lanking.cloud.domain.common.resource.teachAssist.TeachAssistElementType; import com.lanking.cloud.sdk.data.Params; import com.lanking.cloud.sdk.util.CollectionUtils; import com.lanking.uxb.rescon.teach.api.impl.ResconAbstractTeachAssistElementHandle; import com.lanking.uxb.rescon.teach.form.TeachAssistElementForm; /** * 预习目标 模块 * * @author xinyu.zhou * @since 2.2.0 */ @Service @Transactional(readOnly = true) public class ResconTeachAssistElementPrepareGoalHandle extends ResconAbstractTeachAssistElementHandle { @Autowired @Qualifier("TeachAssistElementPrepareGoalRepo") private Repo<TeachAssistElementPrepareGoal, Long> repo; @Autowired @Qualifier("TeachAssistElementPrepareGoalContentRepo") private Repo<TeachAssistElementPrepareGoalContent, Long> contentRepo; @Autowired @Qualifier("TeachAssistCatalogElementRepo") private Repo<TeachAssistCatalogElement, Long> catalogElementRepo; @Override @Transactional public void save(TeachAssistElementForm form) { TeachAssistElementPrepareGoal goal = null; if (form.getId() != null) { goal = repo.get(form.getId()); } if (null == goal) { goal = new TeachAssistElementPrepareGoal(); goal.setSequence(form.getSequence()); goal.setType(getType()); goal.setCreateAt(new Date()); goal.setCreateId(form.getUserId()); goal.setUpdateAt(new Date()); goal.setUpdateId(form.getUserId()); goal.setTeachAssistCatalogId(form.getCatalogId()); repo.save(goal); TeachAssistCatalogElement ce = new TeachAssistCatalogElement(); ce.setElementId(goal.getId()); ce.setSequence(form.getSequence()); ce.setTeachassistCatalogId(form.getCatalogId()); ce.setType(getType()); catalogElementRepo.save(ce); } else { goal.setUpdateAt(new Date()); goal.setUpdateId(form.getUserId()); repo.save(goal); } } @Override @Transactional public void delete(TeachAssistElementForm form) { repo.deleteById(form.getId()); } @Override @Transactional public void sequence(long id, int sequence, long userId) { TeachAssistElementPrepareGoal goal = repo.get(id); if (null != goal) { goal.setSequence(sequence); goal.setUpdateAt(new Date()); goal.setUpdateId(userId); repo.save(goal); } } @Override public List<TeachAssistElementPrepareGoal> get(long catalogId) { return repo.find("$resconFindByCatalog", Params.param("catalogId", catalogId)).list(); } @Override public AbstractTeachAssistElement findOne(long id) { return repo.get(id); } @Override public void saveContent(TeachAssistElementForm form, long elementId) { JSONObject parsedParam = parseForm(form.getParamForm()); TeachAssistElementPrepareGoalContent content = null; if (form.getId() != null) { content = contentRepo.get(form.getId()); } if (content == null) { content = new TeachAssistElementPrepareGoalContent(); content.setGoalId(elementId); content.setSequence(form.getSequence()); } if (parsedParam != null) { content.setSelfTestQuestions(parseList("selfTestQuestions", parsedParam)); content.setName(parsedParam.getString("name")); content.setKnowpoints(parseList("knowpoints", parsedParam)); content.setPreviewQuestions(parseList("previewQuestions", parsedParam)); } contentRepo.save(content); } @Override public void updateContentSequence(long id, int sequence) { TeachAssistElementPrepareGoalContent content = contentRepo.get(id); if (content != null) { content.setSequence(sequence); contentRepo.save(content); } } @Override public TeachAssistElementType getType() { return TeachAssistElementType.PREPARE_GOAL; } @Override public void deleteContent(long id) { contentRepo.deleteById(id); } @Override public List getContents(long id) { return contentRepo.find("$resconFindByElement", Params.param("elementId", id)).list(); } @Override public void deleteByElement(long elementId) { contentRepo.execute("$resconDeleteByElement", Params.param("elementId", elementId)); } @Override public List mgetContents(Collection<Long> ids) { if (CollectionUtils.isEmpty(ids)) { return Collections.EMPTY_LIST; } return contentRepo.find("$resconFindByElements", Params.param("elementIds", ids)).list(); } @Override @Transactional @SuppressWarnings("unchecked") public void copy(long newCatalogId, Collection<Long> ids, long userId) { Date now = new Date(); List<TeachAssistElementPrepareGoal> goals = repo.mgetList(ids); List<Long> gIds = new ArrayList<Long>(goals.size()); Map<Long, List<TeachAssistElementPrepareGoalContent>> contentMap = new HashMap<Long, List<TeachAssistElementPrepareGoalContent>>( goals.size()); for (TeachAssistElementPrepareGoal g : goals) { gIds.add(g.getId()); } List<TeachAssistElementPrepareGoalContent> contents = (List<TeachAssistElementPrepareGoalContent>) this .mgetContents(gIds); for (TeachAssistElementPrepareGoalContent c : contents) { List<TeachAssistElementPrepareGoalContent> list = contentMap.get(c.getGoalId()); if (CollectionUtils.isEmpty(list)) { list = Lists.newArrayList(); } list.add(c); contentMap.put(c.getGoalId(), list); } for (TeachAssistElementPrepareGoal g : goals) { TeachAssistElementPrepareGoal n = new TeachAssistElementPrepareGoal(); n.setCreateAt(now); n.setCreateId(userId); n.setSequence(g.getSequence()); n.setTeachAssistCatalogId(newCatalogId); n.setType(getType()); n.setUpdateAt(now); n.setUpdateId(userId); repo.save(n); TeachAssistCatalogElement ce = new TeachAssistCatalogElement(); ce.setElementId(n.getId()); ce.setSequence(n.getSequence()); ce.setTeachassistCatalogId(newCatalogId); ce.setType(getType()); catalogElementRepo.save(ce); if (CollectionUtils.isNotEmpty(contentMap.get(g.getId()))) { for (TeachAssistElementPrepareGoalContent c : contentMap.get(g.getId())) { TeachAssistElementPrepareGoalContent nc = new TeachAssistElementPrepareGoalContent(); nc.setGoalId(n.getId()); nc.setKnowpoints(c.getKnowpoints()); nc.setName(c.getName()); nc.setPreviewQuestions(c.getPreviewQuestions()); nc.setSelfTestQuestions(c.getSelfTestQuestions()); nc.setSequence(c.getSequence()); contentRepo.save(nc); } } } } }
9230729df627db777b071c3570f7a952d7e3ea4e
8,425
java
Java
src/main/java/de/johni0702/minecraft/gui/element/AbstractGuiTexturedButton.java
ReplayMod/jGui
c79b62a73e649fd6d16a1ffbd9e320555834bc46
[ "MIT" ]
27
2016-03-15T15:11:34.000Z
2021-12-26T15:15:57.000Z
src/main/java/de/johni0702/minecraft/gui/element/AbstractGuiTexturedButton.java
ReplayMod/jGui
c79b62a73e649fd6d16a1ffbd9e320555834bc46
[ "MIT" ]
6
2016-03-15T17:16:17.000Z
2020-08-31T05:07:46.000Z
src/main/java/de/johni0702/minecraft/gui/element/AbstractGuiTexturedButton.java
ReplayMod/jGui
c79b62a73e649fd6d16a1ffbd9e320555834bc46
[ "MIT" ]
14
2016-03-15T15:11:40.000Z
2022-02-22T03:59:49.000Z
30.860806
165
0.656142
995,482
/* * This file is part of jGui API, licensed under the MIT License (MIT). * * Copyright (c) 2016 johni0702 <https://github.com/johni0702> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.johni0702.minecraft.gui.element; import de.johni0702.minecraft.gui.GuiRenderer; import de.johni0702.minecraft.gui.RenderInfo; import de.johni0702.minecraft.gui.container.GuiContainer; import de.johni0702.minecraft.gui.function.Clickable; import de.johni0702.minecraft.gui.utils.lwjgl.Dimension; import de.johni0702.minecraft.gui.utils.lwjgl.Point; import de.johni0702.minecraft.gui.utils.lwjgl.ReadableDimension; import de.johni0702.minecraft.gui.utils.lwjgl.ReadablePoint; import de.johni0702.minecraft.gui.utils.lwjgl.WritableDimension; import de.johni0702.minecraft.gui.utils.lwjgl.WritablePoint; import net.minecraft.util.Identifier; //#if MC>=10904 import net.minecraft.sound.SoundEvents; import net.minecraft.sound.SoundEvent; //#endif //#if MC>=10800 import static com.mojang.blaze3d.platform.GlStateManager.*; //#endif import static de.johni0702.minecraft.gui.versions.MCVer.*; import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; public abstract class AbstractGuiTexturedButton<T extends AbstractGuiTexturedButton<T>> extends AbstractGuiClickable<T> implements Clickable, IGuiTexturedButton<T> { private Identifier texture; //#if MC>=10904 private SoundEvent sound = SoundEvents.UI_BUTTON_CLICK; //#endif private ReadableDimension textureSize = new ReadableDimension() { @Override public int getWidth() { return getMaxSize().getWidth(); } @Override public int getHeight() { return getMaxSize().getHeight(); } @Override public void getSize(WritableDimension dest) { getMaxSize().getSize(dest); } }; private ReadableDimension textureTotalSize; private ReadablePoint textureNormal; private ReadablePoint textureHover; private ReadablePoint textureDisabled; public AbstractGuiTexturedButton() { } public AbstractGuiTexturedButton(GuiContainer container) { super(container); } @Override public void draw(GuiRenderer renderer, ReadableDimension size, RenderInfo renderInfo) { super.draw(renderer, size, renderInfo); renderer.bindTexture(texture); ReadablePoint texture = textureNormal; if (!isEnabled()) { texture = textureDisabled; } else if (isMouseHovering(new Point(renderInfo.mouseX, renderInfo.mouseY))) { texture = textureHover; } if (texture == null) { // Button is disabled but we have no texture for that //#if MC>=11700 //$$ // TODO anything reasonable we can do here? do we even care? //#else color4f(0.5f, 0.5f, 0.5f, 1); //#endif texture = textureNormal; } enableBlend(); blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); renderer.drawTexturedRect(0, 0, texture.getX(), texture.getY(), size.getWidth(), size.getHeight(), textureSize.getWidth(), textureSize.getHeight(), textureTotalSize.getWidth(), textureTotalSize.getHeight()); } @Override public ReadableDimension calcMinSize() { return new Dimension(0, 0); } @Override public void onClick() { //#if MC>=10904 AbstractGuiButton.playClickSound(getMinecraft(), sound); //#else //$$ AbstractGuiButton.playClickSound(getMinecraft()); //#endif super.onClick(); } @Override public T setTexture(Identifier resourceLocation, int size) { return setTexture(resourceLocation, size, size); } @Override public T setTexture(Identifier resourceLocation, int width, int height) { this.texture = resourceLocation; this.textureTotalSize = new Dimension(width, height); return getThis(); } @Override public T setTextureSize(int size) { return setTextureSize(size, size); } @Override public T setTextureSize(int width, int height) { this.textureSize = new Dimension(width, height); return getThis(); } @Override public T setTexturePosH(final int x, final int y) { return setTexturePosH(new Point(x, y)); } @Override public T setTexturePosV(final int x, final int y) { return setTexturePosV(new Point(x, y)); } @Override public T setTexturePosH(final ReadablePoint pos) { this.textureNormal = pos; this.textureHover = new ReadablePoint() { @Override public int getX() { return pos.getX() + textureSize.getWidth(); } @Override public int getY() { return pos.getY(); } @Override public void getLocation(WritablePoint dest) { dest.setLocation(getX(), getY()); } }; return getThis(); } @Override public T setTexturePosV(final ReadablePoint pos) { this.textureNormal = pos; this.textureHover = new ReadablePoint() { @Override public int getX() { return pos.getX(); } @Override public int getY() { return pos.getY() + textureSize.getHeight(); } @Override public void getLocation(WritablePoint dest) { dest.setLocation(getX(), getY()); } }; return getThis(); } @Override public T setTexturePos(int normalX, int normalY, int hoverX, int hoverY) { return setTexturePos(new Point(normalX, normalY), new Point(hoverX, hoverY)); } @Override public T setTexturePos(ReadablePoint normal, ReadablePoint hover) { this.textureNormal = normal; this.textureHover = hover; return getThis(); } @Override public T setTexturePos(int normalX, int normalY, int hoverX, int hoverY, int disabledX, int disabledY) { return setTexturePos(new Point(normalX, normalY), new Point(hoverX, hoverY), new Point(disabledX, disabledY)); } @Override public T setTexturePos(ReadablePoint normal, ReadablePoint hover, ReadablePoint disabled) { this.textureDisabled = disabled; return setTexturePos(normal, hover); } //#if MC>=10904 @Override public T setSound(SoundEvent sound) { this.sound = sound; return getThis(); } public SoundEvent getSound() { return this.sound; } //#endif public Identifier getTexture() { return this.texture; } public ReadableDimension getTextureSize() { return this.textureSize; } public ReadableDimension getTextureTotalSize() { return this.textureTotalSize; } public ReadablePoint getTextureNormal() { return this.textureNormal; } public ReadablePoint getTextureHover() { return this.textureHover; } public ReadablePoint getTextureDisabled() { return this.textureDisabled; } }
923072fb25d92cbdd2b97860cba147a72b55f602
1,687
java
Java
sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/MessageManagementOperations.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/MessageManagementOperations.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/MessageManagementOperations.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
46.861111
119
0.762893
995,483
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.servicebus.implementation; import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.messaging.servicebus.models.ServiceBusReceiveMode; import org.apache.qpid.proton.amqp.transport.DeliveryState; import reactor.core.publisher.Mono; import java.time.OffsetDateTime; import java.util.UUID; /** * Interface for settling and renewing messages. */ public interface MessageManagementOperations { /** * Updates the disposition status of a message given its lock token. * * @return Mono that completes successfully when the message is completed. Otherwise, returns an error. */ Mono<Void> updateDisposition(String lockToken, DeliveryState deliveryState); /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on * the setting specified on the entity. When a message is received in {@link ServiceBusReceiveMode#PEEK_LOCK} mode, * the message is locked on the server for this receiver instance for a duration as specified during the * Queue/Subscription creation (LockDuration). If processing of the message requires longer than this duration, * the lock needs to be renewed. For each renewal, the lock is reset to the entity's LockDuration value. * * @param lockToken The {@link UUID} of the message {@link ServiceBusReceivedMessage} to be renewed. * @return {@link OffsetDateTime} representing the pending renew. */ Mono<OffsetDateTime> renewMessageLock(String lockToken, String associatedLinkName); }
9230736942fdc5635ec6532a59a788a48aa9a703
3,305
java
Java
apps/mcast/api/src/main/java/org/onosproject/mcast/api/McastEvent.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
apps/mcast/api/src/main/java/org/onosproject/mcast/api/McastEvent.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
apps/mcast/api/src/main/java/org/onosproject/mcast/api/McastEvent.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
27.090164
101
0.609077
995,484
/* * Copyright 2018-present Open Networking 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.onosproject.mcast.api; import com.google.common.annotations.Beta; import org.onosproject.event.AbstractEvent; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; /** * An entity representing a multicast event. Event either add or remove * sinks or sources. */ @Beta public class McastEvent extends AbstractEvent<McastEvent.Type, McastRouteUpdate> { /** * Mcast Event type enum. */ public enum Type { /** * A new mcast route has been added. */ ROUTE_ADDED, /** * A mcast route has been removed. */ ROUTE_REMOVED, /** * A set of sources for a mcast route (ie. the subject) has been added. */ SOURCES_ADDED, /** * A set of sources for a mcast route has been removed. */ SOURCES_REMOVED, /** * A set of sinks for a mcast route (ie. the subject) has been added. */ SINKS_ADDED, /** * A set of sinks for a mcast route (ie. the subject) has been removed. */ SINKS_REMOVED } private McastRouteUpdate prevSubject; /** * Creates a McastEvent of a given type using the subject. * * @param type the event type * @param prevSubject the previous mcast information * @param subject the current mcast information */ public McastEvent(McastEvent.Type type, McastRouteUpdate prevSubject, McastRouteUpdate subject) { super(type, subject); this.prevSubject = prevSubject; } /** * Gets the previous subject in this Mcast event. * * @return the previous subject, or null if previous subject is not * specified. */ public McastRouteUpdate prevSubject() { return this.prevSubject; } @Override public int hashCode() { return Objects.hash(type(), subject(), prevSubject()); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof McastEvent)) { return false; } McastEvent that = (McastEvent) other; return Objects.equals(this.subject(), that.subject()) && Objects.equals(this.type(), that.type()) && Objects.equals(this.prevSubject(), that.prevSubject()); } @Override public String toString() { return toStringHelper(this) .add("type", type()) .add("prevSubject", prevSubject()) .add("subject", subject()) .toString(); } }
923073dc61c8c20f67b13eb5ba54b89f866587f5
3,012
java
Java
src/main/java/com/github/am0e/utils/Uids.java
am0e/commons
18ba40101e99cae7a61a3b499eb7f8f45c8cc3e8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/am0e/utils/Uids.java
am0e/commons
18ba40101e99cae7a61a3b499eb7f8f45c8cc3e8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/am0e/utils/Uids.java
am0e/commons
18ba40101e99cae7a61a3b499eb7f8f45c8cc3e8
[ "Apache-2.0" ]
null
null
null
28.961538
119
0.500996
995,485
/******************************************************************************* * 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.github.am0e.utils; /** * UUID/ID utility methods. * * @author Anthony * */ public final class Uids { /** * For converting long to an upper case alpha numeric string. Note no I O U * to avoid the creation of offensive words. */ final static char[] cset_base32 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z' }; public static String getAlphaNumIDFromLong(long v) { return encodeLong(v, cset_base32); } public static long getLongFromAlphaNumID(String id) { return decodeLong(id, cset_base32); } public static String encodeLong(long i, char[] cset) { final int radix = cset.length; char buf[] = new char[20]; boolean negative = (i < 0); int pos = 19; if (!negative) { i = -i; } while (i <= -radix) { buf[pos--] = cset[(int) (-(i % radix))]; i = i / radix; } buf[pos] = cset[(int) (-i)]; if (negative) { buf[--pos] = '*'; } return new String(buf, pos, (20 - pos)); } public static long decodeLong(String s, char[] cset) throws NumberFormatException { if (s == null) { throw new IllegalArgumentException(); } if (s.length() == 0) { return 0; } long result = 0; int i = 0, max = s.length(); final int radix = cset.length; boolean negative = false; if (s.charAt(0) == '*') { negative = true; i++; } while (i < max) { char c = s.charAt(i++); int j; for (j = 0; j != radix && cset[j] != c; j++) { ; } if (j == radix) { return -1; } result *= radix; result += j; } return negative ? -result : result; } }
9230747470b56a2811c48e064b51f5bdf740dee1
479
java
Java
mall-portal/src/main/java/com/macro/mall/portal/domain2/PmsProductEx.java
ng123123/mall
b2bdc0f06c4ed411f1fe6a590c77f3ac54fb991b
[ "Apache-2.0" ]
null
null
null
mall-portal/src/main/java/com/macro/mall/portal/domain2/PmsProductEx.java
ng123123/mall
b2bdc0f06c4ed411f1fe6a590c77f3ac54fb991b
[ "Apache-2.0" ]
null
null
null
mall-portal/src/main/java/com/macro/mall/portal/domain2/PmsProductEx.java
ng123123/mall
b2bdc0f06c4ed411f1fe6a590c77f3ac54fb991b
[ "Apache-2.0" ]
null
null
null
17.107143
52
0.588727
995,486
package com.macro.mall.portal.domain2; import com.macro.mall.model.PmsProduct; /************************************************* Desc: 购物车中选择规格的商品信息 Author: ng123123 Date: 2020/10/20 QQ交流群: 892951935 **************************************************/ public class PmsProductEx extends PmsProduct { private String signature; public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } }
923074954b46bd07a4e37549b5aac740a17286e0
4,546
java
Java
src/test/java/com/oxygenxml/resources/batch/converter/converters/ExcelToDitaTest.java
oxygenxml/oxygen-resources-converter
7f4db68e2ccfc88950cc149a11dc948394b8f9a4
[ "Apache-2.0" ]
15
2017-11-13T10:32:58.000Z
2021-08-23T15:12:30.000Z
src/test/java/com/oxygenxml/resources/batch/converter/converters/ExcelToDitaTest.java
oxygenxml/oxygen-resources-converter
7f4db68e2ccfc88950cc149a11dc948394b8f9a4
[ "Apache-2.0" ]
21
2017-11-15T05:46:48.000Z
2021-06-17T07:14:18.000Z
src/test/java/com/oxygenxml/resources/batch/converter/converters/ExcelToDitaTest.java
oxygenxml/oxygen-resources-converter
7f4db68e2ccfc88950cc149a11dc948394b8f9a4
[ "Apache-2.0" ]
12
2018-10-01T12:47:38.000Z
2021-06-17T17:11:58.000Z
35.795276
134
0.739551
995,487
package com.oxygenxml.resources.batch.converter.converters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.Test; import com.oxygenxml.batch.converter.core.ConverterTypes; import com.oxygenxml.batch.converter.core.extensions.FileExtensionType; import com.oxygenxml.batch.converter.core.transformer.TransformerFactoryCreator; import com.oxygenxml.batch.converter.core.utils.ConverterFileUtils; import com.oxygenxml.resources.batch.converter.BatchConverter; import com.oxygenxml.resources.batch.converter.BatchConverterImpl; import com.oxygenxml.resources.batch.converter.UserInputsProvider; import com.oxygenxml.resources.batch.converter.reporter.ProblemReporter; import tests.utils.ConverterStatusReporterTestImpl; import tests.utils.ConvertorWorkerInteractorTestImpl; import tests.utils.FileComparationUtil; import tests.utils.ProblemReporterTestImpl; import tests.utils.StatusReporterImpl; import tests.utils.TransformerFactoryCreatorImpl; /** * JUnit for Excel to DITA conversion. * @author cosmin_duna */ public class ExcelToDitaTest { @Test public void testConversion() throws Exception { File sample = new File("test-sample/excel.xls"); File expectedOutput = new File("test-sample/excelToDITA.dita"); final File outputFolder = new File(sample.getParentFile(), "out"); TransformerFactoryCreator transformerCreator = new TransformerFactoryCreatorImpl(); ProblemReporter problemReporter = new ProblemReporterTestImpl(); BatchConverter converter = new BatchConverterImpl(problemReporter, new StatusReporterImpl(), new ConverterStatusReporterTestImpl(), new ConvertorWorkerInteractorTestImpl() , transformerCreator); final List<File> inputFiles = new ArrayList<File>(); inputFiles.add(sample); File convertedFile = ConverterFileUtils.getOutputFile(sample, FileExtensionType.DITA_OUTPUT_EXTENSION , outputFolder); try { converter.convertFiles(ConverterTypes.EXCEL_TO_DITA, new UserInputsProvider() { @Override public boolean mustOpenConvertedFiles() { return false; } @Override public File getOutputFolder() { return outputFolder; } @Override public List<File> getInputFiles() { return inputFiles; } @Override public Boolean getAdditionalOptionValue(String additionalOptionId) { return null; } }); assertEquals(FileUtils.readFileToString(expectedOutput), FileUtils.readFileToString(convertedFile)); } finally { FileComparationUtil.deleteRecursivelly(outputFolder); } } /** * <p><b>Description:</b> Test invalid characters are escaped in the resulted DITA document.< </p> * <p><b>Bug ID:</b> EXM-47523</p> * * @author cosmin_duna * * @throws Exception */ @Test public void testInvalidCharsAreEscaped() throws Exception { File inputFile = new File("test-sample/EXM-47523/_sample#@.xlsx"); File expectedOutput = new File("test-sample/EXM-47523/expected.dita"); final File outputFolder = new File(inputFile.getParentFile(), "out"); TransformerFactoryCreator transformerCreator = new TransformerFactoryCreatorImpl(); ProblemReporter problemReporter = new ProblemReporterTestImpl(); BatchConverter converter = new BatchConverterImpl(problemReporter, new StatusReporterImpl(), new ConverterStatusReporterTestImpl(), new ConvertorWorkerInteractorTestImpl() , transformerCreator); final List<File> inputFiles = new ArrayList<File>(); inputFiles.add(inputFile); File convertedFile = ConverterFileUtils.getOutputFile(inputFile, FileExtensionType.DITA_OUTPUT_EXTENSION , outputFolder); try { converter.convertFiles(ConverterTypes.EXCEL_TO_DITA, new UserInputsProvider() { @Override public boolean mustOpenConvertedFiles() { return false; } @Override public File getOutputFolder() { return outputFolder; } @Override public List<File> getInputFiles() { return inputFiles; } @Override public Boolean getAdditionalOptionValue(String additionalOptionId) { return null; } }); assertTrue(FileComparationUtil.compareLineToLine(expectedOutput, convertedFile)); } finally { FileComparationUtil.deleteRecursivelly(outputFolder); } } }
9230753704250f2a4dc3fc8d77a3602e01d48381
843
java
Java
oss-lib-security/src/test/java-spring-boot-1.4.x/it/com/yirendai/oss/lib/security/PermitedController.java
Yirendai/oss-lib
912e24382c4482c851997eee4d29e90af9e7db6c
[ "MIT" ]
2
2017-04-07T16:15:09.000Z
2018-12-07T02:59:36.000Z
oss-lib-security/src/test/java-spring-boot-1.4.x/it/com/yirendai/oss/lib/security/PermitedController.java
Yirendai/oss-lib
912e24382c4482c851997eee4d29e90af9e7db6c
[ "MIT" ]
null
null
null
oss-lib-security/src/test/java-spring-boot-1.4.x/it/com/yirendai/oss/lib/security/PermitedController.java
Yirendai/oss-lib
912e24382c4482c851997eee4d29e90af9e7db6c
[ "MIT" ]
5
2017-04-07T16:14:25.000Z
2022-03-06T10:34:18.000Z
25.545455
72
0.773428
995,488
package it.com.yirendai.oss.lib.security; import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.yirendai.oss.boot.autoconfigure.AppProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; /** * Created by zhanghaolun on 16/10/31. */ @RestController @RequestMapping(path = "/permited") public class PermitedController { @Autowired private AppProperties appProperties; @RequestMapping(path = "/random", method = GET) public String random() { return this.appProperties.getRandom(); } @RequestMapping(path = "/user", method = GET) public Principal getUser(final Principal principal) { return principal; } }
92307616e825cccf77337e41026a5df06daa1158
76
java
Java
platform/funcTests/project1/module1/src/com/intellij/testProject/fabrique/VisualFabrique.java
jonathannewell/intellij-community
c8c00b824a00372781a77c12487fecb86cb85008
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
platform/funcTests/project1/module1/src/com/intellij/testProject/fabrique/VisualFabrique.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
platform/funcTests/project1/module1/src/com/intellij/testProject/fabrique/VisualFabrique.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
1
2019-07-18T16:50:52.000Z
2019-07-18T16:50:52.000Z
15.2
42
0.815789
995,489
package com.intellij.testProject.fabrique; public class VisualFabrique { }
92307660b3d1ef4f6a1a2f00f46fd27b47155253
2,833
java
Java
src/test/java/paxos/fragmentation/FragmentingGroupTest.java
jaksa76/paxos
1b85fd97645c4f7830f7ed69c14550249088123c
[ "Apache-2.0" ]
78
2016-07-05T12:13:18.000Z
2022-03-27T05:04:45.000Z
src/test/java/paxos/fragmentation/FragmentingGroupTest.java
jaksa76/paxos
1b85fd97645c4f7830f7ed69c14550249088123c
[ "Apache-2.0" ]
18
2015-09-30T14:20:03.000Z
2016-01-29T14:53:29.000Z
src/test/java/paxos/fragmentation/FragmentingGroupTest.java
jaksa76/paxos
1b85fd97645c4f7830f7ed69c14550249088123c
[ "Apache-2.0" ]
31
2017-01-01T03:57:28.000Z
2022-03-31T14:23:00.000Z
36.320513
103
0.681257
995,490
package paxos.fragmentation; import org.hamcrest.CustomTypeSafeMatcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Test; import org.mockito.Mockito; import paxos.*; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.*; public class FragmentingGroupTest { @Test public void testNotFragmentingMessage() throws Exception { BasicGroup underlyingGroup = mock(BasicGroup.class); FragmentingGroup group = new FragmentingGroup(underlyingGroup, 0); group.broadcast(createMessageOfLength(60000)); verify(underlyingGroup, times(1)).broadcast(Mockito.<Serializable>any()); } @Test public void testFragmentingMessage() throws Exception { BasicGroup underlyingGroup = mock(BasicGroup.class); FragmentingGroup group = new FragmentingGroup(underlyingGroup, 0); group.broadcast(createMessageOfLength(3 * 64000 + 100)); verify(underlyingGroup, times(3)).broadcast(argThat(messageFragment(64000))); verify(underlyingGroup).broadcast(argThat(messageFragment(127))); } @Test public void testRecomposingMessage() throws Exception { Receiver receiver = mock(Receiver.class); FragmentingGroup.JoinerReceiver joinerReceiver = new FragmentingGroup.JoinerReceiver(receiver); joinerReceiver.receive(createMessageFragment(1, 0, 2)); joinerReceiver.receive(createMessageFragment(1, 1, 2)); joinerReceiver.receive(createMessageFragment(1, 2, 2)); verify(receiver).receive(eq(createMessageOfLength(200))); } private MessageFragment createMessageFragment(long id, int i, int parts) throws IOException { Serializable message = createMessageOfLength(parts * 100); byte[] allBytes = PaxosUtils.serialize(message); byte[] bytes = Arrays.copyOfRange(allBytes, i * 100, Math.min(i * 100 + 100, allBytes.length)); return new MessageFragment(id, bytes, i, parts + 1); } private TypeSafeMatcher<Serializable> messageFragment(final int length) { return new CustomTypeSafeMatcher<Serializable>("message of length " + length) { @Override protected boolean matchesSafely(Serializable serializable) { if (serializable instanceof MessageFragment) { MessageFragment messageFragment = (MessageFragment) serializable; return messageFragment.part.length == length; } return false; } }; } private byte[] createMessageOfLength(int length) { byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) (i%256); } return bytes; } }
923076cb9fda9a10404cbcb8f83db1de8503b448
2,722
java
Java
src/com/groupname/framework/serialization/xml/XMLParser.java
Nudua/semesteroppgave
904c4c3807272d3fb0bba98a82388b79908fd985
[ "MIT" ]
null
null
null
src/com/groupname/framework/serialization/xml/XMLParser.java
Nudua/semesteroppgave
904c4c3807272d3fb0bba98a82388b79908fd985
[ "MIT" ]
null
null
null
src/com/groupname/framework/serialization/xml/XMLParser.java
Nudua/semesteroppgave
904c4c3807272d3fb0bba98a82388b79908fd985
[ "MIT" ]
null
null
null
30.58427
138
0.592212
995,491
package com.groupname.framework.serialization.xml; import com.groupname.framework.util.Tuple; import com.groupname.framework.util.Strings; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A rudimentary XML parser. */ public class XMLParser { /** * Creates a new instance of this class. */ public XMLParser() { } /** * Attempts to parse a valid XML file and returns the class name of the root node * as well as all of it's nodes that represents the fields of the target class. * * @param fileName the XML file to read. * @return a Tuple that contains the className (item1) and a List of XMLNodes (item2) that contains the field names and values. * @throws XMLParseException if there was an issue parsing the XML file. */ public Tuple<String, List<XMLNode>> getFields(Path fileName) throws XMLParseException { List<XMLNode> nodes = new ArrayList<>(); try(BufferedReader reader = Files.newBufferedReader(fileName)) { String line; Pattern rootNodeStart = Pattern.compile("^<(?<RootStart>[a-zA-Z0-9.]+)>$"); String firstLine = reader.readLine(); if(Strings.isNullOrEmpty(firstLine)) { throw new XMLParseException(); } Matcher rootMatcher = rootNodeStart.matcher(firstLine); if(!rootMatcher.matches()) { throw new XMLParseException(); } String className = rootMatcher.group("RootStart"); // Each node (field) within every Pattern nodePattern = Pattern.compile("^<(?<StartTag>[a-zA-Z0-9]+)>(?<Value>.+)</(?<EndTag>[a-zA-Z0-9]+)>$"); //^<[a-zA-Z.]+>$ while ((line = reader.readLine()) != null) { line = line.trim(); Matcher nodeMatcher = nodePattern.matcher(line); if(nodeMatcher.matches()) { String startTag = nodeMatcher.group("StartTag"); String endTag = nodeMatcher.group("EndTag"); if(!startTag.equals(endTag)) { throw new XMLParseException("NewGame and end tag does not much for xml node"); } String value = nodeMatcher.group("Value"); nodes.add(new XMLNode(startTag, value)); } } return new Tuple<>(className, nodes); } catch (IOException exception) { throw new XMLParseException(); } } }
9230795c64d236f7571ae3ed423d42946d3227c9
284
java
Java
src/main/java/com/codetaylor/mc/artisanworktables/modules/worktables/tile/spi/ToolStackHandler.java
copygirl/artisan-worktables
7b0b21cb1186536577252ffc2be938d4a2027570
[ "Apache-2.0" ]
21
2018-01-06T16:57:49.000Z
2020-04-17T02:15:44.000Z
src/main/java/com/codetaylor/mc/artisanworktables/modules/worktables/tile/spi/ToolStackHandler.java
copygirl/artisan-worktables
7b0b21cb1186536577252ffc2be938d4a2027570
[ "Apache-2.0" ]
229
2017-12-30T02:42:35.000Z
2020-06-09T16:29:15.000Z
src/main/java/com/codetaylor/mc/artisanworktables/modules/worktables/tile/spi/ToolStackHandler.java
copygirl/artisan-worktables
7b0b21cb1186536577252ffc2be938d4a2027570
[ "Apache-2.0" ]
12
2017-12-30T00:44:17.000Z
2020-06-02T06:03:16.000Z
18.933333
72
0.767606
995,492
package com.codetaylor.mc.artisanworktables.modules.worktables.tile.spi; import com.codetaylor.mc.athenaeum.inventory.ObservableStackHandler; public class ToolStackHandler extends ObservableStackHandler { public ToolStackHandler( int size ) { super(size); } }
92307a418545cb6363116877adc71440cf14100b
785
java
Java
snail-core/snail-core-config/src/main/java/cn/tomsnail/snail/core/config/server/DefaultConfigChangeListener.java
tomsnail/snail-dev
df031a6b915774a9d67617f8cb3479ebd402d3a9
[ "Apache-2.0" ]
3
2019-03-13T10:22:43.000Z
2019-03-21T13:46:14.000Z
snail-core/snail-core-config/src/main/java/cn/tomsnail/snail/core/config/server/DefaultConfigChangeListener.java
tomsnail/snail-dev
df031a6b915774a9d67617f8cb3479ebd402d3a9
[ "Apache-2.0" ]
2
2019-04-20T14:33:41.000Z
2021-12-10T01:36:47.000Z
snail-core/snail-core-config/src/main/java/cn/tomsnail/snail/core/config/server/DefaultConfigChangeListener.java
tomsnail/snail-dev
df031a6b915774a9d67617f8cb3479ebd402d3a9
[ "Apache-2.0" ]
1
2018-08-21T14:07:39.000Z
2018-08-21T14:07:39.000Z
19.625
78
0.733758
995,493
package cn.tomsnail.snail.core.config.server; import java.util.List; /** * 默认的配置变化监听者 * @author yangsong * @version 0.0.1 * @status 正常 * @date 2016年9月21日 下午3:54:28 * @see */ public class DefaultConfigChangeListener implements IConfigChangeListener{ /** * 监听者列表 */ private List<IConfigChangeListener> changeListeners; @Override public void changed(String path, String value, int type) { if(changeListeners!=null){ for(IConfigChangeListener changeListener:changeListeners){ changeListener.changed(path, value, type); } } } public List<IConfigChangeListener> getChangeListeners() { return changeListeners; } public void setChangeListeners(List<IConfigChangeListener> changeListeners) { this.changeListeners = changeListeners; } }
92307a808e64ce0d330f0a67f33b818a2e61f337
2,285
java
Java
src/test/java/de/davelee/trams/crm/model/UserTest.java
daveajlee/trams-crm
3d8a7376259f19f32682ba48a74d54f39514dde5
[ "Apache-2.0" ]
null
null
null
src/test/java/de/davelee/trams/crm/model/UserTest.java
daveajlee/trams-crm
3d8a7376259f19f32682ba48a74d54f39514dde5
[ "Apache-2.0" ]
null
null
null
src/test/java/de/davelee/trams/crm/model/UserTest.java
daveajlee/trams-crm
3d8a7376259f19f32682ba48a74d54f39514dde5
[ "Apache-2.0" ]
null
null
null
35.153846
77
0.627571
995,494
package de.davelee.trams.crm.model; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; /** * Test cases for the <class>User</class> class which are not covered * by other tests. * @author Dave Lee */ public class UserTest { @Test /** * Test case: build a <code>User</code> object and return string of it. * Expected Result: valid values and string. */ public void testBuilderToString() { User user = User.builder() .firstName("Max") .lastName("Mustermann") .company("Example Company") .userName("mmustermann") .password("test123") .role("Admin") .accountStatus(UserAccountStatus.ACTIVE) .build(); assertEquals("Max", user.getFirstName()); assertEquals("Mustermann", user.getLastName()); assertEquals("Example Company", user.getCompany()); assertEquals("mmustermann", user.getUserName()); assertEquals("test123", user.getPassword()); assertEquals("Admin", user.getRole()); assertEquals(UserAccountStatus.ACTIVE, user.getAccountStatus()); } @Test /** * Test case: construct an empty <code>User</code> object * fill it with values through setters and return string of it. * Expected Result: valid values and string. */ public void testSettersToString() { User user = new User(); user.setFirstName("Max"); user.setLastName("Mustermann"); user.setCompany("Example Company"); user.setUserName("mmustermann"); user.setPassword("test123"); user.setRole("Admin"); user.setAccountStatus(UserAccountStatus.DEACTIVATED); assertNull(user.getId()); assertEquals("Max", user.getFirstName()); assertEquals("Mustermann", user.getLastName()); assertEquals("Example Company", user.getCompany()); assertEquals("mmustermann", user.getUserName()); assertEquals("test123", user.getPassword()); assertEquals("Admin", user.getRole()); assertEquals(UserAccountStatus.DEACTIVATED, user.getAccountStatus()); } }
92307ac0968af9d5d0c60de4f97b20ed3dbd6ba0
3,608
java
Java
app/src/main/java/com/pcchin/loginsys/GeneralFunctions.java
pc-chin/login-system
3da9aa04cd0ef14153247f5f21d1fb9053107e9e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/pcchin/loginsys/GeneralFunctions.java
pc-chin/login-system
3da9aa04cd0ef14153247f5f21d1fb9053107e9e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/pcchin/loginsys/GeneralFunctions.java
pc-chin/login-system
3da9aa04cd0ef14153247f5f21d1fb9053107e9e
[ "Apache-2.0" ]
null
null
null
37.195876
102
0.672949
995,495
package com.pcchin.loginsys; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import org.bouncycastle.crypto.PBEParametersGenerator; import org.bouncycastle.crypto.engines.BlowfishEngine; import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jcajce.provider.digest.SHA3; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.Security; class GeneralFunctions { // Static variables: Creation date, User ID, Device ID (GUID) // Encryption (Salt) : AES, Blowfish, RSA // Hashing (Password, restore code) : SHA, PBKDF2 private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); // Password: Salt, GUID // Code: Salt, creation date // Admin code: GUID * 2 @Contract("_, _, _ -> new") @NotNull static String passwordHash(@NotNull String original, @NotNull String salt, @NotNull String guid) { byte[] originalByte; // 1) PBKDF2 with salt PBEParametersGenerator pbkdfSaltGen = new PKCS5S2ParametersGenerator(); pbkdfSaltGen.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(original.toCharArray()), salt.getBytes(), 20000); KeyParameter saltParams = (KeyParameter)pbkdfSaltGen.generateDerivedParameters(128); originalByte = saltParams.getKey(); // 2) SHA Security.addProvider(new BouncyCastleProvider()); MessageDigest shaDigest = new SHA3.Digest512(); originalByte = shaDigest.digest(originalByte); // 3) Blowfish with GUID BlowfishEngine blowfishEngine = new BlowfishEngine(); blowfishEngine.init(true, new KeyParameter(guid.getBytes())); byte[] responseByte = new byte[originalByte.length]; blowfishEngine.processBlock(originalByte, original.length(), responseByte, 0); return bytesToHex(responseByte); } // Only used in passhash(), separated for clarity @NotNull @Contract("_ -> new") private static String bytesToHex(@NotNull byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } static void storeBitmap(@NotNull Bitmap bitmap, String fullPath) { try { FileOutputStream fileOutputStream = new FileOutputStream(new File(fullPath), false); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream); fileOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } static Bitmap getBitmap(String fullPath) { Bitmap bitmap = null; try { FileInputStream fileInputStream = new FileInputStream(new File(fullPath)); bitmap = BitmapFactory.decodeStream(fileInputStream); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } }
92307b66ded3543f7092ea20887ea22e017d3a41
2,897
java
Java
sdk-libs/halo-content/src/main/java/com/mobgen/halo/android/content/generated/GeneratedContentQueriesLocalDataSource.java
jandrop/halo-android
3dcce9852153d86ed698c7e0c5f1a5fed535f57d
[ "Apache-2.0" ]
6
2016-11-02T12:28:37.000Z
2020-01-10T11:02:01.000Z
sdk-libs/halo-content/src/main/java/com/mobgen/halo/android/content/generated/GeneratedContentQueriesLocalDataSource.java
jandrop/halo-android
3dcce9852153d86ed698c7e0c5f1a5fed535f57d
[ "Apache-2.0" ]
4
2016-11-21T12:32:04.000Z
2018-02-09T11:40:51.000Z
sdk-libs/halo-content/src/main/java/com/mobgen/halo/android/content/generated/GeneratedContentQueriesLocalDataSource.java
jandrop/halo-android
3dcce9852153d86ed698c7e0c5f1a5fed535f57d
[ "Apache-2.0" ]
4
2017-10-03T12:44:21.000Z
2020-01-07T15:34:54.000Z
37.141026
118
0.662409
995,496
package com.mobgen.halo.android.content.generated; import android.database.Cursor; import android.database.SQLException; import android.support.annotation.BoolRes; import android.support.annotation.Keep; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.mobgen.halo.android.content.models.GeneratedContent; import com.mobgen.halo.android.content.models.HaloContentInstance; import com.mobgen.halo.android.content.spec.HaloContentContract; import com.mobgen.halo.android.framework.api.HaloFramework; import com.mobgen.halo.android.framework.common.exceptions.HaloParsingException; import com.mobgen.halo.android.framework.storage.database.HaloDataLite; import com.mobgen.halo.android.sdk.api.Halo; import java.util.Date; /** * The data source to perfom queries against local database. */ @Keep public class GeneratedContentQueriesLocalDataSource { /** * Helper to perfom operation on databse */ private HaloDataLite mDataLite; /** * The constructor of the local data source. * @param haloFramework The framewrok. */ public GeneratedContentQueriesLocalDataSource(@NonNull HaloFramework haloFramework) { mDataLite = haloFramework.storage(HaloContentContract.HALO_CONTENT_STORAGE).db(); } /** * Perfom the query against dabase from annotated code. * * @param query the query to perfom. * @param bindArgs the args to the query. * @return A cursor raw response from databse * @throws SQLException */ @Nullable public Cursor perfomQuery(@NonNull String query,@NonNull Object[] bindArgs) throws SQLException { //convert obects to string to perfom raw queries int length = bindArgs.length; String[] bindstringArgs = new String[length]; for(int i=0;i<length;i++){ if(bindArgs[i]==null){ bindstringArgs[i] = ""; } else if(bindArgs[i] instanceof String) { bindstringArgs[i] = (String)bindArgs[i]; } else if(bindArgs[i] instanceof Integer) { bindstringArgs[i] = bindArgs[i].toString(); } else if(bindArgs[i] instanceof Date) { bindstringArgs[i] = String.valueOf(((Date)bindArgs[i]).getTime()); } else if(bindArgs[i] instanceof Boolean) { bindstringArgs[i] = String.valueOf(bindArgs[i]); } else { try { bindstringArgs[i] = GeneratedContent.serialize(bindArgs[i], Halo.instance().framework().parser()); } catch (HaloParsingException e) { bindstringArgs[i] = ""; } } } Cursor rawResult = mDataLite.getDatabase().rawQuery(query,bindstringArgs); if(rawResult!=null) { rawResult.moveToFirst(); } return rawResult; } }
92307bf40f68f917b1725222603e8a7ac464280f
1,635
java
Java
application-information/src/main/java/ru/art/information/mapping/StatusResponseMapper.java
art-community/art-applications
b72c343266cb948a90f835ae58fdf0aeea7dc481
[ "Apache-2.0" ]
null
null
null
application-information/src/main/java/ru/art/information/mapping/StatusResponseMapper.java
art-community/art-applications
b72c343266cb948a90f835ae58fdf0aeea7dc481
[ "Apache-2.0" ]
null
null
null
application-information/src/main/java/ru/art/information/mapping/StatusResponseMapper.java
art-community/art-applications
b72c343266cb948a90f835ae58fdf0aeea7dc481
[ "Apache-2.0" ]
null
null
null
33.367347
118
0.743731
995,497
/* * ART Java * * Copyright 2019 ART * * 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 ru.art.information.mapping; import ru.art.entity.*; import ru.art.entity.mapper.*; import ru.art.information.model.*; import static ru.art.core.checker.CheckerForEmptiness.*; public interface StatusResponseMapper { String http = "http"; String grpc = "grpc"; String rsocketTcp = "rsocketTcp"; String rsocketWebSocket = "rsocketWebSocket"; ValueToModelMapper<StatusResponse, Entity> toStatusResponse = entity -> isNotEmpty(entity) ? StatusResponse.builder() .http(entity.getBool(http)) .grpc(entity.getBool(grpc)) .rsocketTcp(entity.getBool(rsocketTcp)) .rsocketWebSocket(entity.getBool(rsocketWebSocket)) .build() : StatusResponse.builder().build(); ValueFromModelMapper<StatusResponse, Entity> fromStatusResponse = model -> isNotEmpty(model) ? Entity.entityBuilder() .boolField(http, model.isHttp()) .boolField(grpc, model.isGrpc()) .boolField(rsocketTcp, model.isRsocketTcp()) .boolField(rsocketWebSocket, model.isRsocketWebSocket()) .build() : Entity.entityBuilder().build(); }
92307cb127ebf4d6c9c8fcf60f5ce68ef0d55b26
10,271
java
Java
src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java
JM-Lab/utils-elasticsearch
400ff2eaa11f760cbceeba1b0a13366f6f2df2ec
[ "Apache-2.0" ]
4
2015-09-21T02:56:06.000Z
2018-06-12T07:22:30.000Z
src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java
JM-Lab/utils-elasticsearch
400ff2eaa11f760cbceeba1b0a13366f6f2df2ec
[ "Apache-2.0" ]
3
2020-04-23T17:27:02.000Z
2020-07-22T23:27:08.000Z
src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java
JM-Lab/utils-elasticsearch
400ff2eaa11f760cbceeba1b0a13366f6f2df2ec
[ "Apache-2.0" ]
1
2015-09-22T06:48:09.000Z
2015-09-22T06:48:09.000Z
33.456026
120
0.66605
995,498
package kr.jm.utils.elasticsearch; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequestBuilder; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.xcontent.XContentType; import java.util.Map; /** * The type Jm elasticsearch index. */ public class JMElasticsearchIndex { private final Client jmESClient; /** * Instantiates a new Jm elasticsearch index. * * @param elasticsearchClient the elasticsearch client */ public JMElasticsearchIndex(Client elasticsearchClient) { this.jmESClient = elasticsearchClient; } /** * Index query index response. * * @param indexRequestBuilder the index request builder * @return the index response */ public IndexResponse indexQuery(IndexRequestBuilder indexRequestBuilder) { return JMElasticsearchUtil .logRequestQueryAndReturn("indexQuery", indexRequestBuilder, indexRequestBuilder.execute()); } /** * Index query async action future. * * @param indexRequestBuilder the index request builder * @return the action future */ public ActionFuture<IndexResponse> indexQueryAsync(IndexRequestBuilder indexRequestBuilder) { return JMElasticsearchUtil.logRequestQuery("indexQueryAsync", indexRequestBuilder).execute(); } private IndexRequestBuilder buildIndexRequest(String index, String id, String jsonSource) { return buildIndexRequest(index, id, JMElasticsearchUtil.buildSourceByJsonMapper(jsonSource)); } private IndexRequestBuilder buildIndexRequest(String index, String id, Map<String, Object> source) { return getPrepareIndex(index, id).setSource(source); } private IndexRequestBuilder getPrepareIndex(String index, String id) { return id == null ? jmESClient.prepareIndex().setIndex(index) : jmESClient.prepareIndex().setIndex(index) .setId(id); } private UpdateRequestBuilder buildPrepareUpsert(String index, String id, String jsonString) { return jmESClient.prepareUpdate().setIndex(index).setId(id).setDoc(jsonString, XContentType.JSON) .setUpsert(new IndexRequest(index).id(id).source(jsonString, XContentType.JSON)); } private UpdateRequestBuilder buildPrepareUpsert(String index, String id, Map<String, Object> source) { return jmESClient.prepareUpdate().setIndex(index).setId(id).setDoc(source) .setUpsert(new IndexRequest(index).id(id).source(source)); } /** * Upsert query update response. * * @param updateRequestBuilder the update request builder * @return the update response */ public UpdateResponse upsertQuery(UpdateRequestBuilder updateRequestBuilder) { return JMElasticsearchUtil.logRequestQueryAndReturn("upsertQuery", updateRequestBuilder, updateRequestBuilder.execute()); } /** * Upsert query async action future. * * @param updateRequestBuilder the update request builder * @return the action future */ public ActionFuture<UpdateResponse> upsertQueryAsync(UpdateRequestBuilder updateRequestBuilder) { return JMElasticsearchUtil.logRequestQuery("upsertQueryAsync", updateRequestBuilder).execute(); } /** * Upsert data update response. * * @param index the index * @param id the id * @param source the source * @return the update response */ public UpdateResponse upsertData(String index, String id, Map<String, Object> source) { return upsertQuery(buildPrepareUpsert(index, id, source)); } /** * Upsert data async action future. * * @param index the index * @param id the id * @param source the source * @return the action future */ public ActionFuture<UpdateResponse> upsertDataAsync(String index, String id, Map<String, Object> source) { return upsertQueryAsync(buildPrepareUpsert(index, id, source)); } /** * Upsert data update response. * * @param index the index * @param id the id * @param jsonSource the json source * @return the update response */ public UpdateResponse upsertData(String index, String id, String jsonSource) { return upsertQuery(buildPrepareUpsert(index, id, jsonSource)); } /** * Upsert data async action future. * * @param index the index * @param id the id * @param jsonSource the json source * @return the action future */ public ActionFuture<UpdateResponse> upsertDataAsync(String index, String id, String jsonSource) { return upsertQueryAsync(buildPrepareUpsert(index, id, jsonSource)); } /** * Upsert data with object mapper update response. * * @param index the index * @param id the id * @param sourceObject the source object * @return the update response */ public UpdateResponse upsertDataWithObjectMapper(String index, String id, Object sourceObject) { return upsertData(index, id, JMElasticsearchUtil.buildSourceByJsonMapper(sourceObject)); } /** * Upsert data a sync with object mapper action future. * * @param index the index * @param id the id * @param sourceObject the source object * @return the action future */ public ActionFuture<UpdateResponse> upsertDataASyncWithObjectMapper(String index, String id, Object sourceObject) { return upsertDataAsync(index, id, JMElasticsearchUtil.buildSourceByJsonMapper(sourceObject)); } /** * Send data index response. * * @param index the index * @param id the id * @param source the source * @return the index response */ public IndexResponse sendData(String index, String id, Map<String, Object> source) { return indexQuery(buildIndexRequest(index, id, source)); } /** * Send data string. * * @param index the index * @param source the source * @return the string */ public String sendData(String index, Map<String, Object> source) { return sendData(index, null, source).getId(); } /** * Send data index response. * * @param index the index * @param id the id * @param jsonSource the json source * @return the index response */ public IndexResponse sendData(String index, String id, String jsonSource) { return indexQuery(buildIndexRequest(index, id, jsonSource)); } /** * Send data string. * * @param index the index * @param jsonSource the json source * @return the string */ public String sendData(String index, String jsonSource) { return sendData(index, null, jsonSource).getId(); } /** * Send data with object mapper index response. * * @param index the index * @param id the id * @param sourceObject the source object * @return the index response */ public IndexResponse sendDataWithObjectMapper(String index, String id, Object sourceObject) { return sendData(index, id, JMElasticsearchUtil.buildSourceByJsonMapper(sourceObject)); } /** * Send data with object mapper string. * * @param index the index * @param sourceObject the source object * @return the string */ public String sendDataWithObjectMapper(String index, Object sourceObject) { return sendDataWithObjectMapper(index, null, sourceObject).getId(); } /** * Send data async action future. * * @param index the index * @param id the id * @param source the source * @return the action future */ public ActionFuture<IndexResponse> sendDataAsync(String index, String id, Map<String, Object> source) { return indexQueryAsync(buildIndexRequest(index, id, source)); } /** * Send data async action future. * * @param index the index * @param source the source * @return the action future */ public ActionFuture<IndexResponse> sendDataAsync(String index, Map<String, Object> source) { return indexQueryAsync(buildIndexRequest(index, null, source)); } /** * Send data async action future. * * @param index the index * @param id the id * @param jsonSource the json source * @return the action future */ public ActionFuture<IndexResponse> sendDataAsync(String index, String id, String jsonSource) { return indexQueryAsync(buildIndexRequest(index, id, jsonSource)); } /** * Send data async action future. * * @param index the index * @param jsonSource the json source * @return the action future */ public ActionFuture<IndexResponse> sendDataAsync(String index, String jsonSource) { return indexQueryAsync(buildIndexRequest(index, null, jsonSource)); } /** * Send data async with object mapper action future. * * @param index the index * @param id the id * @param sourceObject the source object * @return the action future */ public ActionFuture<IndexResponse> sendDataAsyncWithObjectMapper(String index, String id, Object sourceObject) { return indexQueryAsync(buildIndexRequest(index, id, JMElasticsearchUtil.buildSourceByJsonMapper(sourceObject))); } /** * Send data async with object mapper action future. * * @param index the index * @param sourceObject the source object * @return the action future */ public ActionFuture<IndexResponse> sendDataAsyncWithObjectMapper(String index, Object sourceObject) { return indexQueryAsync( buildIndexRequest(index, null, JMElasticsearchUtil.buildSourceByJsonMapper(sourceObject))); } }
92307ec42980946252786f279870a181263cc016
4,414
java
Java
components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeJmsMapMessageTest.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeJmsMapMessageTest.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeJmsMapMessageTest.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
35.312
94
0.70299
995,499
/* * 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.camel.component.jms; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.jms.MapMessage; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.support.ExchangeHelper; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jms.core.JmsTemplate; import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class ConsumeJmsMapMessageTest extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(ConsumeJmsMapMessageTest.class); protected JmsTemplate jmsTemplate; private MockEndpoint endpoint; @Test public void testConsumeMapMessage() throws Exception { endpoint.expectedMessageCount(1); jmsTemplate.setPubSubDomain(false); jmsTemplate.send("test.map", session -> { MapMessage mapMessage = session.createMapMessage(); mapMessage.setString("foo", "abc"); mapMessage.setString("bar", "xyz"); return mapMessage; }); endpoint.assertIsSatisfied(); assertCorrectMapReceived(); } protected void assertCorrectMapReceived() { Exchange exchange = endpoint.getReceivedExchanges().get(0); // This should be a JMS Exchange assertNotNull(ExchangeHelper.getBinding(exchange, JmsBinding.class)); JmsMessage in = (JmsMessage) exchange.getIn(); assertNotNull(in); Map<?, ?> map = exchange.getIn().getBody(Map.class); LOG.info("Received map: " + map); assertNotNull(map, "Should have received a map message!"); assertIsInstanceOf(MapMessage.class, in.getJmsMessage()); assertEquals("abc", map.get("foo"), "map.foo"); assertEquals("xyz", map.get("bar"), "map.bar"); assertEquals(2, map.size(), "map.size"); } @Test public void testSendMapMessage() throws Exception { endpoint.expectedMessageCount(1); Map<String, String> map = new HashMap<>(); map.put("foo", "abc"); map.put("bar", "xyz"); template.sendBody("direct:test", map); endpoint.assertIsSatisfied(); assertCorrectMapReceived(); } @Override @BeforeEach public void setUp() throws Exception { super.setUp(); endpoint = getMockEndpoint("mock:result"); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); jmsTemplate = new JmsTemplate(connectionFactory); camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("activemq:test.map").to("mock:result"); from("direct:test").to("activemq:test.map"); } }; } }
92307f1f2d055ad9136417f534a1bdd64d67d62e
4,891
java
Java
rxmicro-annotation-processor-data-mongo/src/test/resources/output/io.rxmicro.examples.data.mongo.model.fields/reflection/model/$$EntityEntityFromMongoDBConverter.java
rxmicro/rxmicro
ce2648101ddd2ba02c06d90078fc15fcee1d6a9f
[ "Apache-2.0" ]
5
2020-03-20T12:27:25.000Z
2022-03-30T08:36:59.000Z
rxmicro-annotation-processor-data-mongo/src/test/resources/output/io.rxmicro.examples.data.mongo.model.fields/reflection/model/$$EntityEntityFromMongoDBConverter.java
rxmicro/rxmicro
ce2648101ddd2ba02c06d90078fc15fcee1d6a9f
[ "Apache-2.0" ]
1
2021-02-01T18:48:56.000Z
2021-02-02T18:07:05.000Z
rxmicro-annotation-processor-data-mongo/src/test/resources/output/io.rxmicro.examples.data.mongo.model.fields/reflection/model/$$EntityEntityFromMongoDBConverter.java
rxmicro/rxmicro
ce2648101ddd2ba02c06d90078fc15fcee1d6a9f
[ "Apache-2.0" ]
null
null
null
75.246154
167
0.715396
995,500
package io.rxmicro.examples.data.mongo.model.fields.reflection.model; import io.rxmicro.data.mongo.detail.EntityFromMongoDBConverter; import io.rxmicro.examples.data.mongo.model.fields.Status; import io.rxmicro.examples.data.mongo.model.fields.reflection.model.nested.$$NestedEntityFromMongoDBConverter; import org.bson.Document; import static rxmicro.$$Reflections.setFieldValue; /** * Generated by {@code RxMicro Annotation Processor} */ public final class $$EntityEntityFromMongoDBConverter extends EntityFromMongoDBConverter<Document, Entity> { private final $$NestedEntityFromMongoDBConverter nestedEntityFromMongoDBConverter = new $$NestedEntityFromMongoDBConverter(); @Override public Entity fromDB(final Document document) { final Entity model = new Entity(); setFieldValue(model, "id", toObjectId(document.get("_id"), "id")); setFieldValue(model, "status", toEnum(Status.class, document.get("status"), "status")); setFieldValue(model, "statusList", toEnumList(Status.class, document.get("statusList"), "statusList")); setFieldValue(model, "aBoolean", toBoolean(document.get("aBoolean"), "aBoolean")); setFieldValue(model, "booleanList", toBooleanList(document.get("booleanList"), "booleanList")); setFieldValue(model, "aByte", toByte(document.get("aByte"), "aByte")); setFieldValue(model, "byteList", toByteList(document.get("byteList"), "byteList")); setFieldValue(model, "aShort", toShort(document.get("aShort"), "aShort")); setFieldValue(model, "shortList", toShortList(document.get("shortList"), "shortList")); setFieldValue(model, "aInteger", toInteger(document.get("aInteger"), "aInteger")); setFieldValue(model, "integerList", toIntegerList(document.get("integerList"), "integerList")); setFieldValue(model, "aLong", toLong(document.get("aLong"), "aLong")); setFieldValue(model, "longList", toLongList(document.get("longList"), "longList")); setFieldValue(model, "aFloat", toFloat(document.get("aFloat"), "aFloat")); setFieldValue(model, "floatList", toFloatList(document.get("floatList"), "floatList")); setFieldValue(model, "aDouble", toDouble(document.get("aDouble"), "aDouble")); setFieldValue(model, "doubleList", toDoubleList(document.get("doubleList"), "doubleList")); setFieldValue(model, "bigDecimal", toBigDecimal(document.get("bigDecimal"), "bigDecimal")); setFieldValue(model, "bigDecimalList", toBigDecimalList(document.get("bigDecimalList"), "bigDecimalList")); setFieldValue(model, "character", toCharacter(document.get("character"), "character")); setFieldValue(model, "characterList", toCharacterList(document.get("characterList"), "characterList")); setFieldValue(model, "string", toString(document.get("string"), "string")); setFieldValue(model, "stringList", toStringList(document.get("stringList"), "stringList")); setFieldValue(model, "pattern", toPattern(document.get("pattern"), "pattern")); setFieldValue(model, "patternList", toPatternList(document.get("patternList"), "patternList")); setFieldValue(model, "instant", toInstant(document.get("instant"), "instant")); setFieldValue(model, "instantList", toInstantList(document.get("instantList"), "instantList")); setFieldValue(model, "localDate", toLocalDate(document.get("localDate"), "localDate")); setFieldValue(model, "localDateList", toLocalDateList(document.get("localDateList"), "localDateList")); setFieldValue(model, "localDateTime", toLocalDateTime(document.get("localDateTime"), "localDateTime")); setFieldValue(model, "localDateTimeList", toLocalDateTimeList(document.get("localDateTimeList"), "localDateTimeList")); setFieldValue(model, "localTime", toLocalTime(document.get("localTime"), "localTime")); setFieldValue(model, "localTimeList", toLocalTimeList(document.get("localTimeList"), "localTimeList")); setFieldValue(model, "uuid", toUUID(document.get("uuid"), "uuid")); setFieldValue(model, "uuidList", toUUIDList(document.get("uuidList"), "uuidList")); setFieldValue(model, "code", toCode(document.get("code"), "code")); setFieldValue(model, "codeList", toCodeList(document.get("codeList"), "codeList")); setFieldValue(model, "binary", toBinary(document.get("binary"), "binary")); setFieldValue(model, "binaryList", toBinaryList(document.get("binaryList"), "binaryList")); setFieldValue(model, "nested", convertToObjectIfNotNull(nestedEntityFromMongoDBConverter, toType(Document.class, document.get("nested"), "nested"))); setFieldValue(model, "nestedList", convertToListIfNotNull(nestedEntityFromMongoDBConverter, toList(Document.class, document.get("nestedList"), "nestedList"))); return model; } }
92307f452b2ab198603ce3e50707379600919205
2,425
java
Java
garage-server/src/main/java/com/yixin/garage/enums/RoleEnum.java
Blithe66/garage-server-dev
964a04fb7569117900dcd72b8c9d4b8ec2a83b07
[ "Apache-2.0" ]
null
null
null
garage-server/src/main/java/com/yixin/garage/enums/RoleEnum.java
Blithe66/garage-server-dev
964a04fb7569117900dcd72b8c9d4b8ec2a83b07
[ "Apache-2.0" ]
3
2020-07-18T16:44:32.000Z
2021-09-20T20:53:23.000Z
garage-server/src/main/java/com/yixin/garage/enums/RoleEnum.java
Blithe66/garage-server-dev
964a04fb7569117900dcd72b8c9d4b8ec2a83b07
[ "Apache-2.0" ]
2
2021-07-12T03:55:26.000Z
2021-09-15T09:55:32.000Z
23.77451
87
0.715464
995,501
package com.yixin.garage.enums; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.yixin.garage.util.ConfigUtil; /** * 系统角色枚举 */ public enum RoleEnum { //安全车库 GARAGE_MANAGE_ROLE("garageRole.garageManageRoleId","车库管理员","车库管理员"), //安全车库 DISPOSE_COMMISSIONER_ROLE("garageRole.disposeCommissionerRoleId","自建库处置专员","自建库处置专员"), //安全车库 ASSETS_COMMISSIONER_ROLE("garageRole.assetsCommissionerRoleId","资产经理","资产经理"), //安全车库 - 车库一览 GARAGE_CHECKLIST_ROLE("garageRole.garageChecklistRoleId","车库一览","车库一览"), ; RoleEnum(String roleName,String jobName) { this.roleName = roleName; this.jobName = jobName; } RoleEnum(String roleName, String jobName, String roleShortName) { this.roleName = roleName; this.jobName = jobName; this.roleShortName = roleShortName; } private String roleName; private String jobName; private String roleShortName; private static Map<String,RoleEnum> roleNameMap; public String getJobName() { return jobName; } public String getRoleName() { return roleName; } public String getRoleShortName(){ return roleShortName; } static { buildMap(); } private static void buildMap(){ roleNameMap = new HashMap<>(); for(RoleEnum one: RoleEnum.values()){ roleNameMap.put(one.getRoleName(), one); } } public static boolean contains(String roleName) { if(roleNameMap==null||roleNameMap.isEmpty()){ buildMap(); } return roleNameMap.containsKey(roleName); } public static RoleEnum getEnumByRoleName(String roleName) { return roleNameMap.get(roleName); } public boolean equals(RoleEnum userRole){ if(userRole == null)return false; return this.roleName.equals(userRole.getRoleName()); } private final String ROLE_PREFIX = "garage.role."; public String getRoleId(){ String roleId = ConfigUtil.getValue(this.getRoleName(),""); if(StringUtils.isBlank(roleId)){ roleId = ConfigUtil.getValue(ROLE_PREFIX+this.getRoleName(),""); } return roleId; } public static List<RoleEnum> getRoleListByBusiType(String roelBusiType) { List<RoleEnum> roleList = new ArrayList<>(); for(RoleEnum roleEnum : RoleEnum.values()){ if(roleEnum.getRoleName().contains(roelBusiType)){ roleList.add(roleEnum); } } return roleList; } }
9230806674c7e735d2e7c382c00131991b79b451
2,949
java
Java
HW05 - Simple Hash Table/src/hr/fer/zemris/java/tecaj/hw5/db/StudentRecord.java
tiendung690/JavaCourse
fff7d3077029344a8319c8da2bf09753475c8b0d
[ "MIT" ]
null
null
null
HW05 - Simple Hash Table/src/hr/fer/zemris/java/tecaj/hw5/db/StudentRecord.java
tiendung690/JavaCourse
fff7d3077029344a8319c8da2bf09753475c8b0d
[ "MIT" ]
null
null
null
HW05 - Simple Hash Table/src/hr/fer/zemris/java/tecaj/hw5/db/StudentRecord.java
tiendung690/JavaCourse
fff7d3077029344a8319c8da2bf09753475c8b0d
[ "MIT" ]
1
2017-07-20T11:05:19.000Z
2017-07-20T11:05:19.000Z
23.039063
88
0.646321
995,502
package hr.fer.zemris.java.tecaj.hw5.db; /** * A record containing all the data about a single student. Every student has * his/her jmbag number which is unique for every student. The student also has * a first name, last name and a final grade. * * @author Kristijan Vulinovic * @version 1.0 */ public class StudentRecord { /** The student's jmbag. */ private final String jmbag; /** The student's last name. */ private String lastName; /** The student's first name. */ private String firstName; /** The student's final grade. */ private int finalGrade; /** * Creates a new {@code StudentRecord} with the values given in the * arguments. * * @param jmbag * the jmbag of the student. * @param lastName * the student's last name. * @param firstName * the student's first name. * @param finalGrade * the student's final grade. */ public StudentRecord(String jmbag, String lastName, String firstName, int finalGrade) { super(); this.jmbag = jmbag; this.lastName = lastName; this.firstName = firstName; this.finalGrade = finalGrade; } /** * Returns the last name of the student. * * @return the last name of the student. */ public String getLastName() { return lastName; } /** * Sets the last name of the student to the new value. * * @param lastName * the new value for the student's last name. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Returns the first name of the student. * * @return the first name of the student. */ public String getFirstName() { return firstName; } /** * Sets the first name of the student to the new value. * * @param firstName * the new value for the student's first name. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Returns the final grade of the student. * * @return the final grade of the student. */ public int getFinalGrade() { return finalGrade; } /** * Sets the final grade of the student to the new value. * * @param finalGrade * the new value for the student's final grade. */ public void setFinalGrade(int finalGrade) { this.finalGrade = finalGrade; } /** * Returns the jmbag of the student. * * @return the jmbag of the student. */ public String getJmbag() { return jmbag; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((jmbag == null) ? 0 : jmbag.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StudentRecord other = (StudentRecord) obj; if (jmbag == null) { if (other.jmbag != null) return false; } else if (!jmbag.equals(other.jmbag)) return false; return true; } }
923080af1bacbb7bb5fe16bada659559265cc880
703
java
Java
src/main/java/com/sunshine/cloudhttp/constant/HttpCode.java
WangJunnan/cloudhttp
2097220727ff61e5acf4312fd924f4262cc7cae8
[ "MIT" ]
1
2019-04-13T11:57:39.000Z
2019-04-13T11:57:39.000Z
src/main/java/com/sunshine/cloudhttp/constant/HttpCode.java
WangJunnan/cloudhttp
2097220727ff61e5acf4312fd924f4262cc7cae8
[ "MIT" ]
null
null
null
src/main/java/com/sunshine/cloudhttp/constant/HttpCode.java
WangJunnan/cloudhttp
2097220727ff61e5acf4312fd924f4262cc7cae8
[ "MIT" ]
2
2020-03-02T03:01:21.000Z
2020-03-05T14:28:26.000Z
15.622222
45
0.561878
995,503
package com.sunshine.cloudhttp.constant; /** * HttpCode * * @author wangjn * @date 2019/3/31 */ public enum HttpCode { STATUS_200(200, "OK"), STATUS_400(400, "Bad Request"), STATUS_403(403, "Forbidden"), STATUS_404(404, "Not Found"), /** * 永久重定向 */ STATUS_301(301, "Moved Permanently"), /** * 临时重定向 */ STATUS_302(302, "Found"), STATUS_500(500, "Internal Server Error"); HttpCode(Integer code, String msg) { this.code = code; this.msg = msg; } private Integer code; private String msg; public Integer getCode() { return code; } public String getMsg() { return msg; } }
923080cf4b9875dcacfa3cc4d9141ba181671082
1,473
java
Java
data/beaconrestapi/src/main/java/tech/pegasys/artemis/beaconrestapi/RestApiConstants.java
saltiniroberto/teku
6fc48e3bd7e27199468e3320baa17afd0aa1374f
[ "Apache-2.0" ]
null
null
null
data/beaconrestapi/src/main/java/tech/pegasys/artemis/beaconrestapi/RestApiConstants.java
saltiniroberto/teku
6fc48e3bd7e27199468e3320baa17afd0aa1374f
[ "Apache-2.0" ]
null
null
null
data/beaconrestapi/src/main/java/tech/pegasys/artemis/beaconrestapi/RestApiConstants.java
saltiniroberto/teku
6fc48e3bd7e27199468e3320baa17afd0aa1374f
[ "Apache-2.0" ]
null
null
null
43.323529
118
0.751527
995,504
/* * Copyright 2020 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package tech.pegasys.artemis.beaconrestapi; public class RestApiConstants { public static final String ROOT = "root"; public static final String SLOT = "slot"; public static final String EPOCH = "epoch"; public static final String TAG_BEACON = "Beacon"; public static final String TAG_NODE = "Node"; public static final String TAG_NETWORK = "Network"; public static final String RES_OK = "200"; // SC_OK public static final String RES_NO_CONTENT = "204"; // SC_NO_CONTENT public static final String RES_BAD_REQUEST = "400"; // SC_BAD_REQUEST public static final String RES_NOT_FOUND = "404"; // SC_NOT_FOUND public static final String RES_INTERNAL_ERROR = "500"; // SC_INTERNAL_SERVER_ERROR public static final String NO_CONTENT_PRE_GENESIS = "No content may be returned if the genesis block has not been set, meaning that there is no head to query."; }
9230813d77389591ba2292102adfdd580b9437e0
481
java
Java
jvm-playground/src/main/java/com/github/prologdb/runtime/playground/jvm/persistence/NullPlaygroundStatePersistenceService.java
prologdb/kotlin-prolog
e675375437ed22144ed14b06639dd0a9835c4e67
[ "MIT" ]
2
2019-06-26T19:35:36.000Z
2020-08-03T02:54:35.000Z
jvm-playground/src/main/java/com/github/prologdb/runtime/playground/jvm/persistence/NullPlaygroundStatePersistenceService.java
prologdb/kotlin-prolog
e675375437ed22144ed14b06639dd0a9835c4e67
[ "MIT" ]
28
2018-11-02T15:49:04.000Z
2022-02-21T09:02:10.000Z
jvm-playground/src/main/java/com/github/prologdb/runtime/playground/jvm/persistence/NullPlaygroundStatePersistenceService.java
prologdb/kotlin-prolog
e675375437ed22144ed14b06639dd0a9835c4e67
[ "MIT" ]
null
null
null
24.05
97
0.752599
995,505
package com.github.prologdb.runtime.playground.jvm.persistence; import java.util.Optional; /** * Implements {@link PlaygroundStatePersistenceService} by never reading anything * and discarding all writes. */ public class NullPlaygroundStatePersistenceService implements PlaygroundStatePersistenceService { @Override public Optional<PlaygroundState> read() { return Optional.empty(); } @Override public void write(PlaygroundState state) { } }
923081452207433fd72663af4b9ec645f0bed8b7
4,581
java
Java
src-plugins/Script_Editor/src/main/java/fiji/scripting/Languages.java
robertb-r/fiji
4eb8d690811c5c9d746e673dbd7c3297ec12dfdf
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2022-03-14T06:26:16.000Z
2022-03-14T06:26:16.000Z
src-plugins/Script_Editor/src/main/java/fiji/scripting/Languages.java
robertb-r/fiji
4eb8d690811c5c9d746e673dbd7c3297ec12dfdf
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2016-09-24T16:47:43.000Z
2016-09-24T16:47:43.000Z
src-plugins/Script_Editor/src/main/java/fiji/scripting/Languages.java
robertb-r/fiji
4eb8d690811c5c9d746e673dbd7c3297ec12dfdf
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
29.178344
148
0.719057
995,506
package fiji.scripting; import BSH.Refresh_BSH_Scripts; import CLI.Refresh_Macros; import Clojure.Refresh_Clojure_Scripts; import JRuby.Refresh_JRuby_Scripts; import Javascript.Refresh_Javascript_Scripts; import Jython.Refresh_Jython_Scripts; import common.RefreshScripts; import fiji.scripting.java.Refresh_Javas; import ij.IJ; import java.awt.event.KeyEvent; import java.util.HashMap; import java.util.Map; import javax.swing.JRadioButtonMenuItem; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; public class Languages { protected Language[] languages; protected Map<String, Language> map; public final static Language fakefile = new Language("Fakefile", SyntaxConstants.SYNTAX_STYLE_NONE, "Fakefile", 0, Refresh_Javas.class, true, true); protected Languages() { languages = new Language[] { new Language(".java", SyntaxConstants.SYNTAX_STYLE_JAVA, "Java", KeyEvent.VK_J, Refresh_Javas.class, true, true), new Language(".js", SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT, "Javascript", KeyEvent.VK_S, Refresh_Javascript_Scripts.class, false, false), new Language(".py", SyntaxConstants.SYNTAX_STYLE_PYTHON, "Python", KeyEvent.VK_P, Refresh_Jython_Scripts.class, false, false), new Language(".rb", SyntaxConstants.SYNTAX_STYLE_RUBY, "Ruby", KeyEvent.VK_R, Refresh_JRuby_Scripts.class, false, false), new Language(".clj", null, "Clojure", KeyEvent.VK_C, Refresh_Clojure_Scripts.class, false, false), /* new Language(".m", null, "Matlab", KeyEvent.VK_M, null, false, false), */ new Language(".bsh", SyntaxConstants.SYNTAX_STYLE_JAVA, "Beanshell", KeyEvent.VK_B, Refresh_BSH_Scripts.class, false, false), new Language(".ijm", null, "ImageJ Macro", KeyEvent.VK_I, Refresh_Macros.class, false, false), new Language("", SyntaxConstants.SYNTAX_STYLE_NONE, "None", KeyEvent.VK_N, null, false, false) }; map = new HashMap<String, Language>(); for (Language language : languages) map.put(language.extension, language); } protected static Languages instance; public static Languages getInstance() { if (instance == null) instance = new Languages(); return instance; } public Language getLanguage(String label) { for (Language language : languages) if (label.equals(language.menuLabel)) return language; return get(""); } public static Language get(String extension) { Languages languages = getInstance(); return languages.map.get(languages.map.containsKey(extension) ? extension : ""); } public String getSyntaxStyle(String extension) { return get(extension).syntaxStyle; } public String getMenuEntry(String extension) { return get(extension).menuLabel; } public RefreshScripts getInterpreter(String extension) { return get(extension).newInterpreter(); } /* The class keeps information about particular language */ public static class Language { String extension; String syntaxStyle; String menuLabel; int shortCut; Class<? extends RefreshScripts> interpreterClass; boolean debuggable, compileable; private JRadioButtonMenuItem item; public Language(String extension, String style, String label, int shortCut, Class<? extends RefreshScripts> interpreterClass, boolean isDebuggable, boolean isCompileable) { this.extension = extension; syntaxStyle = style; menuLabel = label; this.shortCut = shortCut; this.interpreterClass = interpreterClass; debuggable = isDebuggable; compileable = isCompileable; } public boolean isRunnable() { return interpreterClass != null; } // TODO: add a proper interface so we can add other debuggers public boolean isDebuggable() { return debuggable; } public boolean isCompileable() { return compileable; } RefreshScripts newInterpreter() { if (null == interpreterClass) return null; try { return interpreterClass.newInstance(); } catch (InstantiationException ie) { IJ.handleException(ie); } catch (IllegalAccessException iae) { IJ.handleException(iae); } return null; } public void setMenuItem(JRadioButtonMenuItem item) { this.item = item; if (extension.equals("")) fakefile.item = item; } public JRadioButtonMenuItem getMenuItem() { return item; } public String toString() { return "(" + extension + "; interpreter: " + (interpreterClass == null ? "<none>" : interpreterClass.getSimpleName()) + "; " + (isCompileable() ? "" : "not ") + "compileable; " + (isDebuggable() ? "" : "not ") + "debuggable)"; } } }
9230826d982e89064ae0452861752aac9732dca7
918
java
Java
oim-server-run/single/oim-server-single-essential-initiate/src/main/java/com/oimchat/server/run/config/WebFileConfig.java
oimchat/oim-server
55c1a317251b9a219aad6e24925bc423214a8c3d
[ "Apache-2.0" ]
12
2021-01-28T07:50:32.000Z
2022-03-17T09:27:43.000Z
oim-server-run/single/oim-server-single-essential-initiate/src/main/java/com/oimchat/server/run/config/WebFileConfig.java
yuzhanxu/oim-server
dbb087778bc28e04ffefbe39ff9e1200578c9dc8
[ "Apache-2.0" ]
1
2021-03-05T10:17:03.000Z
2021-03-05T11:00:53.000Z
oim-server-run/single/oim-server-single-essential-initiate/src/main/java/com/oimchat/server/run/config/WebFileConfig.java
yuzhanxu/oim-server
dbb087778bc28e04ffefbe39ff9e1200578c9dc8
[ "Apache-2.0" ]
6
2021-02-09T08:07:53.000Z
2022-02-28T08:04:38.000Z
28.6875
101
0.779956
995,507
package com.oimchat.server.run.config; import javax.annotation.Resource; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.config.ResourceHandlerRegistry; import org.springframework.web.reactive.config.WebFluxConfigurer; import com.oimchat.server.general.kernel.support.file.module.common.config.FileServerConfig; /** * * Description <br> * Date 2020-04-20 11:07:05<br> * * @author XiaHui [onlovexiahui@qq.com]<br> * @since 1.0.0 */ @Configuration public class WebFileConfig implements WebFluxConfigurer { @Resource private FileServerConfig fileServerConfig; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { String filePath = fileServerConfig.getPath(); String download = fileServerConfig.getDownloadPath(); registry.addResourceHandler("/" + download + "/**").addResourceLocations("file:" + filePath + "/"); } }
923082a1cdf4626dc14ae5a4021aaccfffcc5a76
478
java
Java
Control Structures Part #1/src/Binary.java
ShrillP/Understanding-Java
bba673df7f148d88b18610137c4da3bd20924125
[ "MIT" ]
null
null
null
Control Structures Part #1/src/Binary.java
ShrillP/Understanding-Java
bba673df7f148d88b18610137c4da3bd20924125
[ "MIT" ]
null
null
null
Control Structures Part #1/src/Binary.java
ShrillP/Understanding-Java
bba673df7f148d88b18610137c4da3bd20924125
[ "MIT" ]
null
null
null
21.727273
75
0.67364
995,508
import java.util.Scanner; public class Binary { public static void main (String args []) { //variables Scanner input = new Scanner (System.in); //variables String binary; //Prompt user to enter a binary line System.out.println("Enter a binary line please:"); binary = input.next(); //Display the binary conversion to decimal System.out.println("Decimal number is: " + Integer.parseInt(binary , 2)); }//end of main method }//end of class
923083094848eb6408fcadf6e5c0567379db48bf
2,962
java
Java
GalaxyQuests/src/main/java/com/galaxy/galaxyquests/quests/quests/external/BedWars1058Quests.java
MangoPlex/Minecraft-Projects
d97e6fa74855e39f77bf117a25b2f2d45d31ccf5
[ "MIT" ]
null
null
null
GalaxyQuests/src/main/java/com/galaxy/galaxyquests/quests/quests/external/BedWars1058Quests.java
MangoPlex/Minecraft-Projects
d97e6fa74855e39f77bf117a25b2f2d45d31ccf5
[ "MIT" ]
null
null
null
GalaxyQuests/src/main/java/com/galaxy/galaxyquests/quests/quests/external/BedWars1058Quests.java
MangoPlex/Minecraft-Projects
d97e6fa74855e39f77bf117a25b2f2d45d31ccf5
[ "MIT" ]
null
null
null
36.567901
90
0.672856
995,509
package com.galaxy.galaxyquests.quests.quests.external; import com.andrei1058.bedwars.api.events.player.PlayerBedBreakEvent; import com.andrei1058.bedwars.api.events.player.PlayerFirstSpawnEvent; import com.andrei1058.bedwars.api.events.player.PlayerKillEvent; import com.andrei1058.bedwars.api.events.shop.ShopBuyEvent; import com.andrei1058.bedwars.api.events.shop.UpgradeBuyEvent; import com.galaxy.galaxyquests.QuestsPlugin; import com.galaxy.galaxyquests.objects.quest.variable.QuestResult; import com.galaxy.galaxyquests.quests.quests.external.executor.ExternalQuestExecutor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; public class BedWars1058Quests extends ExternalQuestExecutor { public BedWars1058Quests(QuestsPlugin plugin) { super(plugin, "bedwars1058"); } @EventHandler(ignoreCancelled = true) public void onPlayerBedBreak(PlayerBedBreakEvent event) { Player player = event.getPlayer(); String victimTeam = event.getVictimTeam().getName(); String arenaName = event.getArena().getDisplayName(); if (victimTeam == null || arenaName == null) { return; } this.execute("break_beds", player, result -> { result.subRoot("arena-name", arenaName); return result.root(victimTeam); }); } @EventHandler(ignoreCancelled = true) public void onPlayerKill(PlayerKillEvent event) { Player killer = event.getKiller(); Player victim = event.getVictim(); PlayerKillEvent.PlayerKillCause deathCause = event.getCause(); String arenaName = event.getArena().getDisplayName(); if (killer == null || victim == null || deathCause == null || arenaName == null) { return; } this.execute("kill_players", killer, result -> { result.subRoot("arena-name", arenaName); result.subRoot("player", victim.getName()); return result.root(deathCause.toString().toLowerCase()); }); } @EventHandler(ignoreCancelled = true) public void onPlayerFirstSpawn(PlayerFirstSpawnEvent event) { Player player = event.getPlayer(); String arenaName = event.getArena().getDisplayName(); String teamName = event.getTeam().getName(); if (arenaName == null || teamName == null) { return; } this.execute("play_games", player, result -> { result.subRoot("team", teamName); return result.root(arenaName); }); } @EventHandler(ignoreCancelled = true) public void onShopBuy(ShopBuyEvent event) { Player player = event.getBuyer(); this.execute("buy_items", player, QuestResult::none); } @EventHandler(ignoreCancelled = true) public void onUpgradeBuy(UpgradeBuyEvent event) { Player player = event.getPlayer(); this.execute("buy_upgrades", player, QuestResult::none); } }
9230837124e9ed8f3f7c023aa14678eb85a8c079
1,805
java
Java
bobo-browse/src/main/java/com/browseengine/bobo/service/BrowseQueryParser.java
linkedin/bobo
f90e48b0c90f72e8611a8a2af239c1993897b75e
[ "Apache-2.0" ]
16
2015-04-21T19:21:45.000Z
2020-12-02T18:17:58.000Z
bobo-browse/src/main/java/com/browseengine/bobo/service/BrowseQueryParser.java
linkedin/bobo
f90e48b0c90f72e8611a8a2af239c1993897b75e
[ "Apache-2.0" ]
null
null
null
bobo-browse/src/main/java/com/browseengine/bobo/service/BrowseQueryParser.java
linkedin/bobo
f90e48b0c90f72e8611a8a2af239c1993897b75e
[ "Apache-2.0" ]
7
2015-06-24T17:33:03.000Z
2019-11-24T17:29:15.000Z
30.59322
94
0.720222
995,510
/** * This software is licensed to you under the Apache License, Version 2.0 (the * "Apache License"). * * LinkedIn's contributions are made under the Apache License. If you contribute * to the Software, the contributions will be deemed to have been made under the * Apache License, unless you expressly indicate otherwise. Please do not make any * contributions that would be inconsistent with the Apache License. * * You may obtain a copy of the Apache License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, this software * distributed under the Apache License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Apache * License for the specific language governing permissions and limitations for the * software governed under the Apache License. * * © 2012 LinkedIn Corp. All Rights Reserved. */ package com.browseengine.bobo.service; import org.apache.lucene.search.DocIdSet; /** * Builds a DocSet from an array of SelectioNodes */ public interface BrowseQueryParser { public static class SelectionNode { private String fieldName; private DocIdSet docSet; public SelectionNode() { } public SelectionNode(String fieldName,DocIdSet docSet) { this.fieldName=fieldName; this.docSet=docSet; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public DocIdSet getDocSet() { return docSet; } public void setDocSet(DocIdSet docSet) { this.docSet = docSet; } } DocIdSet parse(SelectionNode[] selectionNodes,SelectionNode[] notSelectionNodes,int maxDoc); }
923083cb5f21f503477cc13844cd7a8270ae4eba
3,111
java
Java
feature-drools-init/src/main/java/org/onap/policy/drools/droolsinit/DroolsInitFeature.java
onap/policy-drools-pdp
cdcdc706a15a43611787b97201679846b080fa5d
[ "Apache-2.0" ]
5
2018-11-21T19:19:57.000Z
2021-10-15T15:04:25.000Z
feature-drools-init/src/main/java/org/onap/policy/drools/droolsinit/DroolsInitFeature.java
onap/policy-drools-pdp
cdcdc706a15a43611787b97201679846b080fa5d
[ "Apache-2.0" ]
null
null
null
feature-drools-init/src/main/java/org/onap/policy/drools/droolsinit/DroolsInitFeature.java
onap/policy-drools-pdp
cdcdc706a15a43611787b97201679846b080fa5d
[ "Apache-2.0" ]
null
null
null
37.939024
85
0.614272
995,511
/*- * ============LICENSE_START======================================================= * feature-drools-init * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.policy.drools.droolsinit; import java.io.Serializable; import java.util.concurrent.TimeUnit; import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.system.PolicyEngineConstants; /** * This feature inserts an object of class 'DroolsInitFeature.Init' into * every newly-created or updated Drools session, including those that were * initialized with persistent data. Rules matching on objects of this type * can then do things like initialize global data. */ public class DroolsInitFeature implements PolicySessionFeatureApi { // default delay is 10 minutes private static final long DELAY = 600000L; /** * {@inheritDoc}. */ @Override public int getSequenceNumber() { return 0; } /** * {@inheritDoc}. */ @Override public PolicySession.ThreadModel selectThreadModel(PolicySession policySession) { new Init(policySession); return null; } /** * Instances of this class are inserted into Drools memory. */ public static class Init implements Serializable { private static final long serialVersionUID = 1L; /** * Place this instance in Drools memory, and then remove it after * one minute, if it is still there. * * @param policySession the associated session */ public Init(final PolicySession policySession) { // insert this instance into Drools memory final var factHandle = policySession.getKieSession().insert(this); // after 10 minutes, remove the object from Drools memory (if needed) PolicyEngineConstants.getManager().getExecutorService().schedule(() -> { if (policySession.getKieSession().getObject(factHandle) != null) { // object has not been removed by application -- remove it here policySession.getKieSession().delete(factHandle); } }, DELAY, TimeUnit.MILLISECONDS); } } }
9230845ddcd657481bf689d5bea8f10851ec5aa5
1,227
java
Java
src/main/java/pl/informatykapolelektr/polslmysqlrestfullapi/repository/DepartmentRepository.java
Milosz08/SpringBoot_RestfullApi_POLSL
1d35ed7816052764a3f41e13a35044abda71fb9a
[ "Apache-2.0" ]
null
null
null
src/main/java/pl/informatykapolelektr/polslmysqlrestfullapi/repository/DepartmentRepository.java
Milosz08/SpringBoot_RestfullApi_POLSL
1d35ed7816052764a3f41e13a35044abda71fb9a
[ "Apache-2.0" ]
null
null
null
src/main/java/pl/informatykapolelektr/polslmysqlrestfullapi/repository/DepartmentRepository.java
Milosz08/SpringBoot_RestfullApi_POLSL
1d35ed7816052764a3f41e13a35044abda71fb9a
[ "Apache-2.0" ]
null
null
null
40.9
118
0.760391
995,512
/* * Copyright (c) 2021, by Miłosz Gilga <https://miloszgilga.pl> * * 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/license/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 pl.informatykapolelektr.polslmysqlrestfullapi.repository; import org.springframework.data.jpa.repository.*; import org.springframework.data.repository.query.*; import org.springframework.stereotype.*; import pl.informatykapolelektr.polslmysqlrestfullapi.models.*; import java.util.*; @Repository public interface DepartmentRepository extends JpaRepository<Department, String> { @Query("SELECT d FROM Department d WHERE d.title=:t AND d.shortName=:s AND d.link=:l") List<Department> getDepartmentBy(@Param("t") String title, @Param("s") String shortName, @Param("l") String link); }
92308492bc941f11c0fab343145cff711c002247
14,938
java
Java
src/model/ConfigReader.java
sgupta229/Cell-Society
220e982b43f79add759ad5a649ccd1d26c0a617a
[ "MIT" ]
null
null
null
src/model/ConfigReader.java
sgupta229/Cell-Society
220e982b43f79add759ad5a649ccd1d26c0a617a
[ "MIT" ]
null
null
null
src/model/ConfigReader.java
sgupta229/Cell-Society
220e982b43f79add759ad5a649ccd1d26c0a617a
[ "MIT" ]
null
null
null
32.055794
200
0.567948
995,513
package model; import javafx.scene.paint.Color; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.HashMap; import java.util.Collections; import java.util.Arrays; /** <<<<<<< HEAD * This class is responsible for reading config files and parsing the information properly * @author Samuel Chan, William Francis, Sahil Gupta * @purpose Given a string representing a file in the folder /data, parses the data and constructs the data structure for the simulation * @assumptions The file is located in the right location, with the right data format (handles exceptions in case it doesn't) * @dependencies Called in SimulationViewer and other subclasses, requires data .csv file to be in /data * @usage Construct a new ConfigReader by providing the string of the filename, call the getters for relevant info */ public class ConfigReader { private String mySimType; private String myCellShape; private String neighborPolicy; private String edgePolicy; private String isOutlined; private String initialConfig; private int myNumStates; private Map<Integer, State> myStateMap; private int numCols; private int numRows; public static final int policiesLength = 5; public static final int stateObjectsLength = 6; private List<Integer> gridData; /** * constructor of the configuration reader * @param s - the csv file name of the config file * @purpose Constructs a Configreader for a specified file * @assumptions File exists and has correct format * @return does not return anything, but use getter/setters for data * @param s */ public ConfigReader(String s) { gridData = readConfigFile(s + ".csv"); } /** * Makes sure file is correct format first, then actually parses the file * @param filename * @return the List of the data itself, whether generated by the program or parsed from the file */ private List<Integer> readConfigFile(String filename) { Scanner input; try { input = new Scanner(this.getClass().getClassLoader().getResourceAsStream(filename)); input.useDelimiter(",|\\n"); } catch (NullPointerException e){ throw new IllegalArgumentException(filename + " cannot be found", e); } checkConfigFile(filename); return parseFile(input); } /** * Parse the file for relevant data about the simulation * @param input * @return the griddata */ private List<Integer> parseFile(Scanner input) { mySimType = input.next(); myCellShape = input.next(); neighborPolicy = input.next(); edgePolicy = input.next(); isOutlined = input.next(); initialConfig = input.next(); myNumStates = input.nextInt(); myStateMap = new HashMap<>(); for (int i = 0; i < myNumStates; i++){ var name = input.next(); var type = input.nextInt(); var colorString = input.next(); var image = input.next(); var prob = Double.parseDouble(input.next()); var amt = input.nextInt(); State s = new State(name, type, Color.valueOf(colorString), image, prob, amt); myStateMap.put(type, s); } numCols = input.nextInt(); numRows = input.nextInt(); checkValid(); return getResults(input); } /** * Checks to see if the file contains correctly inputted data */ private void checkValid() { getSimType(); getInitialConfig(); getIsOutlined(); getEdgePolicy(); getNeighborPolicy(); getCellShape(); } // Depending on what kind of way to generate the data, get this data (deterministic: read from file, probabilistic: generate according to probability, totalsum: generate based on specified counts) private List<Integer> getResults(Scanner input) { List<Integer> results = new ArrayList<>(); if(initialConfig.equals("DETERMINISTIC")) { while (input.hasNext()) { results.add(input.nextInt()); } } else if (initialConfig.equals("PROBABILISTIC")) { double total = 0; for(int i = 0; i < myStateMap.size(); i++) { total += myStateMap.get(i).getProb(); } if(total != 1.0) { throw new IllegalArgumentException("Probabilities don't sum to 1"); } results = generateProb(); } else if (initialConfig.equals("TOTALSUM")) { int total = 0; for(int i = 0; i < myStateMap.size(); i++) { total += myStateMap.get(i).getAmount(); } if(total != numCols*numRows) { throw new IllegalArgumentException("Probabilities don't sum to total number of Cells"); } results = generateRandom(); } else { throw new IllegalArgumentException("Illegal way of generating grid"); } results.removeAll(Collections.singleton(null)); if (results.size() != numCols * numRows) { throw new IllegalArgumentException("Size of grid created is not equal to total number of cells"); } return results; } // Ascertain file has correct format for data, throws exceptions private void checkConfigFile(String filename) { Scanner input; try { input = new Scanner(this.getClass().getClassLoader().getResourceAsStream(filename)); } catch (NullPointerException e){ throw new IllegalArgumentException(filename + " cannot be found", e); } input.useDelimiter("\\n"); var sim = input.next(); var policy = input.next(); String[] policies = policy.split(","); if(policies.length != policiesLength) { throw new IllegalArgumentException("Policies Length is not correct"); } var numStates = input.next(); int num = 0; try { num = Integer.parseInt(numStates); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("Num States is not formatted correctly", e); } for(int i = 0; i < num; i++) { var state = input.next(); String[] stateObjects = state.split(","); if(stateObjects.length != stateObjectsLength) { throw new IllegalArgumentException("State Objects length is not correct"); } try { int intVal = Integer.parseInt(stateObjects[1]); if(intVal != i) { throw new IllegalArgumentException("State value must be sequentially assigned"); } } catch(IllegalArgumentException e) { throw new IllegalArgumentException("State value is not int correctly", e); } try { Color color = Color.valueOf(stateObjects[2]); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("State color is not formatted correctly", e); } try { double doubleVal = Double.parseDouble(stateObjects[4]); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("Probability is not formatted correctly as a double", e); } try { int intVal = Integer.parseInt(stateObjects[5]); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("Total Sum is not formatted correctly as an int", e); } } var colRows = input.next(); String[] numColRows = colRows.split(","); if(numColRows.length != 2) { throw new IllegalArgumentException("Number of values for col/row must be 2"); } try { num = Integer.parseInt(numColRows[0]); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("Row is not formatted correctly as an int", e); } try { num = Integer.parseInt(numColRows[1]); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("Col is not formatted correctly as an int", e); } } // Generates values based on probabilities given private List<Integer> generateProb() { Integer[] randArr = new Integer[numCols*numRows]; int start = 0; int end; for(int i = 0; i < myStateMap.size(); i++) { double prob = myStateMap.get(i).getProb(); end = (int) (prob * numCols * numRows + start); for(int j = start; j < end; j++) { if(end > randArr.length) { break; } randArr[j] = myStateMap.get(i).getType(); } start = end; } List<Integer> arr = new ArrayList<>(Arrays.asList(randArr)); Collections.shuffle(arr); return arr; } // Generates values based on counts given private List<Integer> generateRandom() { Integer[] randArr = new Integer[numCols*numRows]; int start = 0; int end; for(int i = 0; i < myStateMap.size(); i++) { int amt = myStateMap.get(i).getAmount(); end = amt + start; for(int j = start; j < end; j++) { if(end > randArr.length) { break; } randArr[j] = myStateMap.get(i).getType(); } start = end; } List<Integer> arr = new ArrayList<>(Arrays.asList(randArr)); Collections.shuffle(arr); return arr; } /** * getter method for the number of columns * @return int of number of columns */ public int getNumCols() { return numCols; } /** * getter method for the number of rows * @return the number of rows */ public int getNumRows() { return numRows; } /** * get the grid data * @return a list of the grid data */ public List<Integer> getGridData() { List<Integer> newGrid = new ArrayList<>(); newGrid.addAll(gridData); return newGrid; } /** * gets the simulation type. throws an error if invalid simulation type * @return - the simulation type */ public String getSimType() { if (mySimType.equals("PREDATORPREY")) { return mySimType; } if (mySimType.equals("FIRE")) { return mySimType; } if (mySimType.equals("GAMEOFLIFE")) { return mySimType; } if (mySimType.equals("PERCOLATION")) { return mySimType; } if (mySimType.equals("ROCKPAPERSCISSORS")) { return mySimType; } if (mySimType.equals("SEGREGATION")) { return mySimType; } else { throw new IllegalArgumentException("Simulation type given is invalid"); } } /** * getter method to get the number of states * @return the number of states */ public int getMyNumStates() { return myNumStates; } /** * getter method for the state map * @return the state map */ public Map<Integer, State> getMyStateMap() { return myStateMap; } /** * converts the config reader data into a string (for error checking) * @return a string of the data in the config file */ @Override public String toString() { return "ConfigReader{" + "\nmySimType='" + mySimType + '\'' + "\nmyCellShape='" + myCellShape + '\'' + "\nneighborPolicy=" + neighborPolicy + "\nedgePolicy=" + edgePolicy + "\nisOutlined=" + getIsOutlined() + "\ninitialConfig=" + initialConfig + "\nmyNumStates=" + myNumStates + "\nnumCols=" + numCols + "\nnumRows=" + numRows + "\ngridData=" + gridData + '}'; } /** * gets the cell shape from the config file * @return an int representing the shape */ public int getCellShape() { if (myCellShape.equals("TRIANGLE")) { return 2; } if (myCellShape.equals("HEXAGON")) { return 1; } if (myCellShape.equals("SQUARE")) { return 0; } else { throw new IllegalArgumentException("Cell Shape given is invalid"); } } /** * determines the neighbor policy from the config file * @return an int representing the neighbor policy */ public int getNeighborPolicy() { if (neighborPolicy.equals("DIAGONAL")) { return 2; } if (neighborPolicy.equals("CARDINAL")) { return 1; } if (neighborPolicy.equals("COMPLETE")) { return 0; } else { throw new IllegalArgumentException("Neighbor policy given is invalid"); } } /** * Converts the edge policy specified in the config file to its corresponding integer * @return - the integer representing the edge policy */ public int getEdgePolicy() { if (edgePolicy.equals("KLEINBOTTLE")) { return 2; } if (edgePolicy.equals("TOROIDAL")) { return 1; } if (edgePolicy.equals("BOUNDED")) { return 0; } else { throw new IllegalArgumentException("Edge policy given is invalid"); } } /** * determines whether or not the grid should be outlined from the config file * @return - boolean representing whether or not to outline the cells in the grid */ public boolean getIsOutlined() { if (isOutlined.equalsIgnoreCase("TRUE")) { return true; } if (isOutlined.equalsIgnoreCase("FALSE")) { return false; } else { throw new IllegalArgumentException("Outlined policy given is invalid"); } } /** * Get which way the cells will be generated * @return - the integer representing the way the cells should be generated */ public int getInitialConfig() { if (initialConfig.equals("TOTALSUM")) { return 2; } if (initialConfig.equals("PROBABILISTIC")) { return 1; } if (initialConfig.equals("DETERMINISTIC")) { return 0; } else { throw new IllegalArgumentException("Illegal way of generating grid"); } } }
92308499b82b7dd39eb6ff2fae7045c15f14fcaf
3,940
java
Java
dl4j-perf/src/main/java/org/deeplearning4j/perf/listener/SystemPolling.java
dileeshvar/deeplearning4j
973ebc9fd3522c3d725b81f0caaebeadb46481ad
[ "Apache-2.0" ]
1
2021-11-10T12:29:21.000Z
2021-11-10T12:29:21.000Z
dl4j-perf/src/main/java/org/deeplearning4j/perf/listener/SystemPolling.java
dileeshvar/deeplearning4j
973ebc9fd3522c3d725b81f0caaebeadb46481ad
[ "Apache-2.0" ]
null
null
null
dl4j-perf/src/main/java/org/deeplearning4j/perf/listener/SystemPolling.java
dileeshvar/deeplearning4j
973ebc9fd3522c3d725b81f0caaebeadb46481ad
[ "Apache-2.0" ]
1
2018-08-02T10:49:43.000Z
2018-08-02T10:49:43.000Z
30.307692
110
0.640355
995,514
package org.deeplearning4j.perf.listener; import org.nd4j.shade.jackson.databind.ObjectMapper; import org.nd4j.shade.jackson.dataformat.yaml.YAMLFactory; import oshi.json.SystemInfo; import java.io.File; import java.io.IOException; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Poll a system for its local statistics with a specified time. * The polling process will output a yaml file * in the specified output directory * * with all the related system diagnostics. * * @author Adam Gibson */ public class SystemPolling { private ScheduledExecutorService scheduledExecutorService; private long pollEveryMillis; private File outputDirectory; private NameProvider nameProvider; private ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); private SystemPolling(long pollEveryMillis,File outputDirectory,NameProvider nameProvider) { this.pollEveryMillis = pollEveryMillis; this.outputDirectory = outputDirectory; this.nameProvider = nameProvider; } /** * Run the polling in the background as a thread pool * running every {@link #pollEveryMillis} milliseconds */ public void run() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { SystemInfo systemInfo = new SystemInfo(); HardwareMetric hardwareMetric = HardwareMetric.fromSystem(systemInfo,nameProvider.nextName()); File hardwareFile = new File(outputDirectory,hardwareMetric.getName() + ".yml"); try { objectMapper.writeValue(hardwareFile,hardwareMetric); } catch (IOException e) { e.printStackTrace(); } } },0,pollEveryMillis, TimeUnit.MILLISECONDS); } /** * Shut down the background polling */ public void stopPolling() { scheduledExecutorService.shutdownNow(); } /** * The naming sequence provider. * This is for allowing generation of naming the output * according to some semantic sequence (such as a neural net epoch * or some time stamp) */ public interface NameProvider { String nextName(); } public static class Builder { private long pollEveryMillis; private File outputDirectory; private NameProvider nameProvider = new NameProvider() { @Override public String nextName() { return UUID.randomUUID().toString(); } }; /** * The name provider for this {@link SystemPolling} * the default value for this is a simple UUID * @param nameProvider the name provider to use * @return */ public Builder nameProvider(NameProvider nameProvider) { this.nameProvider = nameProvider; return this; } /** * The interval in milliseconds in which to poll * the system for diagnostics * @param pollEveryMillis the interval in milliseconds * @return */ public Builder pollEveryMillis(long pollEveryMillis) { this.pollEveryMillis = pollEveryMillis; return this; } /** * The output directory for the files * @param outputDirectory the output directory for the logs * @return */ public Builder outputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; return this; } public SystemPolling build() { return new SystemPolling(pollEveryMillis,outputDirectory,nameProvider); } } }
92308611fa106496ffa14ea408e335b2a6252cf0
428
java
Java
src/main/java/com/amazon/crm/party/repo/IndividualRepository.java
vhutie/amazon-crm-party
18f3474c9d17cd617b5f48bac0a18ef0b43a76d1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazon/crm/party/repo/IndividualRepository.java
vhutie/amazon-crm-party
18f3474c9d17cd617b5f48bac0a18ef0b43a76d1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazon/crm/party/repo/IndividualRepository.java
vhutie/amazon-crm-party
18f3474c9d17cd617b5f48bac0a18ef0b43a76d1
[ "Apache-2.0" ]
null
null
null
26.75
79
0.810748
995,515
package com.amazon.crm.party.repo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.amazon.crm.party.model.Individual; import com.google.common.base.Optional; public interface IndividualRepository extends JpaRepository<Individual, Long>{ public List<Individual> findAllByOrderByFullNameAsc(); public Optional<Individual> findById(Long id); public void delete(Long id); }
9230867b7b6b94fc111bbdd0507b72f5eca6ca26
565
java
Java
src/main/java/br/com/zup/casadocodigo/cadastroestadopais/Pais.java
andersonzup/orange-talents-07-template-casa-do-codigo
048afcb1b4bf2ad3b7c298ad74754b1b29cca9e0
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zup/casadocodigo/cadastroestadopais/Pais.java
andersonzup/orange-talents-07-template-casa-do-codigo
048afcb1b4bf2ad3b7c298ad74754b1b29cca9e0
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zup/casadocodigo/cadastroestadopais/Pais.java
andersonzup/orange-talents-07-template-casa-do-codigo
048afcb1b4bf2ad3b7c298ad74754b1b29cca9e0
[ "Apache-2.0" ]
null
null
null
16.142857
55
0.589381
995,516
package br.com.zup.casadocodigo.cadastroestadopais; import javax.persistence.*; @Entity public class Pais { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String nome; public Pais() { } public Pais(Long id, String nome) { this.id = id; this.nome = nome; } public Pais(String nome) { this.nome = nome; } public Long getId() { return id; } public String getNome() { return nome; } }
923086b06f17a78ffc3e27ab386fa5d4b04c2cf6
1,703
java
Java
projects/copper-cassandra/cassandra-storage/src/main/java/org/copperengine/core/persistent/cassandra/CassandraOperation.java
based2/copper-engine
dc1a34b73130996669451183adee00ad47e940c2
[ "Apache-2.0" ]
204
2015-02-05T19:27:25.000Z
2022-03-19T21:51:56.000Z
projects/copper-cassandra/cassandra-storage/src/main/java/org/copperengine/core/persistent/cassandra/CassandraOperation.java
based2/copper-engine
dc1a34b73130996669451183adee00ad47e940c2
[ "Apache-2.0" ]
56
2015-02-27T06:56:02.000Z
2022-01-08T22:02:53.000Z
projects/copper-cassandra/cassandra-storage/src/main/java/org/copperengine/core/persistent/cassandra/CassandraOperation.java
based2/copper-engine
dc1a34b73130996669451183adee00ad47e940c2
[ "Apache-2.0" ]
64
2015-02-03T14:40:19.000Z
2022-03-24T04:41:35.000Z
32.75
86
0.670581
995,517
/* * Copyright 2002-2015 SCOOP Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.copperengine.core.persistent.cassandra; import org.slf4j.Logger; import com.datastax.driver.core.exceptions.NoHostAvailableException; import com.datastax.driver.core.exceptions.QueryExecutionException; abstract class CassandraOperation<T> { private final Logger logger; public CassandraOperation(Logger logger) { this.logger = logger; } public T run() throws Exception { for (int i = 1;; i++) { try { return execute(); } catch (QueryExecutionException | NoHostAvailableException e) { logger.warn("Cassandra operation failed - retrying...", e); } catch (Exception e) { throw e; } final int sleepIntervalMSec = calculateSleepInterval(i); logger.debug("Going to sleep {} msec before next try", sleepIntervalMSec); Thread.sleep(sleepIntervalMSec); } } protected abstract T execute() throws Exception; protected int calculateSleepInterval(int c) { return Math.min(5000, 50 * c); } }
92308f2a4c23102b62a87a26dbc301ba0e645b5c
1,175
java
Java
web-client/src/main/java/eu/cityopt/service/impl/UserDetailsImpl.java
Cityopt/cityopt
41a47edd08145c3d2c249626a26221b48f85e7cb
[ "CNRI-Jython" ]
null
null
null
web-client/src/main/java/eu/cityopt/service/impl/UserDetailsImpl.java
Cityopt/cityopt
41a47edd08145c3d2c249626a26221b48f85e7cb
[ "CNRI-Jython" ]
1
2016-10-31T10:54:19.000Z
2019-09-30T07:36:51.000Z
web-client/src/main/java/eu/cityopt/service/impl/UserDetailsImpl.java
Cityopt/cityopt
41a47edd08145c3d2c249626a26221b48f85e7cb
[ "CNRI-Jython" ]
null
null
null
22.596154
101
0.738723
995,518
package eu.cityopt.service.impl; import java.util.Collection; import java.util.HashSet; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; public class UserDetailsImpl implements UserDetails{ private static final long serialVersionUID = -6509897037222767090L; private Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); private String password; private String username; public UserDetailsImpl(String username, String password, Collection<GrantedAuthority> authorities){ this.username = username; this.password = password; this.authorities = authorities; } public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } public String getPassword() { return this.password; } public String getUsername() { return this.username; } public boolean isAccountNonExpired() { return true; } public boolean isAccountNonLocked() { return true; } public boolean isCredentialsNonExpired() { return true; } public boolean isEnabled() { return true; } }
92308f7e83034de2130e4cbc401932c0d42bfb3d
1,577
java
Java
src/test/java/name/pkrause/blueprint/usecases/cat/UpdateCatUTest.java
PKrause79/blueprint-spring-boot
b89723c0b839175e7519d80262b75ce959501902
[ "Apache-2.0" ]
1
2021-01-25T07:35:23.000Z
2021-01-25T07:35:23.000Z
src/test/java/name/pkrause/blueprint/usecases/cat/UpdateCatUTest.java
PKrause79/blueprint-spring-boot
b89723c0b839175e7519d80262b75ce959501902
[ "Apache-2.0" ]
null
null
null
src/test/java/name/pkrause/blueprint/usecases/cat/UpdateCatUTest.java
PKrause79/blueprint-spring-boot
b89723c0b839175e7519d80262b75ce959501902
[ "Apache-2.0" ]
1
2021-01-25T07:35:24.000Z
2021-01-25T07:35:24.000Z
30.921569
102
0.708307
995,519
package name.pkrause.blueprint.usecases.cat; import name.pkrause.blueprint.entities.Cat; import name.pkrause.blueprint.entities.CatOwner; import name.pkrause.blueprint.entities.CatRepository; import name.pkrause.blueprint.usecases.cat.update.UpdateCat; import name.pkrause.blueprint.usecases.cat.update.UpdateCatRequest; import name.pkrause.blueprint.usecases.cat.update.UpdateCatResponse; 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.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class UpdateCatUTest { private UpdateCat updateCatUseCase; @Mock private CatRepository catRepository; @BeforeEach void setUp() { updateCatUseCase = new UpdateCat(catRepository); } @Nested class UpdateShould { @Test void updateCat() { // Given Cat cat = new Cat("Cat1"); cat.setId(1L); cat.setCatOwner(new CatOwner("Cat owner 1")); // When when(catRepository.save(cat)).thenReturn(cat); UpdateCatResponse result = updateCatUseCase.execute(new UpdateCatRequest(1L, "Cat1", 1L)); // Then assertThat(cat.getId()).isEqualTo(result.getId()); assertThat(cat.getValue()).isEqualTo(result.getValue()); } } }
92308fa782c9ebeccbf7d0dc611349c7e36efdcc
608
java
Java
shopping-store-back/src/main/java/com/gtt/shoppingstoreback/servie/ReturnHistoryServiceImpl.java
taotaomima/Shopping0224
18aefa06a32c2e8b6703dff06e281c0b20971f44
[ "Apache-2.0" ]
null
null
null
shopping-store-back/src/main/java/com/gtt/shoppingstoreback/servie/ReturnHistoryServiceImpl.java
taotaomima/Shopping0224
18aefa06a32c2e8b6703dff06e281c0b20971f44
[ "Apache-2.0" ]
null
null
null
shopping-store-back/src/main/java/com/gtt/shoppingstoreback/servie/ReturnHistoryServiceImpl.java
taotaomima/Shopping0224
18aefa06a32c2e8b6703dff06e281c0b20971f44
[ "Apache-2.0" ]
null
null
null
27.636364
85
0.799342
995,520
package com.gtt.shoppingstoreback.servie; import com.gtt.shoppingstoreback.dao.ReturnHistoryMapper; import com.gtt.shoppingstoreback.po.ReturnHistory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class ReturnHistoryServiceImpl implements ReturnHistoryService { @Resource private ReturnHistoryMapper returnHistoryMapper; @Override public List<ReturnHistory> getByReturnId(Integer returnId) { List<ReturnHistory> byReturnId = returnHistoryMapper.getByReturnId(returnId); return byReturnId; } }
92309139bf66c50b01f6f950c65c16998a1320c2
1,018
java
Java
app/src/main/java/com/avelon/turf/StartupDialog.java
ddjohn/turf
6d42b20bddcfcde25a32399664299ad17cdfd8b9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/avelon/turf/StartupDialog.java
ddjohn/turf
6d42b20bddcfcde25a32399664299ad17cdfd8b9
[ "Apache-2.0" ]
2
2022-01-26T06:00:51.000Z
2022-01-26T06:03:10.000Z
app/src/main/java/com/avelon/turf/StartupDialog.java
ddjohn/turf
6d42b20bddcfcde25a32399664299ad17cdfd8b9
[ "Apache-2.0" ]
null
null
null
27.513514
77
0.682711
995,521
package com.avelon.turf; import android.app.Dialog; import android.os.Bundle; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import com.avelon.turf.utils.Logger; public class StartupDialog extends DialogFragment { Logger logger = new Logger(StartupDialog.class); private String message = "Waiting for valid GPS...\r\n"; private boolean enabled = true; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Turf!").setMessage(this.message); return builder.create(); } public synchronized void addMessage(String message) { this.message += message + "\r\n"; if(enabled) ((AlertDialog)this.getDialog()).setMessage(this.message); } public synchronized void cancel() { enabled = false; logger.error("t=" + this.getDialog()); this.getDialog().cancel(); } }
923092968a73cdef0e8c7ed83b63866ec5750d81
652
java
Java
db4o.j/db4o-core/core/src/com/db4o/foundation/SingleValueIterator.java
iboxdb/db4o-gpl
16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0
[ "Net-SNMP", "Xnet" ]
24
2019-08-25T12:58:07.000Z
2022-03-04T11:20:37.000Z
db4o.j/db4o-core/core/src/com/db4o/foundation/SingleValueIterator.java
iboxdb/db4o-gpl
16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0
[ "Net-SNMP", "Xnet" ]
null
null
null
db4o.j/db4o-core/core/src/com/db4o/foundation/SingleValueIterator.java
iboxdb/db4o-gpl
16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0
[ "Net-SNMP", "Xnet" ]
10
2019-08-30T10:25:41.000Z
2022-02-13T17:40:23.000Z
18.111111
65
0.65184
995,522
/* Copyright (C) 2004 - 2006 Versant Inc. http://www.db4o.com */ package com.db4o.foundation; public class SingleValueIterator implements Iterator4 { private Object _value; private boolean _moved; public SingleValueIterator(Object value) { _value = value; } public Object current() { if (!_moved || _value == Iterators.NO_ELEMENT) { throw new IllegalStateException(); } return _value; } public boolean moveNext() { if (!_moved) { _moved = true; return true; } _value = Iterators.NO_ELEMENT; return false; } public void reset() { throw new NotImplementedException(); } }
9230940a62e0b845bb53fdfad818f64f02e1d574
1,845
java
Java
src/main/java/tech/shunzi/rpc/rdma/endpoint/RdmaRPCEndpointGroup.java
zjs1224522500/DaRPC
e70f96e113ef37f7ce1eaf4462071759c936f01b
[ "Apache-2.0" ]
1
2020-04-24T06:01:54.000Z
2020-04-24T06:01:54.000Z
src/main/java/tech/shunzi/rpc/rdma/endpoint/RdmaRPCEndpointGroup.java
zjs1224522500/DaRPC
e70f96e113ef37f7ce1eaf4462071759c936f01b
[ "Apache-2.0" ]
null
null
null
src/main/java/tech/shunzi/rpc/rdma/endpoint/RdmaRPCEndpointGroup.java
zjs1224522500/DaRPC
e70f96e113ef37f7ce1eaf4462071759c936f01b
[ "Apache-2.0" ]
1
2020-04-28T16:19:19.000Z
2020-04-28T16:19:19.000Z
27.132353
158
0.692141
995,523
package tech.shunzi.rpc.rdma.endpoint; import com.ibm.disni.RdmaCqProvider; import com.ibm.disni.RdmaEndpointGroup; import com.ibm.disni.verbs.IbvQP; import tech.shunzi.rpc.rdma.common.RdmaRPCMessage; import tech.shunzi.rpc.rdma.common.RdmaRPCProtocol; import java.io.IOException; public abstract class RdmaRPCEndpointGroup<E extends RdmaRPCEndpoint<Q, P>, Q extends RdmaRPCMessage, P extends RdmaRPCMessage> extends RdmaEndpointGroup<E> { private int recvQueueSize; private int sendQueueSize; private int bufferSize; private int maxInline; private int timeout; public RdmaRPCEndpointGroup(RdmaRPCProtocol<Q,P> protocol, int timeout, int maxinline, int recvQueue, int sendQueue) throws IOException { super(timeout); this.timeout = timeout; this.recvQueueSize = recvQueue; this.sendQueueSize = Math.max(recvQueue, sendQueue); this.bufferSize = Math.max(protocol.createRequest().size(), protocol.createResponse().size()); this.maxInline = maxinline; } public int getRecvQueueSize() { return recvQueueSize; } public void setRecvQueueSize(int recvQueueSize) { this.recvQueueSize = recvQueueSize; } public int getSendQueueSize() { return sendQueueSize; } public void setSendQueueSize(int sendQueueSize) { this.sendQueueSize = sendQueueSize; } public int getBufferSize() { return bufferSize; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public int getMaxInline() { return maxInline; } public void setMaxInline(int maxInline) { this.maxInline = maxInline; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } }
9230946e72eaa4293410c5c4c60ebbf099b98fe6
1,324
java
Java
src/main/java/com/roguecloud/actions/IAction.java
jgwest/rogue-cloud-client-codewind
e4a673f81842da164db6a72ca6cf5b8128e645aa
[ "Apache-2.0" ]
25
2018-02-13T10:43:15.000Z
2020-03-22T15:58:29.000Z
src/main/java/com/roguecloud/actions/IAction.java
jgwest/rogue-cloud-client-codewind
e4a673f81842da164db6a72ca6cf5b8128e645aa
[ "Apache-2.0" ]
17
2018-03-12T11:48:24.000Z
2020-04-23T16:42:42.000Z
src/main/java/com/roguecloud/actions/IAction.java
jgwest/rogue-cloud-client-codewind
e4a673f81842da164db6a72ca6cf5b8128e645aa
[ "Apache-2.0" ]
40
2018-02-16T16:22:44.000Z
2020-05-01T14:11:06.000Z
34.842105
127
0.728097
995,524
/* * Copyright 2018 IBM Corporation * * 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.roguecloud.actions; /** * The IAction interface, and the *Action classes (CombatAction/DrinkItemAction/etc) correspond to actions that your character * performs in the world. * * To perform an action, create the appropriate action object, and call sendAction(..) from the client class: * ``` * // where somePlayer is a nearby player from the worldState object. * CombatAction ca = new CombatAction (somePlayer); * sendAction(ca); * ``` **/ public interface IAction { /** To determine which type/class the action is, call getActionType() on an IAction. */ public static enum ActionType { STEP, COMBAT, MOVE_INVENTORY_ITEM, EQUIP, DRINK, NULL }; public ActionType getActionType(); }
92309559797307865509f6c34645aa2cc3222544
3,731
java
Java
model-reda-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/PartyAuditTrailQueryV01.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
40
2020-10-13T13:44:59.000Z
2022-03-30T13:58:32.000Z
model-reda-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/PartyAuditTrailQueryV01.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
25
2020-10-04T23:46:22.000Z
2022-03-30T12:31:03.000Z
model-reda-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/PartyAuditTrailQueryV01.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
22
2020-12-22T14:50:22.000Z
2022-03-30T13:19:10.000Z
26.274648
149
0.639775
995,525
package com.prowidesoftware.swift.model.mx.dic; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * The PartyAuditTrailQuery message is sent by an instructing party to the executing party to query for the party audit trail recorded in the system. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PartyAuditTrailQueryV01", propOrder = { "msgHdr", "schCrit", "splmtryData" }) public class PartyAuditTrailQueryV01 { @XmlElement(name = "MsgHdr") protected MessageHeader1 msgHdr; @XmlElement(name = "SchCrit", required = true) protected PartyAuditTrailSearchCriteria2 schCrit; @XmlElement(name = "SplmtryData") protected List<SupplementaryData1> splmtryData; /** * Gets the value of the msgHdr property. * * @return * possible object is * {@link MessageHeader1 } * */ public MessageHeader1 getMsgHdr() { return msgHdr; } /** * Sets the value of the msgHdr property. * * @param value * allowed object is * {@link MessageHeader1 } * */ public PartyAuditTrailQueryV01 setMsgHdr(MessageHeader1 value) { this.msgHdr = value; return this; } /** * Gets the value of the schCrit property. * * @return * possible object is * {@link PartyAuditTrailSearchCriteria2 } * */ public PartyAuditTrailSearchCriteria2 getSchCrit() { return schCrit; } /** * Sets the value of the schCrit property. * * @param value * allowed object is * {@link PartyAuditTrailSearchCriteria2 } * */ public PartyAuditTrailQueryV01 setSchCrit(PartyAuditTrailSearchCriteria2 value) { this.schCrit = value; return this; } /** * Gets the value of the splmtryData property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the splmtryData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSplmtryData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SupplementaryData1 } * * */ public List<SupplementaryData1> getSplmtryData() { if (splmtryData == null) { splmtryData = new ArrayList<SupplementaryData1>(); } return this.splmtryData; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the splmtryData list. * @see #getSplmtryData() * */ public PartyAuditTrailQueryV01 addSplmtryData(SupplementaryData1 splmtryData) { getSplmtryData().add(splmtryData); return this; } }
9230960b012eb6ab0b9a7b08ce073974f365aa1d
1,795
java
Java
luwak/src/main/java/uk/co/flax/luwak/queryrepresentation/QueryRepresentation.java
pskorupinski/LuLead
ef5c8e9af355b0bd68f5a19b8ae1bc22d967f249
[ "Apache-2.0" ]
null
null
null
luwak/src/main/java/uk/co/flax/luwak/queryrepresentation/QueryRepresentation.java
pskorupinski/LuLead
ef5c8e9af355b0bd68f5a19b8ae1bc22d967f249
[ "Apache-2.0" ]
null
null
null
luwak/src/main/java/uk/co/flax/luwak/queryrepresentation/QueryRepresentation.java
pskorupinski/LuLead
ef5c8e9af355b0bd68f5a19b8ae1bc22d967f249
[ "Apache-2.0" ]
null
null
null
20.872093
67
0.64234
995,526
/** * */ package uk.co.flax.luwak.queryrepresentation; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.lucene.search.Query; /** * @author nonlinear * */ public abstract class QueryRepresentation implements Serializable { public byte[] toBytes() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(this); byte[] yourBytes = bos.toByteArray(); return yourBytes; } catch (IOException ex) { ex.printStackTrace(); return null; } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { ex.printStackTrace(); return null; } try { bos.close(); } catch (IOException ex) { ex.printStackTrace(); return null; } } } public static QueryRepresentation fromBytes(byte [] bytes) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = null; try { in = new ObjectInputStream(bis); Object o = in.readObject(); return (QueryRepresentation) o; } catch (IOException ex) { ex.printStackTrace(); return null; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } finally { try { bis.close(); } catch (IOException ex) { ex.printStackTrace(); return null; } try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); return null; } } } public abstract Query getQuery(); }
92309646286c31f6998adcf9b77b82241dd88337
385
java
Java
src/main/java/com/bigcommerce/api/resources/Resource.java
yjenith/bigcommerce-api-java
df890e4d50eeda7b6a2d9fea68565d5602f91cf0
[ "MIT" ]
null
null
null
src/main/java/com/bigcommerce/api/resources/Resource.java
yjenith/bigcommerce-api-java
df890e4d50eeda7b6a2d9fea68565d5602f91cf0
[ "MIT" ]
null
null
null
src/main/java/com/bigcommerce/api/resources/Resource.java
yjenith/bigcommerce-api-java
df890e4d50eeda7b6a2d9fea68565d5602f91cf0
[ "MIT" ]
null
null
null
25.666667
56
0.784416
995,527
package com.bigcommerce.api.resources; import java.util.List; import com.bigcommerce.api.Filter; import com.bigcommerce.api.Form; import com.bigcommerce.api.Response; public interface Resource { public List<? extends Response> listAll(); public List<? extends Response> listAll(Filter filter); public Response getOne(Integer Id); public Boolean update(Integer Id, Form data); }
9230971690d7fd3e6c7e2e99a0ff326bcca0e146
186
java
Java
pattern-design/src/main/java/com/pattern/designpattern/strategy/behavior/FlyNoWay.java
Zychaowill/pattern
a3517a52bf6a2bcf65e7413b0a273bc3be5d80cd
[ "Apache-2.0" ]
1
2018-07-05T07:43:42.000Z
2018-07-05T07:43:42.000Z
pattern-design/src/main/java/com/pattern/designpattern/strategy/behavior/FlyNoWay.java
Zychaowill/pattern
a3517a52bf6a2bcf65e7413b0a273bc3be5d80cd
[ "Apache-2.0" ]
null
null
null
pattern-design/src/main/java/com/pattern/designpattern/strategy/behavior/FlyNoWay.java
Zychaowill/pattern
a3517a52bf6a2bcf65e7413b0a273bc3be5d80cd
[ "Apache-2.0" ]
3
2019-01-25T14:23:27.000Z
2019-08-24T08:37:04.000Z
16.909091
52
0.741935
995,528
package com.pattern.designpattern.strategy.behavior; public class FlyNoWay implements FlyBehavior { @Override public void fly() { System.out.println("Fly without wings..."); } }
9230987d3c3a3f35d78b0234cec94dd40e88cfea
10,593
java
Java
payara5/mq/examples/jms/SynchTopicExample.java
GiorgioCaculli/B3_Application_Entreprise_Multi-Tiers_et_Veille_Technologique
048fcd7d012dfa9986b4dda87ed9e6eee7c4b3a6
[ "BSD-3-Clause" ]
1
2019-05-22T18:05:12.000Z
2019-05-22T18:05:12.000Z
payara5/mq/examples/jms/SynchTopicExample.java
GiorgioCaculli/B3_Application_Entreprise_Multi-Tiers_et_Veille_Technologique
048fcd7d012dfa9986b4dda87ed9e6eee7c4b3a6
[ "BSD-3-Clause" ]
null
null
null
payara5/mq/examples/jms/SynchTopicExample.java
GiorgioCaculli/B3_Application_Entreprise_Multi-Tiers_et_Veille_Technologique
048fcd7d012dfa9986b4dda87ed9e6eee7c4b3a6
[ "BSD-3-Clause" ]
null
null
null
38.944853
81
0.554517
995,529
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2000-2017 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://oss.oracle.com/licenses/CDDL+GPL-1.1 * or LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ import javax.jms.*; /** * The SynchTopicExample class demonstrates the simplest form of the * publish/subscribe model: the producer publishes a message, and the * consumer reads it using a synchronous receive. * <p> * The program contains a SimpleProducer class, a SynchConsumer class, a * main method, and a method that runs the consumer and producer * threads. * <p> * Specify a topic name on the command line when you run the program. * <p> * The program calls methods in the SampleUtilities class. */ public class SynchTopicExample { String topicName = null; int exitResult = 0; /** * The SynchConsumer class fetches a single message from a topic using * synchronous message delivery. */ public class SynchConsumer extends Thread { /** * Runs the thread. */ public void run() { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Topic topic = null; MessageConsumer msgConsumer = null; final boolean NOLOCAL = true; TextMessage inMessage = null; TextMessage outMessage = null; MessageProducer msgProducer = null; /* * Obtain connection factory. * Create connection. * Create session from connection; false means session is not * transacted. * Obtain topic name. */ try { connectionFactory = SampleUtilities.getConnectionFactory(); connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); topic = SampleUtilities.getTopic(topicName, session); } catch (Exception e) { System.out.println("Connection problem: " + e.toString()); if (connection != null) { try { connection.close(); } catch (JMSException ee) {} } System.exit(1); } /* * Create consumer, then start message delivery. Consumer is * non-local so that it won't receive the message we publish. * Wait for text message to arrive, then display its contents. * Close connection and exit. */ try { msgConsumer = session.createConsumer(topic, null, NOLOCAL); connection.start(); inMessage = (TextMessage) msgConsumer.receive(); System.out.println("CONSUMER THREAD: Reading message: " + inMessage.getText()); /* * Notify producer that we received a message and it * can stop broadcasting. */ msgProducer = session.createProducer(topic); outMessage = session.createTextMessage(); outMessage.setText("Done"); msgProducer.send(outMessage); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); exitResult = 1; } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { exitResult = 1; } } } } } /** * The SimpleProducer class publishes a single message to a topic. */ public class SimpleProducer extends Thread { /** * Runs the thread. */ public void run() { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Topic topic = null; MessageConsumer producerControlConsumer = null; final boolean NOLOCAL = true; MessageProducer msgProducer = null; TextMessage sentMessage = null; final String MSG_TEXT = new String("Here is a message "); Message receivedMessage = null; /* * Obtain connection factory. * Create connection. * Create session from connection; false means session is not * transacted. * Obtain topic name. */ try { connectionFactory = SampleUtilities.getConnectionFactory(); connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); topic = SampleUtilities.getTopic(topicName, session); } catch (Exception e) { System.out.println("Connection problem: " + e.toString()); if (connection != null) { try { connection.close(); } catch (JMSException ee) {} } System.exit(1); } /* * Create non-local consumer to receive "Done" message from * another connection; start delivery. * Create producer and text message. * Set message text, display it, and publish message. * Close connection and exit. */ try { producerControlConsumer = session.createConsumer(topic, null, NOLOCAL); connection.start(); /* * Publish a message once per second until consumer * reports that it has finished receiving messages. */ msgProducer = session.createProducer(topic); sentMessage = session.createTextMessage(); for (int i = 1; receivedMessage == null; i++) { sentMessage.setText(MSG_TEXT + i); System.out.println("PRODUCER THREAD: Publishing message: " + sentMessage.getText()); msgProducer.send(sentMessage); try { Thread.sleep(1000); } catch (InterruptedException ie){} receivedMessage = producerControlConsumer.receiveNoWait(); } } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); exitResult = 1; } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { exitResult = 1; } } } } } /** * Instantiates the consumer and producer classes and starts their * threads. * Calls the join method to wait for the threads to die. * <p> * It is essential to start the consumer before starting the producer. * In the publish/subscribe model, a consumer can ordinarily receive only * messages published while it is active. */ public void run_threads() { SynchConsumer synchConsumer = new SynchConsumer(); SimpleProducer simpleProducer = new SimpleProducer(); synchConsumer.start(); simpleProducer.start(); try { synchConsumer.join(); simpleProducer.join(); } catch (InterruptedException e) {} } /** * Reads the topic name from the command line and displays it. The * topic must have been created by the jmsadmin tool. * Calls the run_threads method to execute the program threads. * Exits program. * * @param args the topic used by the example */ public static void main(String[] args) { SynchTopicExample ste = new SynchTopicExample(); if (args.length != 1) { System.out.println("Usage: java SynchTopicExample <topic_name>"); System.exit(1); } ste.topicName = new String(args[0]); System.out.println("Topic name is " + ste.topicName); ste.run_threads(); SampleUtilities.exit(ste.exitResult); } }
92309978091be75b12df70595f10c5c898506b4e
2,137
java
Java
src/com/lightboxtechnologies/spectrum/ImportMetadata.java
jonstewart/sleuthkit-hadoop
aba62418c79753945e9b03c5f38518d42fc08144
[ "Apache-2.0" ]
1
2020-02-29T14:57:39.000Z
2020-02-29T14:57:39.000Z
src/com/lightboxtechnologies/spectrum/ImportMetadata.java
jonstewart/sleuthkit-hadoop
aba62418c79753945e9b03c5f38518d42fc08144
[ "Apache-2.0" ]
null
null
null
src/com/lightboxtechnologies/spectrum/ImportMetadata.java
jonstewart/sleuthkit-hadoop
aba62418c79753945e9b03c5f38518d42fc08144
[ "Apache-2.0" ]
null
null
null
34.467742
136
0.755264
995,530
package com.lightboxtechnologies.spectrum; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.sleuthkit.hadoop.core.SKJobFactory; public class ImportMetadata extends Configured implements Tool { public int run(String[] args) throws ClassNotFoundException, InterruptedException, IOException { if (args.length != 4) { System.err.println("Usage: ImportMetadata <pathToLocalJsonInputFile> <imageID> <friendlyName> <pathToHDFSSequenceFileDirectory>"); return 1; } final String jsonPath = args[0]; final String imageID = args[1]; final String friendlyName = args[2]; final String outDir = args[3]; final Configuration conf = getConf(); final Job job = SKJobFactory.createJobFromConf( imageID, friendlyName, "ImportMetadata", conf ); job.setJarByClass(ImportMetadata.class); job.setMapperClass(ImportMetadataMapper.class); job.setNumReduceTasks(1); job.setReducerClass(Reducer.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(JsonWritable.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileInputFormat.addInputPath(job, new Path(jsonPath)); SequenceFileOutputFormat.setOutputPath(job, new Path(outDir)); HBaseTables.summon( conf, HBaseTables.ENTRIES_TBL_B, HBaseTables.ENTRIES_COLFAM_B ); System.out.println("Spinning off ImportMetadata Job..."); return job.waitForCompletion(true) ? 0 : 1; } public static void main(String[] args) throws Exception { System.exit( ToolRunner.run(HBaseConfiguration.create(), new ImportMetadata(), args) ); } }
923099c873fa14c14211245426fbd589702fadf8
2,339
java
Java
src/main/java/org/multibit/network/Signature.java
arsadighian/multibit
21e2e9d653d291a7dc36d21b6fc14b2a0da48985
[ "MIT" ]
234
2015-01-19T01:54:13.000Z
2022-03-04T11:40:48.000Z
src/main/java/org/multibit/network/Signature.java
arsadighian/multibit
21e2e9d653d291a7dc36d21b6fc14b2a0da48985
[ "MIT" ]
76
2015-02-01T06:50:15.000Z
2022-01-17T15:29:07.000Z
src/main/java/org/multibit/network/Signature.java
arsadighian/multibit
21e2e9d653d291a7dc36d21b6fc14b2a0da48985
[ "MIT" ]
93
2015-01-14T11:25:30.000Z
2022-03-04T11:40:51.000Z
29.987179
104
0.631894
995,531
/** * Copyright 2013 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.network; /** * POJO Containing Signature information - sed by ParseResult */ public class Signature { private String publicKeyAsHex = null; private String signatureText = null; public String getPublicKeyAsHex() { return publicKeyAsHex; } public void setPublicKeyAsHex(String publicKeyAsHex) { this.publicKeyAsHex = publicKeyAsHex; } public String getSignatureText() { return signatureText; } public void setSignatureText(String signatureText) { this.signatureText = signatureText; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((publicKeyAsHex == null) ? 0 : publicKeyAsHex.hashCode()); result = prime * result + ((signatureText == null) ? 0 : signatureText.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Signature)) return false; Signature other = (Signature) obj; if (publicKeyAsHex == null) { if (other.publicKeyAsHex != null) return false; } else if (!publicKeyAsHex.equals(other.publicKeyAsHex)) return false; if (signatureText == null) { if (other.signatureText != null) return false; } else if (!signatureText.equals(other.signatureText)) return false; return true; } @Override public String toString() { return "Signature [publicKeyAsHex=" + publicKeyAsHex + ", signatureText=" + signatureText + "]"; } }
92309bccc60a85bd45437a1a103c9290b7ea5d3d
13,815
java
Java
core/src/main/java/org/talust/core/transaction/TransactionCreator.java
TalustOrg/Talust
bb4cc240d35dc927cf89433070c9594b972183e8
[ "MIT" ]
9
2018-07-05T01:51:03.000Z
2018-10-12T07:05:59.000Z
core/src/main/java/org/talust/core/transaction/TransactionCreator.java
TalustOrg/Talust
bb4cc240d35dc927cf89433070c9594b972183e8
[ "MIT" ]
null
null
null
core/src/main/java/org/talust/core/transaction/TransactionCreator.java
TalustOrg/Talust
bb4cc240d35dc927cf89433070c9594b972183e8
[ "MIT" ]
4
2018-07-26T11:56:58.000Z
2020-01-11T03:16:56.000Z
39.698276
230
0.599855
995,533
package org.talust.core.transaction;/* * MIT License * * Copyright (c) 2017-2018 talust.org talust.io * * 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. * */ import lombok.extern.slf4j.Slf4j; import org.talust.common.crypto.Sha256Hash; import org.talust.common.model.Coin; import org.talust.common.model.DepositAccount; import org.talust.core.core.Definition; import org.talust.core.core.NetworkParams; import org.talust.core.model.Account; import org.talust.core.model.Address; import org.talust.core.network.MainNetworkParams; import org.talust.core.script.ScriptBuilder; import org.talust.core.storage.ChainStateStorage; import org.talust.core.storage.TransactionStorage; import java.util.*; @Slf4j public class TransactionCreator { private TransactionStorage transactionStorage = TransactionStorage.get(); private ChainStateStorage chainStateStorage = ChainStateStorage.get(); private NetworkParams network = MainNetworkParams.get(); public Transaction createRegConsensus(String money, Account account, byte[] nodeHash160) { //根据交易金额获取当前交易地址下所有的未花费交易 Transaction tx = new Transaction(MainNetworkParams.get()); tx.setVersion(Definition.VERSION); tx.setType(Definition.TYPE_REG_CONSENSUS); Coin totalInputCoin = Coin.ZERO; Coin pay = Coin.COIN.multiply((long) Double.parseDouble(money)); List<TransactionOutput> fromOutputs = selectNotSpentTransaction(pay, account.getAddress()); TransactionInput input = new TransactionInput(); for (TransactionOutput output : fromOutputs) { input.addFrom(output); totalInputCoin = totalInputCoin.add(Coin.valueOf(output.getValue())); } //创建一个输入的空签名 if (account.getAccountType() == network.getSystemAccountVersion()||account.getAccountType() == network.getMainAccountVersion()) { //普通账户的签名 input.setScriptSig(ScriptBuilder.createInputScript(null, account.getEcKey(),nodeHash160)); } else { //认证账户的签名 input.setScriptSig(ScriptBuilder.createCertAccountInputScript(null, account.getAccountTransaction().getHash().getBytes(), account.getAddress().getHash160())); } tx.addInput(input); //交易输出 tx.addOutput(pay, Definition.LOCKTIME_THRESHOLD - 1, account.getAddress()); //是否找零( if (totalInputCoin.compareTo(pay) > 0) { tx.addOutput(totalInputCoin.subtract(pay), account.getAddress()); } //签名交易 final LocalTransactionSigner signer = new LocalTransactionSigner(); try { if (account.getAccountType() == network.getSystemAccountVersion()||account.getAccountType() == network.getMainAccountVersion()) { //普通账户的签名 signer.signInputs(tx, account.getEcKey()); } } catch (Exception e) { log.error(e.getMessage(), e); } return tx; } public Transaction createRemConsensus(DepositAccount depositAccount, Account account, byte[] nodeAddress) { Transaction remTx = new Transaction(MainNetworkParams.get()); remTx.setVersion(Definition.VERSION); remTx.setType(Definition.TYPE_REM_CONSENSUS); Coin totalInputCoin = Coin.ZERO; List<Sha256Hash> txhashs = depositAccount.getTxHash(); TransactionInput input = new TransactionInput(); for (Sha256Hash txhash : txhashs) { Transaction tx = transactionStorage.getTransaction(txhash).getTransaction(); input.addFrom(tx.getOutput(0)); totalInputCoin = totalInputCoin.add(Coin.valueOf(tx.getOutput(0).getValue())); } input.setScriptSig(ScriptBuilder.createInputScript(null, account.getEcKey(),nodeAddress)); remTx.addInput(input); if (null == account) { Address address = new Address(MainNetworkParams.get(), depositAccount.getAddress()); remTx.addOutput(totalInputCoin, address); } else { remTx.addOutput(totalInputCoin, account.getAddress()); } return remTx; } public List<TransactionOutput> selectNotSpentTransaction(Coin amount, Address address) { //获取到所有未花费的交易 List<TransactionOutput> outputs = transactionStorage.getNotSpentTransactionOutputs(address.getHash160()); //选择结果存放列表 List<TransactionOutput> thisOutputs = new ArrayList<TransactionOutput>(); if (outputs == null || outputs.size() == 0) { return thisOutputs; } //遍历选择,原则是尽量少的数据,也就是笔数最少 //小于amount的集合 List<TransactionOutput> lessThanList = new ArrayList<TransactionOutput>(); //大于amount的集合 List<TransactionOutput> moreThanList = new ArrayList<TransactionOutput>(); for (TransactionOutput transactionOutput : outputs) { if (transactionOutput.getValue() == amount.value) { //如果刚好相等,则立即返回 thisOutputs.add(transactionOutput); return thisOutputs; } else if (transactionOutput.getValue() > amount.value) { //加入大于集合 moreThanList.add(transactionOutput); } else { //加入小于于集合 lessThanList.add(transactionOutput); } } transferPreferredWithLessNumber(amount, lessThanList, moreThanList, thisOutputs); //依然按照交易时间排序 if (thisOutputs.size() > 0) { Collections.sort(thisOutputs, new Comparator<TransactionOutput>() { @Override public int compare(TransactionOutput o1, TransactionOutput o2) { long v1 = o1.getParent().getTime(); long v2 = o2.getParent().getTime(); if (v1 == v2) { return 0; } else if (v1 > v2) { return 1; } else { return -1; } } }); } return thisOutputs; } /* * 交易选择 -- 优先使用零钱 */ private void transferPreferredWithSmallChangeMulUser(Coin amount, HashMap<String, List<TransactionOutput>> lessThanList, HashMap<String, List<TransactionOutput>> moreThanList, HashMap<String, List<TransactionOutput>> thisOutputs) { if (lessThanList.size() > 0) { //计算所有零钱,是否足够 Coin lessTotal = Coin.ZERO; Iterator<String> lessit = lessThanList.keySet().iterator(); while (lessit.hasNext()) { String address = lessit.next(); List<TransactionOutput> userLessThanlist = lessThanList.get(address); for (TransactionOutput transactionOutput : userLessThanlist) { lessTotal = lessTotal.add(Coin.valueOf(transactionOutput.getValue())); } } if (lessTotal.isLessThan(amount)) { //不够,那么必定有大的 selectOneOutputMulUser(moreThanList, thisOutputs); } else { //选择零钱 selectSmallChangeMulUser(amount, lessThanList, thisOutputs); } } else { //没有比本次交易最大的未输出交易 selectOneOutputMulUser(moreThanList, thisOutputs); } } /* * 交易选择 -- 以交易数据小优先,该种机制尽量选择一笔输入 */ private void transferPreferredWithLessNumber(Coin amount, List<TransactionOutput> lessThanList, List<TransactionOutput> moreThanList, List<TransactionOutput> outputs) { if (moreThanList.size() > 0) { //有比本次交易大的未输出交易,直接使用其中最小的一个 selectOneOutput(moreThanList, outputs); } else { //没有比本次交易最大的未输出交易 selectSmallChange(amount, lessThanList, outputs); } } /* * 交易选择 -- 以交易数据小优先,该种机制尽量选择一笔输入 */ private void transferPreferredWithLessNumberMulUser(Coin amount, HashMap<String, List<TransactionOutput>> lessThanList, HashMap<String, List<TransactionOutput>> moreThanList, HashMap<String, List<TransactionOutput>> outputs) { if (moreThanList.size() > 0) { //有比本次交易大的未输出交易,直接使用其中最小的一个 selectOneOutputMulUser(moreThanList, outputs); } else { //没有比本次交易最大的未输出交易 selectSmallChangeMulUser(amount, lessThanList, outputs); } } /* * 选择列表里面金额最小的一笔作为输出 */ private void selectOneOutput(List<TransactionOutput> moreThanList, List<TransactionOutput> outputs) { if (moreThanList == null || moreThanList.size() == 0) { return; } Collections.sort(moreThanList, new Comparator<TransactionOutput>() { @Override public int compare(TransactionOutput o1, TransactionOutput o2) { long v1 = o1.getValue(); long v2 = o2.getValue(); if (v1 == v2) { return 0; } else if (v1 > v2) { return 1; } else { return -1; } } }); outputs.add(moreThanList.get(0)); } /* * 出现的第一笔为输出 */ private void selectOneOutputMulUser(HashMap<String, List<TransactionOutput>> moreThanList, HashMap<String, List<TransactionOutput>> outputs) { if (moreThanList == null || moreThanList.size() == 0) { return; } Iterator<String> moreit = moreThanList.keySet().iterator(); while (moreit.hasNext()) { String address = moreit.next(); List<TransactionOutput> userMoreThanList = moreThanList.get(address); if (userMoreThanList.size() == 0) { continue; } else { TransactionOutput out = userMoreThanList.get(0); List<TransactionOutput> oneList = new ArrayList<TransactionOutput>(); oneList.add(out); outputs.put(address, oneList); return; } } } /* * 选择零钱,原则是尽量少的找钱,尽量少的使用输出笔数 */ private void selectSmallChange(Coin amount, List<TransactionOutput> lessThanList, List<TransactionOutput> outputs) { if (lessThanList == null || lessThanList.size() == 0) { return; } //排序 Collections.sort(lessThanList, new Comparator<TransactionOutput>() { @Override public int compare(TransactionOutput o1, TransactionOutput o2) { long v1 = o1.getValue(); long v2 = o2.getValue(); if (v1 == v2) { return 0; } else if (v1 > v2) { return 1; } else { return -1; } } }); //已选择的金额 Coin total = Coin.ZERO; //从小到大选择 for (TransactionOutput transactionOutput : lessThanList) { outputs.add(transactionOutput); total = total.add(Coin.valueOf(transactionOutput.getValue())); if (total.isGreaterThan(amount)) { //判断是否可以移除最小的几笔交易 List<TransactionOutput> removeList = new ArrayList<TransactionOutput>(); for (TransactionOutput to : outputs) { total = total.subtract(Coin.valueOf(to.getValue())); if (total.isGreaterThan(amount)) { removeList.add(to); } else { break; } } if (removeList.size() > 0) { outputs.removeAll(removeList); } break; } } } /* * 选择零钱,原则先后顺序 */ private void selectSmallChangeMulUser(Coin amount, HashMap<String, List<TransactionOutput>> lessThanList, HashMap<String, List<TransactionOutput>> outputs) { if (lessThanList == null || lessThanList.size() == 0) { return; } //已选择的金额 Coin total = Coin.ZERO; Iterator<String> lessit = lessThanList.keySet().iterator(); while (lessit.hasNext()) { String address = lessit.next(); List<TransactionOutput> userLessThanList = lessThanList.get(address); List<TransactionOutput> userOutputList = new ArrayList<TransactionOutput>(); //从小到大选择 for (TransactionOutput transactionOutput : userLessThanList) { userOutputList.add(transactionOutput); total = total.add(Coin.valueOf(transactionOutput.getValue())); if (total.isGreaterThan(amount)) { break; } } outputs.put(address, userOutputList); } } }
92309be1276a690589e0d3c4c3ddf3282ab76430
336
java
Java
Cheetah_DAO/src/com/cheetah/beans/BeanException.java
Siliver4/CheetahJEE_Galaxy
5760ae89e5403bdb1ecbfe06b05a7ecfec3d2078
[ "MIT" ]
null
null
null
Cheetah_DAO/src/com/cheetah/beans/BeanException.java
Siliver4/CheetahJEE_Galaxy
5760ae89e5403bdb1ecbfe06b05a7ecfec3d2078
[ "MIT" ]
null
null
null
Cheetah_DAO/src/com/cheetah/beans/BeanException.java
Siliver4/CheetahJEE_Galaxy
5760ae89e5403bdb1ecbfe06b05a7ecfec3d2078
[ "MIT" ]
null
null
null
21
60
0.630952
995,534
package com.cheetah.beans; public class BeanException extends Exception { public BeanException(String message) { super(message); } public BeanException(String message, Throwable cause) { super(message, cause); } public BeanException(Throwable cause) { super(cause); } }
92309d64dd9188d4b4e77b114935ff7febdfec9e
5,784
java
Java
bundles/target/src/main/java/org/jscsi/target/scsi/sense/SenseKey.java
YunLemon/jSCSI
6169bfe73f0b15de7d6485453555389e782ae888
[ "BSD-3-Clause" ]
30
2015-09-08T07:07:39.000Z
2022-03-21T01:22:02.000Z
bundles/target/src/main/java/org/jscsi/target/scsi/sense/SenseKey.java
YunLemon/jSCSI
6169bfe73f0b15de7d6485453555389e782ae888
[ "BSD-3-Clause" ]
8
2015-03-08T19:13:42.000Z
2020-12-10T10:31:43.000Z
bundles/target/src/main/java/org/jscsi/target/scsi/sense/SenseKey.java
YunLemon/jSCSI
6169bfe73f0b15de7d6485453555389e782ae888
[ "BSD-3-Clause" ]
24
2016-02-17T20:07:06.000Z
2021-08-18T13:56:12.000Z
39.616438
121
0.647649
995,535
package org.jscsi.target.scsi.sense; /** * The SENSE KEY field indicates generic information describing an error or exception condition. The field's length is 4 * bits. * * @author Andreas Ergenzinger */ public enum SenseKey { /** * Indicates that there is no specific sense key information to be reported. This may occur for a successful command * or for a command that receives CHECK CONDITION status because one of the FILEMARK, EOM, or ILI bits is set to * one. */ NO_SENSE(0x00), /** * Indicates that the command completed successfully, with some recovery action performed by the device server. * Details may be determined by examining the additional sense bytes and the INFORMATION field. When multiple * recovered errors occur during one command, the choice of which error to report (e.g., first, last, most severe) * is vendor specific. */ RECOVERED_ERROR(0x1), /** * Indicates that the logical unit is not accessible. Operator intervention may be required to correct this * condition. */ NOT_READY(0x2), /** * Indicates that the command terminated with a non-recovered error condition that may have been caused by a flaw in * the medium or an error in the recorded data. This sense key may also be returned if the device server is unable * to distinguish between a flaw in the medium and a specific hardware failure (i.e., sense key 4h * {@link #HARDWARE_ERROR}). */ MEDIUM_ERROR(0x3), /** * Indicates that the device server detected a non-recoverable hardware failure (e.g., controller failure, device * failure, or parity error) while performing the command or during a self test. */ HARDWARE_ERROR(0x4), /** * Indicates that: * * a) The command was addressed to an incorrect logical unit number (see SAM-3); b) The command had an invalid task * attribute (see SAM-3); c) The command was addressed to a logical unit whose current configuration prohibits * processing the command; d) There was an illegal parameter in the CDB; or e) There was an illegal parameter in the * additional parameters supplied as data for some commands (e.g., PERSISTENT RESERVE OUT). * * If the device server detects an invalid parameter in the CDB, it shall terminate the command without altering the * medium. If the device server detects an invalid parameter in the additional parameters supplied as data, the * device server may have already altered the medium. */ ILLEGAL_REQUEST(0x5), /** * Indicates that a unit attention condition has been established (e.g., the removable medium may have been changed, * a logical unit reset occurred). See SAM-3. */ UNIT_ATTENTION(0x6), /** * Indicates that a command that reads or writes the medium was attempted on a block that is protected. The read or * write operation is not performed. */ DATA_PROTECT(0x7), /** * Indicates that a write-once device or a sequential-access device encountered blank medium or format-defined * end-of-data indication while reading or that a write-once device encountered a non-blank medium while writing. */ BLANK_CHECK(0x8), /** * This sense key is available for reporting vendor specific conditions. */ VENDOR_SPECIFIC(0x9), /** * Indicates an EXTENDED COPY command was aborted due to an error condition on the source device, the destination * device, or both (see "errors detected during processing of segment descriptors"). */ COPY_ABORTED(0xa), /** * Indicates that the device server aborted the command. The application client may be able to recover by trying the * command again. */ ABORTED_COMMAND(0xb), /* * 0x0c is obsolete. */ /** * Indicates that a buffered SCSI device has reached the end-of-partition and data may remain in the buffer that has * not been written to the medium. One or more RECOVER BUFFERED DATA command(s) may be issued to read the unwritten * data from the buffer. (See SSC-2.) */ VOLUME_OVERFLOW(0xd), /** * Indicates that the source data did not match the data read from the medium. */ MISCOMPARE(0xe); /* * 0xf is reserved. */ /** * Look-up array that maps sense key values to instances of this enumeration. */ private static SenseKey[] mapping = new SenseKey[16]; static {// initialize mapping final SenseKey[] keys = values(); for (int i = 0; i < keys.length; ++i) mapping[keys[i].value] = keys[i]; // some will remain initialized to null } /** * Returns the {@link SenseKey} instance representing the passed <i>value</i>. * * @param value a sense key value * @return the {@link SenseKey} instance representing the passed <i>value</i> */ public static SenseKey valueOf (final int value) { final int index = 15 & value;// keep only the last four bits if (0 < index || index >= mapping.length) return null; return mapping[index]; } /** * The serialized value of the {@link SenseKey} instance. */ private final int value; /** * The constructor. * * @param value the serialized value of the object. */ private SenseKey (int value) { this.value = value; } /** * The serialized value of the instance. * * @return serialized value of the instance */ public int getValue () { return value; } }
92309d85f6c463a312ef763523a6c5635b90c9f2
1,140
java
Java
[060]Spring-Data-MyBatis/src/main/java/com/kapcb/ccc/domain/Lock.java
kapbc/Spring-Kapcb
0613880498373e50eac6915428a4e2aafbf1b6cc
[ "Apache-2.0" ]
3
2021-01-12T14:11:13.000Z
2021-12-24T03:07:15.000Z
[060]Spring-Data-MyBatis/src/main/java/com/kapcb/ccc/domain/Lock.java
Eircc/Spring-Kapcb
0613880498373e50eac6915428a4e2aafbf1b6cc
[ "Apache-2.0" ]
16
2021-01-07T13:09:16.000Z
2022-03-31T21:03:33.000Z
[060]Spring-Data-MyBatis/src/main/java/com/kapcb/ccc/domain/Lock.java
Eircc/Spring-Kapcb
0613880498373e50eac6915428a4e2aafbf1b6cc
[ "Apache-2.0" ]
null
null
null
17.272727
62
0.507018
995,536
package com.kapcb.ccc.domain; import java.util.List; /** * <a>Title: Lock </a> * <a>Author: kapcb <a> * <a>Description: <a> * * @author kapcb * @version 1.0.0 * @date 2021/2/28 10:13 */ public class Lock { private Integer id; private String lockName; /** * 查询锁的时候查询出所有钥匙 */ private List<Key> keys; public Lock() { } public Lock(Integer id, String lockName, List<Key> keys) { this.id = id; this.lockName = lockName; this.keys = keys; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLockName() { return lockName; } public void setLockName(String lockName) { this.lockName = lockName; } public List<Key> getKeys() { return keys; } public void setKeys(List<Key> keys) { this.keys = keys; } @Override public String toString() { return "Lock{" + "id=" + id + ", lockName='" + lockName + '\'' + ", keys=" + keys + '}'; } }
92309dbbcad34235f259bf90a008916122c113b2
345
java
Java
todo-app/src/main/java/com/curtisnewbie/dao/script/PreInitializationScript.java
CurtisNewbie/todoapp
6c9ee2d1faaa4702e6b8ec3c1dab23e318295f4d
[ "Apache-2.0" ]
1
2020-12-23T09:02:21.000Z
2020-12-23T09:02:21.000Z
todo-app/src/main/java/com/curtisnewbie/dao/script/PreInitializationScript.java
CurtisNewbie/todoapp
6c9ee2d1faaa4702e6b8ec3c1dab23e318295f4d
[ "Apache-2.0" ]
null
null
null
todo-app/src/main/java/com/curtisnewbie/dao/script/PreInitializationScript.java
CurtisNewbie/todoapp
6c9ee2d1faaa4702e6b8ec3c1dab23e318295f4d
[ "Apache-2.0" ]
null
null
null
19.166667
87
0.750725
995,537
package com.curtisnewbie.dao.script; import java.sql.Connection; import java.sql.SQLException; /** * <p> * Script that will be executed before any mapper is created * </p> * * @author yongjie.zhuang */ public interface PreInitializationScript { void preInitialize(ScriptRunner runner, Connection connection) throws SQLException; }
92309dfcbe0feeabadc357b02e84901974ad32ef
1,956
java
Java
javabase/src/main/java/rxjava2/demo/Demos13_Flowable_flatMap.java
HailouWang/DemosForApi
a29728fc4b64fc58f10ee215a6902190b66a69ee
[ "Apache-2.0" ]
1
2017-08-04T02:53:45.000Z
2017-08-04T02:53:45.000Z
javabase/src/main/java/rxjava2/demo/Demos13_Flowable_flatMap.java
HailouWang/DemosForApi
a29728fc4b64fc58f10ee215a6902190b66a69ee
[ "Apache-2.0" ]
null
null
null
javabase/src/main/java/rxjava2/demo/Demos13_Flowable_flatMap.java
HailouWang/DemosForApi
a29728fc4b64fc58f10ee215a6902190b66a69ee
[ "Apache-2.0" ]
null
null
null
33.152542
102
0.452965
995,538
package rxjava2.demo; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import java.util.ArrayList; import java.util.List; import io.reactivex.Flowable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; /** * Created by ifei on 2017/9/18. */ public class Demos13_Flowable_flatMap { public static void main(String args[]){ //1、打印字符数组中的数字和字母分开打印 String[] stringArray1 = new String[]{"1","a","2","b","3","c","4","d"}; String[] stringArray2 = new String[]{"11","aa","22","bb","33","cc","44","dd"}; List<String[]> list = new ArrayList<>(); list.add(stringArray1); list.add(stringArray2); Flowable.fromIterable(list) .flatMap(new Function<String[], Publisher<String>>() { @Override public Publisher<String> apply(@NonNull final String[] strings) throws Exception { return new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { for(int i=0;i<strings.length;i++){ if(i%2==0){ s.onNext(strings[i]); } } for(int i=0;i<strings.length;i++){ if(i%2!=0){ s.onNext(strings[i]); } } } }; } }).subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { System.out.println("---->"+s); } }); } }
92309e066d9a3523a3790af10035d6c27b1a9571
18,682
java
Java
src/main/InterfaceAdapter/FacadeSys.java
ChiehAnChang/HR-System
ce8a595b6d9c3a77f6260052c5ca76d76d6edda2
[ "MIT" ]
null
null
null
src/main/InterfaceAdapter/FacadeSys.java
ChiehAnChang/HR-System
ce8a595b6d9c3a77f6260052c5ca76d76d6edda2
[ "MIT" ]
null
null
null
src/main/InterfaceAdapter/FacadeSys.java
ChiehAnChang/HR-System
ce8a595b6d9c3a77f6260052c5ca76d76d6edda2
[ "MIT" ]
null
null
null
34.660482
177
0.611819
995,539
package main.InterfaceAdapter; import main.UsesCases.*; import java.util.ArrayList; import java.util.List; public class FacadeSys { // === Instance Variables === // === UI Input Data === private final String userID; // ========================== // === Controller === private final EmployeeListController employeeListController; private final LoginListController loginListController; private final PersonalInfoController personalInfoController; private final VerifierController verifierController; private final WorkListController workListController; private final WorkManagerController workManagerController; private final GroupManagerController groupManagerController; // ========================== // === Data Related Class === private final DataGateway fileGateway; private final ILoginList loginList; private final IEmployeeList employeeList; private final IWorkList workList; private final IGroupList groupList; /** * Construct the admin system. This system can let admin manager employee by Uses Cases. * * @param userID the ID of the target user. */ public FacadeSys(String userID) { // UI Input this.userID = userID; // Login this.loginList = new LoginList(); this.loginListController = new LoginListController(this.loginList); // Employee this.employeeList = new EmployeeList(); this.employeeListController = new EmployeeListController(this.employeeList); // Work this.workList = new WorkList(); this.workListController = new WorkListController(this.workList); // Group this.groupList = new GroupList(); // Initial Use Case Controller this.personalInfoController = new PersonalInfoController(new PersonalManager()); this.verifierController = new VerifierController(new Verifier()); this.workManagerController = new WorkManagerController(new WorkManager(), new GroupManager()); this.groupManagerController = new GroupManagerController(new GroupManager()); // Initial DataGateway this.fileGateway = new DataGateway(); } // === System methods === /** * Log in method to the system. * * @param username the username from the input of the targeted user. * @param password the password from the input of the targeted user. * * @return true iff the user can successfully log in. * */ public boolean systemStart(String username, String password) { this.fileGateway.ReadInputFileToLoginList(this.loginList); this.fileGateway.ReadInputFileToEmployeeList(this.employeeList); this.fileGateway.ReadInputFileToWorkList(this.workList); this.fileGateway.ReadInputFileToGroupList(this.groupList); return this.verifierController.verifyLogin(username, password, this.loginList); } /** * Method for ending the system. * */ public void systemEnd(){ this.fileGateway.WriteOutputFile(this.loginList, this.employeeList, this.workList, this.groupList); } // === Personal UI Method === // === Case (i) Check your personal Info ==== /** * Manage the personal information. * * @return the strings with personal information. * */ public String personalInfo(){ StringBuilder result = new StringBuilder(); ArrayList<String> infos = this.personalInfoController.personalInfo(this.loginList, this.employeeList, this.userID); // 0: Name, 1:ID, 3:Phone Number , 4:Address, 5: Department 6: Work hours (PartTime)/ position (Full Time) result.append(infos.get(0)).append(infos.get(1)).append(infos.get(3)).append(infos.get(4)) .append(infos.get(5)).append(infos.get(6)); if (this.verifierController.verifyFullTime(this.userID, this.employeeList)) { // 7: Status, 8: Total vacation with salary, 9: Vacation used result.append(infos.get(7)); result.append(infos.get(8)); result.append(infos.get(9)); } return result.toString(); } // ========================================== // === Case (ii) Check your total Salary (including bonus) ==== /** * Check the total salary for the user. * * @return the strings with total salary. * */ public String checkTotalSalary(){ return this.personalInfoController.checkTotalSalary(this.employeeList, this.userID, this.groupList, this.workList); } // ========================================== // === Case (iii) Check your minimum wage ==== /** * Check the minimum wage for the user. * * @return the strings with minimum wage. * */ public String checkMinimumWage(){ return this.personalInfoController.checkMinimumWage(this.employeeList, this.userID); } // ========================================== // === Case (iv) Check your bonus salary from vacation ==== /** * Check the vocation bonus for the user. * * @return the strings with vocation bonus. * */ public String checkVacationBonus(){ return this.personalInfoController.checkVacationBonus(this.employeeList, this.userID); } // ========================================== // === Case (v) Check your bonus salary from KPI ==== /** * Check the KPI bonus for the user. * * @return the strings with KPI bonus. * */ public String checkKPIBonus(){ return this.personalInfoController.checkKPIBonus(this.employeeList, this.userID, this.groupList, this.workList); } // ========================================== // === Case (vi) Change personal Information ==== /** * Setter method for the user's personal information. * * @return the strings with information if the personal information has been successfully set. * */ public String setPersonalInfo(String option, String response){ // option {1: Name, 2: Password, 3: Address, 4. Phone number} if (this.personalInfoController.setPersonalInfo(option, response, this.loginList, this.userID)){ return "Set personal information success!"; } else{ return "Invalid option or response!"; } } // ================================================== // ================== Work UI Method ================ // === Case (i) Check your own work's information ==== /** * Show if there is work needed to do for the employee. * * @return the string of the work needed to do. * */ public String showAllWorkNeedToDo() { return this.workManagerController.showAllWorkNeedToDo(this.userID, this.groupList, this.workList); } /** * Check the work detail for the employee. * * @param workID the ID of the Work. * * @return the strings with work detail. * */ public String showWorkDetail(String workID) { return this.workManagerController.showWorkDetail(workID, this.workList); } /** * Check if the work existed for the employee. * * @param workID the ID of the Work. * * @return true iff the work existed. * */ public boolean checkWorkExist(String workID) { return this.workListController.checkWorkExist(workID); } // ================================================== // === Case (ii) createWork ==== /** * Create a new Work. * * @param info_list the information list. * * @return true iff the work has been created. * */ public boolean createWork(ArrayList<String> info_list) { if (this.verifierController.verifyLevel(info_list.get(4), this.userID, this.employeeList) && !this.workListController.checkWorkExist(info_list.get(1))) { return this.workListController.createWork(info_list); }else{ return false; } } // ================================================== // === Case (iii) Start a work with assigning leader ==== /** * Assign a leader, i.e. Employee, to the Work. * * @param workID the ID of the Work. * @param leaderID the ID of the leader. * * @return true iff the leader has been assigned. * */ public boolean assignLeaderToWork(String workID, String leaderID) { if (this.workListController.checkWorkExist(workID) && this.verifierController.verifyUserExistence(leaderID, this.loginList)) { String workLevel = this.workListController.FindWorkLevel(workID); String leaderLevel = this.personalInfoController.checkUserLevel(leaderID, this.employeeList); if (this.verifierController.verifyLevel(workLevel, this.userID, this.employeeList)&& this.userID.equals(leaderID)) { this.workManagerController.assignLeaderToWork(workID, leaderID, this.groupList); return true; } if (this.verifierController.verifyLevel(workLevel, this.userID, this.employeeList)&& this.verifierController.verifyLevel(leaderLevel,this.userID,this.employeeList)){ this.workManagerController.assignLeaderToWork(workID, leaderID, this.groupList); return true; } } return false; } // ================================================== // === Case (iv) Distribute a work === /** * Show all the work leader of the Work. * * @return the string with all leaders. * */ public String showAllWorkLead(){ return this.workManagerController.showAllWorkLead(this.userID, this.groupList, this.workList); } /** * Show all the work that has a lower authority level of the targeted employee. * * @return the string with all the applicable Work. * */ public String showAllLowerWork() { String level = this.personalInfoController.checkUserLevel(this.userID, this.employeeList); return this.workManagerController.showAllLowerWork(level, this.workList); } /** * Distribute the Work to the member. * * @param workID the ID of the Work. * @param memberID the member of the Work. * * @return true iff the Work has been successfully distributed. * */ public boolean distributeWork(String workID, String memberID) { if (this.workListController.checkWorkExist(workID) && this.verifierController.verifyUserExistence(memberID, this.loginList)) { String memberLevel = this.personalInfoController.checkUserLevel(memberID, this.employeeList); if (this.verifierController.verifyLeader(this.userID, workID, this.groupList) && this.verifierController.verifyLevel(memberLevel, this.userID, this.employeeList)) { return this.groupManagerController.distributeWork(workID, memberID, this.groupList); } } return false; } public boolean selfLeaderCheck(String workID) { if (this.groupManagerController.groupExist(workID, this.groupList)) { return this.verifierController.verifyLeader(this.userID, workID, groupList); } return false; } public String allGroupMember(String workID) { StringBuilder result = new StringBuilder(); for (String id: this.groupManagerController.allMember(workID, this.groupList)) { List<String> info = this.personalInfoController.personalInfo(this.loginList, this.employeeList, id); result.append(info.get(0)).append(" ").append(id).append(" ").append(info.get(5)).append("\n"); } return result.toString(); } public boolean removeMember(String workID, String memberID) { return this.groupManagerController.removeOneFromGroup(memberID, workID, this.groupList); } // ================================================== // Here are some method used to show other user information, may be used in hr workers or work distribute // === Case (v) Create a user === /** * Create the User for the system. * * @param name the name of the user. * @param password the password of the user. * @param phone the phone number of the user. * @param address the address of the user. * @param department the department of the user. * @param wage the wage of the user. * @param position the position of the user. * @param level the level of user. * @param status the status of the user. * * @return the list of strings with all the information related to the user. * */ public List<String> createUser(String name, String password, String phone, String address, String department, String wage, String position, String level, String status) { List<String> result = new ArrayList<>(); boolean validLevelGiven = this.verifierController.validToCreate(level, this.employeeList, this.userID); result.add(String.valueOf(validLevelGiven)); if (validLevelGiven){ // Give ID result.add(this.loginListController.addUser(name, password,phone, address)); result.add(password); this.employeeListController.addEmployee(department,wage,position,level,status, name);} return result; } // ================================================== // === Case (vi) Delete a user === /** * Delete the user from the system. * * @param targetUserID the ID of the user to be deleted. * * @return true iff the user has been successfully deleted. * */ public boolean deleteUser(String targetUserID) { boolean validLevelGiven = this.verifierController.verifyUserExistence(targetUserID, this.loginList ) && this.verifierController.validToDelete(targetUserID, this.employeeList, this.userID); if (validLevelGiven) { this.employeeListController.deleteEmployee(targetUserID); this.loginListController.deleteUser(targetUserID); this.groupManagerController.removeEmployeeFromAllRelatedGroup(targetUserID, this.groupList); } return validLevelGiven; } // ================================================== // Case 7 Check all lower level employees' salary-related information /** * Check the salaries of the employees who have the lower level of authority from the targeted user. * * * @return a list of strings with the information about salaries of the applicable users. * */ public List<String> checkLowerLevelEmployeeSalary() { List<String> result = new ArrayList<>(); List<String> personalInfo = personalInfoController.personalInfo(this.loginList, this.employeeList, this.userID); // Size < 6 means that the user id is for part-time employee if (personalInfo.size() <= 6) { result.add(personalInfoController.checkTotalSalary(this.employeeList, this.userID, groupList, workList)); } else { result.add(personalInfoController.checkTotalSalary(this.employeeList, this.userID, groupList, workList)); // 8 : Total Vacation with Salary: result.add(personalInfo.get(8)); // 9 :Vacation Used result.add(personalInfo.get(9)); } return result; } /** * Show all users with the lower authority than the targeted user. * * @return a string with the users that have lower level. * */ public String showAllLowerUser() { UserManager u = new UserManager(); StringBuilder result = new StringBuilder(); for (String i : u.getLowerUsers(this.personalInfoController.checkUserLevel(this.userID,this.employeeList), this.loginList,this.employeeList)) { result.append(i).append("\n"); } return result.toString(); } //===================================== // === Case (viii) Change employee's information === /** * Setter method for the employee's information. * * @param userID the ID of the user to be modified. * @param option the option of the user. * @param response the new information. * * @return the string message if the information has been successfully changed. * */ public String setEmployeeInfo(String userID, String option, String response){ // option {1: Department, 2: Level, 3: setWage, 4. Position, 5. State, 6. Vacation with Salary, 7. Vacation Used, // 8. Working hours, 9. reset working hour} if (this.verifierController.verifyUserExistence(userID, this.loginList) && (this.personalInfoController.setEmployeeInfo(userID, option, response, this.employeeList))) { return "Set employee information success"; } else{ return "Invalid option or response, or the employee does not exist!"; } } //===================================== // === Case (X) Extend a Work // Before following method call, we will firstly call the method "showAllWorkLead". /** * Extend the Work deadline. * * @param days the days to be extended. * @param workID the ID of the targeted Work. * * @return true iff the Work has been successfully extended. * */ public boolean extendWork(String days, String workID) { try { Long.parseLong(days); } catch (Exception e) { return false; } if (this.verifierController.verifyLeader(this.userID, workID, this.groupList) && this.workList.checkWorkExist(workID)) { this.workManagerController.extendWork(workID, days, this.workList); return true; } return false; } //===================================== // === Case (XI) Change Work State public void updateAllWorkState() { this.workManagerController.updateStateAll(this.workList); } public boolean changeWorkState(String workID, String state){ if (this.workList.checkWorkExist(workID) && this.verifierController.verifyLeader(this.userID, workID, this.groupList)) { this.workManagerController.changeState(workID, state, this.workList); return true; } return false; } }
92309e1df34c4f52c41f8d5a0ba6de33be16c5a8
208
java
Java
src/schema/behavior/responsibility/demolikeokhttp/Character.java
forgot2015/ForgotHeadFirstJava
64c655bca00b998a6f15405f8e9b64472a8bb1ad
[ "MIT" ]
null
null
null
src/schema/behavior/responsibility/demolikeokhttp/Character.java
forgot2015/ForgotHeadFirstJava
64c655bca00b998a6f15405f8e9b64472a8bb1ad
[ "MIT" ]
null
null
null
src/schema/behavior/responsibility/demolikeokhttp/Character.java
forgot2015/ForgotHeadFirstJava
64c655bca00b998a6f15405f8e9b64472a8bb1ad
[ "MIT" ]
null
null
null
17.333333
54
0.721154
995,540
package schema.behavior.responsibility.demolikeokhttp; /** * @author zongfulin * Date: 2021/4/22 * Time: 09:36 * Description: */ public interface Character { Response processRequest(Chain chain); }
92309e6a260331104e37f8a5c968c508dab6928f
2,432
java
Java
src/main/java/com/igeekinc/util/VolumeManager.java
ashish-amarnath/distributed-data-generator
0e638122bebace6aadf5f2acbeb5f09132a93b71
[ "Apache-2.0" ]
1
2021-07-19T13:25:52.000Z
2021-07-19T13:25:52.000Z
src/main/java/com/igeekinc/util/VolumeManager.java
ashish-amarnath/distributed-data-generator
0e638122bebace6aadf5f2acbeb5f09132a93b71
[ "Apache-2.0" ]
9
2021-04-08T20:53:04.000Z
2022-03-02T16:32:32.000Z
src/main/java/com/igeekinc/util/VolumeManager.java
ashish-amarnath/distributed-data-generator
0e638122bebace6aadf5f2acbeb5f09132a93b71
[ "Apache-2.0" ]
5
2021-02-22T19:58:48.000Z
2022-02-11T12:38:34.000Z
33.315068
101
0.752056
995,541
/* * Copyright 2002-2014 iGeek, Inc. * All Rights Reserved * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igeekinc.util; import java.io.IOException; public abstract class VolumeManager extends ChangeModel { public VolumeManager(CheckCorrectDispatchThread checker) { super(checker); } public abstract Volume [] getVolumes(); public abstract Volume getBootDrive(); public abstract Volume [] getExternalDrives(); public abstract Volume [] getRemovableDrives(); public abstract Volume getVolumeForPath(FilePath path) throws IOException; public Volume getVolumeForPath(String path) throws IOException { FilePath findPath = FilePath.getFilePath(path); return getVolumeForPath(findPath); } public Volume getLargestExternal() { Volume [] externalVolumes = getExternalDrives(); Volume bootVolume = getBootDrive(); long lastBiggest = 0; Volume maxAvailable = null; for (int curVolumeNum = 0; curVolumeNum < externalVolumes.length; curVolumeNum++) { Volume curVolume = externalVolumes[curVolumeNum]; if (curVolume.freeSpace() > lastBiggest && !curVolume.equals(bootVolume)) { maxAvailable = curVolume; lastBiggest = curVolume.freeSpace(); } } return(maxAvailable); } public static final int kMountedOK = 0; public static final int kMountTimedOut = 1; public static final int kPermissionDenied = 2; public static final int kMountFailed = 3; public abstract int mountVolume(Volume volumeToMount, long timeout, boolean userInteractionAllowed); public static final int kMountable = 0; public static final int kNeedsStoredPassword = 1; public static final int kNeedsAccessToStoredPassword = 2; public static final String kVolumeAddedPropertyName = "volumeAdded"; public static final String kVolumeRemovedPropertyName = "volumeRemoved"; public abstract int ensureMountablity(Volume volumeToPreflight); }
92309ea913006c44f76eaa87569f7f34ed14fa76
13,293
java
Java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CampaignAssetSetServiceGrpc.java
giger85/google-ads-java
e91f6aba2638d172baf302dbc3ff1dceb80c70fe
[ "Apache-2.0" ]
1
2022-02-22T08:10:07.000Z
2022-02-22T08:10:07.000Z
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CampaignAssetSetServiceGrpc.java
giger85/google-ads-java
e91f6aba2638d172baf302dbc3ff1dceb80c70fe
[ "Apache-2.0" ]
null
null
null
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CampaignAssetSetServiceGrpc.java
giger85/google-ads-java
e91f6aba2638d172baf302dbc3ff1dceb80c70fe
[ "Apache-2.0" ]
null
null
null
43.159091
203
0.743549
995,542
package com.google.ads.googleads.v10.services; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * <pre> * Service to manage campaign asset set * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/ads/googleads/v10/services/campaign_asset_set_service.proto") @io.grpc.stub.annotations.GrpcGenerated public final class CampaignAssetSetServiceGrpc { private CampaignAssetSetServiceGrpc() {} public static final String SERVICE_NAME = "google.ads.googleads.v10.services.CampaignAssetSetService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest, com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse> getMutateCampaignAssetSetsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "MutateCampaignAssetSets", requestType = com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest.class, responseType = com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest, com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse> getMutateCampaignAssetSetsMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest, com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse> getMutateCampaignAssetSetsMethod; if ((getMutateCampaignAssetSetsMethod = CampaignAssetSetServiceGrpc.getMutateCampaignAssetSetsMethod) == null) { synchronized (CampaignAssetSetServiceGrpc.class) { if ((getMutateCampaignAssetSetsMethod = CampaignAssetSetServiceGrpc.getMutateCampaignAssetSetsMethod) == null) { CampaignAssetSetServiceGrpc.getMutateCampaignAssetSetsMethod = getMutateCampaignAssetSetsMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest, com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "MutateCampaignAssetSets")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse.getDefaultInstance())) .setSchemaDescriptor(new CampaignAssetSetServiceMethodDescriptorSupplier("MutateCampaignAssetSets")) .build(); } } } return getMutateCampaignAssetSetsMethod; } /** * Creates a new async stub that supports all call types for the service */ public static CampaignAssetSetServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CampaignAssetSetServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CampaignAssetSetServiceStub>() { @java.lang.Override public CampaignAssetSetServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignAssetSetServiceStub(channel, callOptions); } }; return CampaignAssetSetServiceStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static CampaignAssetSetServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CampaignAssetSetServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CampaignAssetSetServiceBlockingStub>() { @java.lang.Override public CampaignAssetSetServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignAssetSetServiceBlockingStub(channel, callOptions); } }; return CampaignAssetSetServiceBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static CampaignAssetSetServiceFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CampaignAssetSetServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CampaignAssetSetServiceFutureStub>() { @java.lang.Override public CampaignAssetSetServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignAssetSetServiceFutureStub(channel, callOptions); } }; return CampaignAssetSetServiceFutureStub.newStub(factory, channel); } /** * <pre> * Service to manage campaign asset set * </pre> */ public static abstract class CampaignAssetSetServiceImplBase implements io.grpc.BindableService { /** * <pre> * Creates, updates or removes campaign asset sets. Operation statuses are * returned. * </pre> */ public void mutateCampaignAssetSets(com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getMutateCampaignAssetSetsMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getMutateCampaignAssetSetsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest, com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse>( this, METHODID_MUTATE_CAMPAIGN_ASSET_SETS))) .build(); } } /** * <pre> * Service to manage campaign asset set * </pre> */ public static final class CampaignAssetSetServiceStub extends io.grpc.stub.AbstractAsyncStub<CampaignAssetSetServiceStub> { private CampaignAssetSetServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CampaignAssetSetServiceStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignAssetSetServiceStub(channel, callOptions); } /** * <pre> * Creates, updates or removes campaign asset sets. Operation statuses are * returned. * </pre> */ public void mutateCampaignAssetSets(com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getMutateCampaignAssetSetsMethod(), getCallOptions()), request, responseObserver); } } /** * <pre> * Service to manage campaign asset set * </pre> */ public static final class CampaignAssetSetServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<CampaignAssetSetServiceBlockingStub> { private CampaignAssetSetServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CampaignAssetSetServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignAssetSetServiceBlockingStub(channel, callOptions); } /** * <pre> * Creates, updates or removes campaign asset sets. Operation statuses are * returned. * </pre> */ public com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse mutateCampaignAssetSets(com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getMutateCampaignAssetSetsMethod(), getCallOptions(), request); } } /** * <pre> * Service to manage campaign asset set * </pre> */ public static final class CampaignAssetSetServiceFutureStub extends io.grpc.stub.AbstractFutureStub<CampaignAssetSetServiceFutureStub> { private CampaignAssetSetServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CampaignAssetSetServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CampaignAssetSetServiceFutureStub(channel, callOptions); } /** * <pre> * Creates, updates or removes campaign asset sets. Operation statuses are * returned. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse> mutateCampaignAssetSets( com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getMutateCampaignAssetSetsMethod(), getCallOptions()), request); } } private static final int METHODID_MUTATE_CAMPAIGN_ASSET_SETS = 0; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final CampaignAssetSetServiceImplBase serviceImpl; private final int methodId; MethodHandlers(CampaignAssetSetServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_MUTATE_CAMPAIGN_ASSET_SETS: serviceImpl.mutateCampaignAssetSets((com.google.ads.googleads.v10.services.MutateCampaignAssetSetsRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v10.services.MutateCampaignAssetSetsResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class CampaignAssetSetServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { CampaignAssetSetServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.ads.googleads.v10.services.CampaignAssetSetServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("CampaignAssetSetService"); } } private static final class CampaignAssetSetServiceFileDescriptorSupplier extends CampaignAssetSetServiceBaseDescriptorSupplier { CampaignAssetSetServiceFileDescriptorSupplier() {} } private static final class CampaignAssetSetServiceMethodDescriptorSupplier extends CampaignAssetSetServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; CampaignAssetSetServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (CampaignAssetSetServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new CampaignAssetSetServiceFileDescriptorSupplier()) .addMethod(getMutateCampaignAssetSetsMethod()) .build(); } } } return result; } }
9230a049c7b0b5b8197985eb8bf2dc82ae58eeec
7,326
java
Java
src/main/java/net/torocraft/torohealth/util/ModMenuEntry.java
Samekichi/ToroHealth
6031095c15a0991e6edefce2c3beb4dcbb15d325
[ "CC0-1.0" ]
null
null
null
src/main/java/net/torocraft/torohealth/util/ModMenuEntry.java
Samekichi/ToroHealth
6031095c15a0991e6edefce2c3beb4dcbb15d325
[ "CC0-1.0" ]
null
null
null
src/main/java/net/torocraft/torohealth/util/ModMenuEntry.java
Samekichi/ToroHealth
6031095c15a0991e6edefce2c3beb4dcbb15d325
[ "CC0-1.0" ]
null
null
null
38.968085
205
0.711575
995,543
package net.torocraft.torohealth.util; import io.github.prospector.modmenu.api.ModMenuApi; import java.util.function.Function; import me.shedaniel.clothconfig2.api.ConfigBuilder; import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; import me.shedaniel.clothconfig2.impl.builders.SubCategoryBuilder; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.gui.screen.Screen; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.torocraft.torohealth.ToroHealth; import net.torocraft.torohealth.util.Config.Mode; import net.torocraft.torohealth.util.Config.NumberType; @Environment(EnvType.CLIENT) public class ModMenuEntry implements ModMenuApi { @Override public String getModId() { return ToroHealth.MODID; } private static Text title(String text) { return new TranslatableText(text); } private static final Config DEFAULTS = new Config(); @Override public Function<Screen, ? extends Screen> getConfigScreenFactory() { return (screen) -> { ConfigBuilder builder = ConfigBuilder.create().setParentScreen(screen).setTitle(title("config.title")); ConfigEntryBuilder entryBuilder = ConfigEntryBuilder.create(); Config newConfig = ConfigLoader.get(); ConfigCategory hudCategory = builder.getOrCreateCategory(title("config.category.hud")); hudCategory.addEntry(entryBuilder .startIntField(title("config.hud.hideDelay"), newConfig.hud.hideDelay) .setSaveConsumer(val -> newConfig.hud.hideDelay = val) .setDefaultValue(DEFAULTS.hud.hideDelay) .build()); hudCategory.addEntry(entryBuilder .startFloatField(title("config.hud.x"), newConfig.hud.x) .setSaveConsumer(val -> newConfig.hud.x = val) .setDefaultValue(DEFAULTS.hud.x) .build()); hudCategory.addEntry(entryBuilder .startFloatField(title("config.hud.y"), newConfig.hud.y) .setSaveConsumer(val -> newConfig.hud.y = val) .setDefaultValue(DEFAULTS.hud.y) .build()); hudCategory.addEntry(entryBuilder .startFloatField(title("config.hud.scale"), newConfig.hud.scale) .setSaveConsumer(val -> newConfig.hud.scale = val) .setDefaultValue(DEFAULTS.hud.scale) .build()); ConfigCategory barCategory = builder.getOrCreateCategory(title("config.torohealth.category.bar")); barCategory.addEntry(entryBuilder .startEnumSelector(title("config.bar.damageNumberType"), NumberType.class, newConfig.bar.damageNumberType) .setSaveConsumer(val -> newConfig.bar.damageNumberType = val) .setDefaultValue(DEFAULTS.bar.damageNumberType) .build()); ColorSection friendColor = new ColorSection(entryBuilder, barCategory, "config.torohealth.friendColor.title", newConfig.bar.friendColor, DEFAULTS.bar.friendColor); ColorSection friendColorSecondary = new ColorSection(entryBuilder, barCategory, "config.torohealth.friendColorSecondary.title", newConfig.bar.friendColorSecondary, DEFAULTS.bar.friendColorSecondary); ColorSection foeColor = new ColorSection(entryBuilder, barCategory, "config.torohealth.foeColor.title", newConfig.bar.foeColor, DEFAULTS.bar.foeColor); ColorSection foeColorSecondary = new ColorSection(entryBuilder, barCategory, "config.torohealth.foeColorSecondary.title", newConfig.bar.foeColorSecondary, DEFAULTS.bar.foeColorSecondary); friendColor.build(); friendColorSecondary.build(); foeColor.build(); foeColorSecondary.build(); ConfigCategory inWorldCategory = builder.getOrCreateCategory(title("config.torohealth.category.inWorld")); inWorldCategory.addEntry(entryBuilder .startEnumSelector(title("config.inWorld.mode"), Mode.class, newConfig.inWorld.mode) .setSaveConsumer(val -> newConfig.inWorld.mode = val) .setDefaultValue(DEFAULTS.inWorld.mode) .build()); inWorldCategory.addEntry(entryBuilder .startFloatField(title("config.inWorld.distance"), newConfig.inWorld.distance) .setSaveConsumer(val -> newConfig.inWorld.distance = val) .setDefaultValue(DEFAULTS.inWorld.distance) .build()); builder.setSavingRunnable(() -> { newConfig.bar.friendColor = friendColor.getColor(); newConfig.bar.friendColorSecondary = friendColorSecondary.getColor(); newConfig.bar.foeColor = foeColor.getColor(); newConfig.bar.foeColorSecondary = foeColorSecondary.getColor(); ConfigLoader.set(newConfig); }); return builder.build(); }; } private static int getRed(int color) { return getByte(color, 3); } private static int getGreen(int color) { return getByte(color, 2); } private static int getBlue(int color) { return getByte(color, 1); } private static int getAlpha(int color) { return getByte(color, 0); } private static int setRed(int color, int value) { return setByte(color, (byte) value, 3); } private static int setGreen(int color, int value) { return setByte(color, (byte) value, 2); } private static int setBlue(int color, int value) { return setByte(color, (byte) value, 1); } private static int setAlpha(int color, int value) { return setByte(color, (byte) value, 0); } public static int getByte(int l, int position) { return (l >> 8 * position) & 0x0ff; } public static int setByte(int i, byte b, int position) { if (position > 3) { throw new IndexOutOfBoundsException("byte position of " + position); } int mask = ~(0xff << position * 8); int insert = (b << position * 8) & ~mask; return i & mask | insert; } private static class ColorSection { private ConfigEntryBuilder entryBuilder; private ConfigCategory category; private Text title; private int color; private int defaultColor; public ColorSection(ConfigEntryBuilder entryBuilder, ConfigCategory category, String title, int color, int defaultColor) { this.entryBuilder = entryBuilder; this.category = category; this.title = new TranslatableText(title); this.color = color; this.defaultColor = defaultColor; } public void build() { SubCategoryBuilder sub = entryBuilder.startSubCategory(title); sub.add(entryBuilder.startIntSlider(title("config.torohealth.red"), getRed(color), 0, 255).setSaveConsumer(v -> color = setRed(color, v)).setDefaultValue(getRed(defaultColor)).build()); sub.add(entryBuilder.startIntSlider(title("config.torohealth.green"), getGreen(color), 0, 255).setSaveConsumer(v -> color = setGreen(color, v)).setDefaultValue(getGreen(defaultColor)).build()); sub.add(entryBuilder.startIntSlider(title("config.torohealth.blue"), getBlue(color), 0, 255).setSaveConsumer(v -> color = setBlue(color, v)).setDefaultValue(getBlue(defaultColor)).build()); sub.add(entryBuilder.startIntSlider(title("config.torohealth.alpha"), getAlpha(color), 0, 255).setSaveConsumer(v -> color = setAlpha(color, v)).setDefaultValue(getAlpha(defaultColor)).build()); category.addEntry(sub.build()); } public int getColor() { return color; } } }
9230a0c787d5c967ccf8592e74319bc56f3bae7b
4,341
java
Java
java/JARS/hibernate-release-5.6.0.Final/project/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java
midnightbr/Faculdade
9a5a4b251e85fec002a2b1c7ddba25c2030d2e7c
[ "MIT" ]
1
2021-11-11T01:36:23.000Z
2021-11-11T01:36:23.000Z
java/JARS/hibernate-release-5.6.0.Final/project/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java
midnightbr/Faculdade
9a5a4b251e85fec002a2b1c7ddba25c2030d2e7c
[ "MIT" ]
null
null
null
java/JARS/hibernate-release-5.6.0.Final/project/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java
midnightbr/Faculdade
9a5a4b251e85fec002a2b1c7ddba25c2030d2e7c
[ "MIT" ]
null
null
null
31.230216
107
0.790141
995,544
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.envers.test.performance; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import javax.persistence.EntityManager; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.boot.internal.EnversIntegrator; import org.hibernate.envers.test.AbstractEnversTest; import org.hibernate.jpa.HibernateEntityManagerFactory; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.spi.Bootstrap; import org.hibernate.jpa.test.PersistenceUnitDescriptorAdapter; import org.hibernate.testing.AfterClassOnce; import org.hibernate.testing.BeforeClassOnce; import org.junit.Before; /** * @author Adam Warski (adam at warski dot org) * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class AbstractEntityManagerTest extends AbstractEnversTest { public static final Dialect DIALECT = Dialect.getDialect(); private EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder; private StandardServiceRegistryImpl serviceRegistry; private HibernateEntityManagerFactory emf; private EntityManager entityManager; private AuditReader auditReader; private boolean audited; public void addConfigurationProperties(Properties configuration) { } protected static Dialect getDialect() { return DIALECT; } private void closeEntityManager() { if ( entityManager != null ) { entityManager.close(); entityManager = null; } } @Before public void newEntityManager() { closeEntityManager(); entityManager = emf.createEntityManager(); if ( audited ) { auditReader = AuditReaderFactory.get( entityManager ); } } @BeforeClassOnce public void init() throws IOException { init( true, getAuditStrategy() ); } protected void init(boolean audited, String auditStrategy) throws IOException { this.audited = audited; Properties configurationProperties = new Properties(); configurationProperties.putAll( Environment.getProperties() ); if ( !audited ) { configurationProperties.setProperty( EnversIntegrator.AUTO_REGISTER, "false" ); } if ( createSchema() ) { configurationProperties.setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" ); configurationProperties.setProperty( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); configurationProperties.setProperty( EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false" ); } if ( auditStrategy != null && !"".equals( auditStrategy ) ) { configurationProperties.setProperty( "org.hibernate.envers.audit_strategy", auditStrategy ); } addConfigurationProperties( configurationProperties ); configurationProperties.put( AvailableSettings.LOADED_CLASSES, Arrays.asList( getAnnotatedClasses() ) ); entityManagerFactoryBuilder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( new PersistenceUnitDescriptorAdapter(), configurationProperties ); emf = entityManagerFactoryBuilder.build().unwrap( HibernateEntityManagerFactory.class ); serviceRegistry = (StandardServiceRegistryImpl) emf.getSessionFactory() .getServiceRegistry() .getParentServiceRegistry(); newEntityManager(); } protected Class[] getAnnotatedClasses() { return new Class[0]; } protected boolean createSchema() { return true; } private BootstrapServiceRegistryBuilder createBootstrapRegistryBuilder() { return new BootstrapServiceRegistryBuilder(); } @AfterClassOnce public void close() { closeEntityManager(); emf.close(); //NOTE we don't build the service registry so we don't destroy it } public EntityManager getEntityManager() { return entityManager; } public AuditReader getAuditReader() { return auditReader; } }
9230a0c9a18bd405f104b14db9338dc4466c758e
339
java
Java
src/main/java/pattern/templatemethod/MapView.java
JS3322/pattern_java
0435970a809c6845d5dedeeab0234605c6098f9c
[ "MIT" ]
null
null
null
src/main/java/pattern/templatemethod/MapView.java
JS3322/pattern_java
0435970a809c6845d5dedeeab0234605c6098f9c
[ "MIT" ]
null
null
null
src/main/java/pattern/templatemethod/MapView.java
JS3322/pattern_java
0435970a809c6845d5dedeeab0234605c6098f9c
[ "MIT" ]
null
null
null
24.214286
52
0.702065
995,545
package pattern.templatemethod; public abstract class MapView { protected abstract void connectMapServer(); protected abstract void showMapOnScreen(); protected abstract void moveToCurrentLocation(); public void initMap () { connectMapServer(); showMapOnScreen(); moveToCurrentLocation(); } }
9230a224f819906b3e3181a60a7c70e23b14631a
2,839
java
Java
spark/spark-spa/src/main/java/com/thoughtworks/go/spark/spa/ClickyPipelineConfigController.java
Bewalticus/gocd
62f52dcf6f8bce1bf0d55802bb14d4b405fbbe01
[ "Apache-2.0" ]
2
2015-12-06T01:40:12.000Z
2016-12-01T22:19:28.000Z
spark/spark-spa/src/main/java/com/thoughtworks/go/spark/spa/ClickyPipelineConfigController.java
Bewalticus/gocd
62f52dcf6f8bce1bf0d55802bb14d4b405fbbe01
[ "Apache-2.0" ]
154
2016-07-08T15:02:12.000Z
2019-09-23T17:37:38.000Z
spark/spark-spa/src/main/java/com/thoughtworks/go/spark/spa/ClickyPipelineConfigController.java
Bewalticus/gocd
62f52dcf6f8bce1bf0d55802bb14d4b405fbbe01
[ "Apache-2.0" ]
2
2016-05-20T23:20:43.000Z
2017-05-25T12:13:47.000Z
37.355263
155
0.728778
995,546
/* * Copyright 2020 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.spark.spa; import com.thoughtworks.go.server.service.support.toggle.FeatureToggleService; import com.thoughtworks.go.server.service.support.toggle.Toggles; import com.thoughtworks.go.spark.Routes; import com.thoughtworks.go.spark.SparkController; import com.thoughtworks.go.spark.spring.SPAAuthenticationHelper; import spark.ModelAndView; import spark.Request; import spark.Response; import spark.TemplateEngine; import java.util.HashMap; import java.util.Map; import static spark.Spark.*; public class ClickyPipelineConfigController implements SparkController { private final SPAAuthenticationHelper authenticationHelper; private final FeatureToggleService featureToggleService; private final TemplateEngine engine; public ClickyPipelineConfigController(SPAAuthenticationHelper authenticationHelper, FeatureToggleService featureToggleService, TemplateEngine engine) { this.authenticationHelper = authenticationHelper; this.featureToggleService = featureToggleService; this.engine = engine; } @Override public String controllerBasePath() { return Routes.PipelineConfig.SPA_BASE; } @Override public void setupRoutes() { path(controllerBasePath(), () -> { before(Routes.PipelineConfig.NAME + "/edit", authenticationHelper::checkPipelineGroupAdminOfPipelineOrGroupInURLUserAnd403); get(Routes.PipelineConfig.NAME + "/edit", this::index, engine); }); } public ModelAndView index(Request request, Response response) { if (!featureToggleService.isToggleOn(Toggles.NEW_PIPELINE_CONFIG_SPA)) { throw authenticationHelper.renderNotFoundResponse("The page you are looking for is not found."); } String pipelineName = request.params("pipeline_name"); Map<Object, Object> object = new HashMap<>() {{ put("viewTitle", "Pipeline"); put("meta", meta(pipelineName)); }}; return new ModelAndView(object, null); } private Map<String, Object> meta(String pipelineName) { final Map<String, Object> meta = new HashMap<>(); meta.put("pipelineName", pipelineName); return meta; } }
9230a27739151a26727c959ffc971157855b6c60
2,021
java
Java
src/main/java/com/techjar/ledcm/hardware/tcp/packet/PacketAnimationOptionList.java
Techjar/LEDCubeManager
f4e73ebb65761602928ecfe874cd449da0d8b0ff
[ "MIT" ]
2
2020-01-01T19:46:16.000Z
2020-12-28T17:55:00.000Z
src/main/java/com/techjar/ledcm/hardware/tcp/packet/PacketAnimationOptionList.java
Techjar/LEDCubeManager
f4e73ebb65761602928ecfe874cd449da0d8b0ff
[ "MIT" ]
5
2015-09-19T11:25:58.000Z
2016-01-15T11:32:13.000Z
src/main/java/com/techjar/ledcm/hardware/tcp/packet/PacketAnimationOptionList.java
Techjar/LEDCubeManager
f4e73ebb65761602928ecfe874cd449da0d8b0ff
[ "MIT" ]
5
2015-07-17T18:26:20.000Z
2020-03-02T13:16:40.000Z
26.246753
100
0.720435
995,547
package com.techjar.ledcm.hardware.tcp.packet; import com.techjar.ledcm.hardware.animation.AnimationOption; import com.techjar.ledcm.hardware.tcp.NetworkUtil; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; /** * * @author Techjar */ public class PacketAnimationOptionList extends Packet { private AnimationOption[] options; private String[] values; public PacketAnimationOptionList() { } public PacketAnimationOptionList(AnimationOption[] options, String[] values) { this.options = options; this.values = values; } @Override public void readData(DataInputStream stream) throws IOException { options = new AnimationOption[stream.readInt()]; values = new String[options.length]; for (int i = 0; i < options.length; i++) { String id = stream.readUTF(); String name = stream.readUTF(); AnimationOption.OptionType type = AnimationOption.OptionType.values()[stream.readUnsignedByte()]; Object[] params = new Object[stream.readUnsignedByte()]; for (int j = 0; j < params.length; j++) { params[j] = NetworkUtil.unmarshalObject(stream); } options[i] = new AnimationOption(id, name, type, params); values[i] = stream.readUTF(); } } @Override public void writeData(DataOutputStream stream) throws IOException { stream.writeInt(options.length); for (int i = 0; i < options.length; i++) { AnimationOption option = options[i]; stream.writeUTF(option.getId()); stream.writeUTF(option.getName()); stream.writeByte(option.getType().ordinal()); stream.writeByte(option.getParams().length); for (Object obj : option.getParams()) { NetworkUtil.marshalObject(obj, stream); } stream.writeUTF(values[i]); } } @Override public int getRequiredCapabilities() { return Capabilities.CONTROL_DATA; } @Override public void process() { throw new UnsupportedOperationException(); } public AnimationOption[] getOptions() { return options; } public String[] getValues() { return values; } }
9230a3c2a9ba0479f363510ea72270d4f654a467
1,494
java
Java
src/main/java/com/jrdm/exploit/model/ExploitInfoResponse.java
jrdelmar/jninvas
3b4f14b5add2fa2bdebd6827b3d7ca28c595d9df
[ "MIT" ]
1
2019-03-19T14:10:24.000Z
2019-03-19T14:10:24.000Z
src/main/java/com/jrdm/exploit/model/ExploitInfoResponse.java
jrdelmar/jninvas
3b4f14b5add2fa2bdebd6827b3d7ca28c595d9df
[ "MIT" ]
null
null
null
src/main/java/com/jrdm/exploit/model/ExploitInfoResponse.java
jrdelmar/jninvas
3b4f14b5add2fa2bdebd6827b3d7ca28c595d9df
[ "MIT" ]
null
null
null
18
53
0.702811
995,548
package com.jrdm.exploit.model; import java.util.Arrays; import com.google.gson.annotations.SerializedName; public class ExploitInfoResponse { @SerializedName("src") private String sourceLink; @SerializedName("desc") private String description; private String cvss; @SerializedName("copyright_title") private String copyright; @SerializedName("copyright_link") private String copyrightLink; // private String[] exploits; public String getSourceLink() { return sourceLink; } public String getDescription() { return description; } public String getCvss() { return cvss; } public String getCopyright() { return copyright; } public String getCopyrightLink() { return copyrightLink; } /* public String[] getExploits() { return exploits; }*/ public void setSourceLink(String sourceLink) { this.sourceLink = sourceLink; } public void setDescription(String description) { this.description = description; } public void setCvss(String cvss) { this.cvss = cvss; } public void setCopyright(String copyright) { this.copyright = copyright; } public void setCopyrightLink(String copyrightLink) { this.copyrightLink = copyrightLink; } @Override public String toString(){ return "\nInfo {" + "\nsource: " + sourceLink + "\ndescription: " + description + "\ncvss:" + cvss + "\ncopyright:" + copyright + "\ncopyright_link:" + copyrightLink //+ "\nexploits:" + Arrays.toString(exploits) + "}"; } }
9230a40e6472710c5c385dc46092daaba43566ec
675
java
Java
app/src/main/java/com/n1rocket/framework/mvp/data/network/api/LoginApi.java
n1rocket/eggs-android
1ae21a63ea167412d25d217311cb4c6201e78959
[ "Apache-2.0" ]
3
2017-10-12T17:46:33.000Z
2017-10-20T07:32:39.000Z
app/src/main/java/com/n1rocket/framework/mvp/data/network/api/LoginApi.java
n1rocket/eggs-android
1ae21a63ea167412d25d217311cb4c6201e78959
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/n1rocket/framework/mvp/data/network/api/LoginApi.java
n1rocket/eggs-android
1ae21a63ea167412d25d217311cb4c6201e78959
[ "Apache-2.0" ]
null
null
null
27
68
0.76
995,549
package com.n1rocket.framework.mvp.data.network.api; import com.n1rocket.framework.mvp.data.network.model.LoginResponse; import com.n1rocket.framework.mvp.data.network.model.LogoutResponse; import io.reactivex.Observable; import retrofit2.http.GET; /** * @author QuangNguyen (quangctkm9207). */ public interface LoginApi { @GET("/v2/588d14f4100000a9072d2943") Observable<LoginResponse> loginGoogle(); @GET("/v2/588d15d3100000ae072d2944") Observable<LoginResponse> loginFacebook(); @GET("/v2/588d15f5100000a8072d2945") Observable<LoginResponse> loginServer(); @GET("/v2/588d161c100000a9072d2946") Observable<LogoutResponse> logout(); }