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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9239cd5c33bda0c82e4c5cab7684e66a8147d4ce | 13,030 | java | Java | HTTPShortcuts/app/src/main/java/ch/rmy/android/http_shortcuts/activities/ExecuteActivity.java | stefb965/HTTP-Shortcuts | a22fa748dc736396af0bac823726cc211e0288c9 | [
"MIT"
] | null | null | null | HTTPShortcuts/app/src/main/java/ch/rmy/android/http_shortcuts/activities/ExecuteActivity.java | stefb965/HTTP-Shortcuts | a22fa748dc736396af0bac823726cc211e0288c9 | [
"MIT"
] | null | null | null | HTTPShortcuts/app/src/main/java/ch/rmy/android/http_shortcuts/activities/ExecuteActivity.java | stefb965/HTTP-Shortcuts | a22fa748dc736396af0bac823726cc211e0288c9 | [
"MIT"
] | null | null | null | 38.664688 | 173 | 0.601305 | 998,961 | package ch.rmy.android.http_shortcuts.activities;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.VolleyError;
import org.jdeferred.AlwaysCallback;
import org.jdeferred.DoneCallback;
import org.jdeferred.FailCallback;
import org.jdeferred.Promise;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import ch.rmy.android.http_shortcuts.R;
import ch.rmy.android.http_shortcuts.http.HttpRequester;
import ch.rmy.android.http_shortcuts.http.ShortcutResponse;
import ch.rmy.android.http_shortcuts.realm.Controller;
import ch.rmy.android.http_shortcuts.realm.models.Shortcut;
import ch.rmy.android.http_shortcuts.realm.models.Variable;
import ch.rmy.android.http_shortcuts.utils.GsonUtil;
import ch.rmy.android.http_shortcuts.utils.IntentUtil;
import ch.rmy.android.http_shortcuts.variables.ResolvedVariables;
import ch.rmy.android.http_shortcuts.variables.VariableResolver;
import fr.castorflex.android.circularprogressbar.CircularProgressBar;
import io.github.kbiakov.codeview.CodeView;
public class ExecuteActivity extends BaseActivity {
public static final String ACTION_EXECUTE_SHORTCUT = "ch.rmy.android.http_shortcuts.resolveVariablesAndExecute";
public static final String EXTRA_SHORTCUT_ID = "id";
public static final String EXTRA_VARIABLE_VALUES = "variable_values";
private static final int TOAST_MAX_LENGTH = 400;
private Controller controller;
private Shortcut shortcut;
private ShortcutResponse lastResponse;
private ProgressDialog progressDialog;
@Bind(R.id.response_text)
TextView responseText;
@Bind(R.id.response_text_container)
View responseTextContainer;
@Bind(R.id.formatted_response_text)
CodeView formattedResponseText;
@Bind(R.id.progress_spinner)
CircularProgressBar progressSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long shortcutId = IntentUtil.getShortcutId(getIntent());
Map<String, String> variableValues = IntentUtil.getVariableValues(getIntent());
controller = new Controller();
shortcut = controller.getDetachedShortcutById(shortcutId);
if (shortcut == null) {
showToast(getString(R.string.shortcut_not_found), Toast.LENGTH_LONG);
controller.destroy();
finishWithoutAnimation();
return;
}
setTitle(shortcut.getSafeName(getContext()));
if (Shortcut.FEEDBACK_ACTIVITY.equals(shortcut.getFeedback())) {
setTheme(R.style.LightTheme);
setContentView(R.layout.activity_execute);
}
Promise promise = resolveVariablesAndExecute(variableValues);
if (promise.isPending()) {
promise.done(new DoneCallback() {
@Override
public void onDone(Object result) {
if (!shortcut.feedbackUsesUI()) {
finishWithoutAnimation();
}
}
}).fail(new FailCallback() {
@Override
public void onFail(Object result) {
finishWithoutAnimation();
}
});
} else {
if (!shortcut.feedbackUsesUI()) {
finishWithoutAnimation();
}
}
}
public Promise resolveVariablesAndExecute(Map<String, String> variableValues) {
List<Variable> variables = controller.getVariables();
return new VariableResolver(this)
.resolve(shortcut, variables, variableValues)
.done(new DoneCallback<ResolvedVariables>() {
@Override
public void onDone(ResolvedVariables resolvedVariables) {
execute(resolvedVariables);
}
}).fail(new FailCallback<Void>() {
@Override
public void onFail(Void result) {
controller.destroy();
}
});
}
private void execute(final ResolvedVariables resolvedVariables) {
showProgress();
HttpRequester.executeShortcut(getContext(), shortcut, resolvedVariables).done(new DoneCallback<ShortcutResponse>() {
@Override
public void onDone(ShortcutResponse response) {
setLastResponse(response);
if (shortcut.isFeedbackErrorsOnly()) {
finishWithoutAnimation();
} else {
boolean simple = shortcut.getFeedback().equals(Shortcut.FEEDBACK_TOAST_SIMPLE);
String output = simple ? String.format(getString(R.string.executed), shortcut.getSafeName(getContext())) : generateOutputFromResponse(response);
displayOutput(output, response.getContentType());
}
}
}).fail(new FailCallback<VolleyError>() {
@Override
public void onFail(VolleyError error) {
if (!shortcut.feedbackUsesUI() && Shortcut.RETRY_POLICY_WAIT_FOR_INTERNET.equals(shortcut.getRetryPolicy()) && error.networkResponse == null) {
controller.createPendingExecution(shortcut.getId(), resolvedVariables.toList());
if (!Shortcut.FEEDBACK_NONE.equals(shortcut.getFeedback())) {
showToast(String.format(getContext().getString(R.string.execution_delayed), shortcut.getSafeName(getContext())), Toast.LENGTH_LONG);
}
finishWithoutAnimation();
} else {
setLastResponse(null);
boolean simple = shortcut.getFeedback().equals(Shortcut.FEEDBACK_TOAST_SIMPLE_ERRORS) || shortcut.getFeedback().equals(Shortcut.FEEDBACK_TOAST_SIMPLE);
displayOutput(generateOutputFromError(error, simple), ShortcutResponse.TYPE_TEXT);
}
}
}).always(new AlwaysCallback<ShortcutResponse, VolleyError>() {
@Override
public void onAlways(Promise.State state, ShortcutResponse resolved, VolleyError rejected) {
hideProgress();
controller.destroy();
}
});
}
private String generateOutputFromResponse(ShortcutResponse response) {
return response.getBodyAsString();
}
private String generateOutputFromError(VolleyError error, boolean simple) {
String name = shortcut.getSafeName(getContext());
if (error.networkResponse != null) {
StringBuilder builder = new StringBuilder();
builder.append(String.format(getString(R.string.error_http), name, error.networkResponse.statusCode));
if (!simple && error.networkResponse.data != null) {
try {
builder.append("\n");
builder.append("\n");
builder.append(new String(error.networkResponse.data));
} catch (Exception e) {
}
}
return builder.toString();
} else {
if (error.getCause() != null && error.getCause().getMessage() != null) {
return String.format(getString(R.string.error_other), name, error.getCause().getMessage());
} else if (error.getMessage() != null) {
return String.format(getString(R.string.error_other), name, error.getMessage());
} else {
return String.format(getString(R.string.error_other), name, error.getClass().getSimpleName());
}
}
}
private void showProgress() {
switch (shortcut.getFeedback()) {
case Shortcut.FEEDBACK_DIALOG: {
if (progressDialog == null) {
progressDialog = ProgressDialog.show(getContext(), null, String.format(getString(R.string.progress_dialog_message), shortcut.getSafeName(getContext())));
}
break;
}
case Shortcut.FEEDBACK_ACTIVITY: {
progressSpinner.setVisibility(View.VISIBLE);
responseTextContainer.setVisibility(View.GONE);
formattedResponseText.setVisibility(View.GONE);
break;
}
}
}
private void hideProgress() {
if (shortcut == null) {
return;
}
switch (shortcut.getFeedback()) {
case Shortcut.FEEDBACK_DIALOG: {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
break;
}
case Shortcut.FEEDBACK_ACTIVITY: {
progressSpinner.setVisibility(View.GONE);
break;
}
}
}
private void displayOutput(String output, String type) {
switch (shortcut.getFeedback()) {
case Shortcut.FEEDBACK_TOAST_SIMPLE:
case Shortcut.FEEDBACK_TOAST_SIMPLE_ERRORS: {
showToast(output, Toast.LENGTH_SHORT);
break;
}
case Shortcut.FEEDBACK_TOAST:
case Shortcut.FEEDBACK_TOAST_ERRORS: {
showToast(truncateIfNeeded(output, TOAST_MAX_LENGTH), Toast.LENGTH_LONG);
break;
}
case Shortcut.FEEDBACK_DIALOG: {
new MaterialDialog.Builder(getContext())
.title(shortcut.getSafeName(getContext()))
.content(output)
.positiveText(R.string.button_ok)
.dismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
finishWithoutAnimation();
}
})
.show();
break;
}
case Shortcut.FEEDBACK_ACTIVITY: {
switch (type) {
case ShortcutResponse.TYPE_JSON: {
formattedResponseText.setCode(GsonUtil.prettyPrint(output), "json");
formattedResponseText.setVisibility(View.VISIBLE);
break;
}
case ShortcutResponse.TYPE_XML: {
formattedResponseText.setCode(output, "xml");
formattedResponseText.setVisibility(View.VISIBLE);
break;
}
default: {
responseText.setText(output);
responseTextContainer.setVisibility(View.VISIBLE);
break;
}
}
break;
}
}
}
private static String truncateIfNeeded(String string, int maxLength) {
return string.length() > maxLength ? string.substring(0, maxLength) + "…" : string;
}
private void showToast(String message, int duration) {
Toast.makeText(getContext(), message, duration).show();
}
private void setLastResponse(ShortcutResponse response) {
this.lastResponse = response;
invalidateOptionsMenu();
}
@Override
protected void finishWithoutAnimation() {
hideProgress();
super.finishWithoutAnimation();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.execute_activity_menu, menu);
menu.findItem(R.id.action_share_response).setVisible(canShareResponse());
return super.onCreateOptionsMenu(menu);
}
private boolean canShareResponse() {
return lastResponse != null;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_share_response) {
shareLastResponse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void shareLastResponse() {
if (!canShareResponse()) {
return;
}
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType(ShortcutResponse.TYPE_TEXT);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, lastResponse.getBodyAsString());
startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_title)));
}
@Override
protected int getNavigateUpIcon() {
return R.drawable.ic_clear;
}
}
|
9239cd9f889a7428e949f52efc85a53c31976424 | 1,559 | java | Java | benchmark/src/main/java/com/zappos/json/benchmark/data/SimpleBean.java | Zappos/zappos-json | 340633f5db75c2e09ce49bfc3e5f67e8823f5a37 | [
"Apache-2.0"
] | 9 | 2015-12-21T05:33:20.000Z | 2020-11-10T06:29:23.000Z | benchmark/src/main/java/com/zappos/json/benchmark/data/SimpleBean.java | Zappos/zappos-json | 340633f5db75c2e09ce49bfc3e5f67e8823f5a37 | [
"Apache-2.0"
] | 4 | 2015-12-22T07:49:12.000Z | 2020-05-15T21:05:36.000Z | benchmark/src/main/java/com/zappos/json/benchmark/data/SimpleBean.java | Zappos/zappos-json | 340633f5db75c2e09ce49bfc3e5f67e8823f5a37 | [
"Apache-2.0"
] | 6 | 2015-11-18T11:27:40.000Z | 2020-11-10T09:06:59.000Z | 22.271429 | 76 | 0.65619 | 998,962 | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package com.zappos.json.benchmark.data;
import java.util.Random;
import com.zappos.json.util.Strings;
/**
*
* @author Hussachai Puripunpinyo
*
*/
public class SimpleBean {
private static final Random RANDOM = new Random();
private String string;
private Boolean flag;
private int number;
public static SimpleBean random(){
SimpleBean bean = new SimpleBean();
bean.string = Strings.randomAlphabetic(32);
bean.flag = RANDOM.nextBoolean();
bean.number = RANDOM.nextInt(100);
return bean;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
|
9239ce2f8b6d3a08d6d6649fd35b53217ee8fd90 | 9,167 | java | Java | Spigot/src/main/java/net/warchamer12/parkour/commands/ParkourCommand.java | warchamer12/Parkour-Plugin | bc92c7a5b73bbf5e553652384b514b03a86dc1cf | [
"Apache-2.0"
] | null | null | null | Spigot/src/main/java/net/warchamer12/parkour/commands/ParkourCommand.java | warchamer12/Parkour-Plugin | bc92c7a5b73bbf5e553652384b514b03a86dc1cf | [
"Apache-2.0"
] | null | null | null | Spigot/src/main/java/net/warchamer12/parkour/commands/ParkourCommand.java | warchamer12/Parkour-Plugin | bc92c7a5b73bbf5e553652384b514b03a86dc1cf | [
"Apache-2.0"
] | null | null | null | 54.565476 | 127 | 0.508781 | 998,963 | package net.warchamer12.parkour.commands;
import net.warchamer12.parkour.Parkour;
import net.warchamer12.parkour.configs.area.ParkourConfigEasy;
import net.warchamer12.parkour.configs.area.ParkourConfigHard;
import net.warchamer12.parkour.configs.area.ParkourConfigMedium;
import net.warchamer12.parkour.configs.area.ParkourConfigUltra;
import net.warchamer12.parkour.objects.AreaObject;
import net.warchamer12.parkour.objects.ParkourObject;
import net.warchamer12.parkour.utils.Util;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ParkourCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) { return true; }
Player player = (Player) sender;
Location loc = player.getLocation();
if (player.hasPermission("parkour.admin")) {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("easy")) {
AreaObject.parkours.add(player);
player.sendMessage(Util.fixColor("&cDolaczyles do areny!"));
return true;
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("stworz")) {
if (args[1].equalsIgnoreCase("easy")) {
ParkourObject.easy += 1;
player.sendMessage(ChatColor.GREEN + "Stworzono parkour o nazwie " + args[1]);
ParkourConfigEasy.create();
ParkourConfigEasy.get().set("nazwa", "Easy " + ParkourObject.getEasy());
ParkourConfigEasy.get().set("spawn", loc);
ParkourConfigEasy.save();
Parkour.getPlugin().getConfig().set("easy", ParkourObject.getEasy());
Parkour.getPlugin().saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("medium")) {
ParkourObject.medium += 1;
player.sendMessage(ChatColor.GREEN + "Stworzono parkour o nazwie " + args[1]);
ParkourConfigMedium.create();
ParkourConfigMedium.get().set("nazwa", "Medium " + ParkourObject.getMedium());
ParkourConfigMedium.get().set("spawn", loc);
ParkourConfigMedium.save();
Parkour.getPlugin().getConfig().set("medium", ParkourObject.getMedium());
Parkour.getPlugin().saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("hard")) {
ParkourObject.hard += 1;
player.sendMessage(ChatColor.GREEN + "Stworzono parkour o nazwie " + args[1]);
ParkourConfigHard.create();
ParkourConfigHard.get().set("nazwa", "Hard " + ParkourObject.getHard());
ParkourConfigHard.get().set("spawn", loc);
ParkourConfigHard.save();
Parkour.getPlugin().getConfig().set("hard", ParkourObject.getHard());
Parkour.getPlugin().saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("ultra")) {
ParkourObject.ultra += 1;
player.sendMessage(ChatColor.GREEN + "Stworzono parkour o nazwie " + args[1]);
ParkourConfigUltra.create();
ParkourConfigUltra.get().set("nazwa", "Ultra " + ParkourObject.getUltra());
ParkourConfigUltra.get().set("spawn", loc);
ParkourConfigUltra.save();
Parkour.getPlugin().getConfig().set("ultra", ParkourObject.getUltra());
Parkour.getPlugin().saveConfig();
return true;
} else {
player.sendMessage(Util.fixColor("&cNiepoprawna forma!"));
return true;
}
} else {
this.helpCommand(player);
return true;
}
} else if (args.length == 3) {
if (args[0].equalsIgnoreCase("ustawspawn")) {
if (args[1].equalsIgnoreCase("easy")) {
ParkourConfigEasy.getFileParkour(args[2]);
ParkourConfigEasy.get().set("spawn", loc);
ParkourConfigEasy.save();
player.sendMessage(Util.fixColor("&cUstawiono spawn dla mapy " + args[2] + " na kordynatach: " + loc));
return true;
} else if (args[1].equalsIgnoreCase("medium")) {
ParkourConfigMedium.getFileParkour(args[2]);
ParkourConfigMedium.get().set("spawn", loc);
ParkourConfigMedium.save();
player.sendMessage(Util.fixColor("&cUstawiono spawn dla mapy " + args[2] + " na kordynatach: " + loc));
return true;
} else if (args[1].equalsIgnoreCase("hard")) {
ParkourConfigHard.getFileParkour(args[2]);
ParkourConfigHard.get().set("spawn", loc);
ParkourConfigHard.save();
player.sendMessage(Util.fixColor("&cUstawiono spawn dla mapy " + args[2] + " na kordynatach: " + loc));
return true;
} else if (args[1].equalsIgnoreCase("ultra")) {
ParkourConfigUltra.getFileParkour(args[2]);
ParkourConfigUltra.get().set("spawn", loc);
ParkourConfigUltra.save();
player.sendMessage(Util.fixColor("&cUstawiono spawn dla mapy " + args[2] + " na kordynatach: " + loc));
return true;
} else {
player.sendMessage(Util.fixColor("&cNiepoprawna forma!"));
return true;
}
} else if (args[0].equalsIgnoreCase("usun")) {
if (args[1].equalsIgnoreCase("easy")) {
ParkourConfigEasy.delete(args[2]);
ParkourObject.easy -= 1;
Parkour.getPlugin().getConfig().set("easy", ParkourObject.getEasy());
player.sendMessage(Util.fixColor("&cUsunieto arene " + args[2] + " !"));
Parkour.getPlugin().saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("medium")) {
ParkourConfigMedium.delete(args[2]);
ParkourObject.medium -= 1;
Parkour.getPlugin().getConfig().set("medium", ParkourObject.getMedium());
player.sendMessage(Util.fixColor("&cUsunieto arene " + args[2] + " !"));
Parkour.getPlugin().saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("hard")) {
ParkourConfigHard.delete(args[2]);
ParkourObject.hard -= 1;
Parkour.getPlugin().getConfig().set("hard", ParkourObject.getHard());
player.sendMessage(Util.fixColor("&cUsunieto arene " + args[2] + " !"));
Parkour.getPlugin().saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("ultra")) {
ParkourConfigUltra.delete(args[2]);
ParkourObject.ultra -= 1;
Parkour.getPlugin().getConfig().set("ultra", ParkourObject.getUltra());
player.sendMessage(Util.fixColor("&cUsunieto arene " + args[2] + " !"));
Parkour.getPlugin().saveConfig();
return true;
} else {
player.sendMessage(Util.fixColor("&cNiepoprawna forma!"));
return true;
}
} else {
this.helpCommand(player);
return true;
}
} else {
this.helpCommand(player);
return true;
}
} else {
player.sendMessage(Util.fixColor("&cNie masz uprawnien!"));
}
return false;
}
private void helpCommand(Player player) {
player.sendMessage(Util.fixColor("&c/parkour stworz easy/medium/hard/ultra"));
player.sendMessage(Util.fixColor("&c/parkour usun easy/medium/hard/ultra id"));
player.sendMessage(Util.fixColor("&c/parkour ustawspawn easy/medium/hard/ultra id"));
}
}
|
9239ce67921e3639cfb58af8b80a0b63dbdc7f43 | 2,689 | java | Java | contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.java | BurningBright/lucene | 4ef7508d7600f6ceeceda83f7086c8811cecf2c9 | [
"Apache-2.0"
] | 6 | 2020-10-27T06:11:59.000Z | 2021-09-09T13:52:42.000Z | contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.java | BurningBright/lucene | 4ef7508d7600f6ceeceda83f7086c8811cecf2c9 | [
"Apache-2.0"
] | 8 | 2020-11-16T20:41:38.000Z | 2022-02-01T01:05:45.000Z | sourcedata/lucene-solr-releases-lucene-2.2.0/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.java | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | null | null | null | 33.725 | 80 | 0.699036 | 998,964 | package org.apache.lucene.swing.models;
/**
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import junit.framework.TestCase;
/**
* @author Jonathan Simon - efpyi@example.com
*/
public class TestUpdatingTable extends TestCase {
private BaseTableModel baseTableModel;
private TableSearcher tableSearcher;
RestaurantInfo infoToAdd1, infoToAdd2;
protected void setUp() throws Exception {
baseTableModel = new BaseTableModel(DataStore.getRestaurants());
tableSearcher = new TableSearcher(baseTableModel);
infoToAdd1 = new RestaurantInfo();
infoToAdd1.setName("Pino's");
infoToAdd1.setType("Italian");
infoToAdd2 = new RestaurantInfo();
infoToAdd2.setName("Pino's");
infoToAdd2.setType("Italian");
}
public void testAddWithoutSearch(){
assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());
int count = tableSearcher.getRowCount();
baseTableModel.addRow(infoToAdd1);
count++;
assertEquals(count, tableSearcher.getRowCount());
}
public void testRemoveWithoutSearch(){
assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());
int count = tableSearcher.getRowCount();
baseTableModel.addRow(infoToAdd1);
baseTableModel.removeRow(infoToAdd1);
assertEquals(count, tableSearcher.getRowCount());
}
public void testAddWithSearch(){
assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());
tableSearcher.search("pino's");
int count = tableSearcher.getRowCount();
baseTableModel.addRow(infoToAdd2);
count++;
assertEquals(count, tableSearcher.getRowCount());
}
public void testRemoveWithSearch(){
assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());
baseTableModel.addRow(infoToAdd1);
tableSearcher.search("pino's");
int count = tableSearcher.getRowCount();
baseTableModel.removeRow(infoToAdd1);
count--;
assertEquals(count, tableSearcher.getRowCount());
}
}
|
9239ced1c137a3f28bc4c90f348aae37a48acb34 | 2,892 | java | Java | generictools/src/main/java/com/flys/generictools/dao/db/DatabaseHelper.java | amadoubakari/e-bible | 693d6eab9249031f4cc5d03c1de3c1f9a91698e5 | [
"MIT"
] | null | null | null | generictools/src/main/java/com/flys/generictools/dao/db/DatabaseHelper.java | amadoubakari/e-bible | 693d6eab9249031f4cc5d03c1de3c1f9a91698e5 | [
"MIT"
] | null | null | null | generictools/src/main/java/com/flys/generictools/dao/db/DatabaseHelper.java | amadoubakari/e-bible | 693d6eab9249031f4cc5d03c1de3c1f9a91698e5 | [
"MIT"
] | null | null | null | 35.268293 | 119 | 0.668396 | 998,965 | package com.flys.generictools.dao.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import java.util.List;
/**
* Created by User on 07/05/2018.
*/
public class DatabaseHelper<T, K> extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something appropriate for your app
private static final String DATABASE_NAME = "flys.db";
// any time you make changes to your database objects, you may have to increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
private Dao<T, K> simpleDao = null;
private RuntimeExceptionDao<T, K> simpleRuntimeDao = null;
List<Class<?>> classList;
public DatabaseHelper(Context context, int ormlite_config, List<Class<?>> classList) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, ormlite_config);
this.classList = classList;
}
/**
* This is called when the database is first created. Usually you should call createTable statements here to create
* the tables that will store your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
for (Class<?> entityClass:classList
) {
TableUtils.createTableIfNotExists(connectionSource,entityClass);
}
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* This is called when your application is upgraded and it has a higher version number. This allows you to adjust
* the various data to match the new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
for (Class<?> entityClass:classList
) {
TableUtils.dropTable(connectionSource, entityClass, true);
}
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
//Database init
List<Class<?>> init(){
return null;
}
}
|
9239cefb39843e1f989c03d457cc0d2cbc82c257 | 325 | java | Java | src/main/java/org/example/wordladder/exceptions/DictionaryLoadErrorException.java | marrow16/WordLadder | c4395bb502d7afb847658fbaaf7e6cecf6be03f5 | [
"Apache-2.0"
] | 1 | 2021-12-13T17:15:48.000Z | 2021-12-13T17:15:48.000Z | src/main/java/org/example/wordladder/exceptions/DictionaryLoadErrorException.java | marrow16/WordLadder | c4395bb502d7afb847658fbaaf7e6cecf6be03f5 | [
"Apache-2.0"
] | 1 | 2021-09-19T01:28:05.000Z | 2021-09-19T18:11:12.000Z | src/main/java/org/example/wordladder/exceptions/DictionaryLoadErrorException.java | marrow16/WordLadder | c4395bb502d7afb847658fbaaf7e6cecf6be03f5 | [
"Apache-2.0"
] | null | null | null | 27.083333 | 77 | 0.753846 | 998,966 | package org.example.wordladder.exceptions;
public class DictionaryLoadErrorException extends ApplicationErrorException {
public DictionaryLoadErrorException(String message) {
super(message);
}
public DictionaryLoadErrorException(String message, Throwable cause) {
super(message, cause);
}
}
|
9239cf06ed6a0b34d6121a84751fcb5c29f5250e | 1,492 | java | Java | BasicSyntaxConditionalStatementsAndLoops/src/exercises/RageExpenses.java | DeianH94/JavaFundamentals2 | bb845ba6ca0493f0438c96af1f93d64d11d23f25 | [
"MIT"
] | null | null | null | BasicSyntaxConditionalStatementsAndLoops/src/exercises/RageExpenses.java | DeianH94/JavaFundamentals2 | bb845ba6ca0493f0438c96af1f93d64d11d23f25 | [
"MIT"
] | null | null | null | BasicSyntaxConditionalStatementsAndLoops/src/exercises/RageExpenses.java | DeianH94/JavaFundamentals2 | bb845ba6ca0493f0438c96af1f93d64d11d23f25 | [
"MIT"
] | null | null | null | 31.744681 | 70 | 0.546917 | 998,967 | package exercises;
import java.util.Scanner;
public class RageExpenses {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lostGameCount = Integer.parseInt(scanner.nextLine());
double headsetPrice = Double.parseDouble(scanner.nextLine());
double mousePrice = Double.parseDouble(scanner.nextLine());
double keyboardPrice = Double.parseDouble(scanner.nextLine());
double displayPrice = Double.parseDouble(scanner.nextLine());
double totalExpense = 0;
int destroyedKeyboardCount = 0;
for (int i = 1; i <= lostGameCount; i++) {
boolean destroyedHeadset = false;
boolean destroyedMouse = false;
boolean destroyDisplay = false;
if (i % 2 == 0) {
totalExpense += headsetPrice;
destroyedHeadset = true;
}
if (i % 3 == 0) {
totalExpense += mousePrice;
destroyedMouse = true;
}
if (destroyedHeadset && destroyedMouse) {
totalExpense += keyboardPrice;
destroyedKeyboardCount++;
if (destroyedKeyboardCount % 2 == 0) {
destroyDisplay = true;
}
}
if (destroyDisplay) {
totalExpense += displayPrice;
}
}
System.out.printf("Rage expenses: %.2f lv.%n", totalExpense);
}
}
|
9239d00a64b704c76cdb430ba683cf818a85ea36 | 3,224 | java | Java | platforms/android/WeexFrameworkWrapper/app/src/main/java/com/benmu/drop/activity/module/GoogleLoginModule.java | hyh2008312/Price-Drop-App | 520edea9d0d1a886c93c243050a330eade58cc7e | [
"MIT"
] | null | null | null | platforms/android/WeexFrameworkWrapper/app/src/main/java/com/benmu/drop/activity/module/GoogleLoginModule.java | hyh2008312/Price-Drop-App | 520edea9d0d1a886c93c243050a330eade58cc7e | [
"MIT"
] | null | null | null | platforms/android/WeexFrameworkWrapper/app/src/main/java/com/benmu/drop/activity/module/GoogleLoginModule.java | hyh2008312/Price-Drop-App | 520edea9d0d1a886c93c243050a330eade58cc7e | [
"MIT"
] | null | null | null | 39.317073 | 111 | 0.709367 | 998,968 | package com.benmu.drop.activity.module;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.widget.Toast;
import com.benmu.drop.R;
import com.benmu.drop.activity.MainActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
/**
* @author luzhenqiang
* @desc google login
* @date 2018/5/25 下午4:38
* @since 1.0.1
*/
public class GoogleLoginModule extends WXModule {
private JSCallback googleSingoutCallback;
private GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 12321;
@Override
public void onActivityCreate() {
super.onActivityCreate();
}
// 判断是否第三方登录 // 判断accout 是否为空
public void isCheckGoogleLogin() {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(mWXSDKInstance.getContext());
}
// 开始进行google登录
@JSMethod
public void startGoogleLogin(
JSCallback jsSuccessCallback, JSCallback jsFailedCallback) {
((MainActivity)mWXSDKInstance.getContext()).setGoogleCallback(jsSuccessCallback,jsFailedCallback);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(mWXSDKInstance.getContext().getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(mWXSDKInstance.getContext(), gso);
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
((Activity) mWXSDKInstance.getContext()).startActivityForResult(signInIntent, RC_SIGN_IN);
}
// 开始进行google退出
@JSMethod
public void startGoogleLSignOut(
JSCallback jsSuccessCallback) {
this.googleSingoutCallback = jsSuccessCallback;
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(mWXSDKInstance.getContext().getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(mWXSDKInstance.getContext(), gso);
mGoogleSignInClient.signOut()
.addOnCompleteListener((Activity) mWXSDKInstance.getContext(), new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
googleSingoutCallback.invoke(new Object());
Toast.makeText(mWXSDKInstance.getContext(),"退出成功",Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
|
9239d0317dd11e0f6dda345db628f6b5fa7202de | 1,091 | java | Java | Houseclub/src/main/java/me/grishka/houseclub/api/model/User.java | Fa1c0n35/Houseclub | d08878b0d4f3db8aff82681f560e2154592dd850 | [
"Unlicense"
] | 2,956 | 2021-02-20T10:56:01.000Z | 2022-02-25T05:12:56.000Z | Houseclub/src/main/java/me/grishka/houseclub/api/model/User.java | Fa1c0n35/Houseclub | d08878b0d4f3db8aff82681f560e2154592dd850 | [
"Unlicense"
] | 317 | 2021-02-20T11:18:31.000Z | 2022-03-05T20:09:49.000Z | Houseclub/src/main/java/me/grishka/houseclub/api/model/User.java | Fa1c0n35/Houseclub | d08878b0d4f3db8aff82681f560e2154592dd850 | [
"Unlicense"
] | 525 | 2021-02-20T11:58:29.000Z | 2021-12-31T13:55:06.000Z | 19.836364 | 63 | 0.727773 | 998,969 | package me.grishka.houseclub.api.model;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable{
public int userId;
public String name;
public String photoUrl;
public String username;
@Override
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags){
dest.writeInt(this.userId);
dest.writeString(this.name);
dest.writeString(this.photoUrl);
dest.writeString(this.username);
}
public void readFromParcel(Parcel source){
this.userId=source.readInt();
this.name=source.readString();
this.photoUrl=source.readString();
this.username=source.readString();
}
public User(){
}
protected User(Parcel in){
this.userId=in.readInt();
this.name=in.readString();
this.photoUrl=in.readString();
this.username=in.readString();
}
public static final Creator<User> CREATOR=new Creator<User>(){
@Override
public User createFromParcel(Parcel source){
return new User(source);
}
@Override
public User[] newArray(int size){
return new User[size];
}
};
}
|
9239d1c09fa7d24357b134c56095b51bbae6ed56 | 1,486 | java | Java | src/main/java/com/binance/dex/api/client/crosschain/ContentEnum.java | dogenkigen/java-sdk | 5b332f7f5f20a95ee088411f94d28aaf6c024162 | [
"Apache-2.0"
] | 102 | 2019-02-10T16:34:38.000Z | 2022-01-23T21:35:30.000Z | src/main/java/com/binance/dex/api/client/crosschain/ContentEnum.java | dogenkigen/java-sdk | 5b332f7f5f20a95ee088411f94d28aaf6c024162 | [
"Apache-2.0"
] | 47 | 2019-03-04T05:55:49.000Z | 2022-02-14T02:58:56.000Z | src/main/java/com/binance/dex/api/client/crosschain/ContentEnum.java | dogenkigen/java-sdk | 5b332f7f5f20a95ee088411f94d28aaf6c024162 | [
"Apache-2.0"
] | 70 | 2019-02-10T16:34:29.000Z | 2022-01-05T07:10:58.000Z | 38.102564 | 120 | 0.734859 | 998,970 | package com.binance.dex.api.client.crosschain;
import com.binance.dex.api.client.crosschain.content.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
@Getter
@AllArgsConstructor
public enum ContentEnum {
ApproveBindSynPack(1, 0, ApproveBindSyn.class),
BindSynPack(1, 2, BindSyn.class),
TransferOutRefundPack(2, 1, TransferOutRefund.class),
TransferOutSynPack(2, 2, TransferOutSyn.class),
TransferInSynPack(3, 0, TransferInSyn.class),
StakingCommonAckPack(8, 1, CommonAck.class),
IbcValidatorSetPack(8, 2, IbcValidatorSet.class),
GovCommonAckPack(9, 1, CommonAck.class),
SideDowntimeSlashPack(11, 0, com.binance.dex.api.client.crosschain.content.SideDowntimeSlash.class),
MirrorSynPack(4, 0, MirrorSyn.class),
MirrorSynAckPack(4, 1, MirrorAck.class),
MirrorSyncSynPack(5, 0, MirrorSyncSyn.class),
MirrorSyncAckPack(5, 1, MirrorSyncAck.class)
;
private Integer channelId;
private Integer packType;
private Class<? extends Content> clazz;
public static Class<? extends Content> getClass(Integer channelId, Integer packType) {
Optional<ContentEnum> optional = Arrays.stream(ContentEnum.values())
.filter(contentEnum -> channelId.equals(contentEnum.channelId) && packType.equals(contentEnum.packType))
.findAny();
return optional.<Class<? extends Content>>map(ContentEnum::getClazz).orElse(null);
}
}
|
9239d1c3ea9c8077ba2bfaca7022327476eabf15 | 835 | java | Java | spring-learning-ioc/src/main/java/lifecycle/processor/MyBeanPostProcessor.java | leofeez/spring-learning | eb6ac87e889251476fec5d8df3752d90e10c09c8 | [
"Apache-2.0"
] | null | null | null | spring-learning-ioc/src/main/java/lifecycle/processor/MyBeanPostProcessor.java | leofeez/spring-learning | eb6ac87e889251476fec5d8df3752d90e10c09c8 | [
"Apache-2.0"
] | 1 | 2020-03-12T12:55:45.000Z | 2020-03-12T12:55:45.000Z | spring-learning-ioc/src/main/java/lifecycle/processor/MyBeanPostProcessor.java | leofeez/spring-learning | eb6ac87e889251476fec5d8df3752d90e10c09c8 | [
"Apache-2.0"
] | null | null | null | 30.925926 | 103 | 0.691018 | 998,971 | package lifecycle.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 在bean初始化之前进行前置处理
// 在 init method 调用之前调用
System.out.println("MyBeanPostProcessor bean = [" + bean + "], beanName = [" + beanName + "]");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 在bean初始化之后进行前置处理
// 在 init method 调用之后调用
System.out.println("MyBeanPostProcessor bean = [" + bean + "], beanName = [" + beanName + "]");
return bean;
}
}
|
9239d28d8b62a398824c9dd692f0a3fca2a9121a | 680 | java | Java | refactor-techniques/organizing-data/src/test/java/cc/oobootcamp/refactor/replace/data/value/with/object/ReplaceDataValueWithObjectTest.java | oo-bootcamp/refactoring-kata | a93cdd8b45fa51201ef33341bb0f5cf6759d2d9a | [
"MIT"
] | 3 | 2018-09-10T07:35:40.000Z | 2021-02-05T18:34:06.000Z | refactor-techniques/organizing-data/src/test/java/cc/oobootcamp/refactor/replace/data/value/with/object/ReplaceDataValueWithObjectTest.java | refactoring-kata/refactoring-kata | a93cdd8b45fa51201ef33341bb0f5cf6759d2d9a | [
"MIT"
] | null | null | null | refactor-techniques/organizing-data/src/test/java/cc/oobootcamp/refactor/replace/data/value/with/object/ReplaceDataValueWithObjectTest.java | refactoring-kata/refactoring-kata | a93cdd8b45fa51201ef33341bb0f5cf6759d2d9a | [
"MIT"
] | 3 | 2019-05-04T14:27:42.000Z | 2020-12-15T10:27:20.000Z | 30.909091 | 102 | 0.726471 | 998,972 | package cc.oobootcamp.refactor.replace.data.value.with.object;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
public class ReplaceDataValueWithObjectTest {
@Test
public void should_get_number_of_orders_for_customer() {
List<Order> orders = Arrays.asList(new Order("Kent"), new Order("Kent"), new Order("Martin"));
assertEquals(2, NumberOfOrdersFor(orders, "Kent"));
}
private static long NumberOfOrdersFor(List<Order> orders, String customer) {
return orders.stream().filter(o -> Objects.equals(o.getCustomer(), customer)).count();
}
} |
9239d2a322b119b9255b88f2c2e78055c66c64f0 | 1,237 | java | Java | AlgorithmJava/src/top/pusenyang/leetcode/L001.java | PusenYang/OoAlgorithm | 3e34517894f5c84f49a17c42bccb09004dd92ba4 | [
"MIT"
] | null | null | null | AlgorithmJava/src/top/pusenyang/leetcode/L001.java | PusenYang/OoAlgorithm | 3e34517894f5c84f49a17c42bccb09004dd92ba4 | [
"MIT"
] | null | null | null | AlgorithmJava/src/top/pusenyang/leetcode/L001.java | PusenYang/OoAlgorithm | 3e34517894f5c84f49a17c42bccb09004dd92ba4 | [
"MIT"
] | null | null | null | 32.552632 | 82 | 0.612773 | 998,973 | package top.pusenyang.leetcode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 给定一个整数数组 num和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
*
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
*/
public class L001 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int tmp = target - nums[i];
// if tmp exists and is not num[i] itself
if (map.containsKey(tmp) && map.get(tmp) != i) {
return new int[]{i, map.get(tmp)};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] tmpNum = br.readLine().split(" ");
int[] array = Arrays.stream(tmpNum).mapToInt(Integer::parseInt).toArray();
int target = Integer.parseInt(br.readLine());
L001 l = new L001();
Arrays.stream(l.twoSum(array, target)).forEach(System.out::println);
}
}
|
9239d37999215fc7b606265c10b7f9b71d4e7c45 | 757 | java | Java | tests/src/test/java/com/revolsys/fgdb/test/field/GeometryField.java | pauldaustin/gba-revolsys | 561c5a2f858b54ab4503e7ae5cffeac11d5d8952 | [
"Apache-2.0"
] | 5 | 2015-02-23T04:53:44.000Z | 2021-03-03T17:18:24.000Z | tests/src/test/java/com/revolsys/fgdb/test/field/GeometryField.java | pauldaustin/gba-revolsys | 561c5a2f858b54ab4503e7ae5cffeac11d5d8952 | [
"Apache-2.0"
] | 5 | 2021-08-13T23:45:14.000Z | 2022-03-31T19:59:23.000Z | tests/src/test/java/com/revolsys/fgdb/test/field/GeometryField.java | pauldaustin/gba-revolsys | 561c5a2f858b54ab4503e7ae5cffeac11d5d8952 | [
"Apache-2.0"
] | 8 | 2015-02-23T04:53:45.000Z | 2022-03-26T22:35:36.000Z | 28.037037 | 86 | 0.742404 | 998,974 | package com.revolsys.fgdb.test.field;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.jeometry.common.data.type.DataType;
import com.revolsys.geometry.model.GeometryFactory;
public class GeometryField extends FgdbField {
public GeometryField(final String name, final DataType type, final boolean required,
final GeometryFactory geometryFactory) {
super(name, type, required);
setGeometryFactory(geometryFactory);
}
@SuppressWarnings("unchecked")
@Override
public <T> T read(final ByteBuffer buffer) throws IOException {
// final Geometry geometry = null;
// final long length = FgdbReader.readVarUInt(buffer);
// buffer.read(new byte[(int)length]);
// return (T)geometry;
return null;
}
}
|
9239d398df4b82f2bd67048b9866d04280a39441 | 624 | java | Java | src/framework/GSize.java | pi0/MSP | 6a85460ed898c428a5e0c9a7fc26ff46203b38e2 | [
"MIT"
] | 1 | 2016-06-22T13:05:58.000Z | 2016-06-22T13:05:58.000Z | src/framework/GSize.java | pi0/MSP | 6a85460ed898c428a5e0c9a7fc26ff46203b38e2 | [
"MIT"
] | null | null | null | src/framework/GSize.java | pi0/MSP | 6a85460ed898c428a5e0c9a7fc26ff46203b38e2 | [
"MIT"
] | null | null | null | 20.8 | 46 | 0.520833 | 998,975 | package framework;
public class GSize {
public int width, height;
public GSize(int width, int height) {
this.width = width;
this.height = height;
}
public GSize(String s) {
String[] d = s.split("[xX\\*]");
this.width = Integer.parseInt(d[0]);
this.height = Integer.parseInt(d[1]);
}
public int getArea() {
return width * height;
}
public String toString() {
return width + "X" + height;
}
public void resize(GSize delta) {
width += delta.width;
height += delta.height;
}
}
|
9239d47100bdc54031330b66f8f5dd478a3dd8e7 | 1,091 | java | Java | src/main/java/com/github/braully/constant/ExpressionType.java | braully/prototyping-base-udm | c265311749725dadad5677fc7239ddbae931125d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/braully/constant/ExpressionType.java | braully/prototyping-base-udm | c265311749725dadad5677fc7239ddbae931125d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/braully/constant/ExpressionType.java | braully/prototyping-base-udm | c265311749725dadad5677fc7239ddbae931125d | [
"Apache-2.0"
] | null | null | null | 23.212766 | 82 | 0.702108 | 998,976 | /*
Copyright 2109 Braully Rocha
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.github.braully.constant;
/**
*
* @author braully
*/
public enum ExpressionType {
//TODO: Translate and unify
SIMPLES("Substituição simples"), EXCEL("Expressão excel"), JS("Expressão js");
private final String label;
private ExpressionType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public String getDescricao() {
return label;
}
@Override
public String toString() {
return this.label;
}
}
|
9239d6cbb18f460a25ef7252f23d0d25ec68960d | 1,208 | java | Java | src/main/java/com/divae/firstspirit/access/editor/fslist/IdProvidingFormDataMock.java | heikobarthel/firstspirit-mocks | e3777d2afd8b767c87db6ebec261f0b884b61f7d | [
"Apache-2.0"
] | 1 | 2017-10-24T11:45:44.000Z | 2017-10-24T11:45:44.000Z | src/main/java/com/divae/firstspirit/access/editor/fslist/IdProvidingFormDataMock.java | heikobarthel/firstspirit-mocks | e3777d2afd8b767c87db6ebec261f0b884b61f7d | [
"Apache-2.0"
] | 2 | 2018-08-14T08:01:02.000Z | 2018-08-17T07:53:04.000Z | src/main/java/com/divae/firstspirit/access/editor/fslist/IdProvidingFormDataMock.java | heikobarthel/firstspirit-mocks | e3777d2afd8b767c87db6ebec261f0b884b61f7d | [
"Apache-2.0"
] | 2 | 2018-08-17T06:06:37.000Z | 2022-02-16T10:02:50.000Z | 35.529412 | 219 | 0.767384 | 998,977 | package com.divae.firstspirit.access.editor.fslist;
import com.divae.firstspirit.forms.FormDataMock.DefaultFormDataBuilder;
import com.divae.firstspirit.forms.FormDataMock.FormDataBuilder;
import de.espirit.firstspirit.access.editor.fslist.IdProvidingFormData;
import static org.mockito.Mockito.when;
public final class IdProvidingFormDataMock {
private IdProvidingFormDataMock() {
throw new UnsupportedOperationException("Don't use default constructor");
}
public static IdProvidingFormDataBuilder idProvidingFormDataWith(Long id) {
return new DefaultIdProvidingFormDataBuilder(id);
}
public interface IdProvidingFormDataBuilder extends FormDataBuilder<IdProvidingFormData, IdProvidingFormDataBuilder> {
}
private static final class DefaultIdProvidingFormDataBuilder extends DefaultFormDataBuilder<IdProvidingFormData, IdProvidingFormDataBuilder, DefaultIdProvidingFormDataBuilder> implements IdProvidingFormDataBuilder {
private DefaultIdProvidingFormDataBuilder(Long id) {
super(id);
withId(id);
}
private void withId(Long id) {
when(getBuildable().getId()).thenReturn(id);
}
}
}
|
9239d7727cc7b9345584450f2a928509dfe31c7d | 3,633 | java | Java | 80.Sharding/sharding-core/src/main/java/com/xiudoua/micro/study/service/impl/UserinfoServiceImpl.java | north0808/SpringAll | 5e31ec2135e147e29b0c598ca2559e15bba6272c | [
"MIT"
] | null | null | null | 80.Sharding/sharding-core/src/main/java/com/xiudoua/micro/study/service/impl/UserinfoServiceImpl.java | north0808/SpringAll | 5e31ec2135e147e29b0c598ca2559e15bba6272c | [
"MIT"
] | null | null | null | 80.Sharding/sharding-core/src/main/java/com/xiudoua/micro/study/service/impl/UserinfoServiceImpl.java | north0808/SpringAll | 5e31ec2135e147e29b0c598ca2559e15bba6272c | [
"MIT"
] | null | null | null | 25.765957 | 97 | 0.738508 | 998,978 | package com.xiudoua.micro.study.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.xiudoua.micro.study.constant.IdGeneraterKey;
import com.xiudoua.micro.study.dao.IUserinfoDao;
import com.xiudoua.micro.study.entity.UserinfoEntity;
import com.xiudoua.micro.study.model.UserinfoVO;
import com.xiudoua.micro.study.service.IUserinfoService;
import com.xiudoua.micro.study.service.SequenceService;
import com.xiudoua.micro.study.utils.MyClassUtil;
/**
* @desc
* @author JustFresh
* @time 2021年2月19日 下午1:54:48
*/
@Service
public class UserinfoServiceImpl implements IUserinfoService{
private static final Logger logger = LoggerFactory.getLogger(UserinfoServiceImpl.class);
@Autowired
private IUserinfoDao userinfoDao;
@Autowired
private SequenceService sequenceService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
*
* @param param
* @return
*/
private UserinfoEntity getEntity(UserinfoVO param) {
if(param != null) {
UserinfoEntity res = new UserinfoEntity();
BeanUtils.copyProperties(param, res);
return res;
}
return null;
}
/**
*
* @param entity
* @return
*/
private UserinfoVO getVO(UserinfoEntity entity) {
if(entity != null) {
UserinfoVO res = new UserinfoVO();
BeanUtils.copyProperties(entity, res);
return res;
}
return null;
}
/**
*
* @param entityList
* @return
*/
private List<UserinfoVO> getVOList(List<UserinfoEntity> entityList){
if(entityList != null && !entityList.isEmpty()) {
List<UserinfoVO> resList = new ArrayList<>();
for(UserinfoEntity entity : entityList) {
resList.add(getVO(entity));
}
return resList;
}
return null;
}
@Transactional(rollbackOn = Exception.class)
public List<UserinfoVO> batchSave(List<UserinfoVO> userinfoList) {
if(userinfoList != null && !userinfoList.isEmpty()) {
List<UserinfoEntity> entityList = new ArrayList<>();
for(UserinfoVO vo : userinfoList) {
entityList.add(getEntity(vo));
}
return getVOList(userinfoDao.saveAll(entityList));
}
return null;
}
@Override
@Transactional
public Long saveAndReturnByDB(UserinfoVO param) {
String seqName = MyClassUtil.getTableName(UserinfoEntity.class);
Long id = sequenceService.getNextVal(seqName);
param.setId(id);
userinfoDao.save(this.getEntity(param));
return id;
}
@Override
public Long saveAndReturnByRedis(UserinfoVO param) {
Long id = redisTemplate.opsForValue().increment(IdGeneraterKey.REDIS_KEY_GENERATER_USERINFO,1);
param.setId(id);
try {
UserinfoEntity entity = userinfoDao.save(this.getEntity(param));
if(entity != null) {
return id;
}
logger.error("使用Redis方式生成主键保存TB_USERINFO数据失败!");
redisTemplate.opsForValue().decrement(IdGeneraterKey.REDIS_KEY_GENERATER_USERINFO,1);
} catch (Exception e) {
logger.error("使用Redis方式生成主键保存TB_USERINFO数据出错!",e);
redisTemplate.opsForValue().decrement(IdGeneraterKey.REDIS_KEY_GENERATER_USERINFO,1);
}
return null;
}
@Override
public Long save(UserinfoVO param) {
try {
UserinfoEntity entity = userinfoDao.save(this.getEntity(param));
if(entity == null) {
logger.error("保存TB_USERINFO数据失败!");
return null;
}
return entity.getId();
} catch (Exception e) {
logger.error("保存TB_USERINFO数据出错!",e);
}
return null;
}
} |
9239d79f934c59f6217c3cecdf1198bbbd5b372e | 106 | java | Java | code/Common/src/main/java/net/selenate/common/comms/SeOptionSelectMethod.java | AnaMarjanica/selenate | 2f7ad32db0e8150c8a015ba1506c70e31a890c4b | [
"BSD-3-Clause"
] | null | null | null | code/Common/src/main/java/net/selenate/common/comms/SeOptionSelectMethod.java | AnaMarjanica/selenate | 2f7ad32db0e8150c8a015ba1506c70e31a890c4b | [
"BSD-3-Clause"
] | null | null | null | code/Common/src/main/java/net/selenate/common/comms/SeOptionSelectMethod.java | AnaMarjanica/selenate | 2f7ad32db0e8150c8a015ba1506c70e31a890c4b | [
"BSD-3-Clause"
] | null | null | null | 13.25 | 34 | 0.764151 | 998,979 | package net.selenate.common.comms;
public enum SeOptionSelectMethod {
INDEX,
VALUE,
VISIBLE_TEXT
}
|
9239d87cab33526f93b862ddbaa81d47ca69ddbe | 363 | java | Java | src/main/java/com/fangxuele/tool/push/logic/msgsender/SendResult.java | git-tianbo/WePush | 6a2a49bce7c4c5798133cb93641f2598a20e4213 | [
"MIT"
] | 2,819 | 2017-06-23T10:06:18.000Z | 2022-03-30T02:58:53.000Z | src/main/java/com/fangxuele/tool/push/logic/msgsender/SendResult.java | thup/WePush | c6bbfdac32c838f3365f155d744cdacf0bac6857 | [
"MIT"
] | 46 | 2017-07-06T01:23:11.000Z | 2022-03-15T06:42:48.000Z | src/main/java/com/fangxuele/tool/push/logic/msgsender/SendResult.java | thup/WePush | c6bbfdac32c838f3365f155d744cdacf0bac6857 | [
"MIT"
] | 826 | 2017-06-23T09:58:10.000Z | 2022-03-29T10:24:56.000Z | 15.782609 | 67 | 0.69146 | 998,980 | package com.fangxuele.tool.push.logic.msgsender;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* <pre>
* 发送结果
* </pre>
*
* @author <a href="https://github.com/rememberber">RememBerBer</a>
* @since 2019/6/15.
*/
@Getter
@Setter
@ToString
public class SendResult {
private boolean success = false;
private String info;
}
|
9239d9511cfda1771121010de98caca5f5de19d6 | 962 | java | Java | heima-leadnews-admin/src/main/java/com/heima/admin/kafka/listener/WemediaNewsAutoListener.java | liangzhuo1/projrct | e6e3415ae30ac64cc6812856928c0bceab81223b | [
"Apache-2.0"
] | null | null | null | heima-leadnews-admin/src/main/java/com/heima/admin/kafka/listener/WemediaNewsAutoListener.java | liangzhuo1/projrct | e6e3415ae30ac64cc6812856928c0bceab81223b | [
"Apache-2.0"
] | null | null | null | heima-leadnews-admin/src/main/java/com/heima/admin/kafka/listener/WemediaNewsAutoListener.java | liangzhuo1/projrct | e6e3415ae30ac64cc6812856928c0bceab81223b | [
"Apache-2.0"
] | null | null | null | 34.357143 | 94 | 0.776507 | 998,981 | package com.heima.admin.kafka.listener;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.constans.message.NewsAutoScanConstants;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class WemediaNewsAutoListener {
@Autowired
WemediaNewsAutoScanService wemediaNewsAutoScanService;
@KafkaListener(topics = NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC)
public void recevieMessage(ConsumerRecord<?,?> record){
Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);
if(optional.isPresent()){
Object value = record.value();
wemediaNewsAutoScanService.autoScanByMediaNewsId(Integer.valueOf((String) value));
}
}
}
|
9239d9564a6b4784094dcd5992cd4bbf566340b3 | 21,944 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Drive2XYHeading.java | jrasor/csee113S21 | 9b9b78abad9cc5344cf3e09ac86a5d8eb9340b67 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Drive2XYHeading.java | jrasor/csee113S21 | 9b9b78abad9cc5344cf3e09ac86a5d8eb9340b67 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Drive2XYHeading.java | jrasor/csee113S21 | 9b9b78abad9cc5344cf3e09ac86a5d8eb9340b67 | [
"MIT"
] | null | null | null | 42.859375 | 131 | 0.700465 | 998,982 | /* Copyright (c) 2019 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification,
* are permitted (subject to the limitations in the disclaimer below)
* provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to
* endorse or
* promote products derived from this software without specific prior written
* permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
import java.util.ArrayList;
import java.util.List;
import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.DEGREES;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.XYZ;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.YZX;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesReference.EXTRINSIC;
import static org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection.BACK;
/**
* This 2020-2021 OpMode illustrates the basics of using the Vuforia
* localizer to determine
* positioning and orientation of robot on the ULTIMATE GOAL FTC field.
* The code is structured as a LinearOpMode
* <p>
* When images are located, Vuforia is able to determine the position and
* orientation of the
* image relative to the camera. This sample code then combines that
* information with a
* knowledge of where the target images are on the field, to determine the
* location of the camera.
* <p>
* From the Audience perspective, the Red Alliance station is on the right
* and the
* Blue Alliance Station is on the left.
* <p>
* There are a total of five image targets for the ULTIMATE GOAL game.
* Three of the targets are placed in the center of the Red Alliance,
* Audience (Front),
* and Blue Alliance perimeter walls.
* Two additional targets are placed on the perimeter wall, one in front of
* each Tower Goal.
* Refer to the Field Setup manual for more specific location details
* <p>
* A final calculation then uses the location of the camera on the robot to
* determine the
* robot's location and orientation on the field.
*
* @see VuforiaLocalizer
* @see VuforiaTrackableDefaultListener
* see ultimategoal/doc/tutorial/FTC_FieldCoordinateSystemDefinition.pdf
* <p>
* Use Android Studio to Copy this Class, and Paste it into your team's code
* folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver
* Station OpMode list.
* <p>
* IMPORTANT: In order to use this OpMode, you need to obtain your own
* Vuforia license key as
* is explained below.
*/
@TeleOp(name = "Drive2XYHeading", group = "Concept")
//@Disabled
public class Drive2XYHeading extends LinearOpMode {
private ElapsedTime runtime = new ElapsedTime();
/* = = Vuforia initialization. = = */
// IMPORTANT: For Phone Camera, set 1) the camera source and 2) the
// orientation, based on how your phone is mounted:
// 1) Camera Source. Valid choices are: BACK (behind screen) or FRONT
// (selfie side)
// 2) Phone Orientation. Choices are: PHONE_IS_PORTRAIT = true (portrait)
// or PHONE_IS_PORTRAIT = false (landscape)
//
// NOTE: If you are running on a CONTROL HUB, with only one USB WebCam, you
// must select CAMERA_CHOICE = BACK; and PHONE_IS_PORTRAIT = false;
//
private static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
private static final boolean PHONE_IS_PORTRAIT = false;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The
* string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only,
* and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from
* the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they
* contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web
* site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY =
GenericFTCRobot.VUFORIA_KEY;
// Since ImageTarget trackables use mm to specifiy their dimensions, we
// must use mm for all the physical dimension.
// We will define some constants and conversions here
private static final float mmPerInch = 25.4f;
private static final float mmTargetHeight = (6) * mmPerInch; //
// the height of the center of the target image above the floor
// Constants for perimeter targets
private static final float halfField = 72 * mmPerInch;
private static final float quadField = 36 * mmPerInch;
// Class Members
private OpenGLMatrix lastLocation = null;
private VuforiaLocalizer vuforia = null;
private boolean targetVisible = false;
private float phoneXRotate = 0;
private float phoneYRotate = 0;
private float phoneZRotate = 0;
double yCorrection = -0.04;
double headingCorrection = 0.5;
static final double STRAIGHT_SPEED = 0.6;
static final double TURN_SPEED = 0.2;
static final double MAX_CORRECTION = TURN_SPEED;
static final double MIN_CORRECTION = -TURN_SPEED;
double targetX = 74.0; // Aim for robot front to end up near the picture.
double currentX = 0; // We'll refine this by Vuforia if target image is
// visible.
double errorX = currentX - targetX;
static final double ERROR_X_TOLERANCE = 16.0;
// avoids large and unstable bearing changes on final approach.
double targetY = 35.5; // Also so robot can be near the picture.
double currentY;
double errorY;
static final double ERROR_Y_TOLERANCE = 1.0;
double targetHeadingDegrees = 0.0;
double targetHeadingRadians = targetHeadingDegrees * Math.PI / 180.0;
double currentHeadingDegrees;
double currentHeadingRadians;
double errorHeadingDegrees;
double errorHeadingRadians;
double targetBearingRadians = 0.0;
double targetBearingDegrees = targetBearingRadians * 180 / Math.PI;
double currentBearingRadians;
double errorBearingRadians;
double currentBearingDegrees;
double errorBearingDegrees;
double correction = 0.0;
@Override
public void runOpMode() {
while (!gamepad1.y) {
telemetry.addLine("Tuning controls. Press yellow Y button to " +
"finish tuning, even if no tuning done.");
telemetry.addLine(" Pad left/right: more/less Y error correction" +
".");
telemetry.addLine(" Green B button: more heading correction.");
telemetry.addLine(" Blue X button: less heading correction.");
telemetry.addLine("Press the Yellow Y button to finish tuning.");
if (gamepad1.dpad_right) {
gamepad1.dpad_right = false;
yCorrection *= 1.1;
sleep(300);
}
if (gamepad1.dpad_left) {
gamepad1.dpad_left = false;
yCorrection /= 1.1;
sleep(300);
}
if (gamepad1.b) {
gamepad1.b = false;
headingCorrection *= 1.1;
sleep(300);
}
if (gamepad1.x) {
gamepad1.x = false;
headingCorrection /= 1.1;
sleep(300);
}
telemetry.addData("Bearing correction",
" %5.3f Heading correction %5.3f", yCorrection,
headingCorrection);
telemetry.update();
}
Pullbot robot = new Pullbot(this);
String initReport = robot.init(hardwareMap);
telemetry.addData("Robot status", "initialized.");
telemetry.addData("Initialization report", initReport);
telemetry.update();
/*
* Configure Vuforia by creating a Parameter object, and passing it to
* the Vuforia engine.
* We can pass Vuforia the handle to a camera preview resource (on the RC
* phone);
* If no camera monitor is desired, use the parameter-less constructor
* instead (commented out below).
*/
int cameraMonitorViewId =
hardwareMap.appContext.getResources().getIdentifier(
"cameraMonitorViewId", "id",
hardwareMap.appContext.getPackageName());
VuforiaLocalizer.Parameters parameters =
new VuforiaLocalizer.Parameters(cameraMonitorViewId);
// VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer
// .Parameters();
parameters.vuforiaLicenseKey = VUFORIA_KEY;
parameters.cameraDirection = CAMERA_CHOICE;
// Make sure extended tracking is disabled for this example.
parameters.useExtendedTracking = false;
// Instantiate the Vuforia engine
vuforia = ClassFactory.getInstance().createVuforia(parameters);
// Load the data sets for the trackable objects. These particular data
// sets are stored in the 'assets' part of our application.
VuforiaTrackables targetsUltimateGoal =
this.vuforia.loadTrackablesFromAsset("UltimateGoal");
VuforiaTrackable blueTowerGoalTarget = targetsUltimateGoal.get(0);
blueTowerGoalTarget.setName("Blue Tower Goal Target");
VuforiaTrackable redTowerGoalTarget = targetsUltimateGoal.get(1);
redTowerGoalTarget.setName("Red Tower Goal Target");
VuforiaTrackable redAllianceTarget = targetsUltimateGoal.get(2);
redAllianceTarget.setName("Red Alliance Target");
VuforiaTrackable blueAllianceTarget = targetsUltimateGoal.get(3);
blueAllianceTarget.setName("Blue Alliance Target");
VuforiaTrackable frontWallTarget = targetsUltimateGoal.get(4);
frontWallTarget.setName("Front Wall Target");
// For convenience, gather together all the trackable objects in one
// easily-iterable collection */
List<VuforiaTrackable> allTrackables = new ArrayList<VuforiaTrackable>();
allTrackables.addAll(targetsUltimateGoal);
/**
* In order for localization to work, we need to tell the system where
* each target is on the field, and
* where the phone resides on the robot. These specifications are in the
* form of <em>transformation matrices.</em>
* Transformation matrices are a central, important concept in the math
* here involved in localization.
* See
* <a href="https://en.wikipedia.org/wiki/Transformation_matrix">Transformation Matrix</a>
* for detailed information. Commonly, you'll encounter transformation
* matrices as instances
* of the {@link OpenGLMatrix} class.
*
* If you are standing in the Red Alliance Station looking towards the
* center of the field,
* - The X axis runs from your left to the right. (positive from the
* center to the right)
* - The Y axis runs from the Red Alliance Station towards the other
* side of the field
* where the Blue Alliance Station is. (Positive is from the
* center, towards the BlueAlliance station)
* - The Z axis runs from the floor, upwards towards the ceiling.
* (Positive is above the floor)
*
* Before being transformed, each target image is conceptually located at
* the origin of the field's
* coordinate system (the center of the field), facing up.
*/
//Set the position of the perimeter targets with relation to origin
// (center of field)
redAllianceTarget.setLocation(OpenGLMatrix
.translation(0, -halfField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90
, 0, 180)));
blueAllianceTarget.setLocation(OpenGLMatrix
.translation(0, halfField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90
, 0, 0)));
frontWallTarget.setLocation(OpenGLMatrix
.translation(-halfField, 0, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90
, 0, 90)));
// The tower goal targets are located a quarter field length from the
// ends of the back perimeter wall.
blueTowerGoalTarget.setLocation(OpenGLMatrix
.translation(halfField, quadField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90
, 0, -90)));
redTowerGoalTarget.setLocation(OpenGLMatrix
.translation(halfField, -quadField, mmTargetHeight)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90
, 0, -90)));
//
// Create a transformation matrix describing where the phone is on the
// robot.
//
// NOTE !!!! It's very important that you turn OFF your phone's
// Auto-Screen-Rotation option.
// Lock it into Portrait for these numbers to work.
//
// Info: The coordinate frame for the robot looks the same as the field.
// The robot's "forward" direction is facing out along X axis, with the
// LEFT side facing out along the Y axis.
// Z is UP on the robot. This equates to a bearing angle of Zero degrees.
//
// The phone starts out lying flat, with the screen facing Up and with
// the physical top of the phone
// pointing to the LEFT side of the Robot.
// The two examples below assume that the camera is facing forward out
// the front of the robot.
// We need to rotate the camera around it's long axis to bring the
// correct camera forward.
if (CAMERA_CHOICE == BACK) {
phoneYRotate = -90;
} else {
phoneYRotate = 90;
}
// Rotate the phone vertical about the X axis if it's in portrait mode
if (PHONE_IS_PORTRAIT) {
phoneXRotate = 90;
}
// Next, translate the camera lens to where it is on the robot.
// In this example, it is centered (left to right), but forward of the
// middle of the robot, and above ground level.
final float CAMERA_FORWARD_DISPLACEMENT = 4.0f * mmPerInch; // eg:
// Camera is 4 Inches in front of robot center
final float CAMERA_VERTICAL_DISPLACEMENT = 8.0f * mmPerInch; // eg:
// Camera is 8 Inches above ground
final float CAMERA_LEFT_DISPLACEMENT = 0; // eg: Camera is ON the
// robot's center line
OpenGLMatrix robotFromCamera = OpenGLMatrix
.translation(CAMERA_FORWARD_DISPLACEMENT, CAMERA_LEFT_DISPLACEMENT,
CAMERA_VERTICAL_DISPLACEMENT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, YZX, DEGREES,
phoneYRotate, phoneZRotate, phoneXRotate));
/** Let all the trackable listeners know where the phone is. */
for (VuforiaTrackable trackable : allTrackables) {
((VuforiaTrackableDefaultListener) trackable.getListener()).setPhoneInformation(robotFromCamera, parameters.cameraDirection);
}
// WARNING:
// In this sample, we do not wait for PLAY to be pressed. Target
// Tracking is started immediately when INIT is pressed.
// This sequence is used to enable the new remote DS Camera Preview
// feature to be used with this sample.
// CONSEQUENTLY do not put any driving commands in this loop.
// To restore the normal opmode structure, just un-comment the following
// line:
// waitForStart();
// Note: To use the remote camera preview:
// AFTER you hit Init on the Driver Station, use the "options menu" to
// select "Camera Stream"
// Tap the preview window to receive a fresh image.
targetsUltimateGoal.activate();
while (!isStopRequested()) {
targetVisible = false;
for (VuforiaTrackable trackable : allTrackables) {
if (((VuforiaTrackableDefaultListener) trackable.getListener()).isVisible()) {
telemetry.addData("Visible Target", trackable.getName());
targetVisible = true;
OpenGLMatrix robotLocationTransform =
((VuforiaTrackableDefaultListener) trackable.getListener()).getUpdatedRobotLocation();
if (robotLocationTransform != null) {
lastLocation = robotLocationTransform;
}
break;
}
}
// Report robot location and heading (if we know).
if (targetVisible) {
VectorF translation = lastLocation.getTranslation();
telemetry.addData("Pos ", "{X, Y} = %5.1f\", %5.1f\"",
translation.get(0) / GenericFTCRobot.mmPerInch,
translation.get(1) / GenericFTCRobot.mmPerInch);
Orientation rotation =
Orientation.getOrientation(lastLocation, EXTRINSIC,
XYZ, DEGREES);
telemetry.addData("Heading", "%4.0f\u00B0", rotation.thirdAngle);
} else {
telemetry.addData("Visible Target", "none");
}
telemetry.update();
// Report where the robot is located, if we can see a Vuforia image.
if (targetVisible && Math.abs(errorX) > ERROR_X_TOLERANCE) {
// Report position (translation) and position error of robot in inches.
VectorF translation = lastLocation.getTranslation();
currentX = translation.get(0) / GenericFTCRobot.mmPerInch;
currentY = translation.get(1) / GenericFTCRobot.mmPerInch;
errorX = currentX - targetX;
errorY = currentY - targetY;
telemetry.addData("Position error", "X, Y = %4.1f, %4.1f",
errorX, errorY);
// Report bearing and bearing error of target from robot.
currentBearingRadians = Math.atan2(-errorY, -errorX);
currentBearingDegrees = currentBearingRadians * 180.0 / Math.PI;
errorBearingRadians = currentBearingRadians - targetBearingRadians;
errorBearingDegrees = errorBearingRadians * 180.0 / Math.PI;
telemetry.addData("Bearing", " %4.0f\u00B0 error: %4.0f\u00B0",
currentBearingDegrees, errorBearingDegrees);
// Report robot heading in degrees, and error of that heading.
Orientation rotation =
Orientation.getOrientation(lastLocation, EXTRINSIC,
XYZ,
DEGREES);
currentHeadingDegrees = rotation.thirdAngle;
currentHeadingRadians = currentHeadingDegrees * Math.PI / 180.0;
errorHeadingDegrees = currentHeadingDegrees - targetHeadingDegrees;
errorBearingRadians = currentBearingRadians - targetBearingRadians;
errorHeadingRadians = errorHeadingDegrees * Math.PI / 180.0;
telemetry.addData(
"Heading", "%4.0f\u00B0 Heading error %4.0f\u00B0",
currentHeadingDegrees, errorHeadingDegrees);
// find motor speed corrections.
correction =
yCorrection * errorY - headingCorrection * errorHeadingRadians;
correction = Math.min(Math.max(correction, MIN_CORRECTION),
MAX_CORRECTION);
// Todo: slow down when errorX gets small.
// Apply those corrections to drive motors.
// This is a Pullbot, not a Pushbot.
robot.leftDrive.setPower(-TURN_SPEED + correction);
robot.rightDrive.setPower(-TURN_SPEED - correction);
telemetry.addData("Motor speeds",
"correction %5.3f left %5.3f right %5.3f",
correction, TURN_SPEED - correction, TURN_SPEED + correction);
} else if (!targetVisible) {
telemetry.addLine("Visible target lost. Stopping.");
robot.leftDrive.setPower(0.0);
robot.rightDrive.setPower(0.0);
// Todo: try to recover from this by turning on axis, guessing
// from last known position.
} else {
telemetry.addLine("We have arrived. Stopping.");
// Clean up residual heading error.
robot.turnAngle(TURN_SPEED, -errorHeadingRadians);
robot.leftDrive.setPower(0.0);
robot.rightDrive.setPower(0.0);
// Disable tracking when we are done.
targetsUltimateGoal.deactivate();
stop();
}
}
// Disable Tracking when we are done;
targetsUltimateGoal.deactivate();
}
}
|
9239d96cdd4c8118a655e8bcb536b897e1c61ea8 | 125 | java | Java | Cats/Cats-application/src/main/java/pl/martitafilix/cats/CatsApp.java | emefix/Kobiety-do-kodu | f6823b46cfb9647d9c29a3d7001b3f5c8913f502 | [
"Apache-2.0"
] | null | null | null | Cats/Cats-application/src/main/java/pl/martitafilix/cats/CatsApp.java | emefix/Kobiety-do-kodu | f6823b46cfb9647d9c29a3d7001b3f5c8913f502 | [
"Apache-2.0"
] | null | null | null | Cats/Cats-application/src/main/java/pl/martitafilix/cats/CatsApp.java | emefix/Kobiety-do-kodu | f6823b46cfb9647d9c29a3d7001b3f5c8913f502 | [
"Apache-2.0"
] | null | null | null | 12.5 | 41 | 0.704 | 998,983 | package pl.martitafilix.cats;
public class CatsApp {
public static void main(String[] args) {
new AppInterface();
}
}
|
9239d9b674ccea56dafef998560afa279254b481 | 481 | java | Java | app-service/src/main/java/com/hao/app/service/SysLogsService.java | haoguowei/app | 00292f4b5594e50df448a6fcabeee378ac5f2f4e | [
"Apache-2.0"
] | null | null | null | app-service/src/main/java/com/hao/app/service/SysLogsService.java | haoguowei/app | 00292f4b5594e50df448a6fcabeee378ac5f2f4e | [
"Apache-2.0"
] | 2 | 2019-12-25T11:52:22.000Z | 2019-12-25T11:52:33.000Z | app-service/src/main/java/com/hao/app/service/SysLogsService.java | haoguowei/app | 00292f4b5594e50df448a6fcabeee378ac5f2f4e | [
"Apache-2.0"
] | 1 | 2017-01-02T12:54:46.000Z | 2017-01-02T12:54:46.000Z | 15.516129 | 68 | 0.615385 | 998,984 | package com.hao.app.service;
import com.hao.app.commons.entity.result.JsonResult;
import com.hao.app.pojo.SysLogs;
/**
* 系统日志处理
*
* @author haoguowei
*
*/
public interface SysLogsService {
/**
* 分页查询日志记录
* @param name
* @param start
* @param limit
* @return
*/
JsonResult<SysLogs> searchLogs(String name, int start, int limit);
/**
* 写日志
* @param user
* @param string
*/
void writeLog(String user, String string);
}
|
9239da08479b28c485643c8277b31747f9d00d9b | 4,494 | java | Java | provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | 34.045455 | 167 | 0.628171 | 998,985 | /*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.provisioning.impl;
import java.util.HashMap;
import java.util.Map;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
/**
* Class for caching ResourceType instances with a parsed schemas.
*
* @author Radovan Semancik
*
*/
@Component
public class ResourceCache {
private static final Trace LOGGER = TraceManager.getTrace(ResourceCache.class);
private Map<String,PrismObject<ResourceType>> cache;
ResourceCache() {
cache = new HashMap<>();
}
public synchronized void put(PrismObject<ResourceType> resource) throws SchemaException {
String oid = resource.getOid();
if (oid == null) {
throw new SchemaException("Attempt to cache "+resource+" without an OID");
}
String version = resource.getVersion();
if (version == null) {
throw new SchemaException("Attempt to cache "+resource+" without version");
}
PrismObject<ResourceType> cachedResource = cache.get(oid);
if (cachedResource == null) {
LOGGER.debug("Caching(new): {}", resource);
cache.put(oid, resource.createImmutableClone());
} else {
if (compareVersion(resource.getVersion(), cachedResource.getVersion())) {
LOGGER.debug("Caching fizzle, resource already cached: {}", resource);
// We already have equivalent resource, nothing to do
} else {
LOGGER.debug("Caching(replace): {}", resource);
cache.put(oid, resource.createImmutableClone());
}
}
}
private boolean compareVersion(String version1, String version2) {
if (version1 == null && version2 == null) {
return true;
}
if (version1 == null || version2 == null) {
return false;
}
return version1.equals(version2);
}
public synchronized PrismObject<ResourceType> get(PrismObject<ResourceType> resource, GetOperationOptions options) throws SchemaException {
return get(resource.getOid(), resource.getVersion(), options);
}
public synchronized PrismObject<ResourceType> get(String oid, String requestedVersion, GetOperationOptions options) throws SchemaException {
if (oid == null) {
return null;
}
PrismObject<ResourceType> cachedResource = cache.get(oid);
if (cachedResource == null) {
LOGGER.debug("MISS(not cached) for {}", oid);
return null;
}
if (!compareVersion(requestedVersion, cachedResource.getVersion())) {
LOGGER.debug("MISS(wrong version) for {}", oid);
LOGGER.trace("Cached resource version {} does not match requested resource version {}, purging from cache", cachedResource.getVersion(), requestedVersion);
cache.remove(oid);
return null;
}
if (GetOperationOptions.isReadOnly(options)) {
try { // MID-4574
cachedResource.checkImmutability();
} catch (IllegalStateException ex) {
LOGGER.error("Failed immutability test", ex);
cache.remove(oid);
return null;
}
LOGGER.trace("HIT(read only) for {}", cachedResource);
return cachedResource;
} else {
LOGGER.debug("HIT(returning clone) for {}", cachedResource);
return cachedResource.clone();
}
}
/**
* Returns currently cached version. FOR DIAGNOSTICS ONLY.
*/
public synchronized String getVersion(String oid) {
if (oid == null) {
return null;
}
PrismObject<ResourceType> cachedResource = cache.get(oid);
if (cachedResource == null) {
return null;
}
return cachedResource.getVersion();
}
public synchronized void remove(String oid) {
cache.remove(oid);
}
}
|
9239dba147e27a89c2475659da181a7089acba2c | 1,054 | java | Java | src/main/java/net/moznion/jesqulin/JesqueQueuer.java | moznion/jesqulin | 9385c30f2d1b0c5bdbf43f267b79113eba85cc8f | [
"MIT"
] | null | null | null | src/main/java/net/moznion/jesqulin/JesqueQueuer.java | moznion/jesqulin | 9385c30f2d1b0c5bdbf43f267b79113eba85cc8f | [
"MIT"
] | null | null | null | src/main/java/net/moznion/jesqulin/JesqueQueuer.java | moznion/jesqulin | 9385c30f2d1b0c5bdbf43f267b79113eba85cc8f | [
"MIT"
] | null | null | null | 28.486486 | 112 | 0.64611 | 998,986 | package net.moznion.jesqulin;
/**
* Queuer class for Jesque.
*
* @param <T>
* @param <Y>
*/
public class JesqueQueuer<T extends JesqueArgument, Y extends JesqueAction<T>> {
private final Class<Y> actionClass;
private final JesqueClient jesqueClient;
private final String queueName;
public JesqueQueuer(final Class<Y> actionClass,
final JesqueClient jesqueClient) throws IllegalAccessException, InstantiationException {
this.actionClass = actionClass;
this.jesqueClient = jesqueClient;
final JesqueAction action = actionClass.newInstance();
queueName = action.getQueueName();
}
/**
* Enqueues the job to Jesqueue's queue.
* <p>
* Passed argument will be transformed to Job of Jesque.
*
* @param argument The argument that represents job.
*/
public void enqueue(final T argument) {
jesqueClient.enqueue(
queueName,
new JesqueJobFactory<T, Y>().create(actionClass, argument)
);
}
}
|
9239dc154ec60e2818163e372834af7eceaa6aca | 84 | java | Java | test/src/test/java/org/zstack/test/applianceVm/ApplianceVmValidator.java | anlow12/zstack | 77ac7189c34a22aba944d3b7b36d5df84f7d4718 | [
"Apache-2.0"
] | 879 | 2017-02-16T02:01:44.000Z | 2022-03-31T15:44:28.000Z | test/src/test/java/org/zstack/test/applianceVm/ApplianceVmValidator.java | Abortbeen/zstack | 40f195893250b84881798a702f3b2455c83336a1 | [
"Apache-2.0"
] | 482 | 2017-02-13T09:57:37.000Z | 2022-03-31T07:17:29.000Z | test/src/test/java/org/zstack/test/applianceVm/ApplianceVmValidator.java | Abortbeen/zstack | 40f195893250b84881798a702f3b2455c83336a1 | [
"Apache-2.0"
] | 306 | 2017-02-13T08:31:29.000Z | 2022-03-14T07:58:46.000Z | 12 | 36 | 0.738095 | 998,987 | package org.zstack.test.applianceVm;
/**
*/
public class ApplianceVmValidator {
}
|
9239dc20706b32cdae60cb13b3b982216b8b3f88 | 2,187 | java | Java | src/main/java/org/olat/user/ui/admin/bulk/move/UserBulkMove.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 191 | 2018-03-29T09:55:44.000Z | 2022-03-23T06:42:12.000Z | src/main/java/org/olat/user/ui/admin/bulk/move/UserBulkMove.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 68 | 2018-05-11T06:19:00.000Z | 2022-01-25T18:03:26.000Z | src/main/java/org/olat/user/ui/admin/bulk/move/UserBulkMove.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 139 | 2018-04-27T09:46:11.000Z | 2022-03-27T08:52:50.000Z | 27.797468 | 82 | 0.746357 | 998,988 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.user.ui.admin.bulk.move;
import java.util.List;
import org.olat.basesecurity.OrganisationRoles;
import org.olat.core.id.Identity;
import org.olat.core.id.Organisation;
/**
*
* Initial date: 27 mai 2019<br>
* @author srosse, lyhxr@example.com, http://www.frentix.com
*
*/
public class UserBulkMove {
private final List<Identity> identities;
private final Organisation organisation;
private Organisation targetOrganisation;
private List<OrganisationRoles> roles;
private List<Identity> identitiesToMove;
public UserBulkMove(Organisation organisation, List<Identity> identities) {
this.organisation = organisation;
this.identities = identities;
}
public List<Identity> getIdentities() {
return identities;
}
public Organisation getOrganisation() {
return organisation;
}
public Organisation getTargetOrganisation() {
return targetOrganisation;
}
public void setTargetOrganisation(Organisation targetOrganisation) {
this.targetOrganisation = targetOrganisation;
}
public List<OrganisationRoles> getRoles() {
return roles;
}
public void setRoles(List<OrganisationRoles> roles) {
this.roles = roles;
}
public List<Identity> getIdentitiesToMove() {
return identitiesToMove;
}
public void setIdentitiesToMove(List<Identity> identitiesToMove) {
this.identitiesToMove = identitiesToMove;
}
}
|
9239dfbf098c52253e186f5af0f41000d7a1ed77 | 314 | java | Java | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/dbaas/logs/OvhStreamColdStorageTargetEnum.java | marstona/ovh-java-sdk | b574fbbac59832fda7a4fedaf3cb1f074135f714 | [
"BSD-3-Clause"
] | 12 | 2017-04-04T07:20:48.000Z | 2021-04-20T07:54:21.000Z | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/dbaas/logs/OvhStreamColdStorageTargetEnum.java | marstona/ovh-java-sdk | b574fbbac59832fda7a4fedaf3cb1f074135f714 | [
"BSD-3-Clause"
] | 7 | 2017-04-05T04:54:16.000Z | 2019-09-24T11:17:05.000Z | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/dbaas/logs/OvhStreamColdStorageTargetEnum.java | marstona/ovh-java-sdk | b574fbbac59832fda7a4fedaf3cb1f074135f714 | [
"BSD-3-Clause"
] | 3 | 2019-10-10T13:51:22.000Z | 2020-11-13T14:30:45.000Z | 15.7 | 50 | 0.719745 | 998,989 | package net.minidev.ovh.api.dbaas.logs;
/**
* Possible values for StreamColdStorageTargetEnum
*/
public enum OvhStreamColdStorageTargetEnum {
PCA("PCA"),
PCS("PCS");
final String value;
OvhStreamColdStorageTargetEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
|
9239e016409e46bce29adf33180bce17ea7b4952 | 701 | java | Java | demo-arthas-spring-boot/src/main/java/com/example/demo/arthas/user/UserController.java | tayanzhuifeng/spring-boot-inside | 057a8a52f4c48da3e3381b4e1ed295e597505581 | [
"MIT"
] | 202 | 2017-08-22T14:48:04.000Z | 2022-01-27T01:23:27.000Z | demo-arthas-spring-boot/src/main/java/com/example/demo/arthas/user/UserController.java | tayanzhuifeng/spring-boot-inside | 057a8a52f4c48da3e3381b4e1ed295e597505581 | [
"MIT"
] | 1 | 2020-06-04T12:17:48.000Z | 2020-06-04T12:17:48.000Z | demo-arthas-spring-boot/src/main/java/com/example/demo/arthas/user/UserController.java | tayanzhuifeng/spring-boot-inside | 057a8a52f4c48da3e3381b4e1ed295e597505581 | [
"MIT"
] | 179 | 2017-09-20T04:27:06.000Z | 2022-03-24T02:19:27.000Z | 26.961538 | 84 | 0.730385 | 998,990 | package com.example.demo.arthas.user;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@GetMapping("/user/{id}")
public User findUserById(@PathVariable Integer id) {
logger.info("id: {}" , id);
if (id != null && id < 1) {
return new User(id, "name" + id);
// throw new IllegalArgumentException("id < 1");
} else {
return new User(id, "name" + id);
}
}
}
|
9239e048189662ba25a9ebea84d2a334844c3c29 | 2,401 | java | Java | mc-mms/mc-mms-server/src/test/java/net/maritimecloud/server/security/ApacheSecurityTest.java | MaritimeConnectivityPlatform/MaritimeCloud | 79cb7a26aa3253a30e7bbbd1fb89b55e69d6ca83 | [
"Apache-2.0"
] | 3 | 2018-09-10T18:28:40.000Z | 2019-11-20T18:05:56.000Z | mc-mms/mc-mms-server/src/test/java/net/maritimecloud/server/security/ApacheSecurityTest.java | MaritimeConnectivityPlatform/MaritimeCloud | 79cb7a26aa3253a30e7bbbd1fb89b55e69d6ca83 | [
"Apache-2.0"
] | null | null | null | mc-mms/mc-mms-server/src/test/java/net/maritimecloud/server/security/ApacheSecurityTest.java | MaritimeConnectivityPlatform/MaritimeCloud | 79cb7a26aa3253a30e7bbbd1fb89b55e69d6ca83 | [
"Apache-2.0"
] | 2 | 2019-10-12T10:42:42.000Z | 2020-06-07T07:27:56.000Z | 36.378788 | 113 | 0.723032 | 998,991 | /* Copyright (c) 2011 Danish Maritime Authority.
*
* 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 net.maritimecloud.server.security;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import net.maritimecloud.mms.server.security.AuthenticationException;
import net.maritimecloud.mms.server.security.impl.ApacheConfSecurityHandler;
import net.maritimecloud.mms.server.security.impl.UsernamePasswordToken;
import org.junit.Test;
import java.net.URISyntaxException;
import static org.junit.Assert.assertTrue;
/**
* Test of the apache security functionality, i.e. htpasswd passwords and AuthGroupFile-style group files
* <p/>
* Hint:
* Generate a htpasswd file using: htpasswd -c htpasswd-users mmsuser
*/
public class ApacheSecurityTest {
public static String getResourcePath(String file) throws URISyntaxException {
if (!file.startsWith("/")) {
file = "/" + file;
}
return ApacheSecurityTest.class.getResource(file).toExternalForm().substring("file:".length());
}
@Test
public void testHtpasswdAuthentication() throws Exception {
Config conf = ConfigFactory.parseString("htpasswd-file = \"" + getResourcePath("htpasswd-users") + "\"");
ApacheConfSecurityHandler securityHandler = new ApacheConfSecurityHandler();
securityHandler.init(conf);
UsernamePasswordToken authToken = new UsernamePasswordToken();
authToken.setUsername("mmsuser");
authToken.setPassword("changeit".toCharArray());
securityHandler.authenticate(authToken);
authToken.setPassword("dontchangeit".toCharArray());
try {
securityHandler.authenticate(authToken);
assertTrue("False positive authentication", false);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationException);
}
}
}
|
9239e1d3b81ed41f326bd5d90ecbe1b126280454 | 2,697 | java | Java | app/src/main/java/de/karzek/diettracker/data/mapper/ServingDataMapper.java | MarjanaKarzek/android_diet_tracker | 6b4288c8d4a26876be5f98d61c0c625dd911df27 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/de/karzek/diettracker/data/mapper/ServingDataMapper.java | MarjanaKarzek/android_diet_tracker | 6b4288c8d4a26876be5f98d61c0c625dd911df27 | [
"Apache-2.0"
] | 12 | 2018-04-20T16:37:25.000Z | 2019-02-08T09:50:33.000Z | app/src/main/java/de/karzek/diettracker/data/mapper/ServingDataMapper.java | MarjanaKarzek/android_diet_tracker | 6b4288c8d4a26876be5f98d61c0c625dd911df27 | [
"Apache-2.0"
] | 1 | 2018-10-10T18:00:12.000Z | 2018-10-10T18:00:12.000Z | 36.945205 | 134 | 0.684835 | 998,992 | package de.karzek.diettracker.data.mapper;
import java.util.ArrayList;
import java.util.List;
import de.karzek.diettracker.data.cache.model.ServingEntity;
import de.karzek.diettracker.data.cache.model.UnitEntity;
import de.karzek.diettracker.data.model.ServingDataModel;
import io.realm.Realm;
import io.realm.RealmList;
/**
* Created by MarjanaKarzek on 27.05.2018.
*
* @author Marjana Karzek
* @version 1.0
* @date 27.05.2018
*/
public class ServingDataMapper {
public ServingDataModel transform(ServingEntity servingEntity){
ServingDataModel servingDataModel = null;
if(servingEntity != null){
servingDataModel = new ServingDataModel(servingEntity.getId(),
servingEntity.getDescription(),
servingEntity.getAmount(),
new UnitDataMapper().transform(servingEntity.getUnit())
);
}
return servingDataModel;
}
public ArrayList<ServingDataModel> transformAll(List<ServingEntity> servingEntities){
ArrayList<ServingDataModel> servingDataModelList = new ArrayList<>();
for (ServingEntity entity: servingEntities){
servingDataModelList.add(transform(entity));
}
return servingDataModelList;
}
public ServingEntity transformToEntity(ServingDataModel servingDataModel){
Realm realm = Realm.getDefaultInstance();
ServingEntity servingEntity = null;
if(servingDataModel != null){
startWriteTransaction();
if(realm.where(ServingEntity.class).equalTo("id", servingDataModel.getId()).findFirst() == null)
realm.createObject(ServingEntity.class, servingDataModel.getId());
servingEntity = realm.copyFromRealm(realm.where(ServingEntity.class).equalTo("id", servingDataModel.getId()).findFirst());
servingEntity.setDescription(servingDataModel.getDescription());
servingEntity.setAmount(servingDataModel.getAmount());
servingEntity.setUnit(new UnitDataMapper().transformToEntity(servingDataModel.getUnit()));
}
return servingEntity;
}
public RealmList<ServingEntity> transformAllToEntity(List<ServingDataModel> servingDataModels) {
RealmList<ServingEntity> servingEntities = new RealmList<>();
startWriteTransaction();
for (ServingDataModel data: servingDataModels){
servingEntities.add(transformToEntity(data));
}
return servingEntities;
}
private void startWriteTransaction(){
Realm realm = Realm.getDefaultInstance();
if(!realm.isInTransaction()){
realm.beginTransaction();
}
}
}
|
9239e280a853989b0c6eca29ca4380d39efbf71c | 4,924 | java | Java | src/main/java/ru/leonidm/telegram_utils/utils/RRequest.java | LeonidMem/TelegramUtilsM | df4a251acc58722c6066ed07193c4b352a901cce | [
"MIT"
] | null | null | null | src/main/java/ru/leonidm/telegram_utils/utils/RRequest.java | LeonidMem/TelegramUtilsM | df4a251acc58722c6066ed07193c4b352a901cce | [
"MIT"
] | null | null | null | src/main/java/ru/leonidm/telegram_utils/utils/RRequest.java | LeonidMem/TelegramUtilsM | df4a251acc58722c6066ed07193c4b352a901cce | [
"MIT"
] | null | null | null | 30.02439 | 111 | 0.593826 | 998,993 | package ru.leonidm.telegram_utils.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
public class RRequest implements Cloneable {
private final String url;
private final Map<String, String> parameters = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();
private InputStream responseInputStream = null;
private int responseCode = 0;
public RRequest(String url) {
this.url = url;
}
public RRequest addHeader(String key, String value) {
headers.put(key, value);
return this;
}
/**
* @param keysAndValues Keys and values, like "Content-type", "application/json"
* @throws IllegalArgumentException If input array has odd amount of values
* (there isn't a value for last key)
*/
public RRequest addHeaders(String... keysAndValues) {
if(keysAndValues.length % 2 == 1) throw new IllegalArgumentException();
for(int i = 0; i < keysAndValues.length; i += 2) {
headers.put(keysAndValues[i], keysAndValues[i + 1]);
}
return this;
}
public RRequest addParameter(String key, String value) {
parameters.put(key, value);
return this;
}
public RRequest addParameters(String... keysAndValues) {
if(keysAndValues.length % 2 == 1) throw new IllegalArgumentException();
for(int i = 0; i < keysAndValues.length; i += 2) {
parameters.put(keysAndValues[i], keysAndValues[i + 1]);
}
return this;
}
public byte[] getResponse(boolean printException) {
try {
byte[] out = responseInputStream.readAllBytes();
responseInputStream.close();
return out;
} catch(Exception e) {
if(printException) e.printStackTrace();
}
return null;
}
public String getResponseString(boolean printException) {
try {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseInputStream));
String line;
while((line = reader.readLine()) != null) {
out.append(line).append('\n');
}
return out.toString();
} catch(Exception e) {
if(printException) e.printStackTrace();
}
return null;
}
public int getResponseCode() {
return responseCode;
}
@Override
public RRequest clone() {
try {
return (RRequest) super.clone();
} catch(CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public RRequest send(Method method, boolean printException) {
return send(method, null, printException);
}
public RRequest send(Method method, byte[] bytes, boolean printException) {
try {
StringBuilder urlBuilder = new StringBuilder(url);
if(parameters.size() != 0) {
urlBuilder.append('?');
for(Map.Entry<String, String> parameter : parameters.entrySet()) {
urlBuilder.append(parameter.getKey()).append('=').append(parameter.getValue()).append('&');
}
urlBuilder.replace(urlBuilder.length() - 1, urlBuilder.length(), "");
}
URL url = new URL(urlBuilder.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method.toString());
connection.setDoOutput(true);
method.consumer.accept(connection, bytes);
for(Map.Entry<String, String> header : headers.entrySet()) {
connection.setRequestProperty(header.getValue(), header.getKey());
}
connection.setRequestProperty("keepAlive", "false");
responseCode = connection.getResponseCode();
responseInputStream = connection.getInputStream();
} catch(Exception e) {
if(printException) e.printStackTrace();
}
return this;
}
public enum Method {
GET, POST((connection, bytes) -> {
try {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(bytes);
} catch(Exception e) {
e.printStackTrace();
}
});
private final BiConsumer<HttpURLConnection, byte[]> consumer;
Method() {
this.consumer = (connection, bytes) -> {};
}
Method(BiConsumer<HttpURLConnection, byte[]> consumer) {
this.consumer = consumer;
}
}
}
|
9239e2f6c1eb805a29bba6ffd3242d30afb39554 | 1,315 | java | Java | src/main/java/io/latent/storm/rabbitmq/TupleToMessageNonDynamic.java | Dictanova/storm-rabbitmq | 31497247a096469214f3dfaa4cd47360c65ab039 | [
"MIT"
] | 108 | 2015-01-20T15:02:27.000Z | 2020-11-04T03:02:02.000Z | src/main/java/io/latent/storm/rabbitmq/TupleToMessageNonDynamic.java | Dictanova/storm-rabbitmq | 31497247a096469214f3dfaa4cd47360c65ab039 | [
"MIT"
] | 30 | 2015-01-13T22:57:02.000Z | 2018-10-01T01:55:24.000Z | src/main/java/io/latent/storm/rabbitmq/TupleToMessageNonDynamic.java | Dictanova/storm-rabbitmq | 31497247a096469214f3dfaa4cd47360c65ab039 | [
"MIT"
] | 73 | 2015-01-13T11:51:08.000Z | 2022-02-02T22:15:57.000Z | 23.070175 | 83 | 0.765019 | 998,994 | package io.latent.storm.rabbitmq;
import io.latent.storm.rabbitmq.config.ProducerConfig;
import org.apache.storm.tuple.Tuple;
import java.util.Map;
public abstract class TupleToMessageNonDynamic extends TupleToMessage
{
private String exchangeName;
private String routingKey;
private String contentType;
private String contentEncoding;
private boolean persistent;
@Override
protected void prepare(@SuppressWarnings("rawtypes") Map stormConfig)
{
ProducerConfig producerConfig = ProducerConfig.getFromStormConfig(stormConfig);
exchangeName = producerConfig.getExchangeName();
routingKey = producerConfig.getRoutingKey();
contentType = producerConfig.getContentType();
contentEncoding = producerConfig.getContentEncoding();
persistent = producerConfig.isPersistent();
}
@Override
protected String determineExchangeName(Tuple input)
{
return exchangeName;
}
@Override
protected String determineRoutingKey(Tuple input)
{
return routingKey;
}
@Override
protected String specifyContentType(Tuple input)
{
return contentType;
}
@Override
protected String specifyContentEncoding(Tuple input)
{
return contentEncoding;
}
@Override
protected boolean specifyMessagePersistence(Tuple input)
{
return persistent;
}
}
|
9239e4458875ef68cbefcb5a9ab187effeb8296b | 5,589 | java | Java | ssz/src/test/java/tech/pegasys/teku/ssz/backing/tree/TreeTest.java | byz-f/teku | 4600a346a1ef33bb555d83ff83bac4368b7092a4 | [
"Apache-2.0"
] | 1 | 2020-05-10T12:17:04.000Z | 2020-05-10T12:17:04.000Z | ssz/src/test/java/tech/pegasys/teku/ssz/backing/tree/TreeTest.java | byz-f/teku | 4600a346a1ef33bb555d83ff83bac4368b7092a4 | [
"Apache-2.0"
] | 1 | 2021-02-26T04:58:18.000Z | 2021-03-03T00:31:19.000Z | ssz/src/test/java/tech/pegasys/teku/ssz/backing/tree/TreeTest.java | Nashatyrev/artemis | 01ebad0c3d1a74dc939aeb6dbdeea1cb196589aa | [
"Apache-2.0"
] | null | null | null | 41.4 | 118 | 0.709966 | 998,995 | /*
* Copyright 2020 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.teku.ssz.backing.tree;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.ByteOrder;
import java.util.List;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.junit.jupiter.api.Test;
import tech.pegasys.teku.ssz.TestUtil;
import tech.pegasys.teku.ssz.backing.tree.TreeNode.BranchNode;
import tech.pegasys.teku.ssz.backing.tree.TreeUpdates.Update;
public class TreeTest {
public static TreeNode newTestLeaf(long l) {
return TreeNode.createLeafNode(Bytes32.leftPad(Bytes.ofUnsignedLong(l, ByteOrder.BIG_ENDIAN)));
}
@Test
public void testCreateTreeFromLeafNodes() {
BranchNode n1 =
(BranchNode)
TreeUtil.createTree(
IntStream.range(0, 5).mapToObj(TreeTest::newTestLeaf).collect(Collectors.toList()));
BranchNode n10 = (BranchNode) n1.left();
BranchNode n11 = (BranchNode) n1.right();
BranchNode n100 = (BranchNode) n10.left();
BranchNode n101 = (BranchNode) n10.right();
BranchNode n110 = (BranchNode) n11.left();
BranchNode n111 = (BranchNode) n11.right();
assertThat(n100.left()).isEqualTo(newTestLeaf(0));
assertThat(n100.right()).isEqualTo(newTestLeaf(1));
assertThat(n101.left()).isEqualTo(newTestLeaf(2));
assertThat(n101.right()).isEqualTo(newTestLeaf(3));
assertThat(n110.left()).isEqualTo(newTestLeaf(4));
assertThat(n110.right()).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n111.left()).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n111.right()).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n1.get(0b1)).isSameAs(n1);
assertThat(n1.get(0b10)).isSameAs(n10);
assertThat(n1.get(0b111)).isSameAs(n111);
assertThat(n1.get(0b1000)).isSameAs(n100.left());
assertThat(n1.get(0b1100)).isSameAs(n110.left());
assertThat(n10.get(0b100)).isSameAs(n100.left());
assertThat(n11.get(0b100)).isSameAs(n110.left());
}
@Test
public void testZeroLeafDefaultTree() {
TreeNode n1 = TreeUtil.createDefaultTree(5, TreeUtil.ZERO_LEAF);
assertThat(n1.get(0b1000)).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n1.get(0b1111)).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n1.get(0b100)).isSameAs(n1.get(0b101));
assertThat(n1.get(0b100)).isSameAs(n1.get(0b110));
assertThat(n1.get(0b100)).isSameAs(n1.get(0b111));
assertThat(n1.get(0b10)).isSameAs(n1.get(0b11));
}
@Test
public void testNonZeroLeafDefaultTree() {
TreeNode zeroTree = TreeUtil.createDefaultTree(5, TreeUtil.ZERO_LEAF);
TreeNode defaultLeaf = newTestLeaf(111);
BranchNode n1 = (BranchNode) TreeUtil.createDefaultTree(5, defaultLeaf);
assertThat(n1.get(0b1000)).isSameAs(defaultLeaf);
assertThat(n1.get(0b1001)).isSameAs(defaultLeaf);
assertThat(n1.get(0b1100)).isSameAs(defaultLeaf);
assertThat(n1.get(0b1101)).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n1.get(0b1111)).isSameAs(TreeUtil.ZERO_LEAF);
assertThat(n1.get(0b111)).isSameAs(zeroTree.get(0b111));
}
@Test
public void testUpdated() {
TreeNode zeroTree = TreeUtil.createDefaultTree(8, TreeUtil.ZERO_LEAF);
TreeNode t1 = zeroTree.updated(8 + 0, newTestLeaf(111));
TreeNode t1_ = zeroTree.updated(8 + 0, newTestLeaf(111));
assertThat(t1).isNotSameAs(t1_);
assertThat(t1.get(8 + 0)).isEqualTo(newTestLeaf(111));
assertThat(IntStream.range(1, 8).mapToObj(idx -> t1.get(8 + idx)))
.containsOnly(TreeUtil.ZERO_LEAF);
assertThat(t1.hashTreeRoot()).isEqualTo(t1_.hashTreeRoot());
TreeNode t2 = t1.updated(8 + 3, newTestLeaf(222));
TreeNode t2_ =
zeroTree.updated(
new TreeUpdates(
List.of(new Update(8 + 0, newTestLeaf(111)), new Update(8 + 3, newTestLeaf(222)))));
assertThat(t2).isNotSameAs(t2_);
assertThat(t2.get(8 + 0)).isEqualTo(newTestLeaf(111));
assertThat(t2.get(8 + 3)).isEqualTo(newTestLeaf(222));
assertThat(IntStream.of(1, 2, 4, 5, 6, 7).mapToObj(idx -> t2.get(8 + idx)))
.containsOnly(TreeUtil.ZERO_LEAF);
assertThat(t2.hashTreeRoot()).isEqualTo(t2_.hashTreeRoot());
TreeNode zeroTree_ =
t2.updated(
new TreeUpdates(
List.of(
new Update(8 + 0, TreeUtil.ZERO_LEAF), new Update(8 + 3, TreeUtil.ZERO_LEAF))));
assertThat(zeroTree.hashTreeRoot()).isEqualTo(zeroTree_.hashTreeRoot());
}
@Test
// The threading test is probabilistic and may have false positives
// (i.e. pass on incorrect implementation)
public void testHashThreadSafe() {
// since the hash can be calculated lazily and cached inside TreeNode there are
// potential threading issues
TreeNode tree = TreeUtil.createDefaultTree(32 * 1024, newTestLeaf(111));
List<Future<Bytes32>> hasheFuts = TestUtil.executeParallel(() -> tree.hashTreeRoot(), 512);
assertThat(TestUtil.waitAll(hasheFuts)).containsOnly(tree.hashTreeRoot());
}
}
|
9239e448386585be815f155d186f06d84e16c386 | 170 | java | Java | src/ekraft/javabrake/db/Chapter.java | Gigafrosty/JavaBrake | 7faabb50a2beee07f000f3c7aed1c78f3d03810e | [
"MIT"
] | null | null | null | src/ekraft/javabrake/db/Chapter.java | Gigafrosty/JavaBrake | 7faabb50a2beee07f000f3c7aed1c78f3d03810e | [
"MIT"
] | null | null | null | src/ekraft/javabrake/db/Chapter.java | Gigafrosty/JavaBrake | 7faabb50a2beee07f000f3c7aed1c78f3d03810e | [
"MIT"
] | null | null | null | 10.625 | 31 | 0.688235 | 998,996 | package ekraft.javabrake.db;
import lombok.Data;
/**
* Created by ekraft on 8/29/15
*/
@Data
public class Chapter {
private int index;
private int duration;
}
|
9239e44ad26cb3a132b1f5490788d0a70bb55780 | 803 | java | Java | blue-jdbc/src/test/java/test/jdbc/model/UserGroup.java | blue0121/blue | f66ed548cb7c4c4a89341b6d2866a607c03c2243 | [
"Apache-2.0"
] | null | null | null | blue-jdbc/src/test/java/test/jdbc/model/UserGroup.java | blue0121/blue | f66ed548cb7c4c4a89341b6d2866a607c03c2243 | [
"Apache-2.0"
] | null | null | null | blue-jdbc/src/test/java/test/jdbc/model/UserGroup.java | blue0121/blue | f66ed548cb7c4c4a89341b6d2866a607c03c2243 | [
"Apache-2.0"
] | null | null | null | 13.163934 | 43 | 0.702366 | 998,997 | package test.jdbc.model;
import blue.jdbc.annotation.Mapper;
/**
* @author Jin Zheng
* @since 1.0 2019-11-22
*/
@Mapper
public class UserGroup
{
private Integer userId;
private String userName;
private Integer groupId;
private String groupName;
public UserGroup()
{
}
public Integer getUserId()
{
return userId;
}
public void setUserId(Integer userId)
{
this.userId = userId;
}
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public Integer getGroupId()
{
return groupId;
}
public void setGroupId(Integer groupId)
{
this.groupId = groupId;
}
public String getGroupName()
{
return groupName;
}
public void setGroupName(String groupName)
{
this.groupName = groupName;
}
}
|
9239e459c920ff02ba98f26fdbccffc346fd95b7 | 4,642 | java | Java | src/main/java/seedu/address/logic/commands/RemindCommand.java | BrittonAlone/main | af6fa396e3f70e45e3a7aef0052cd3ac12d6b9be | [
"MIT"
] | null | null | null | src/main/java/seedu/address/logic/commands/RemindCommand.java | BrittonAlone/main | af6fa396e3f70e45e3a7aef0052cd3ac12d6b9be | [
"MIT"
] | 55 | 2019-03-03T23:53:53.000Z | 2019-04-17T02:37:18.000Z | src/main/java/seedu/address/logic/commands/RemindCommand.java | BrittonAlone/main | af6fa396e3f70e45e3a7aef0052cd3ac12d6b9be | [
"MIT"
] | 6 | 2019-02-18T08:43:26.000Z | 2019-02-28T10:39:03.000Z | 32.690141 | 117 | 0.619991 | 998,998 | package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import javafx.collections.ObservableList;
import seedu.address.logic.CommandHistory;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.Model;
import seedu.address.model.task.Task;
/**
* Set a reminder of the nearest tasks for user, those tasks can be specified by task category.
*/
public class RemindCommand extends Command {
public static final String COMMAND_WORD = "remind";
public static final String MESSAGE_USAGE = "remind: give reminds on specified requirement\n"
+ "Parameters:\n"
+ "1. start/ddl: Tasketch will give a reminding task list ordered by task start time or deadline.\n"
+ "2. a/e/c/r/o start/ddl: Tasketch will give a reminding task list of specified category\n"
+ "of tasks ordered by start time or deadline.\n";
public static final String COMMAND_PARAMETERS = "Parameters:\n"
+ "1. start/ddl: Tasketch will give a reminding task list ordered by task start time or deadline.\n"
+ "2. a/e/c/r/o start/ddl: Tasketch will give a reminding task list of specified category\n"
+ "of tasks ordered by start time or deadline.\n";
public static final String MESSAGE_REMIND_SUCCESS = "Reminder shown!";
public static final String MESSAGE_LOGIN = "Please login first";
private String arguments;
private ObservableList<Task> shownTaskList;
/**
* Constructor of RemindCommand.
*/
public RemindCommand(String userInput) {
this.arguments = userInput;
}
/**
* Access function of arguments.
*/
public String getArguments() {
return this.arguments;
}
/**
* A boolean function to verify user's input
*/
private boolean isValidCategory(String input) {
if (!input.equals("a") && !input.equals("e")
&& !input.equals("c") && !input.equals("r") && !input.equals("o")) {
return false;
} else {
return true;
}
}
public ObservableList<Task> getShownTaskList() {
return this.shownTaskList;
}
/**
* A boolean function to verify user's input
*/
private boolean isValidTime(String input) {
if (!input.equals("start") && !input.equals("ddl")) {
return false;
} else {
return true;
}
}
/**
* A predicate function decide which task to choose
*/
private boolean meetRequirement(Task task, String givenCategory) {
if (task.getCategories().value.equals(givenCategory)) {
return true;
} else {
return false;
}
}
@Override
public CommandResult execute(Model model, CommandHistory history) throws CommandException, ParseException {
requireNonNull(model);
if (!model.getLoginStatus()) {
throw new CommandException(MESSAGE_LOGIN);
}
String trimmedArguments = arguments.trim();
String[] splitedInput = trimmedArguments.split("\\s");
if (splitedInput.length == 1) {
if (!isValidTime(splitedInput[0])) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, RemindCommand.MESSAGE_USAGE));
} else if (splitedInput[0].equals("start")) {
//model.sortByStart();
model.sortRemindListByStart();
} else {
//model.sortByEnd();
model.sortRemindListByEnd();
}
model.commitTaskBook();
} else if (splitedInput.length == 2) {
if (!isValidCategory(splitedInput[0]) || !isValidTime(splitedInput[1])) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, RemindCommand.MESSAGE_USAGE));
} else {
if (splitedInput[1].equals("start")) {
model.sortRemindListByStart();
model.filterRemindList(splitedInput[0]);
} else {
model.sortRemindListByEnd();
model.filterRemindList(splitedInput[0]);
}
}
model.commitTaskBook();
} else {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, RemindCommand.MESSAGE_USAGE));
}
return new CommandResult(MESSAGE_REMIND_SUCCESS);
}
}
|
9239e47097232efa6f13d5cd02323cf1e4fbd9b1 | 1,534 | java | Java | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/inheritance/InheritanceVehicleTestCases.java | brettdavidson3/eclipselink.runtime | a992a67ce49ca56117df4632c9c0c70938a0b28e | [
"BSD-3-Clause"
] | null | null | null | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/inheritance/InheritanceVehicleTestCases.java | brettdavidson3/eclipselink.runtime | a992a67ce49ca56117df4632c9c0c70938a0b28e | [
"BSD-3-Clause"
] | null | null | null | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/inheritance/InheritanceVehicleTestCases.java | brettdavidson3/eclipselink.runtime | a992a67ce49ca56117df4632c9c0c70938a0b28e | [
"BSD-3-Clause"
] | null | null | null | 46.484848 | 91 | 0.646675 | 998,999 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.inheritance;
import org.eclipse.persistence.testing.oxm.mappings.XMLWithJSONMappingTestCases;
public class InheritanceVehicleTestCases extends XMLWithJSONMappingTestCases {
public InheritanceVehicleTestCases(String name) throws Exception {
super(name);
setProject(new InheritanceProject());
setControlDocument("org/eclipse/persistence/testing/oxm/inheritance/vehicle.xml");
setControlJSON("org/eclipse/persistence/testing/oxm/inheritance/vehicle.json");
}
public Object getControlObject() {
Vehicle vehicle = new Vehicle();
vehicle.model = "Blah Blah";
vehicle.manufacturer = "Some Place";
vehicle.topSpeed = 10000;
return vehicle;
}
}
|
9239e471b676c713ddba5ad06348f6600ddf7543 | 1,105 | java | Java | servicekeeper-core/src/main/java/io/esastack/servicekeeper/core/configsource/PlainConfigSource.java | Mkabaka/esa-servicekeeper | a8f064d7470cf02d559334c87176b95088729254 | [
"Apache-2.0"
] | 15 | 2021-05-08T08:55:52.000Z | 2022-02-18T08:02:37.000Z | servicekeeper-core/src/main/java/io/esastack/servicekeeper/core/configsource/PlainConfigSource.java | Mkabaka/esa-servicekeeper | a8f064d7470cf02d559334c87176b95088729254 | [
"Apache-2.0"
] | 10 | 2021-07-28T02:06:55.000Z | 2022-03-07T16:04:33.000Z | servicekeeper-core/src/main/java/io/esastack/servicekeeper/core/configsource/PlainConfigSource.java | Mkabaka/esa-servicekeeper | a8f064d7470cf02d559334c87176b95088729254 | [
"Apache-2.0"
] | 7 | 2021-05-08T10:05:15.000Z | 2022-02-22T12:16:59.000Z | 26.95122 | 75 | 0.707692 | 999,000 | /*
* Copyright 2021 OPPO ESA Stack Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.esastack.servicekeeper.core.configsource;
import io.esastack.servicekeeper.core.common.ResourceId;
import java.util.Map;
public interface PlainConfigSource extends ConfigSource {
/**
* Get external config by resourceId
*
* @param key the key to get configuration
* @return configuration
*/
ExternalConfig config(ResourceId key);
/**
* Get all configs.
*
* @return config map.
*/
Map<ResourceId, ExternalConfig> all();
}
|
9239e68a3798bda71a9899aa9227ccfae69e4e74 | 393 | java | Java | src/main/java/org/openmuc/openiec61850/internal/cli/Action.java | mz-automation/openiec61850 | febe96dc73f5e918b31fac7ba4aaa545a4deddda | [
"Apache-2.0"
] | 5 | 2017-12-13T18:01:49.000Z | 2022-03-09T21:51:02.000Z | src/main/java/org/openmuc/openiec61850/internal/cli/Action.java | mzillgith/openiec61850 | d8b08b09820dc0645569f8de55879c3be0d0541f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/openmuc/openiec61850/internal/cli/Action.java | mzillgith/openiec61850 | d8b08b09820dc0645569f8de55879c3be0d0541f | [
"Apache-2.0"
] | 4 | 2018-03-16T13:12:33.000Z | 2022-01-22T04:09:50.000Z | 17.863636 | 51 | 0.638677 | 999,001 | package org.openmuc.openiec61850.internal.cli;
public class Action {
private final String key;
private final String description;
public Action(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() {
return key;
}
public String getDescription() {
return description;
}
}
|
9239e6fd7526af46bb3c83f8daaf31d94b966c78 | 338 | java | Java | src/main/java/com/devs/sistemabarbearia/SistemaBarbeariaApplication.java | marc05v1/Sistema-Barbearia | 65cc0280abe3d60ca135b8867eb75c63c6dbefe2 | [
"MIT"
] | 1 | 2021-07-05T13:28:00.000Z | 2021-07-05T13:28:00.000Z | src/main/java/com/devs/sistemabarbearia/SistemaBarbeariaApplication.java | marc05v1/Sistema-Barbearia | 65cc0280abe3d60ca135b8867eb75c63c6dbefe2 | [
"MIT"
] | null | null | null | src/main/java/com/devs/sistemabarbearia/SistemaBarbeariaApplication.java | marc05v1/Sistema-Barbearia | 65cc0280abe3d60ca135b8867eb75c63c6dbefe2 | [
"MIT"
] | null | null | null | 24.142857 | 68 | 0.83432 | 999,002 | package com.devs.sistemabarbearia;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SistemaBarbeariaApplication {
public static void main(String[] args) {
SpringApplication.run(SistemaBarbeariaApplication.class, args);
}
}
|
9239e728002ed8e91c767894002d448c00335deb | 981 | java | Java | src/test/java/com/liveperson/faas/csds/CsdsMapClientTest.java | slauber/faas-client-jdk | b3bfa6971303858f4b193f8e350e16175132421c | [
"MIT"
] | null | null | null | src/test/java/com/liveperson/faas/csds/CsdsMapClientTest.java | slauber/faas-client-jdk | b3bfa6971303858f4b193f8e350e16175132421c | [
"MIT"
] | 57 | 2020-02-04T13:44:50.000Z | 2022-03-31T14:24:26.000Z | src/test/java/com/liveperson/faas/csds/CsdsMapClientTest.java | slauber/faas-client-jdk | b3bfa6971303858f4b193f8e350e16175132421c | [
"MIT"
] | 3 | 2020-04-29T13:53:35.000Z | 2021-12-12T23:42:34.000Z | 26.513514 | 76 | 0.737003 | 999,003 | package com.liveperson.faas.csds;
import com.liveperson.faas.exception.CsdsRetrievalException;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class CsdsMapClientTest {
private static final String SERVICE = "service";
private static final String BASE_URI = "uri";
private Map<String, String> serviceMap;
private CsdsClient csdsClient;
@Before
public void setUp() {
serviceMap = Collections.singletonMap(SERVICE, BASE_URI);
csdsClient = new CsdsMapClient(serviceMap);
}
@Test
public void getDomainSuccess() throws CsdsRetrievalException {
assertEquals(csdsClient.getDomain(SERVICE), BASE_URI);
}
@Test(expected = CsdsRetrievalException.class)
public void getDomainCsdsEntryNotFound() throws CsdsRetrievalException {
assertEquals(csdsClient.getDomain("Does not Exist"), BASE_URI);
}
} |
9239e778390baad88a5feeafd54dea862fa4bbe9 | 12,596 | java | Java | core/src/test/java/org/apache/druid/math/expr/FunctionTest.java | AngryUbuntuNerd/druid | bb18ef7044e706fa98d2da8b8ce81121498978ea | [
"Apache-2.0"
] | 1 | 2022-01-31T18:04:30.000Z | 2022-01-31T18:04:30.000Z | core/src/test/java/org/apache/druid/math/expr/FunctionTest.java | AngryUbuntuNerd/druid | bb18ef7044e706fa98d2da8b8ce81121498978ea | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/apache/druid/math/expr/FunctionTest.java | AngryUbuntuNerd/druid | bb18ef7044e706fa98d2da8b8ce81121498978ea | [
"Apache-2.0"
] | null | null | null | 32.802083 | 121 | 0.622023 | 999,004 | /*
* 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.druid.math.expr;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.testing.InitializedNullHandlingTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.Nullable;
public class FunctionTest extends InitializedNullHandlingTest
{
private Expr.ObjectBinding bindings;
@Before
public void setup()
{
ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
builder.put("x", "foo");
builder.put("y", 2);
builder.put("z", 3.1);
builder.put("a", new String[] {"foo", "bar", "baz", "foobar"});
builder.put("b", new Long[] {1L, 2L, 3L, 4L, 5L});
builder.put("c", new Double[] {3.1, 4.2, 5.3});
bindings = Parser.withMap(builder.build());
}
@Test
public void testCaseSimple()
{
assertExpr("case_simple(x,'baz','is baz','foo','is foo','is other')", "is foo");
assertExpr("case_simple(x,'baz','is baz','bar','is bar','is other')", "is other");
assertExpr("case_simple(y,2,'is 2',3,'is 3','is other')", "is 2");
assertExpr("case_simple(z,2,'is 2',3,'is 3','is other')", "is other");
}
@Test
public void testCaseSearched()
{
assertExpr("case_searched(x=='baz','is baz',x=='foo','is foo','is other')", "is foo");
assertExpr("case_searched(x=='baz','is baz',x=='bar','is bar','is other')", "is other");
assertExpr("case_searched(y==2,'is 2',y==3,'is 3','is other')", "is 2");
assertExpr("case_searched(z==2,'is 2',z==3,'is 3','is other')", "is other");
}
@Test
public void testConcat()
{
assertExpr("concat(x,' ',y)", "foo 2");
if (NullHandling.replaceWithDefault()) {
assertExpr("concat(x,' ',nonexistent,' ',y)", "foo 2");
} else {
assertArrayExpr("concat(x,' ',nonexistent,' ',y)", null);
}
assertExpr("concat(z)", "3.1");
assertArrayExpr("concat()", null);
}
@Test
public void testReplace()
{
assertExpr("replace(x,'oo','ab')", "fab");
assertExpr("replace(x,x,'ab')", "ab");
assertExpr("replace(x,'oo',y)", "f2");
}
@Test
public void testSubstring()
{
assertExpr("substring(x,0,2)", "fo");
assertExpr("substring(x,1,2)", "oo");
assertExpr("substring(x,y,1)", "o");
assertExpr("substring(x,0,-1)", "foo");
assertExpr("substring(x,0,100)", "foo");
}
@Test
public void testStrlen()
{
assertExpr("strlen(x)", 3L);
assertExpr("strlen(nonexistent)", NullHandling.defaultLongValue());
}
@Test
public void testStrpos()
{
assertExpr("strpos(x, 'o')", 1L);
assertExpr("strpos(x, 'o', 0)", 1L);
assertExpr("strpos(x, 'o', 1)", 1L);
assertExpr("strpos(x, 'o', 2)", 2L);
assertExpr("strpos(x, 'o', 3)", -1L);
assertExpr("strpos(x, '')", 0L);
assertExpr("strpos(x, 'x')", -1L);
}
@Test
public void testLower()
{
assertExpr("lower('FOO')", "foo");
}
@Test
public void testUpper()
{
assertExpr("upper(x)", "FOO");
}
@Test
public void testIsNull()
{
assertExpr("isnull(null)", 1L);
assertExpr("isnull('abc')", 0L);
}
@Test
public void testIsNotNull()
{
assertExpr("notnull(null)", 0L);
assertExpr("notnull('abc')", 1L);
}
@Test
public void testLpad()
{
assertExpr("lpad(x, 5, 'ab')", "abfoo");
assertExpr("lpad(x, 4, 'ab')", "afoo");
assertExpr("lpad(x, 2, 'ab')", "fo");
assertArrayExpr("lpad(x, 0, 'ab')", null);
assertArrayExpr("lpad(x, 5, null)", null);
assertArrayExpr("lpad(null, 5, x)", null);
}
@Test
public void testRpad()
{
assertExpr("rpad(x, 5, 'ab')", "fooab");
assertExpr("rpad(x, 4, 'ab')", "fooa");
assertExpr("rpad(x, 2, 'ab')", "fo");
assertArrayExpr("rpad(x, 0, 'ab')", null);
assertArrayExpr("rpad(x, 5, null)", null);
assertArrayExpr("rpad(null, 5, x)", null);
}
@Test
public void testArrayConstructor()
{
assertArrayExpr("array(1, 2, 3, 4)", new Long[]{1L, 2L, 3L, 4L});
assertArrayExpr("array(1, 2, 3, 'bar')", new Long[]{1L, 2L, 3L, null});
assertArrayExpr("array(1.0)", new Double[]{1.0});
assertArrayExpr("array('foo', 'bar')", new String[]{"foo", "bar"});
}
@Test
public void testArrayLength()
{
assertExpr("array_length([1,2,3])", 3L);
assertExpr("array_length(a)", 4);
}
@Test
public void testArrayOffset()
{
assertExpr("array_offset([1, 2, 3], 2)", 3L);
assertArrayExpr("array_offset([1, 2, 3], 3)", null);
assertExpr("array_offset(a, 2)", "baz");
}
@Test
public void testArrayOrdinal()
{
assertExpr("array_ordinal([1, 2, 3], 3)", 3L);
assertArrayExpr("array_ordinal([1, 2, 3], 4)", null);
assertExpr("array_ordinal(a, 3)", "baz");
}
@Test
public void testArrayOffsetOf()
{
assertExpr("array_offset_of([1, 2, 3], 3)", 2L);
assertExpr("array_offset_of([1, 2, 3], 4)", NullHandling.replaceWithDefault() ? -1L : null);
assertExpr("array_offset_of(a, 'baz')", 2);
}
@Test
public void testArrayOrdinalOf()
{
assertExpr("array_ordinal_of([1, 2, 3], 3)", 3L);
assertExpr("array_ordinal_of([1, 2, 3], 4)", NullHandling.replaceWithDefault() ? -1L : null);
assertExpr("array_ordinal_of(a, 'baz')", 3);
}
@Test
public void testArrayContains()
{
assertExpr("array_contains([1, 2, 3], 2)", 1L);
assertExpr("array_contains([1, 2, 3], 4)", 0L);
assertExpr("array_contains([1, 2, 3], [2, 3])", 1L);
assertExpr("array_contains([1, 2, 3], [3, 4])", 0L);
assertExpr("array_contains(b, [3, 4])", 1L);
}
@Test
public void testArrayOverlap()
{
assertExpr("array_overlap([1, 2, 3], [2, 4, 6])", 1L);
assertExpr("array_overlap([1, 2, 3], [4, 5, 6])", 0L);
}
@Test
public void testArrayAppend()
{
assertArrayExpr("array_append([1, 2, 3], 4)", new Long[]{1L, 2L, 3L, 4L});
assertArrayExpr("array_append([1, 2, 3], 'bar')", new Long[]{1L, 2L, 3L, null});
assertArrayExpr("array_append([], 1)", new String[]{"1"});
assertArrayExpr("array_append(<LONG>[], 1)", new Long[]{1L});
}
@Test
public void testArrayConcat()
{
assertArrayExpr("array_concat([1, 2, 3], [2, 4, 6])", new Long[]{1L, 2L, 3L, 2L, 4L, 6L});
assertArrayExpr("array_concat([1, 2, 3], 4)", new Long[]{1L, 2L, 3L, 4L});
assertArrayExpr("array_concat(0, [1, 2, 3])", new Long[]{0L, 1L, 2L, 3L});
assertArrayExpr("array_concat(map(y -> y * 3, b), [1, 2, 3])", new Long[]{3L, 6L, 9L, 12L, 15L, 1L, 2L, 3L});
assertArrayExpr("array_concat(0, 1)", new Long[]{0L, 1L});
}
@Test
public void testArrayToString()
{
assertExpr("array_to_string([1, 2, 3], ',')", "1,2,3");
assertExpr("array_to_string([1], '|')", "1");
assertExpr("array_to_string(a, '|')", "foo|bar|baz|foobar");
}
@Test
public void testStringToArray()
{
assertArrayExpr("string_to_array('1,2,3', ',')", new String[]{"1", "2", "3"});
assertArrayExpr("string_to_array('1', ',')", new String[]{"1"});
assertArrayExpr("string_to_array(array_to_string(a, ','), ',')", new String[]{"foo", "bar", "baz", "foobar"});
}
@Test
public void testArrayCast()
{
assertArrayExpr("cast([1, 2, 3], 'STRING_ARRAY')", new String[]{"1", "2", "3"});
assertArrayExpr("cast([1, 2, 3], 'DOUBLE_ARRAY')", new Double[]{1.0, 2.0, 3.0});
assertArrayExpr("cast(c, 'LONG_ARRAY')", new Long[]{3L, 4L, 5L});
assertArrayExpr("cast(string_to_array(array_to_string(b, ','), ','), 'LONG_ARRAY')", new Long[]{1L, 2L, 3L, 4L, 5L});
assertArrayExpr("cast(['1.0', '2.0', '3.0'], 'LONG_ARRAY')", new Long[]{1L, 2L, 3L});
}
@Test
public void testArraySlice()
{
assertArrayExpr("array_slice([1, 2, 3, 4], 1, 3)", new Long[] {2L, 3L});
assertArrayExpr("array_slice([1.0, 2.1, 3.2, 4.3], 2)", new Double[] {3.2, 4.3});
assertArrayExpr("array_slice(['a', 'b', 'c', 'd'], 4, 6)", new String[] {null, null});
assertArrayExpr("array_slice([1, 2, 3, 4], 2, 2)", new Long[] {});
assertArrayExpr("array_slice([1, 2, 3, 4], 5, 7)", null);
assertArrayExpr("array_slice([1, 2, 3, 4], 2, 1)", null);
}
@Test
public void testArrayPrepend()
{
assertArrayExpr("array_prepend(4, [1, 2, 3])", new Long[]{4L, 1L, 2L, 3L});
assertArrayExpr("array_prepend('bar', [1, 2, 3])", new Long[]{null, 1L, 2L, 3L});
assertArrayExpr("array_prepend(1, [])", new String[]{"1"});
assertArrayExpr("array_prepend(1, <LONG>[])", new Long[]{1L});
assertArrayExpr("array_prepend(1, <DOUBLE>[])", new Double[]{1.0});
}
@Test
public void testGreatest()
{
// Same types
assertExpr("greatest(y, 0)", 2L);
assertExpr("greatest(34.0, z, 5.0, 767.0", 767.0);
assertExpr("greatest('B', x, 'A')", "foo");
// Different types
assertExpr("greatest(-1, z, 'A')", "A");
assertExpr("greatest(-1, z)", 3.1);
assertExpr("greatest(1, 'A')", "A");
// Invalid types
try {
assertExpr("greatest(1, ['A'])", null);
Assert.fail("Did not throw IllegalArgumentException");
}
catch (IllegalArgumentException e) {
Assert.assertEquals("Function[greatest] does not accept STRING_ARRAY types", e.getMessage());
}
// Null handling
assertExpr("greatest()", null);
assertExpr("greatest(null, null)", null);
assertExpr("greatest(1, null, 'A')", "A");
}
@Test
public void testLeast()
{
// Same types
assertExpr("least(y, 0)", 0L);
assertExpr("least(34.0, z, 5.0, 767.0", 3.1);
assertExpr("least('B', x, 'A')", "A");
// Different types
assertExpr("least(-1, z, 'A')", "-1");
assertExpr("least(-1, z)", -1.0);
assertExpr("least(1, 'A')", "1");
// Invalid types
try {
assertExpr("least(1, [2, 3])", null);
Assert.fail("Did not throw IllegalArgumentException");
}
catch (IllegalArgumentException e) {
Assert.assertEquals("Function[least] does not accept LONG_ARRAY types", e.getMessage());
}
// Null handling
assertExpr("least()", null);
assertExpr("least(null, null)", null);
assertExpr("least(1, null, 'A')", "1");
}
private void assertExpr(final String expression, @Nullable final Object expectedResult)
{
final Expr expr = Parser.parse(expression, ExprMacroTable.nil());
Assert.assertEquals(expression, expectedResult, expr.eval(bindings).value());
final Expr exprNoFlatten = Parser.parse(expression, ExprMacroTable.nil(), false);
final Expr roundTrip = Parser.parse(exprNoFlatten.stringify(), ExprMacroTable.nil());
Assert.assertEquals(expr.stringify(), expectedResult, roundTrip.eval(bindings).value());
final Expr roundTripFlatten = Parser.parse(expr.stringify(), ExprMacroTable.nil());
Assert.assertEquals(expr.stringify(), expectedResult, roundTripFlatten.eval(bindings).value());
Assert.assertEquals(expr.stringify(), roundTrip.stringify());
Assert.assertEquals(expr.stringify(), roundTripFlatten.stringify());
}
private void assertArrayExpr(final String expression, @Nullable final Object[] expectedResult)
{
final Expr expr = Parser.parse(expression, ExprMacroTable.nil());
Assert.assertArrayEquals(expression, expectedResult, expr.eval(bindings).asArray());
final Expr exprNoFlatten = Parser.parse(expression, ExprMacroTable.nil(), false);
final Expr roundTrip = Parser.parse(exprNoFlatten.stringify(), ExprMacroTable.nil());
Assert.assertArrayEquals(expression, expectedResult, roundTrip.eval(bindings).asArray());
final Expr roundTripFlatten = Parser.parse(expr.stringify(), ExprMacroTable.nil());
Assert.assertArrayEquals(expression, expectedResult, roundTripFlatten.eval(bindings).asArray());
Assert.assertEquals(expr.stringify(), roundTrip.stringify());
Assert.assertEquals(expr.stringify(), roundTripFlatten.stringify());
}
}
|
9239e81d8aab954ed16976e082d8da166991edab | 2,690 | java | Java | prism/src/main/java/com/android/prism/crash/Cockroach.java | alexknight/prism | c0886f350098733a3eedb5570b8f77b267c48ab8 | [
"Apache-2.0"
] | null | null | null | prism/src/main/java/com/android/prism/crash/Cockroach.java | alexknight/prism | c0886f350098733a3eedb5570b8f77b267c48ab8 | [
"Apache-2.0"
] | null | null | null | prism/src/main/java/com/android/prism/crash/Cockroach.java | alexknight/prism | c0886f350098733a3eedb5570b8f77b267c48ab8 | [
"Apache-2.0"
] | null | null | null | 29.888889 | 102 | 0.571004 | 999,006 | package com.android.prism.crash;
import android.os.Handler;
import android.os.Looper;
/**
* Created by qingge on 2018/8/4.
*/
public final class Cockroach {
public interface ExceptionHandler {
void handlerException(Thread thread, Throwable throwable);
}
private Cockroach() {
}
private static ExceptionHandler sExceptionHandler;
private static Thread.UncaughtExceptionHandler sUncaughtExceptionHandler;
private static boolean sInstalled = false;//标记位,避免重复安装卸载
/**
* 当主线程或子线程抛出异常时会调用exceptionHandler.handlerException(Thread thread, Throwable throwable)
* <p>
* exceptionHandler.handlerException可能运行在非UI线程中。
* <p>
* 若设置了Thread.setDefaultUncaughtExceptionHandler则可能无法捕获子线程异常。
*
* @param exceptionHandler
*/
public static synchronized void install(ExceptionHandler exceptionHandler) {
if (sInstalled) {
return;
}
sInstalled = true;
sExceptionHandler = exceptionHandler;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
while (true) {
try {
Looper.loop();
} catch (Throwable e) {
// Binder.clearCallingIdentity();
if (e instanceof QuitCockroachException) {
return;
}
if (sExceptionHandler != null) {
sExceptionHandler.handlerException(Looper.getMainLooper().getThread(), e);
}
}
}
}
});
sUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
if (sExceptionHandler != null) {
sExceptionHandler.handlerException(t, e);
}
}
});
}
public static synchronized void uninstall() {
if (!sInstalled) {
return;
}
sInstalled = false;
sExceptionHandler = null;
//卸载后恢复默认的异常处理逻辑,否则主线程再次抛出异常后将导致ANR,并且无法捕获到异常位置
Thread.setDefaultUncaughtExceptionHandler(sUncaughtExceptionHandler);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
throw new QuitCockroachException("Quit Cockroach.....");//主线程抛出异常,迫使 while (true) {}结束
}
});
}
} |
9239e8d39646030c15d6aac570a9484652b16d7f | 190 | java | Java | src/main/java/com/knowshare/enums/TipoImagenEnum.java | know-share/KS-Entities | 9075f88b59fea47b29a013e7019fbf18021c36e6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/knowshare/enums/TipoImagenEnum.java | know-share/KS-Entities | 9075f88b59fea47b29a013e7019fbf18021c36e6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/knowshare/enums/TipoImagenEnum.java | know-share/KS-Entities | 9075f88b59fea47b29a013e7019fbf18021c36e6 | [
"Apache-2.0"
] | null | null | null | 12.666667 | 58 | 0.652632 | 999,007 | /**
*
*/
package com.knowshare.enums;
/**
* Tipo de imágenes que se manejan dentro de la aplicación
* @author Miguel Montañez
*
*/
public enum TipoImagenEnum {
PNG, JPG, JPEG,
;
}
|
9239e8e9d136e25265e0635af332363624f62737 | 1,032 | java | Java | src/main/java/gwt/material/design/demo/client/application/charts/ChartsModule.java | RLHawk1/gwt-material-demo | ef9ede80abac6e5fed4cbe0ede772eb44f674c71 | [
"Apache-2.0"
] | 38 | 2015-04-03T19:24:01.000Z | 2020-05-26T19:39:33.000Z | src/main/java/gwt/material/design/demo/client/application/charts/ChartsModule.java | RLHawk1/gwt-material-demo | ef9ede80abac6e5fed4cbe0ede772eb44f674c71 | [
"Apache-2.0"
] | 73 | 2015-05-07T01:48:31.000Z | 2021-03-08T12:15:00.000Z | src/main/java/gwt/material/design/demo/client/application/charts/ChartsModule.java | RLHawk1/gwt-material-demo | ef9ede80abac6e5fed4cbe0ede772eb44f674c71 | [
"Apache-2.0"
] | 75 | 2015-04-14T22:22:13.000Z | 2022-01-29T18:17:35.000Z | 31.272727 | 75 | 0.73062 | 999,008 | package gwt.material.design.demo.client.application.charts;
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2016 GwtMaterialDesign
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.gwtplatform.mvp.client.gin.AbstractPresenterModule;
public class ChartsModule extends AbstractPresenterModule {
@Override
protected void configure() {
bindPresenter(ChartsPresenter.class, ChartsPresenter.MyView.class,
ChartsView.class, ChartsPresenter.MyProxy.class);
}
}
|
9239e9090e651c1339f76ae65451783c0959dd5f | 2,424 | java | Java | test/atunibz/dperez/approject1617/xml/XMLUsersTest.java | davide-perez/music-manager | c842cac021900af825df7135a1226f6f28e967f0 | [
"MIT"
] | null | null | null | test/atunibz/dperez/approject1617/xml/XMLUsersTest.java | davide-perez/music-manager | c842cac021900af825df7135a1226f6f28e967f0 | [
"MIT"
] | null | null | null | test/atunibz/dperez/approject1617/xml/XMLUsersTest.java | davide-perez/music-manager | c842cac021900af825df7135a1226f6f28e967f0 | [
"MIT"
] | null | null | null | 31.480519 | 99 | 0.731848 | 999,009 | package atunibz.dperez.approject1617.xml;
import static org.junit.Assert.*;
import org.junit.Test;
import atunibz.dperez.approject1617.user.User;
public class XMLUsersTest {
XMLUsers userXML = new XMLUsers();
User user = new User("test", "test");
//test add() by adding a user and checking if the number of users
//has increased by 1 (the user is then remove to allow the other tests to run
//properly).
@Test
public void testAdd() {
int numberOfUsersBefore = userXML.getDocument().getElementsByTagName("user").getLength();
userXML.add(user);
int numberOfUsersAfter = userXML.getDocument().getElementsByTagName("user").getLength();
assertEquals(numberOfUsersAfter, numberOfUsersBefore + 1);
userXML.remove("test");//removed to do not affect other tests
}
//adds a user and checks if it is contained in the file
@Test
public void testAdd2(){
userXML.add(user);
assertTrue(userXML.contains(user.getUsername()));
userXML.remove(user.getUsername());//removed to do not affect other tests
}
//adds a user, checks the number of users in the file and checks if it decreases after removing it
//and if the user is not present in the file
@Test
public void testRemove() {
userXML.add(user);
int numberOfUsersBefore = userXML.getDocument().getElementsByTagName("user").getLength();
userXML.remove("test");
int numberOfUsersAfter = userXML.getDocument().getElementsByTagName("user").getLength();
assertTrue(numberOfUsersAfter == numberOfUsersBefore - 1 && !userXML.contains("test"));
}
//attempts to remove a user that does not exist
@Test(expected = NullPointerException.class)
public void testRemove2(){
userXML.remove("test");
}
//tests if a user is contained in the users.xml file after adding it
@Test
public void testContains() {
userXML.add(user);
assertTrue(userXML.contains("test"));
userXML.remove("test");//removes the user to do not affect other tests
}
//test if a user is not contained in the users.xml file
@Test
public void testContains2(){
assertFalse(userXML.contains("test"));
}
//adds a user and then mocks some login attempts
@Test
public void testAuthenticate(){
userXML.add(user);
assertTrue(userXML.authenticate("test", "test"));
assertFalse(userXML.authenticate("test", "tset"));
assertFalse(userXML.authenticate("tset", "test"));
userXML.remove("test");//removes the user to do not affect other tests
}
}
|
9239e94f198251fdac78d8a8db9e28cd6d069a46 | 3,301 | java | Java | src/main/java/com/example/application/views/group/GroupList.java | digest15/StudentsApp | 6c8e9942aec19a050e63f275bf0044eb6f6768b9 | [
"Unlicense"
] | null | null | null | src/main/java/com/example/application/views/group/GroupList.java | digest15/StudentsApp | 6c8e9942aec19a050e63f275bf0044eb6f6768b9 | [
"Unlicense"
] | null | null | null | src/main/java/com/example/application/views/group/GroupList.java | digest15/StudentsApp | 6c8e9942aec19a050e63f275bf0044eb6f6768b9 | [
"Unlicense"
] | null | null | null | 28.704348 | 98 | 0.646168 | 999,010 | package com.example.application.views.group;
import com.example.application.backend.dto.group.GroupDto;
import com.example.application.backend.dto.group.GroupDtoForGrid;
import com.example.application.backend.dao.group.GroupDao;
import com.example.application.views.components.AbstractItemList;
import com.example.application.views.main.MainView;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;
@Route(value = "groups", layout = MainView.class)
@PageTitle("Group list")
public class GroupList extends AbstractItemList {
private GroupDao dao;
private Grid<GroupDtoForGrid> grid;
private GroupEdit editor;
private Dialog dialog = new Dialog();
@Autowired
public GroupList(GroupDao dao, GroupEdit editor) {
this.dao = dao;
this.editor = editor;
init();
}
@Override
protected void init() {
super.init();
filter.setPlaceholder("Filter by Spetiality name");
}
@Override
protected Component createGrid() {
grid = new Grid<>(GroupDtoForGrid.class);
grid.removeColumnByKey("id");
grid.asSingleSelect();
grid.addItemDoubleClickListener(e -> handDoubleClickOnGrid(e.getItem()));
return grid;
}
@Override
protected void updateList() {
String pattern = filter.getPattern();
if (pattern.isEmpty()) {
grid.setItems(dao.getItemsForGrid());
}else {
grid.setItems(dao.getItemsForGrid(pattern));
}
}
@Override
protected void addItem() {
openEditor(new GroupDto());
}
@Override
protected void editItem() {
Optional<GroupDtoForGrid> groupOptional = grid.getSelectionModel().getFirstSelectedItem();
if (groupOptional.isPresent()) {
openEditor(dao.findById(groupOptional.get().getId()));
}else {
Notification.show(SELECT_ITEM_NOTIFICATION_TEXT);
}
}
@Override
protected void deleteItem() {
Optional<GroupDtoForGrid> groupOptional = grid.getSelectionModel().getFirstSelectedItem();
if (groupOptional.isPresent()) {
dao.delete(dao.findById(groupOptional.get().getId()));
updateList();
}else {
Notification.show(SELECT_ITEM_NOTIFICATION_TEXT);
}
}
private void handDoubleClickOnGrid(GroupDtoForGrid item) {
openEditor(dao.findById(item.getId()));
}
private void openEditor(GroupDto group) {
if (group != null) {
editor.setItem(group);
editor.setOnSaveHandler(e -> {
dao.save((GroupDto) e);
closeDialog();
updateList();
});
editor.setOnCancelHandler(e -> closeDialog());
dialog.setResizable(true);
dialog.setCloseOnOutsideClick(false);
dialog.add(editor);
dialog.open();
}
}
private void closeDialog() {
dialog.close();
}
}
|
9239e9545fb0e39f23c4ec6899f6146ffe4d79b8 | 3,414 | java | Java | platform-server/platform-server-statistics/src/main/java/com/plm/platform/server/statistics/service/impl/ReportServiceImpl.java | chenwenhua666/platform-cloud | 15550dc0e58ddd52dd9ac73f3b708c4469cea4ba | [
"Apache-2.0"
] | null | null | null | platform-server/platform-server-statistics/src/main/java/com/plm/platform/server/statistics/service/impl/ReportServiceImpl.java | chenwenhua666/platform-cloud | 15550dc0e58ddd52dd9ac73f3b708c4469cea4ba | [
"Apache-2.0"
] | null | null | null | platform-server/platform-server-statistics/src/main/java/com/plm/platform/server/statistics/service/impl/ReportServiceImpl.java | chenwenhua666/platform-cloud | 15550dc0e58ddd52dd9ac73f3b708c4469cea4ba | [
"Apache-2.0"
] | 1 | 2020-11-20T15:38:58.000Z | 2020-11-20T15:38:58.000Z | 43.21519 | 114 | 0.761863 | 999,011 | package com.plm.platform.server.statistics.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.plm.platform.common.core.entity.PlatformResponse;
import com.plm.platform.common.core.entity.constant.CustomConstant;
import com.plm.platform.common.core.entity.constant.StringConstant;
import com.plm.platform.common.core.exception.PlatformException;
import com.plm.platform.common.core.utils.FileUtil;
import com.plm.platform.common.core.utils.PlatformUtil;
import com.plm.platform.common.redis.service.RedisService;
import com.plm.platform.server.statistics.service.ReportService;
import com.plm.platform.server.statistics.utils.TemplateUtil;
import com.plm.platform.server.statistics.vo.MailValidationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileSystemUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
/**
* @author crystal
*/
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ReportServiceImpl implements ReportService {
private static final String SUFFIX = "_report.pdf";
private static final String DOWNLOAD_NAME = "private_report.pdf";
private final RedisService redisService;
@Override
public void downloadReport(MailValidationVO mailValidationVO, HttpServletResponse response) throws Exception {
validated(mailValidationVO);
JSONObject data = toJsonObject(PlatformUtil.getCurrentUser());
String prefix = System.currentTimeMillis() + StringConstant.UNDER_LINE + UUID.randomUUID().toString();
String fileName = prefix + SUFFIX;
File file = new File(CustomConstant.FILE_PATH + fileName);
TemplateUtil.createFileByTemplate(CustomConstant.PDF_TEMPLATE, file, data);
FileUtil.download(CustomConstant.FILE_PATH + fileName, DOWNLOAD_NAME, true, response);
FileSystemUtils.deleteRecursively(new File(CustomConstant.FILE_PATH));
}
@Override
public PlatformResponse viewReport(MailValidationVO mailValidationVO) throws Exception {
validated(mailValidationVO);
JSONObject data = toJsonObject(PlatformUtil.getCurrentUser());
String constant = TemplateUtil.getTemplateContent(CustomConstant.PDF_TEMPLATE, data);
PlatformResponse platformResponse = new PlatformResponse();
return platformResponse.data(constant);
}
private void validated(MailValidationVO mailValidationVO) throws PlatformException {
String key = CustomConstant.EMAIL_CODE + mailValidationVO.getEmail();
String code = mailValidationVO.getCode();
Object codeInRedis = redisService.get(key);
if (StringUtils.isBlank(code)) {
throw new PlatformException("请输入验证码");
}
if (codeInRedis == null) {
throw new PlatformException("验证码已过期");
}
if (!StringUtils.equalsIgnoreCase(code, String.valueOf(codeInRedis))) {
throw new PlatformException("验证码不正确");
}
}
private JSONObject toJsonObject(Object o) {
return JSONObject.parseObject(JSONObject.toJSON(o).toString());
}
}
|
9239e992aff966ec71f9afd795af3e052a6c7e5a | 1,544 | java | Java | rabbitmq-producer/src/main/java/com/goosuu/rabbitmq/WorkQueuesProducer.java | dumin199101/RabbitMQ | f791b0c3429fea735ebd2b7ef42cf5cbbe5d4ede | [
"Apache-2.0"
] | null | null | null | rabbitmq-producer/src/main/java/com/goosuu/rabbitmq/WorkQueuesProducer.java | dumin199101/RabbitMQ | f791b0c3429fea735ebd2b7ef42cf5cbbe5d4ede | [
"Apache-2.0"
] | null | null | null | rabbitmq-producer/src/main/java/com/goosuu/rabbitmq/WorkQueuesProducer.java | dumin199101/RabbitMQ | f791b0c3429fea735ebd2b7ef42cf5cbbe5d4ede | [
"Apache-2.0"
] | null | null | null | 24.903226 | 108 | 0.613342 | 999,012 | package com.goosuu.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class WorkQueuesProducer {
static final String QUEUE_NAME = "work_queue";
public static void main(String[] args) throws IOException, TimeoutException {
// 1.创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
// 2.主机地址;默认为 localhost
factory.setHost("192.168.1.16");
// 3.连接端口;默认为 5672
factory.setPort(5672);
// 4.虚拟主机名称;默认为 /
factory.setVirtualHost("/itcast");
// 5.连接用户名;默认为guest
factory.setUsername("lieyan");
// 6.连接密码;默认为guest
factory.setPassword("123456");
// 创建连接
Connection connection = factory.newConnection();
// 创建频道
Channel channel = connection.createChannel();
// 创建队列
/*
参数一:队列名称
参数二:是否定义持久化队列
参数三:是否独占本次连接
参数四:是否在不使用的时候自动删除队列
参数五:队列其他参数
*/
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
// 要发送的消息
for (int i = 1; i <= 100 ; i++) {
String message = i + "Hello,我是你的宝贝";
// 消息持久化
channel.basicPublish("",QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
}
//释放资源
channel.close();
connection.close();
}
}
|
9239e9fc535650e94d2daac850e1c4773123a1cf | 2,621 | java | Java | modules/core/src/main/java/org/apache/ignite/plugin/security/AuthenticationContext.java | DirectXceriD/apache-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 36 | 2015-11-05T04:46:27.000Z | 2021-12-29T08:26:02.000Z | modules/core/src/main/java/org/apache/ignite/plugin/security/AuthenticationContext.java | gridgain/incubator-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 13 | 2016-08-29T11:54:08.000Z | 2020-12-08T08:47:04.000Z | modules/core/src/main/java/org/apache/ignite/plugin/security/AuthenticationContext.java | gridgain/incubator-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 15 | 2016-03-18T09:25:39.000Z | 2021-10-01T05:49:39.000Z | 23.612613 | 75 | 0.636398 | 999,013 | /*
* 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.plugin.security;
import java.net.*;
import java.util.*;
/**
* Authentication context.
*/
public class AuthenticationContext {
/** Subject type. */
private GridSecuritySubjectType subjType;
/** Subject ID.w */
private UUID subjId;
/** Credentials. */
private GridSecurityCredentials credentials;
/** Subject address. */
private InetSocketAddress addr;
/**
* Gets subject type.
*
* @return Subject type.
*/
public GridSecuritySubjectType subjectType() {
return subjType;
}
/**
* Sets subject type.
*
* @param subjType Subject type.
*/
public void subjectType(GridSecuritySubjectType subjType) {
this.subjType = subjType;
}
/**
* Gets subject ID.
*
* @return Subject ID.
*/
public UUID subjectId() {
return subjId;
}
/**
* Sets subject ID.
*
* @param subjId Subject ID.
*/
public void subjectId(UUID subjId) {
this.subjId = subjId;
}
/**
* Gets security credentials.
*
* @return Security credentials.
*/
public GridSecurityCredentials credentials() {
return credentials;
}
/**
* Sets security credentials.
*
* @param credentials Security credentials.
*/
public void credentials(GridSecurityCredentials credentials) {
this.credentials = credentials;
}
/**
* Gets subject network address.
*
* @return Subject network address.
*/
public InetSocketAddress address() {
return addr;
}
/**
* Sets subject network address.
*
* @param addr Subject network address.
*/
public void address(InetSocketAddress addr) {
this.addr = addr;
}
}
|
9239eaca97e444134a667ec9fa47ebf9694cc7f5 | 1,937 | java | Java | src/shared/iClient.java | vince-stri/Chess-Project | f20e2b336ef10948e50ed3f86ca73d796c714a5c | [
"MIT"
] | null | null | null | src/shared/iClient.java | vince-stri/Chess-Project | f20e2b336ef10948e50ed3f86ca73d796c714a5c | [
"MIT"
] | null | null | null | src/shared/iClient.java | vince-stri/Chess-Project | f20e2b336ef10948e50ed3f86ca73d796c714a5c | [
"MIT"
] | null | null | null | 24.833333 | 83 | 0.720186 | 999,014 | package shared;
import java.rmi.Remote;
import java.rmi.RemoteException;
import server.model.board.Board;
/**
* Interface of the Client object, used by RMI
* @version 1.0
* @author enzo moretto
*/
public interface iClient extends Remote {
public int GetIdAccount() throws RemoteException;
public void SetIdAccount(int idAccount) throws RemoteException;
/**
* Gives the client's user name
* @return the user name
*/
public String GetPseudo() throws RemoteException;
/**
* Allows the client to change its user name
* @param pseudo the new user name
*/
public void SetPseudo(String pseudo) throws RemoteException;
/**
* Get the client's token
* @return the token
*/
public String GetToken() throws RemoteException;
/**
* Allows the server to change the client's token
* @param token the newly generated token
*/
public void SetToken(String token) throws RemoteException;
/**
* Gives a string to display to the client, sent by another player
* @param message the string to display
*/
public void PostMsg(String message) throws RemoteException;
/**
* Gives the board to display to the client
* @param board the board to displau
*/
public void PostBoard(Board board) throws RemoteException;
/**
* Gives a string to display to the client, sent by the server
* @param message the string to display
*/
public void PostInfo(String info) throws RemoteException;
/**
* Tests equality between two clients, based upon their token (universally unique)
* @param client the client to be compared with
* @return true if the tokens match, false otherwise
*/
public boolean equals(iClient client) throws RemoteException;
/**
* Get the GMId saved by the client
* @return the GMId saved
*/
public String getGMId() throws RemoteException;
/**
* Set a saved GMId
* @param GMId the saved GMId
*/
public void setGMId(String GMId) throws RemoteException;
}
|
9239ebfd217e49618f5945adcad66e1fd77300a7 | 253 | java | Java | Springboot-DynamicData/src/main/java/com/markly/datasource/TargetDataSource.java | sys-spearmint/train-java | 2ce75d5bdf3599f3da23c7cd482763d9a7ba6f53 | [
"Apache-2.0"
] | null | null | null | Springboot-DynamicData/src/main/java/com/markly/datasource/TargetDataSource.java | sys-spearmint/train-java | 2ce75d5bdf3599f3da23c7cd482763d9a7ba6f53 | [
"Apache-2.0"
] | null | null | null | Springboot-DynamicData/src/main/java/com/markly/datasource/TargetDataSource.java | sys-spearmint/train-java | 2ce75d5bdf3599f3da23c7cd482763d9a7ba6f53 | [
"Apache-2.0"
] | null | null | null | 13.315789 | 36 | 0.703557 | 999,015 | package com.markly.datasource;
import java.lang.annotation.*;
/**
* 多数据源注解
* <p/>
* 指定要使用的数据源
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String name() default "";
}
|
9239ec54d555e064b5f041a92257eb07a2108c5d | 3,613 | java | Java | app/src/main/java/com/wtwd/standard/utils/DialogUtil.java | w77996/temp | 9d6a0fd0b77db4b8dd4459a1f6725093e142242c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/wtwd/standard/utils/DialogUtil.java | w77996/temp | 9d6a0fd0b77db4b8dd4459a1f6725093e142242c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/wtwd/standard/utils/DialogUtil.java | w77996/temp | 9d6a0fd0b77db4b8dd4459a1f6725093e142242c | [
"Apache-2.0"
] | null | null | null | 31.973451 | 145 | 0.675616 | 999,016 | package com.wtwd.standard.utils;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.wtwd.standard.R;
/**
* Created by Administrator on 2018/3/20 0020.
*/
public class DialogUtil {
/**
* 选择左右手弹框
*
* @param mActivity Activity对象
* @param mDialog Dialog对象
* @param mLeftClick 选择左手点击事件监听
* @param mRightClick 选择右手点击事件监听
*/
public static void chooseHandsDialog(Activity mActivity, Dialog mDialog, View.OnClickListener mLeftClick, View.OnClickListener mRightClick) {
View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_choose_hands, null, false);
TextView text_left_hand = (TextView) view.findViewById(R.id.text_left_hand);
TextView text_right_hand = (TextView) view.findViewById(R.id.text_right_hand);
mDialog.setContentView(view);
mDialog.setCanceledOnTouchOutside(true);
text_left_hand.setOnClickListener(mLeftClick);
text_right_hand.setOnClickListener(mRightClick);
mDialog.show();
setDialoglayoutParams(mActivity, mDialog);
}
public static void commitDialog(Activity mActivity, final Dialog mDialog, String title, View.OnClickListener mRightCommitClick){
View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_commit,null,false);
TextView text_commit_title = (TextView)view.findViewById(R.id.text_commit_title);
TextView text_refuse = (TextView)view.findViewById(R.id.text_refuse);
TextView text_commit = (TextView)view.findViewById(R.id.text_commit);
text_commit_title.setText(title);
mDialog.setContentView(view);
mDialog.setCanceledOnTouchOutside(true);
text_refuse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
text_commit.setOnClickListener(mRightCommitClick);
mDialog.show();
setDialoglayoutParams(mActivity,mDialog);
}
public static void setDialoglayoutParams(Activity mActivity, Dialog selectedDialog) {
Window dialogWindow = selectedDialog.getWindow();
WindowManager m = mActivity.getWindowManager();
Display d = m.getDefaultDisplay();
WindowManager.LayoutParams p = dialogWindow.getAttributes();
//设置高度和宽度
p.height = WindowManager.LayoutParams.WRAP_CONTENT;
p.width = (int) (d.getWidth());
//设置位置
p.gravity = Gravity.BOTTOM;
p.y = 0; //设置Dialog与底部的margin值,与左右一致
//设置Dialog本身透明度
// p.alpha = 0.5f;
dialogWindow.setAttributes(p);
}
// public static void setDialoglayoutParams(Activity mActivity, Dialog selectedDialog) {
// Window dialogWindow = selectedDialog.getWindow();
// WindowManager m = mActivity.getWindowManager();
//
// Display d = m.getDefaultDisplay();
// WindowManager.LayoutParams p = dialogWindow.getAttributes();
//
// //设置高度和宽度
// p.height = WindowManager.LayoutParams.WRAP_CONTENT;
// p.width = (int) (d.getWidth() * 0.9);
// //设置位置
// p.gravity = Gravity.BOTTOM;
// p.y = (int) (d.getWidth() * 0.05); //设置Dialog与底部的margin值,与左右一致
//
// //设置Dialog本身透明度
//// p.alpha = 0.5f;
// dialogWindow.setAttributes(p);
// }
}
|
9239ee9a0bb9f94249c8f01582c68967737185ee | 1,119 | java | Java | foxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/impl/KubernetesClusterDiscoveryConfig.java | anjalinauhwar/foxtrot-1 | 1852de95363e09428176832c7184ac6c973e4bd0 | [
"Apache-2.0"
] | null | null | null | foxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/impl/KubernetesClusterDiscoveryConfig.java | anjalinauhwar/foxtrot-1 | 1852de95363e09428176832c7184ac6c973e4bd0 | [
"Apache-2.0"
] | 1 | 2022-01-25T09:30:17.000Z | 2022-01-25T09:30:17.000Z | foxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/impl/KubernetesClusterDiscoveryConfig.java | appform-io/foxtrot | ae2c7cf52878ea395e506c9939b8438fba23817f | [
"Apache-2.0"
] | null | null | null | 31.083333 | 78 | 0.764969 | 999,017 | /**
* Copyright 2016 Flipkart Internet Pvt. Ltd.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.flipkart.foxtrot.core.querystore.impl;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class KubernetesClusterDiscoveryConfig extends ClusterDiscoveryConfig {
@JsonProperty
private boolean disableMulticast = false;
public KubernetesClusterDiscoveryConfig() {
super(ClusterDiscoveryType.FOXTROT_KUBERNETES);
}
}
|
9239efd7dc473087f7912768de1161bd9c113df0 | 1,763 | java | Java | deleting-compaction-strategy/src/main/java/com/protectwise/cassandra/db/compaction/example/AllAtomDeleter.java | protectwise/cassandra-util | 25640872efee15d23f7e610858947ea0555bc956 | [
"Apache-2.0"
] | 33 | 2016-09-10T15:47:24.000Z | 2020-07-30T06:01:48.000Z | deleting-compaction-strategy/src/main/java/com/protectwise/cassandra/db/compaction/example/AllAtomDeleter.java | protectwise/cassandra-util | 25640872efee15d23f7e610858947ea0555bc956 | [
"Apache-2.0"
] | 10 | 2016-12-19T12:41:10.000Z | 2019-06-26T12:49:34.000Z | deleting-compaction-strategy/src/main/java/com/protectwise/cassandra/db/compaction/example/AllAtomDeleter.java | protectwise/cassandra-util | 25640872efee15d23f7e610858947ea0555bc956 | [
"Apache-2.0"
] | 15 | 2016-12-13T10:46:09.000Z | 2021-03-12T10:43:44.000Z | 31.482143 | 137 | 0.783891 | 999,018 | /*
* Copyright 2016 ProtectWise, 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.protectwise.cassandra.db.compaction.example;
import com.protectwise.cassandra.db.compaction.AbstractClusterDeletingConvictor;
import com.protectwise.cassandra.db.compaction.AbstractSimpleDeletingConvictor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.OnDiskAtom;
import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
import org.apache.cassandra.db.composites.Composite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class AllAtomDeleter extends AbstractSimpleDeletingConvictor
{
private static final Logger logger = LoggerFactory.getLogger(AllAtomDeleter.class);
/**
* @param cfs
* @param options
*/
public AllAtomDeleter(ColumnFamilyStore cfs, Map<String, String> options)
{
super(cfs, options);
logger.warn("You are using an example deleting compaction strategy. Direct production use of these classes is STRONGLY DISCOURAGED!");
}
@Override
public boolean shouldKeepAtom(OnDiskAtomIterator partition, OnDiskAtom atom)
{
return false;
}
@Override
public boolean shouldKeepPartition(OnDiskAtomIterator key)
{
return true;
}
}
|
9239f050616adc8fe9434465b939cd8b1ff8e338 | 9,383 | java | Java | ucs-nifi-extensions/nifi-ucs-nifi-extensions-processors/src/main/java/org/socraticgrid/hl7/ucs/nifi/controller/UCSControllerServiceProxy.java | SocraticGrid/UCS-Implementation | 39744d0df7f3c7fbb5da98c18b1cb375e6e99a60 | [
"Apache-2.0"
] | 1 | 2016-04-27T02:38:44.000Z | 2016-04-27T02:38:44.000Z | ucs-nifi-extensions/nifi-ucs-nifi-extensions-processors/src/main/java/org/socraticgrid/hl7/ucs/nifi/controller/UCSControllerServiceProxy.java | SocraticGrid/UCS-Implementation | 39744d0df7f3c7fbb5da98c18b1cb375e6e99a60 | [
"Apache-2.0"
] | null | null | null | ucs-nifi-extensions/nifi-ucs-nifi-extensions-processors/src/main/java/org/socraticgrid/hl7/ucs/nifi/controller/UCSControllerServiceProxy.java | SocraticGrid/UCS-Implementation | 39744d0df7f3c7fbb5da98c18b1cb375e6e99a60 | [
"Apache-2.0"
] | null | null | null | 35.950192 | 235 | 0.747948 | 999,019 | /*
* Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedicine.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.socraticgrid.hl7.ucs.nifi.controller;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.annotation.lifecycle.OnShutdown;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.quartz.SchedulerException;
import org.socraticgrid.hl7.services.uc.model.Conversation;
import org.socraticgrid.hl7.services.uc.model.Message;
import org.socraticgrid.hl7.services.uc.model.QueryFilter;
import org.socraticgrid.hl7.services.uc.model.UserContactInfo;
import org.socraticgrid.hl7.ucs.nifi.common.model.Adapter;
import org.socraticgrid.hl7.ucs.nifi.common.model.ResolvedAddresses;
import org.socraticgrid.hl7.ucs.nifi.common.model.UCSStatus;
import org.socraticgrid.hl7.ucs.nifi.controller.store.MessageStoreController;
import org.socraticgrid.hl7.ucs.nifi.controller.user.UserContactInfoResolverController;
import org.socraticgrid.hl7.ucs.nifi.processor.model.MessageWithUnreachableHandlers;
import org.socraticgrid.hl7.ucs.nifi.services.TimedOutMessage;
/**
*
* @author esteban
*/
public class UCSControllerServiceProxy extends AbstractControllerService implements UCSController {
public static final PropertyDescriptor MESSAGE_STORE_IMPL = new PropertyDescriptor.Builder()
.name("MessageStoreController")
.description("The name of a concrete implementation of MessageStoreController interface")
.required(true)
.identifiesControllerService(MessageStoreController.class)
.build();
public static final PropertyDescriptor USER_CONTACT_INFO_RESOLVER_IMPL = new PropertyDescriptor.Builder()
.name("UserContactInfoController")
.description("A concrete implementation UserContactInfoResolverController interface")
.required(true)
.identifiesControllerService(UserContactInfoResolverController.class)
.build();
public static final PropertyDescriptor SERVICE_STATUS_CONTROLLER_SERVICE = new PropertyDescriptor.Builder()
.name("ServiceStatusControllerService")
.description(
"The Service Status Controller Service that this Processor uses to update the Status of this Adapter.")
.identifiesControllerService(ServiceStatusController.class)
.required(true).build();
private UCSControllerService service;
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
final List<PropertyDescriptor> descriptors = new ArrayList<>();
descriptors.add(MESSAGE_STORE_IMPL);
descriptors.add(USER_CONTACT_INFO_RESOLVER_IMPL);
descriptors.add(SERVICE_STATUS_CONTROLLER_SERVICE);
return descriptors;
}
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws Exception {
UserContactInfoResolverController userContactInfoResolver = context.getProperty(USER_CONTACT_INFO_RESOLVER_IMPL).asControllerService(UserContactInfoResolverController.class);
MessageStoreController messageStore = context.getProperty(MESSAGE_STORE_IMPL).asControllerService(MessageStoreController.class);
ServiceStatusController serviceStatusControllerService = context.getProperty(SERVICE_STATUS_CONTROLLER_SERVICE).asControllerService(ServiceStatusController.class);
this.service = new UCSControllerServiceImpl.UCSControllerServiceImplBuilder().setMessageStore(messageStore).setUserContactInfoResolver(userContactInfoResolver).setServiceStatusController(serviceStatusControllerService).build();
this.service.start();
}
@OnShutdown
public void onShutdown() throws Exception {
this.service.stop();
}
@Override
public ResolvedAddresses resolvePhysicalAddressesByServiceId(Message message) {
return this.service.resolvePhysicalAddressesByServiceId(message);
}
@Override
public UserContactInfo resolveUserContactInfo(String userId) {
return this.service.resolveUserContactInfo(userId);
}
@Override
public void start() {
//nobody is never going to call this method.
}
@Override
public void stop() {
//nobody is never going to call this method.
}
@Override
public void saveMessage(Message message) {
this.service.saveMessage(message);
}
@Override
public void updateMessage(Message message) {
this.service.updateMessage(message);
}
@Override
public Optional<Message> getMessageById(String messageId) {
return this.service.getMessageById(messageId);
}
@Override
public List<Message> listMessages() {
return this.service.listMessages();
}
@Override
public List<Message> listMessages(long from, long total) {
return this.service.listMessages(from, total);
}
@Override
public Set<Message> getRelatedMessages(String messageId) {
return this.service.getRelatedMessages(messageId);
}
@Override
public void saveMessageReference(Message message, String recipientId, String reference) {
this.service.saveMessageReference(message, recipientId, reference);
}
@Override
public Optional<Message> getMessageByReference(String reference) {
return this.service.getMessageByReference(reference);
}
@Override
public Optional<String> getRecipientIdByReference(String reference) {
return this.service.getRecipientIdByReference(reference);
}
@Override
public boolean isKnownConversation(String conversationId) {
return this.service.isKnownConversation(conversationId);
}
@Override
public String registerUCSClientCallback(URL callback) {
return this.service.registerUCSClientCallback(callback);
}
@Override
public void unregisterUCSClientCallback(String registrationId) {
this.service.unregisterUCSClientCallback(registrationId);
}
@Override
public Collection<URL> getUCSClientCallbacks() {
return this.service.getUCSClientCallbacks();
}
@Override
public void notifyAboutMessageWithUnreachableHandlers(MessageWithUnreachableHandlers message) {
this.service.notifyAboutMessageWithUnreachableHandlers(message);
}
@Override
public Set<MessageWithUnreachableHandlers> consumeMessagesWithUnreachableHandlers() {
return this.service.consumeMessagesWithUnreachableHandlers();
}
@Override
public void notifyAboutMessageWithResponseTimeout(TimedOutMessage message) {
this.service.notifyAboutMessageWithResponseTimeout(message);
}
@Override
public Set<TimedOutMessage> consumeMessagesWithResponseTimeout() {
return this.service.consumeMessagesWithResponseTimeout();
}
@Override
public void setupResponseTimeout(Message message) throws SchedulerException {
this.service.setupResponseTimeout(message);
}
@Override
public String registerUCSAlertingCallback(URL callback) {
return this.service.registerUCSAlertingCallback(callback);
}
@Override
public void unregisterUCSAlertingCallback(String registrationId) {
this.service.unregisterUCSAlertingCallback(registrationId);
}
@Override
public Collection<URL> getUCSAlertingCallbacks() {
return this.service.getUCSAlertingCallbacks();
}
@Override
public List<Adapter> getSupportedAdapters() {
return this.service.getSupportedAdapters();
}
@Override
public UCSStatus getServiceStatus() {
return this.service.getServiceStatus();
}
@Override
public void saveConversation(Conversation conversation) {
this.service.saveConversation(conversation);
}
@Override
public Optional<Conversation> getConversationById(String conversationId) {
return this.service.getConversationById(conversationId);
}
@Override
public List<Message> listMessagesByConversationId(String conversationId) {
return this.service.listMessagesByConversationId(conversationId);
}
@Override
public List<Message> listMessagesByConversationId(String conversationId, Optional<Long> from, Optional<Long> total) {
return this.service.listMessagesByConversationId(conversationId, from, total);
}
@Override
public List<Conversation> queryConversations(String query, List<QueryFilter> filters) {
return this.service.queryConversations(query, filters);
}
}
|
9239f0d4590f87ad05753fea505080ef10662152 | 164 | java | Java | src/main/java/com/bytesaim/util/TRunnable.java | bytesaim/laner | 7f479c641f014ec78c8d9ca004d94aa72d8583ff | [
"MIT"
] | 3 | 2019-09-03T10:50:09.000Z | 2019-09-03T11:06:11.000Z | src/main/java/com/bytesaim/util/TRunnable.java | sourcerersproject/codewalker | 7f479c641f014ec78c8d9ca004d94aa72d8583ff | [
"MIT"
] | null | null | null | src/main/java/com/bytesaim/util/TRunnable.java | sourcerersproject/codewalker | 7f479c641f014ec78c8d9ca004d94aa72d8583ff | [
"MIT"
] | null | null | null | 18.222222 | 45 | 0.75 | 999,020 | package com.bytesaim.util;
import java.io.IOException;
public interface TRunnable extends Runnable {
boolean isRunning();
void stop() throws Exception;
}
|
9239f1dc1e4afc86b200d5c7ab3f671aeb208f50 | 3,626 | java | Java | jfreechart-master/src/test/java/org/jfree/chart/axis/SymbolAxisTest.java | jmdgg-iscte/ES-LIGE-2Sem-2022-Grupo-32 | 7f5c8f7b78a4497fabb4f9b71c36f76abb9387d0 | [
"MIT"
] | 2 | 2022-02-23T12:20:23.000Z | 2022-03-15T22:20:27.000Z | jfreechart-master/src/test/java/org/jfree/chart/axis/SymbolAxisTest.java | jmdgg-iscte/ES-LIGE-2Sem-2022-Grupo-32 | 7f5c8f7b78a4497fabb4f9b71c36f76abb9387d0 | [
"MIT"
] | 1 | 2022-02-23T12:08:18.000Z | 2022-02-23T12:08:18.000Z | jfreechart-master/src/test/java/org/jfree/chart/axis/SymbolAxisTest.java | jmdgg-iscte/ES-LIGE-2Sem-2022-Grupo-32 | 7f5c8f7b78a4497fabb4f9b71c36f76abb9387d0 | [
"MIT"
] | null | null | null | 32.375 | 79 | 0.616933 | 999,021 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2022, by David Gilbert and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------------
* SymbolicAxisTest.java
* ---------------------
* (C) Copyright 2003-2022, by David Gilbert and Contributors.
*
* Original Author: David Gilbert;
* Contributor(s): -;
*
*/
package org.jfree.chart.axis;
import java.awt.Color;
import org.jfree.chart.TestUtils;
import org.jfree.chart.internal.CloneUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for the {@link SymbolAxis} class.
*/
public class SymbolAxisTest {
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
String[] tickLabels = new String[] {"One", "Two", "Three"};
SymbolAxis a1 = new SymbolAxis("Test Axis", tickLabels);
SymbolAxis a2 = TestUtils.serialised(a1);
assertEquals(a1, a2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
SymbolAxis a1 = new SymbolAxis("Axis", new String[] {"A", "B"});
SymbolAxis a2 = CloneUtils.clone(a1);
assertNotSame(a1, a2);
assertSame(a1.getClass(), a2.getClass());
assertEquals(a1, a2);
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
SymbolAxis a1 = new SymbolAxis("Axis", new String[] {"A", "B"});
SymbolAxis a2 = new SymbolAxis("Axis", new String[] {"A", "B"});
assertEquals(a1, a2);
assertEquals(a2, a1);
a1 = new SymbolAxis("Axis 2", new String[] {"A", "B"});
assertNotEquals(a1, a2);
a2 = new SymbolAxis("Axis 2", new String[] {"A", "B"});
assertEquals(a1, a2);
a1 = new SymbolAxis("Axis 2", new String[] {"C", "B"});
assertNotEquals(a1, a2);
a2 = new SymbolAxis("Axis 2", new String[] {"C", "B"});
assertEquals(a1, a2);
a1.setGridBandsVisible(false);
assertNotEquals(a1, a2);
a2.setGridBandsVisible(false);
assertEquals(a1, a2);
a1.setGridBandPaint(Color.BLACK);
assertNotEquals(a1, a2);
a2.setGridBandPaint(Color.BLACK);
assertEquals(a1, a2);
a1.setGridBandAlternatePaint(Color.RED);
assertNotEquals(a1, a2);
a2.setGridBandAlternatePaint(Color.RED);
assertEquals(a1, a2);
}
}
|
9239f205257c19382aec2dc5612d798fb4890376 | 278 | java | Java | staffjoy-gateway/src/main/java/xyz/staffjoy/getaway/exceptions/GetawayException.java | SpaceanHub/staffjoy | 78ba1b2af2fc9cef8ca1be197ee063f5556f2a07 | [
"MIT"
] | 1 | 2021-06-12T21:19:27.000Z | 2021-06-12T21:19:27.000Z | staffjoy-gateway/src/main/java/xyz/staffjoy/getaway/exceptions/GetawayException.java | SpaceanHub/staffjoy | 78ba1b2af2fc9cef8ca1be197ee063f5556f2a07 | [
"MIT"
] | null | null | null | staffjoy-gateway/src/main/java/xyz/staffjoy/getaway/exceptions/GetawayException.java | SpaceanHub/staffjoy | 78ba1b2af2fc9cef8ca1be197ee063f5556f2a07 | [
"MIT"
] | null | null | null | 23.166667 | 62 | 0.71223 | 999,022 | package xyz.staffjoy.getaway.exceptions;
public class GetawayException extends RuntimeException {
public GetawayException(String message) {
super(message);
}
public GetawayException(String message, Throwable cause) {
super(message, cause);
}
}
|
9239f279a489176d14e67248ec4c8a49e520213e | 16,785 | java | Java | cali.lang.base/src/com/cali/Engine.java | cali-lang/cali.lang.base | 3786d29ca2530b8ff58dbfe3261139873f245c64 | [
"Apache-2.0"
] | 1 | 2018-11-15T20:19:45.000Z | 2018-11-15T20:19:45.000Z | cali.lang.base/src/com/cali/Engine.java | cali-lang/cali.lang.base | 3786d29ca2530b8ff58dbfe3261139873f245c64 | [
"Apache-2.0"
] | null | null | null | cali.lang.base/src/com/cali/Engine.java | cali-lang/cali.lang.base | 3786d29ca2530b8ff58dbfe3261139873f245c64 | [
"Apache-2.0"
] | null | null | null | 30.798165 | 114 | 0.692464 | 999,023 | /*
* Copyright 2017 Austin Lehman
*
* 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.cali;
import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.cali.ast.*;
import com.cali.stdlib.Lang;
import com.cali.stdlib.console;
import com.cali.types.*;
/**
* Engine object represents a Cali interpreter instance. Then engine handles
* parsing files and strings, storing includes/classes and running Cali
* code.
* @author austin
*/
public class Engine {
/**
* The security manager instance for this engine.
*/
private SecurityManagerInt secman = null;
/**
* Flag for printing debug statements to standard out.
*/
private boolean debug = false;
/**
* Stores the file names of any included Cali code files.
*/
private List<String> fileNames = new ArrayList<String>();
/**
* Flag for initialization is complete. This is set to true once
* the base cali object have been parsed. Once set to true calls to
* addClass will instantiate static classes right away.
*/
private boolean initComplete = false;
/*
* Main class.
*/
private boolean mainClassFound = false;
private astClass mainClassDef = null;
private CaliObject mainClassInstance = null;
/*
* Main function.
*/
private boolean mainFunctFound = false;
private astFunctDef mainFunctDef = null;
private CaliList mainFunctArgs = new CaliList(false);
private CallStack mainCallStack = new CallStack();
/**
* This flag is set if the parser encounters errors. This is used
* when parsing the initial source code prior to running the application. If
* set to true the interpreter will fail to start.
*/
private boolean hasParseErrors = false;
/**
* Allowed resource include paths. These are includes that are
* located within the JAR package.
*/
private List<String> resourceIncludePaths = new ArrayList<String>();
/**
* Allowed include paths.
*/
private List<String> includePaths = new ArrayList<String>();
/**
* List of Cali includes.
*/
private List<String> includes = new ArrayList<String>();
/*
* Class objects storage for engine.
*/
private Map<String, astClass> classes = new ConcurrentHashMap<String, astClass>();
private Map<String, CaliType> staticClasses = new ConcurrentHashMap<String, CaliType>();
/**
* Default constructor. When called this gets an instance of the Universe object
* and initializes it if not already done. It loads universe classes and instantiates
* static classes. Finally it sets the initComplete flag to true.
* @throws Exception on failure to instantiate SecurityManagerImpl object.
*/
public Engine () throws Exception {
this(new SecurityManagerImpl());
}
/**
* Default constructor. When called this gets an instance of the Universe object
* and initializes it if not already done. It loads universe classes and instantiates
* static classes. Finally it sets the initComplete flag to true.
* @param SecMan is a SecurityManagerImpl object for the engine.
* @throws Exception on init failure or failure to instantiate static classes.
*/
public Engine(SecurityManagerInt SecMan) throws Exception {
this.secman = SecMan;
Universe u = Universe.get();
u.init(this);
// If needed, load base classes.
this.loadUniverseClasses();
// Instantiate the static classes.
this.instantiateStaticClasses();
this.initComplete = true;
}
/**
* Gets the instance of the security manager for this Engine.
* @return A SecurityManagerInt object of the security manager.
*/
public SecurityManagerInt getSecurityManager() {
return this.secman;
}
/**
* Adds a Cali include to the interpreter. The include can be a standard library
* language include. It can also be a file that exists in one f the includePaths
* if any are set.
* @param Include is a String with the include to add.
* @throws Exception on parse failure.
*/
public void addInclude(String Include) throws Exception {
if (this.debug) console.get().info("Engine.addInclude(): Include: " + Include);
if (Lang.get().langIncludes.containsKey(Include)) {
if (!this.includes.contains(Include)) {
if (this.debug) console.get().info("Engine.addInclude(): Adding langInclude: " + Include);
this.includes.add(Include);
this.parseString(Include, Lang.get().langIncludes.get(Include));
}
} else {
if (this.debug) console.get().info("Engine.addInclude(): Attempting to find in resourceIncludePaths ...");
for (String pth : this.resourceIncludePaths) {
List<String> resDir = Lang.get().listResourceDirectory(pth);
String tinc = pth + Include;
for (String fname : resDir) {
if (fname.contains(tinc)) {
if (this.debug) console.get().info("Engine.addInclude(): Include " + Include + " found in '" + fname + "'");
this.includes.add(tinc);
this.parseString(Include, Util.loadResource(tinc));
return;
}
}
}
if (this.debug) console.get().info("Engine.addInclude(): Attempting to find in includePaths ...");
for (String pth : this.includePaths) {
String tinc = pth + Include;
File f = new File(tinc);
if (f.exists()) {
if (!this.includes.contains(tinc)) {
if (this.debug) console.get().info("Engine.addInclude(): Include " + Include + " found in '" + pth + "'");
this.includes.add(tinc);
this.parseFile(tinc);
break;
}
}
}
if (this.debug) console.get().info("Engine.addInclude(): Include '" + Include + "' not found at all.");
}
}
/**
* Adds an include path to the list of search paths for Cali includes.
* @param Path is a String with the search path to add.
*/
public void addIncludePath(String Path) {
String tinc = Path;
if (!tinc.endsWith("/")) {
tinc += "/";
}
this.includePaths.add(tinc);
}
/**
* Gets a list of the search include paths.
* @return A List of Strings with the include paths.
*/
public List<String> getIncludePaths() {
return this.includePaths;
}
/**
* Adds an include path for a resource directory with a JAR file
* to the list of resource include paths.
* @param Path is a String with the search resource path to add.
*/
public void addResourceIncludePath(String Path) {
String tinc = Path;
if (!tinc.endsWith("/")) {
tinc += "/";
}
this.resourceIncludePaths.add(tinc);
}
/**
* Gets a list of the resource search include paths.
* @return A List of Strings with the resource include paths.
*/
public List<String> getResourceIncludePath() {
return this.resourceIncludePaths;
}
/**
* Gets a list of current includes.
* @return A List of Strings with the current includes.
*/
public List<String> getIncludes() {
return this.includes;
}
public void addClass(astNode TCls) throws caliException {
astClass Cls = (astClass)TCls;
this.classes.put(Cls.getName(), Cls);
this.setClassConstructor(Cls);
if (Cls.getStatic() && this.initComplete) {
// Instantiate static class now.
this.instantiateStaticClass(Cls);
}
}
/**
* Gets a class instance (astClass) object from
* the list of class definitions with the provided name.
* @param Name is a String with the class to get.
* @return An astClass object with the class definition or null if not found.
*/
public astClass getClassByName(String Name) {
return this.classes.get(Name);
}
/**
* Checks to see if a class definition with the provided name exists in the engine.
* Note that this doesn't include static classes.
* @param Name is a String with the class definition to search for.
* @return A boolean with true for exists and false for not.
*/
public boolean containsClass(String Name) {
if (this.classes.containsKey(Name)) {
return true;
}
return false;
}
/**
* Checks to see if a static class definition with the provided name exists
* in the engine.
* @param Name is a String with the class definition to search for.
* @return A boolean with true for exists and false for not.
*/
public boolean containsStaticClass(String Name) {
if (this.staticClasses.containsKey(Name)) {
return true;
}
return false;
}
/**
* Gets the static class object instance with the provided name.
* @param Name is a string with the class definition to get.
* @return An astClass definition for the class or null if not found.
*/
public CaliType getStaticClass(String Name) {
return this.staticClasses.get(Name);
}
/**
* Gets a Map with the current class names and their astClass
* definition objects as values.
* @return A Map of (String, astClass) with the current classes.
*/
public Map<String, astClass> getClasses() {
return this.classes;
}
/**
* Sets the debug flag. If set to true the engine will print various
* verbose debug statements to standard output.
* @param Debug is a boolean with true for debug and false for not.
*/
public void setDebug(boolean Debug) {
this.debug = Debug;
}
/**
* Gets the debug flag.
* @return A boolean with true for debug and false for not.
*/
public boolean getDebug() {
return this.debug;
}
/**
* This function loads the native type class definitions
* in the Engine class set. This is need if you want to
* say create a new native type using the new operator.
*/
public void loadUniverseClasses() {
// Add universe classes.
Map<String, astClass> clses = Universe.get().getClasses();
for (String key : clses.keySet()) {
if (!this.classes.containsKey(key)) {
this.classes.put(key, clses.get(key));
}
}
}
/**
* The interpreter will parse the Cali code file with the provided file name.
* @param FileName is a String with the Cali code file to parse.
* @throws Exception on parse failure.
*/
public void parseFile(String FileName) throws Exception {
this.parseString(FileName, Util.read(FileName));
}
/**
* The interpreter will parse the provided Cali code string. It also
* ties that code to the provided file name internally.
* @param FileName is a String with the file name to assign to the provided code.
* @param Contents is a String with the Cali code to parse.
* @throws Exception on parse failure.
*/
public void parseString(String FileName, String Contents) throws Exception {
Lexer scanner = new Lexer(new StringReader(Contents));
parser p = new parser(scanner, this, FileName);
p.parse();
this.fileNames.add(FileName);
}
/**
* Runs the Cali engine. This function goes though and identifies
* the first class with a main function. If not found it will throw an exception.
* If found it will call the entry point of the application (main function).
* @throws caliException on failure to find main class or on parse errors.
*/
public void run() throws caliException {
if (!this.hasParseErrors) {
if (this.debug)
System.out.println("[debug] Running program now ...");
this.mainCallStack = new CallStack();
// Set the main class and function.
if (this.setMainClassAndFunct()) {
this.callMain();
} else {
throw new caliException("Engine.run(): Failed to find main class.");
}
} else {
throw new caliException("Engine.run(): Parse errors were encountered. Not running.");
}
}
/**
* Sets the constructor function reference for the
* provided astClass class definition object.
* @param ac is a astClass object to set.
*/
private void setClassConstructor(astClass ac) {
if (ac.containsFunction(ac.getName())) {
ac.setConstructor((astFunctDef)ac.getFunct(ac.getName()));
}
}
/**
* Function instantiates objects for all static class definitions. This is
* called once all the base lang classes have been parsed.
* @throws caliException
*/
private void instantiateStaticClasses() throws caliException {
for (String cname : this.classes.keySet()) {
astClass ac = this.classes.get(cname);
if (ac.getStatic()) {
this.instantiateStaticClass(ac);
}
}
}
/**
* Instantiates a static class object with the provided class definition.
* @param ac is a astClass class definition object.
* @throws caliException
*/
private void instantiateStaticClass(astClass ac) throws caliException {
if (this.debug)
System.out.println("[debug] Instantiating static class: " + ac.getName());
CaliType aci = null;
Environment tenv = new Environment(this);
Members locals = new Members();
tenv.setEnvironment((CaliObject)aci, locals, this.mainCallStack);
aci = (CaliObject) ac.instantiate(tenv, false, new CaliList());
if(!aci.isEx()) {
this.staticClasses.put(ac.getName(), aci);
} else {
throw new caliException(((CaliException)aci).getStackTrace());
}
}
/**
* Searches through list of class definitions looking for the
* first one that contains a main function. Once found it sets
* it's private mainClassFound and mainFunctFound variables. It
* then breaks and returns true if found.
* @return A boolean with true if main function found and set and
* false for not.
*/
private boolean setMainClassAndFunct() {
boolean found = false;
for (String cname : this.classes.keySet()) {
if (found) break;
astClass ac = this.classes.get(cname);
if (ac.containsFunction("main")) {
this.mainClassFound = true;
this.mainClassDef = ac;
this.mainFunctFound = true;
this.mainFunctDef = (astFunctDef) ac.getFunct("main");
found = true;
break;
}
}
return found;
}
/**
* This is the program entry point. This function setups up the environment,
* locals and instantiates the main class. It then compiles the main function
* arguments and then calls main to kick off program execution.
* @throws caliException
*/
private void callMain() throws caliException {
Environment tenv = new Environment(this);
Members locals = new Members();
tenv.setEnvironment(null, locals, this.mainCallStack);
CaliType tci = this.mainClassDef.instantiate(tenv, false, new CaliList());
if(!tci.isEx())
{
this.mainClassInstance = (CaliObject) tci;
tenv.setClassInstance(this.mainClassInstance);
/*
* Main is expecting a list of args, but the function is expecting
* a list as well, so list inside of list.
*/
CaliList margs = new CaliList();
margs.add(this.mainFunctArgs);
/*
* Call main.
*/
CaliType ret = new CaliNull();
ret = this.mainClassDef.call(tenv, false, "main", margs);
if(ret.isEx()) {
CaliException ex = (CaliException)ret;
System.err.println(((CaliTypeInt)ex).str());
}
} else {
CaliException ex = (CaliException)tci;
System.err.println(ex.toString());
}
}
/**
* Instantiates a new object with the provided class name.
* @param Name is a String with the class name to instantiate.
* @return A newly intsantiated CaliObject.
* @throws caliException if class not found.
*/
public CaliObject instantiateObject(String Name) throws caliException {
if (this.classes.containsKey(Name)) {
Environment tenv = new Environment(this);
Members locals = new Members();
tenv.setEnvironment(this.mainClassInstance, locals, this.mainCallStack);
return (CaliObject) this.classes.get(Name).instantiate(tenv);
} else {
throw new caliException("Attempting to instantiate object of type '" + Name + "' but class not found!");
}
}
/**
* Sets the parse error flag. If set prior to run being called, run will
* throw an exception because of the parse error. This is called by the
* Cali parser generated from cali.cup.
*/
public void setParseError() {
this.hasParseErrors = true;
}
/**
* Obligatory toString method.
* @return A String representing the engine includes and classes.
*/
@Override
public String toString() {
String rstr = "";
rstr += "Parser loaded the following cali files ...\n";
for(int i = 0; i < this.includes.size(); i++) {
rstr += "INCLUDE={'" + this.includes.get(i) + "'}\n";
}
rstr += "\n";
rstr += "loadClassList found the following classes ...\n";
for(String className : this.classes.keySet()) {
rstr += "CLASS={" + className + "}\n";
rstr += this.classes.get(className).toString();
}
rstr += "\n";
return rstr;
}
}
|
9239f2e4afebefc6a5b580b954c55a10b8be5d26 | 2,380 | java | Java | sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ServiceEndpointPropertiesFormat.java | alexbuckgit/azure-sdk-for-java | 622f39c5b5dea4a26ffcf3d9ea0b46ae6b8e809a | [
"MIT"
] | 1 | 2022-01-08T06:43:30.000Z | 2022-01-08T06:43:30.000Z | sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ServiceEndpointPropertiesFormat.java | alexbuckgit/azure-sdk-for-java | 622f39c5b5dea4a26ffcf3d9ea0b46ae6b8e809a | [
"MIT"
] | null | null | null | sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ServiceEndpointPropertiesFormat.java | alexbuckgit/azure-sdk-for-java | 622f39c5b5dea4a26ffcf3d9ea0b46ae6b8e809a | [
"MIT"
] | null | null | null | 26.741573 | 99 | 0.660504 | 999,024 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The service endpoint properties. */
@Fluent
public final class ServiceEndpointPropertiesFormat {
/*
* The type of the endpoint service.
*/
@JsonProperty(value = "service")
private String service;
/*
* A list of locations.
*/
@JsonProperty(value = "locations")
private List<String> locations;
/*
* The provisioning state of the service endpoint resource.
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/**
* Get the service property: The type of the endpoint service.
*
* @return the service value.
*/
public String service() {
return this.service;
}
/**
* Set the service property: The type of the endpoint service.
*
* @param service the service value to set.
* @return the ServiceEndpointPropertiesFormat object itself.
*/
public ServiceEndpointPropertiesFormat withService(String service) {
this.service = service;
return this;
}
/**
* Get the locations property: A list of locations.
*
* @return the locations value.
*/
public List<String> locations() {
return this.locations;
}
/**
* Set the locations property: A list of locations.
*
* @param locations the locations value to set.
* @return the ServiceEndpointPropertiesFormat object itself.
*/
public ServiceEndpointPropertiesFormat withLocations(List<String> locations) {
this.locations = locations;
return this;
}
/**
* Get the provisioningState property: The provisioning state of the service endpoint resource.
*
* @return the provisioningState value.
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
9239f474db3408d1ca383588118099b2ec5dea8a | 669 | java | Java | jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/complex/Book.java | m-pavel/jpa2ddl | f3652bd9f4f95c5dfa1c02a95946f1ec3362bb17 | [
"Apache-2.0"
] | 103 | 2017-11-02T16:46:09.000Z | 2022-02-28T05:24:39.000Z | jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/complex/Book.java | m-pavel/jpa2ddl | f3652bd9f4f95c5dfa1c02a95946f1ec3362bb17 | [
"Apache-2.0"
] | 36 | 2017-10-23T11:26:31.000Z | 2022-03-25T02:02:12.000Z | jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/complex/Book.java | m-pavel/jpa2ddl | f3652bd9f4f95c5dfa1c02a95946f1ec3362bb17 | [
"Apache-2.0"
] | 36 | 2017-10-27T11:23:44.000Z | 2022-03-24T04:31:05.000Z | 23.892857 | 87 | 0.796712 | 999,025 | package com.devskiller.jpa2ddl.complex;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import java.util.HashSet;
import java.util.Set;
@Entity
class Book {
@Id
private Long id;
@ElementCollection
@JoinColumn
@OnDelete(action = OnDeleteAction.CASCADE)
@CollectionTable(indexes = {@Index(name = "fk_book_chapter", columnList = "book_id")})
public final Set<Chapter> chapters = new HashSet<>();
}
|
9239f4d40c873b9164f233c9fe9b7bd7a269133e | 956 | java | Java | modules/slack/src/main/java/com/spotify/apollo/slack/Slack.java | lukebelliveau/apollo | 913cae482efaea1106e32e67b008bc884c283d48 | [
"Apache-2.0"
] | null | null | null | modules/slack/src/main/java/com/spotify/apollo/slack/Slack.java | lukebelliveau/apollo | 913cae482efaea1106e32e67b008bc884c283d48 | [
"Apache-2.0"
] | 1 | 2021-05-03T15:43:01.000Z | 2021-05-03T15:43:01.000Z | modules/slack/src/main/java/com/spotify/apollo/slack/Slack.java | lukebelliveau/apollo | 913cae482efaea1106e32e67b008bc884c283d48 | [
"Apache-2.0"
] | null | null | null | 28.117647 | 75 | 0.700837 | 999,026 | /*
* -\-\-
* Spotify Apollo Slack Module
* --
* Copyright (C) 2013 - 2015 Spotify AB
* --
* 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.spotify.apollo.slack;
import java.io.Closeable;
public interface Slack extends Closeable {
/**
* Post a message to slack.
* @param message the message to post.
* @return {@code true} if the message was posted successfully.
*/
boolean post(String message);
}
|
9239f52d3e4cae71bb1e778a51c8d04ea1ad83d2 | 173 | java | Java | realm-transformer/src/main/templates/Version.java | cbush/realm-java | 93de40d513b9978dc8a0e28eedfca698ea5a760f | [
"Apache-2.0"
] | 10 | 2017-11-27T03:18:15.000Z | 2021-08-10T07:21:44.000Z | realm-transformer/src/main/templates/Version.java | cbush/realm-java | 93de40d513b9978dc8a0e28eedfca698ea5a760f | [
"Apache-2.0"
] | null | null | null | realm-transformer/src/main/templates/Version.java | cbush/realm-java | 93de40d513b9978dc8a0e28eedfca698ea5a760f | [
"Apache-2.0"
] | 10 | 2018-04-20T08:43:59.000Z | 2022-03-16T02:52:53.000Z | 24.714286 | 62 | 0.728324 | 999,027 | package io.realm.transformer;
public class Version {
public static final String VERSION = "@version@";
public static final String SYNC_VERSION = "@syncVersion@";
}
|
9239f5996ebab8837bba49613b6b9d33baf6f845 | 1,050 | java | Java | Dagger2Demo/app/src/main/java/com/example/clevo/dagger2demo/module/TotalModule.java | hexingbo/Android_Dome | 809442de1c3735668115507df37129d128a170aa | [
"Apache-2.0"
] | 666 | 2015-03-18T02:09:34.000Z | 2021-08-25T06:24:27.000Z | Dagger2Demo/app/src/main/java/com/example/clevo/dagger2demo/module/TotalModule.java | hexingbo/Android_Dome | 809442de1c3735668115507df37129d128a170aa | [
"Apache-2.0"
] | 7 | 2017-04-26T07:06:49.000Z | 2019-07-08T08:05:13.000Z | Dagger2Demo/app/src/main/java/com/example/clevo/dagger2demo/module/TotalModule.java | hexingbo/Android_Dome | 809442de1c3735668115507df37129d128a170aa | [
"Apache-2.0"
] | 371 | 2015-03-18T02:09:33.000Z | 2021-09-10T02:41:05.000Z | 21 | 58 | 0.682857 | 999,028 | package com.example.clevo.dagger2demo.module;
import com.example.clevo.dagger2demo.ScopeDemo;
import com.example.clevo.dagger2demo.ScopeDemo2;
import com.example.clevo.dagger2demo.interfaces.ForModel1;
import com.example.clevo.dagger2demo.interfaces.ForModel2;
import com.example.clevo.dagger2demo.model.ModelC;
import com.example.clevo.dagger2demo.model.ModelD;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
/**
* Created by Clevo on 2016/7/11.
*/
@Module
public class TotalModule {
int a;
int b;
public TotalModule(int a, int b) {
this.a=a;
this.b=b;
}
@ScopeDemo
@Provides
// @Named("ForModel1")
@ForModel1
public ModelD providesModelD1() {
return new ModelD(a, b);
}
@ScopeDemo2
@Provides
// @Named("ForModel2")
@ForModel2
public ModelD providesModelD2() {
return new ModelD(b, a);
}
@Provides
public ModelD providesModelD3(ModelC modelC) {
return new ModelD(modelC.getA(), modelC.getB());
}
}
|
9239f600f1dff2cf4c9ad4d724225e9e3d88f352 | 393 | java | Java | smart-system-core/src/main/java/org/jeecg/modules/wePower/smartPublicityProject/mapper/SmartPublicityProjectMapper.java | IM-Tse/smart-system-server | c5f8f0498e7a8a8b6b0afbd588bfc3334074cc9a | [
"MIT"
] | null | null | null | smart-system-core/src/main/java/org/jeecg/modules/wePower/smartPublicityProject/mapper/SmartPublicityProjectMapper.java | IM-Tse/smart-system-server | c5f8f0498e7a8a8b6b0afbd588bfc3334074cc9a | [
"MIT"
] | 5 | 2021-11-11T09:10:52.000Z | 2021-12-14T10:49:28.000Z | smart-system-core/src/main/java/org/jeecg/modules/wePower/smartPublicityProject/mapper/SmartPublicityProjectMapper.java | IM-Tse/smart-system-server | c5f8f0498e7a8a8b6b0afbd588bfc3334074cc9a | [
"MIT"
] | 21 | 2021-11-01T04:26:39.000Z | 2022-03-11T02:13:27.000Z | 26.2 | 88 | 0.793893 | 999,029 | package org.jeecg.modules.wePower.smartPublicityProject.mapper;
import org.jeecg.modules.wePower.smartPublicityProject.entity.SmartPublicityProject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @Description: 项目管理
* @Author: jeecg-boot
* @Date: 2022-03-09
* @Version: V1.0
*/
public interface SmartPublicityProjectMapper extends BaseMapper<SmartPublicityProject> {
}
|
9239f65d34ec67ef6fd92ae1c1d27c0b60d0415a | 461 | java | Java | distributed-transaction-support/dtx-common/src/main/java/rabbit/open/dtx/common/exception/DeadLockException.java | RabbitOpen/RabbitORM2 | c447e2c2f4545826288b61be02c7b6e0467fef77 | [
"Apache-2.0"
] | 21 | 2017-12-11T03:15:27.000Z | 2019-10-21T10:24:34.000Z | distributed-transaction-support/dtx-common/src/main/java/rabbit/open/dtx/common/exception/DeadLockException.java | RabbitOpen/RabbitORM2 | c447e2c2f4545826288b61be02c7b6e0467fef77 | [
"Apache-2.0"
] | 3 | 2019-12-21T16:20:57.000Z | 2022-03-31T19:54:52.000Z | distributed-transaction-support/dtx-common/src/main/java/rabbit/open/dtx/common/exception/DeadLockException.java | RabbitOpen/RabbitORM2 | c447e2c2f4545826288b61be02c7b6e0467fef77 | [
"Apache-2.0"
] | 3 | 2019-05-15T06:21:17.000Z | 2019-08-06T09:41:09.000Z | 28.8125 | 116 | 0.700651 | 999,030 | package rabbit.open.dtx.common.exception;
/**
* DTX死锁异常, 不同的分支尝试获取同一个资源
* @author xiaoqianbin
* @date 2019/12/4
**/
@SuppressWarnings("serial")
public class DeadLockException extends DtxException {
public DeadLockException(Long lockBranch, Long currentBranch, String lock) {
super(String.format("dead lock is detected! branch[%s] tried to hold lock[%s] which was hold by branch[%s]",
currentBranch, lock, lockBranch));
}
}
|
9239f69ad9830c59e756bbcd62902a53ddda6469 | 2,176 | java | Java | src/main/java/net/gliby/voicechat/common/networking/voiceservers/MinecraftVoiceServer.java | GameModsBR/VoiceChat | dbcc5d22d24e7068b6fd0f0ac72d577e1fd99045 | [
"Apache-2.0",
"Unlicense"
] | 19 | 2017-04-16T18:28:57.000Z | 2021-03-02T15:16:32.000Z | src/main/java/net/gliby/voicechat/common/networking/voiceservers/MinecraftVoiceServer.java | sekwah41/VoiceChat | d80d11d71f66f3b5af51a89123cc1f912294e403 | [
"Apache-2.0",
"Unlicense"
] | 21 | 2017-01-01T21:07:22.000Z | 2018-08-13T16:37:37.000Z | src/main/java/net/gliby/voicechat/common/networking/voiceservers/MinecraftVoiceServer.java | sekwah41/VoiceChat | d80d11d71f66f3b5af51a89123cc1f912294e403 | [
"Apache-2.0",
"Unlicense"
] | 19 | 2017-02-22T14:10:35.000Z | 2019-10-15T18:33:17.000Z | 36.881356 | 131 | 0.747702 | 999,031 | package net.gliby.voicechat.common.networking.voiceservers;
import net.gliby.voicechat.VoiceChat;
import net.gliby.voicechat.common.VoiceChatServer;
import net.gliby.voicechat.common.networking.packets.MinecraftClientEntityPositionPacket;
import net.gliby.voicechat.common.networking.packets.MinecraftClientVoiceEndPacket;
import net.gliby.voicechat.common.networking.packets.MinecraftClientVoicePacket;
import net.minecraft.entity.player.EntityPlayerMP;
public class MinecraftVoiceServer extends VoiceServer {
private final VoiceChatServer voiceChat;
public MinecraftVoiceServer(VoiceChatServer voiceChat) {
this.voiceChat = voiceChat;
}
@Override
public EnumVoiceNetworkType getType() {
return EnumVoiceNetworkType.MINECRAFT;
}
@Override
public void handleVoiceData(EntityPlayerMP player, byte[] data, byte divider, int id, boolean end) {
this.voiceChat.getServerNetwork().getDataManager().addQueue(player, data, divider, id, end);
}
@Override
public void sendChunkVoiceData(EntityPlayerMP player, int entityID, boolean direct, byte[] samples, byte chunkSize) {
VoiceChat.getDispatcher().sendTo(new MinecraftClientVoicePacket(chunkSize, samples, entityID, direct), player);
}
@Override
public void sendEntityPosition(EntityPlayerMP player, int entityID, double x, double y, double z) {
VoiceChat.getDispatcher().sendTo(new MinecraftClientEntityPositionPacket(entityID, x, y, z), player);
}
@Override
public void sendVoiceData(EntityPlayerMP player, int entityID, boolean direct, byte[] samples) {
VoiceChat.getDispatcher().sendTo(new MinecraftClientVoicePacket((byte) samples.length, samples, entityID, direct), player);
}
@Override
public void sendVoiceEnd(EntityPlayerMP player, int id) {
VoiceChat.getDispatcher().sendTo(new MinecraftClientVoiceEndPacket(id), player);
}
@Override
public boolean start() {
VoiceChatServer.getLogger().warn("Minecraft Networking is not recommended and is consider very slow, please setup UDP.");
return true;
}
@Override
public void stop() {
}
}
|
9239f84bcf4a1c97abdafd71c76b53f9fdd4b37d | 1,607 | java | Java | spring-cloud-deployer-resource-docker/src/test/java/org/springframework/cloud/deployer/resource/docker/DockerResourceTests.java | zjsun/spring-cloud-deployer | d758f5a6f816bb2a6d0f6adccde2e6d9c6fa4292 | [
"Apache-2.0"
] | 146 | 2016-02-29T16:25:18.000Z | 2022-03-22T20:13:23.000Z | spring-cloud-deployer-resource-docker/src/test/java/org/springframework/cloud/deployer/resource/docker/DockerResourceTests.java | zjsun/spring-cloud-deployer | d758f5a6f816bb2a6d0f6adccde2e6d9c6fa4292 | [
"Apache-2.0"
] | 295 | 2016-03-04T13:31:12.000Z | 2022-03-29T15:12:27.000Z | spring-cloud-deployer-resource-docker/src/test/java/org/springframework/cloud/deployer/resource/docker/DockerResourceTests.java | zjsun/spring-cloud-deployer | d758f5a6f816bb2a6d0f6adccde2e6d9c6fa4292 | [
"Apache-2.0"
] | 80 | 2016-02-29T16:02:57.000Z | 2022-03-10T15:21:17.000Z | 30.320755 | 93 | 0.7542 | 999,032 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.deployer.resource.docker;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests for the {@link DockerResource}.
*
* @author Thomas Risberg
*/
public class DockerResourceTests {
String image = "sringcloud/hello-kube:latest";
@Test
public void testResource() throws IOException, URISyntaxException {
DockerResource r = new DockerResource(image);
assertEquals(image, r.getURI().getSchemeSpecificPart());
}
@Test
public void testUri() throws IOException, URISyntaxException {
DockerResource r = new DockerResource(URI.create(DockerResource.URI_SCHEME + ":" + image));
assertEquals(image, r.getURI().getSchemeSpecificPart());
}
@Test(expected=IllegalArgumentException.class)
public void testInvalidUri() throws IOException, URISyntaxException {
DockerResource r = new DockerResource(URI.create("http:" + image));
}
}
|
9239f8ccbe3b0c0b7f229f7c77dffa492e534658 | 2,035 | java | Java | src/main/java/example/auth/MyAccessDeniedHandler.java | bati11/study-springboot | 6ac2ae2c86068549b4ba4bd1e516e23cc3ae0c4a | [
"MIT"
] | null | null | null | src/main/java/example/auth/MyAccessDeniedHandler.java | bati11/study-springboot | 6ac2ae2c86068549b4ba4bd1e516e23cc3ae0c4a | [
"MIT"
] | null | null | null | src/main/java/example/auth/MyAccessDeniedHandler.java | bati11/study-springboot | 6ac2ae2c86068549b4ba4bd1e516e23cc3ae0c4a | [
"MIT"
] | null | null | null | 39.134615 | 164 | 0.759214 | 999,033 | package example.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.CsrfException;
import org.springframework.stereotype.Component;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class MyAccessDeniedHandler extends AccessDeniedHandlerImpl {
private static String ERROR_PAGE = "/access-denied";
private SessionHelper sessionHelper;
private ForwardingUrl forwardingUrl;
public MyAccessDeniedHandler(SessionHelper sessionHelper, ForwardingUrl forwardingUrl) {
super();
this.sessionHelper = sessionHelper;
this.forwardingUrl = forwardingUrl;
this.setErrorPage(ERROR_PAGE);
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException instanceof CsrfException || accessDeniedException instanceof AuthorizationServiceException) {
super.handle(request, response, accessDeniedException);
} else {
request.setAttribute(WebAttributes.ACCESS_DENIED_403,
accessDeniedException);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
String rootPage = sessionHelper.currentAccount()
.map(loginAccount -> "/users/" + loginAccount.getUserId())
.orElse(ERROR_PAGE);
RequestDispatcher dispatcher = request.getRequestDispatcher(rootPage);
dispatcher.forward(request, response);
}
}
}
|
9239f8d30c73c5fce152d164c50291c6c9813340 | 543 | java | Java | features/mtwilson-flavor-model/src/main/java/com/intel/mtwilson/flavor/model/HostTrustStatus.java | intel-secl/verification-service | e86f134f3c693590e5e12e69a76f65d5f00b932b | [
"BSD-3-Clause"
] | 3 | 2019-10-19T13:10:57.000Z | 2020-10-16T07:07:07.000Z | features/mtwilson-flavor-model/src/main/java/com/intel/mtwilson/flavor/model/HostTrustStatus.java | intel-secl/verification-service | e86f134f3c693590e5e12e69a76f65d5f00b932b | [
"BSD-3-Clause"
] | 2 | 2020-06-11T13:52:21.000Z | 2021-02-03T19:31:39.000Z | features/mtwilson-flavor-model/src/main/java/com/intel/mtwilson/flavor/model/HostTrustStatus.java | intel-secl/verification-service | e86f134f3c693590e5e12e69a76f65d5f00b932b | [
"BSD-3-Clause"
] | 3 | 2019-10-19T13:11:07.000Z | 2021-03-03T03:23:26.000Z | 19.392857 | 62 | 0.697974 | 999,034 | /*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.mtwilson.flavor.model;
public class HostTrustStatus {
public TrustInformation trustStatus;
public HostTrustStatus() {
}
public HostTrustStatus(TrustInformation trustStatus) {
this.trustStatus = trustStatus;
}
public TrustInformation getTrustStatus() {
return trustStatus;
}
public void setTrustStatus(TrustInformation trustStatus) {
this.trustStatus = trustStatus;
}
}
|
9239f997dfd1ecb7cad298769f9732263bd2da5a | 941 | java | Java | src/main/java/stream/flarebot/flarebot/util/objects/ApiRoute.java | Sculas/FlareBot | 83623a85d005d3addfa6bc7010b51e752e79de9b | [
"MIT"
] | 49 | 2017-01-13T14:53:23.000Z | 2021-12-20T21:05:28.000Z | src/main/java/stream/flarebot/flarebot/util/objects/ApiRoute.java | Tominous/FlareBot | c2e9ec000e79adfa0cf2a1e58707dc22f707be55 | [
"MIT"
] | 90 | 2017-01-27T15:04:52.000Z | 2018-04-05T12:49:57.000Z | src/main/java/stream/flarebot/flarebot/util/objects/ApiRoute.java | Tominous/FlareBot | c2e9ec000e79adfa0cf2a1e58707dc22f707be55 | [
"MIT"
] | 70 | 2017-01-16T15:35:21.000Z | 2022-01-04T11:57:06.000Z | 26.885714 | 159 | 0.611052 | 999,035 | package stream.flarebot.flarebot.util.objects;
import org.apache.commons.lang3.StringUtils;
public class ApiRoute {
private String url;
private int params;
public String getUrl() {
return url;
}
public int getParams() {
return params;
}
public ApiRoute(String url) {
int open = StringUtils.countMatches(url, "{");
if (open != StringUtils.countMatches(url, "}")) {
throw new IllegalArgumentException("Number of { does not match number of }");
}
this.url = url.replaceAll("\\{.*?}", "%s");
this.params = open;
}
public String getCompiledUrl(String... params) {
if (this.params != params.length) {
throw new IllegalArgumentException(String.format("Number of params given (%d) does not match required amount (%d) !", params.length, this.params));
}
return String.format(this.url, params);
}
}
|
9239f9e2ecab7bb454689ecbaf2923b8e016f12f | 1,289 | java | Java | spark-bigquery-dsv2/spark-2.4-bigquery/src/main/java/com/google/cloud/spark/bigquery/v2/Spark24InputPartitionReader.java | nivaldoh/spark-bigquery-connector | 6031228d8652174b50395406018d754ec781d156 | [
"Apache-2.0"
] | 63 | 2019-03-07T01:42:40.000Z | 2020-01-15T16:33:28.000Z | spark-bigquery-dsv2/spark-2.4-bigquery/src/main/java/com/google/cloud/spark/bigquery/v2/Spark24InputPartitionReader.java | nivaldoh/spark-bigquery-connector | 6031228d8652174b50395406018d754ec781d156 | [
"Apache-2.0"
] | 73 | 2019-03-14T19:43:56.000Z | 2020-01-15T18:44:46.000Z | spark-bigquery-dsv2/spark-2.4-bigquery/src/main/java/com/google/cloud/spark/bigquery/v2/Spark24InputPartitionReader.java | nivaldoh/spark-bigquery-connector | 6031228d8652174b50395406018d754ec781d156 | [
"Apache-2.0"
] | 36 | 2019-03-15T00:25:40.000Z | 2020-01-15T11:06:24.000Z | 28.644444 | 78 | 0.746315 | 999,036 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spark.bigquery.v2;
import com.google.cloud.spark.bigquery.v2.context.InputPartitionReaderContext;
import java.io.IOException;
import org.apache.spark.sql.sources.v2.reader.InputPartitionReader;
class Spark24InputPartitionReader<T> implements InputPartitionReader<T> {
private InputPartitionReaderContext<T> context;
public Spark24InputPartitionReader(InputPartitionReaderContext<T> context) {
this.context = context;
}
@Override
public boolean next() throws IOException {
return context.next();
}
@Override
public T get() {
return context.get();
}
@Override
public void close() throws IOException {
context.close();
}
}
|
9239faa0c21736ceb83808d745e4032dae575b6f | 3,142 | java | Java | actionbar/src/com/contec/FragmentTabs.java | ruixuekaifa/android--Demos | 4191901c70fdfe17a5b81416f4f34c175eb56faf | [
"Apache-2.0"
] | 4 | 2018-04-19T06:26:56.000Z | 2021-05-02T13:45:57.000Z | actionbar/src/com/contec/FragmentTabs.java | ruixuekaifa/android--Demos | 4191901c70fdfe17a5b81416f4f34c175eb56faf | [
"Apache-2.0"
] | null | null | null | actionbar/src/com/contec/FragmentTabs.java | ruixuekaifa/android--Demos | 4191901c70fdfe17a5b81416f4f34c175eb56faf | [
"Apache-2.0"
] | 4 | 2015-07-31T10:03:17.000Z | 2017-05-18T13:26:50.000Z | 34.527473 | 92 | 0.610757 | 999,037 | package com.contec;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;
/**
* This demonstrates the use of action bar tabs and how they interact
* with other action bar features.
*/
public class FragmentTabs extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
// bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
bar.addTab(bar.newTab()
.setText("Simple"));
bar.addTab(bar.newTab()
.setText("Contacts"));
bar.addTab(bar.newTab()
.setText("Apps"));
bar.addTab(bar.newTab()
.setText("Throttle"));
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
/*public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public TabListener(Activity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
// if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
// ft.detach(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
}
}*/
} |
9239fb73f2e3a80d58238d8213345e54dfe53149 | 1,323 | java | Java | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/oa/wedrive/WxCpSpaceSettingRequest.java | hallkk/WxJava | 4de09fa5656e51ee2215d85d2d04af5b7a900b5c | [
"Apache-2.0"
] | 2 | 2022-01-27T15:22:25.000Z | 2022-01-28T01:12:40.000Z | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/oa/wedrive/WxCpSpaceSettingRequest.java | hallkk/WxJava | 4de09fa5656e51ee2215d85d2d04af5b7a900b5c | [
"Apache-2.0"
] | null | null | null | weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/oa/wedrive/WxCpSpaceSettingRequest.java | hallkk/WxJava | 4de09fa5656e51ee2215d85d2d04af5b7a900b5c | [
"Apache-2.0"
] | 2 | 2022-01-27T15:22:36.000Z | 2022-01-28T01:12:44.000Z | 24.5 | 82 | 0.79743 | 999,038 | package me.chanjar.weixin.cp.bean.oa.wedrive;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
/**
* 权限管理请求.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class WxCpSpaceSettingRequest implements Serializable {
private static final long serialVersionUID = -4960239393895754138L;
@SerializedName("userid")
private String userId;
@SerializedName("spaceid")
private String spaceId;
@SerializedName("enable_watermark")
private Boolean enableWatermark;
@SerializedName("add_member_only_admin")
private Boolean addMemberOnlyAdmin;
@SerializedName("enable_share_url")
private Boolean enableShareUrl;
@SerializedName("share_url_no_approve")
private Boolean shareUrlNoApprove;
@SerializedName("share_url_no_approve_default_auth")
private Integer shareUrlNoApproveDefaultAuth;
public static WxCpSpaceSettingRequest fromJson(String json) {
return WxCpGsonBuilder.create().fromJson(json, WxCpSpaceSettingRequest.class);
}
public String toJson() {
return WxCpGsonBuilder.create().toJson(this);
}
}
|
9239fe34c08586523a5324b7c574e79ea3955edc | 10,731 | java | Java | app/src/main/java/im/qq/com/im/controller/fragment/ContactListFragment.java | tiankonglong/IM | 654640cfe8fa2117953944aa35fb90c563fac2a9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/im/qq/com/im/controller/fragment/ContactListFragment.java | tiankonglong/IM | 654640cfe8fa2117953944aa35fb90c563fac2a9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/im/qq/com/im/controller/fragment/ContactListFragment.java | tiankonglong/IM | 654640cfe8fa2117953944aa35fb90c563fac2a9 | [
"Apache-2.0"
] | null | null | null | 32.128743 | 109 | 0.571056 | 999,039 | package im.qq.com.im.controller.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import im.qq.com.im.LoginActivity;
import im.qq.com.im.R;
import im.qq.com.im.controller.activity.AddContactActivity;
import im.qq.com.im.controller.activity.ChatActivity;
import im.qq.com.im.controller.activity.GroupListActivity;
import im.qq.com.im.controller.activity.InvitationActivity;
import im.qq.com.im.model.bean.UserInfo;
import im.qq.com.im.model.db.Model;
import im.qq.com.im.utils.Constant;
import im.qq.com.im.utils.SpUtils;
/**
* Created by asdf on 2017/12/14.
*/
/*从环信服务器获取联系人信息:
思路:进入ContactListFragment,进入setUpView方法,创建getContactFromHxServer().
获取到所有联系人的id,检验,转换数据,保存好友的本地数据库,刷新页面。
代码剖析:
1.我们是要从环信服务器获取信息,所以必须开启一个线程
2.获取所有好友的环信id
3.校验是否为空
4.转换数据,因为环信那边只能拿到id,我们这边数据存储是存整个用户对象
5.把用户列表存储到本地数据库
6.刷新页面,刷新之前先判断getActivity是否为空,防止页面切换的时候,报空指针*/
public class ContactListFragment extends EaseContactListFragment{
private ImageView iv_contact_red;
private LinearLayout ll_contact_invite;
private LocalBroadcastManager mLBM;
private String mHxid;
private BroadcastReceiver ContactInviteChangeReceive = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//更新红点
iv_contact_red.setVisibility(View.VISIBLE);
SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true);
}
};
private BroadcastReceiver ContactChangReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//刷新页面
refreshContact();
}
};
private BroadcastReceiver GroupChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//更新红点
iv_contact_red.setVisibility(View.VISIBLE);
SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, true);
}
};
//从环信服务器获取所有的联系人信息
private void getContactFromHxServer() {
Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
//获取到所有的好友的环信的id
List<String> hxids = EMClient.getInstance().contactManager().getAllContactsFromServer();
//校验
if (hxids != null && hxids.size() >= 0) {
List<UserInfo> contacts = new ArrayList<UserInfo>();
//转换
for (String hxid : hxids) {
UserInfo userInfo = new UserInfo(hxid);
contacts.add(userInfo);
}
//保存好友信息到本地数据库
Model.getInstance().getDbManager().getContactTableDao().savaContacts(contacts,true);
//判断getActivity是否为空,防止页面切换的时候,报空指针
if (getActivity() == null) {
return;
}
//刷新页面
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
refreshContact();
}
});
}
} catch (HyphenateException e) {
e.printStackTrace();
}
}
});
}
//刷新页面
private void refreshContact() {
//获取数据
List<UserInfo> contacts = Model.getInstance().getDbManager().getContactTableDao().getContacts();
//校验
if (contacts != null && contacts.size() >= 0) {
//设置数据,环信已经给我们做了刷新方法
Map<String, EaseUser> contactsMap = new HashMap<>();
//转换
for (UserInfo contact : contacts) {
EaseUser easeUser = new EaseUser(contact.getHxid());
contactsMap.put(contact.getHxid(), easeUser);
}
setContactsMap(contactsMap);
//刷新页面
refresh();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
//获取环信id
int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
EaseUser easeUser = (EaseUser) listView.getItemAtPosition(position);
mHxid = easeUser.getUsername();
//添加布局
getActivity().getMenuInflater().inflate(R.menu.delete, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.contact_delett) {
//执行删除选中的联系人操作
deleteContact();
return true;
}
return super.onContextItemSelected(item);
}
//执行删除选中的联系人操作
private void deleteContact() {
Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
//从环信服务器中删除联系人
EMClient.getInstance().contactManager().deleteContact(mHxid);
//本地数据库的更新
Model.getInstance().getDbManager().getContactTableDao().deleteContactByHxId(mHxid);
if (getActivity() == null) {
return;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// toast提示
Toast.makeText(getActivity(), "删除" + mHxid + "成功", Toast.LENGTH_SHORT).show();
//刷新页面
refreshContact();
}
});
} catch (HyphenateException e) {
e.printStackTrace();
if (getActivity() == null) {
return;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//提示
Toast.makeText(getActivity(),"删除" + mHxid + "失败", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
@Override
protected void setUpView() {
super.setUpView();
//注册广播
mLBM = LocalBroadcastManager.getInstance(getActivity());
mLBM.registerReceiver(ContactInviteChangeReceive, new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
mLBM.registerReceiver(ContactChangReceiver, new IntentFilter(Constant.CONTACT_CHANGED));
mLBM.registerReceiver(GroupChangeReceiver, new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
titleBar.setRightLayoutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddContactActivity.class);
startActivity(intent);
//getActivity().finish();
}
});
//邀请信息条目的点击事件
ll_contact_invite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//红点的处理
iv_contact_red.setVisibility(View.GONE);
SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE, false);
//跳转到邀请信息列表页面
Intent intent = new Intent(getActivity(), InvitationActivity.class);
startActivity(intent);
}
});
//初始化红点显示
boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);
iv_contact_red.setVisibility(isNewInvite? View.VISIBLE: View.GONE);
//从环信服务器获取所有的联系人信息
getContactFromHxServer();
//绑定listview和contextmenu
registerForContextMenu(listView);
}
@Override
public void onDestroy() {
super.onDestroy();
mLBM.unregisterReceiver(ContactInviteChangeReceive);
mLBM.unregisterReceiver(ContactChangReceiver);
mLBM.unregisterReceiver(GroupChangeReceiver);
}
@Override
protected void initView() {
super.initView();
//布局显示加号
titleBar.setRightImageResource(R.drawable.em_add);
titleBar.setTitle("通讯录");
//添加头布局
View headerView = View.inflate(getActivity(),R.layout.header_fragment_contact,null);
listView.addHeaderView(headerView);
//获取红点对象
iv_contact_red = (ImageView) headerView.findViewById(R.id.iv_contact_red);
//获取邀请信息条目的对象
ll_contact_invite = (LinearLayout) headerView.findViewById(R.id.ll_contact_invite);
//跳转到群组列表页面
LinearLayout ll_contact_group = (LinearLayout) headerView.findViewById(R.id.ll_contact_group);
ll_contact_group.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), GroupListActivity.class);
startActivity(intent);
}
});
//设置listview条目的点击事件
setContactListItemClickListener(new EaseContactListItemClickListener() {
@Override
public void onListItemClicked(EaseUser user) {
if (user == null) {
return;
}
Intent intent = new Intent(getActivity(), ChatActivity.class);
//传递参数
intent.putExtra(EaseConstant.EXTRA_USER_ID, user.getUsername());
startActivity(intent);
}
});
}
}
|
9239ff5f00436c4eb9def840f52578a1b95639e6 | 6,008 | java | Java | rtmppublisher/src/main/java/com/takusemba/rtmppublisher/AudioPlayerHandler.java | hitgou/RtmpPublisher | 8bd1e473040bd09ced6cf4195d10a442738f3c41 | [
"Apache-2.0"
] | null | null | null | rtmppublisher/src/main/java/com/takusemba/rtmppublisher/AudioPlayerHandler.java | hitgou/RtmpPublisher | 8bd1e473040bd09ced6cf4195d10a442738f3c41 | [
"Apache-2.0"
] | null | null | null | rtmppublisher/src/main/java/com/takusemba/rtmppublisher/AudioPlayerHandler.java | hitgou/RtmpPublisher | 8bd1e473040bd09ced6cf4195d10a442738f3c41 | [
"Apache-2.0"
] | null | null | null | 32.301075 | 131 | 0.588382 | 999,040 | package com.takusemba.rtmppublisher;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;
import com.today.im.opus.OpusUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.Semaphore;
/**
* 实时音频播放处理类<br/>
* 使用示例代码如下:<br/>
*
* <pre>
* audioPlayerHandler = new AudioPlayerHandler();
* audioPlayerHandler.prepare();// 播放前需要prepare。可以重复prepare
* // 直接将需要播放的数据传入即可
* audioPlayerHandler.onPlaying(data, 0, data.length);
* </pre>
*
* @author
*/
public class AudioPlayerHandler implements Runnable {
private final static String TAG = "AudioPlayerHandler";
private AudioTrack audioTrack = null;// 录音文件播放对象
private boolean isPlaying = false;// 标记是否正在录音中
private int bufferSize = -1;// 播放缓冲大小
private LinkedBlockingDeque<Object> dataQueue = new LinkedBlockingDeque<>();
// 互斥信号量
private Semaphore semaphore = new Semaphore(1);
// 是否释放资源的标志位
private boolean release = false;
private AudioManager audioManager;
private int sessionId;
private AudioAttributes audioAttributes = new AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_MUSIC).build();
private AudioFormat audioFormat = new AudioFormat.Builder().setEncoding(AudioFormat.ENCODING_PCM_16BIT).
setSampleRate(AudioRecorder.SAMPLE_RATE).setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build();
public AudioPlayerHandler(AudioManager audioManager) {
try {
this.audioManager = audioManager;
this.sessionId = audioManager.generateAudioSessionId();
// 获取缓冲 大小
bufferSize = AudioTrack.getMinBufferSize(AudioRecorder.SAMPLE_RATE, AudioRecorder.CHANNEL_OUT_MONO,
AudioRecorder.AUDIO_FORMAT);
// 实例AudioTrack
// audioTrack = new AudioTrack(audioAttributes, audioFormat, bufferSize, AudioTrack.MODE_STREAM, sessionId);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, AudioRecorder.SAMPLE_RATE,
AudioRecorder.CHANNEL_OUT_MONO, AudioRecorder.AUDIO_FORMAT, bufferSize,
AudioTrack.MODE_STREAM);
// audioTrack.setStereoVolume(AudioTrack.getMaxVolume(), AudioTrack.getMaxVolume());
// 默认需要抢占一个信号量。防止播放进程执行
// semaphore.acquire();
// 开启播放线程
new Thread(this).start();
} catch (Exception e) {
Log.e(TAG, "启动播放出错", e);
e.printStackTrace();
}
}
/**
* 播放,当有新数据传入时, 1,2,3
*
* @param data 语音byte数组
* @param startIndex 开始的偏移量
* @param length 数据长度
*/
public synchronized void onPlaying(byte[] data, int startIndex, int length) {
if (AudioTrack.ERROR_BAD_VALUE == bufferSize) {// 初始化错误
return;
}
try {
byte[] newData = Arrays.copyOfRange(data, 1, data.length);
dataQueue.putLast(newData);
// semaphore.release();
} catch (InterruptedException e) {
Log.e(TAG, "启动播放出错", e);
e.printStackTrace();
}
}
/**
* 准备播放
*/
public void prepare() {
if (audioTrack != null && !isPlaying) {
audioTrack.play();
}
isPlaying = true;
}
/**
* 停止播放
*/
public void stop() {
if (audioTrack != null) {
audioTrack.stop();
}
isPlaying = false;
}
/**
* 释放资源
*/
public void release() {
release = true;
isPlaying = false;
// semaphore.release();
if (audioTrack != null) {
audioTrack.release();
audioTrack = null;
}
}
@Override
public void run() {
final OpusUtils opusUtils = new OpusUtils();
final Long createDecoder = opusUtils.createDecoder(AudioRecorder.SAMPLE_RATE, AudioRecorder.CHANEL_IN_OPUS);
byte[] bufferArray = new byte[80];
File file = new File(AudioRecorder.recorderPcmFilePath);
File fileDir = file.getParentFile();
if (!fileDir.exists()) {
fileDir.mkdirs();
}
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
BufferedOutputStream fileOpusBufferedOutputStream = new BufferedOutputStream(fileOutputStream);
while (isPlaying) {
if (dataQueue.size() > 0) {
byte[] data = (byte[]) dataQueue.pollFirst();
fileOpusBufferedOutputStream.write(data);//写入OPUS
audioTrack.write(data, 0, data.length);
// short[] decodeBufferArray = new short[bufferArray.length * 4];
// int size = opusUtils.decode(createDecoder, data, decodeBufferArray);
// if (size > 0) {
// short[] decodeArray = new short[size];
// System.arraycopy(decodeBufferArray, 0, decodeArray, 0, size);
// audioTrack.write(decodeArray, 0, decodeArray.length);
// }
} else {
try {
Thread.sleep(10);
// semaphore.acquire();
} catch (InterruptedException e) {
Log.e(TAG, "启动播放出错", e);
e.printStackTrace();
}
}
}
Log.e(TAG, "播放结束");
fileOpusBufferedOutputStream.close();
fileOutputStream.close();
opusUtils.destroyEncoder(createDecoder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
9239ff9120a68eb3f5ce540dbfbc16edf16d8c2d | 8,173 | java | Java | resource/src/main/java/org/jboss/gravia/resource/spi/AbstractResourceStore.java | tdiesler/gravia | 6a77d5894e96303270626d4f3aa61b8226c176c0 | [
"Apache-2.0"
] | 2 | 2016-02-04T09:15:33.000Z | 2016-02-16T10:27:03.000Z | resource/src/main/java/org/jboss/gravia/resource/spi/AbstractResourceStore.java | tdiesler/gravia | 6a77d5894e96303270626d4f3aa61b8226c176c0 | [
"Apache-2.0"
] | 10 | 2015-07-24T09:23:44.000Z | 2015-12-09T18:07:54.000Z | resource/src/main/java/org/jboss/gravia/resource/spi/AbstractResourceStore.java | tdiesler/gravia | 6a77d5894e96303270626d4f3aa61b8226c176c0 | [
"Apache-2.0"
] | null | null | null | 32.078431 | 133 | 0.59621 | 999,041 | /*
* #%L
* Gravia :: Resource
* %%
* Copyright (C) 2010 - 2014 JBoss by Red Hat
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.jboss.gravia.resource.spi;
import static org.jboss.gravia.resource.spi.ResourceLogger.LOGGER;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.gravia.resource.Capability;
import org.jboss.gravia.resource.MatchPolicy;
import org.jboss.gravia.resource.Requirement;
import org.jboss.gravia.resource.Resource;
import org.jboss.gravia.resource.ResourceIdentity;
import org.jboss.gravia.resource.ResourceStore;
import org.jboss.gravia.utils.IllegalArgumentAssertion;
/**
* An abstract {@link ResourceStore}
*
* @author upchh@example.com
* @since 02-Jul-2010
*/
public abstract class AbstractResourceStore implements ResourceStore {
private final String storeName;
private final Map<ResourceIdentity, Resource> resources = new LinkedHashMap<ResourceIdentity, Resource>();
private final Map<CacheKey, Set<Capability>> capabilityCache = new ConcurrentHashMap<CacheKey, Set<Capability>>();
private final MatchPolicy matchPolicy;
public AbstractResourceStore(String storeName, MatchPolicy matchPolicy) {
IllegalArgumentAssertion.assertNotNull(storeName, "storeName");
IllegalArgumentAssertion.assertNotNull(matchPolicy, "matchPolicy");
this.storeName = storeName;
this.matchPolicy = matchPolicy;
}
@Override
public String getName() {
return storeName;
}
@Override
public MatchPolicy getMatchPolicy() {
return matchPolicy;
}
@Override
public Iterator<Resource> getResources() {
final Iterator<Resource> itres;
synchronized (resources) {
Set<Resource> snapshot = new LinkedHashSet<Resource>(resources.values());
itres = snapshot.iterator();
}
return new Iterator<Resource>() {
@Override
public boolean hasNext() {
synchronized (resources) {
return itres.hasNext();
}
}
@Override
public Resource next() {
synchronized (resources) {
return itres.next();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public Resource addResource(Resource res) {
synchronized (resources) {
if (getResourceInternal(res.getIdentity()) != null)
throw new IllegalArgumentException("Resource already added: " + res);
LOGGER.debug("Add to {}: {}", storeName, res);
// Add resource capabilites
for (Capability cap : res.getCapabilities(null)) {
CacheKey cachekey = CacheKey.create(cap);
getCachedCapabilities(cachekey).add(cap);
}
// Log cap/req details
if (LOGGER.isDebugEnabled()) {
for (Capability cap : res.getCapabilities(null)) {
LOGGER.debug(" {}", cap);
}
for (Requirement req : res.getRequirements(null)) {
LOGGER.debug(" {}", req);
}
}
resources.put(res.getIdentity(), res);
return res;
}
}
@Override
public Resource removeResource(ResourceIdentity resid) {
synchronized (resources) {
Resource res = resources.remove(resid);
if (res != null) {
LOGGER.debug("Remove from {}: {}", storeName, res);
// Remove resource capabilities
for (Capability cap : res.getCapabilities(null)) {
CacheKey cachekey = CacheKey.create(cap);
Set<Capability> cachecaps = getCachedCapabilities(cachekey);
cachecaps.remove(cap);
if (cachecaps.isEmpty()) {
capabilityCache.remove(cachekey);
}
}
}
return res;
}
}
@Override
public Resource getResource(ResourceIdentity resid) {
return getResourceInternal(resid);
}
private Resource getResourceInternal(ResourceIdentity resid) {
synchronized (resources) {
return resources.get(resid);
}
}
@Override
public Set<Capability> findProviders(Requirement req) {
CacheKey cachekey = CacheKey.create(req);
Set<Capability> result = new HashSet<Capability>();
for (Capability cap : findCachedCapabilities(cachekey)) {
if (matchPolicy.match(cap, req)) {
result.add(cap);
}
}
return Collections.unmodifiableSet(result);
}
private synchronized Set<Capability> getCachedCapabilities(CacheKey key) {
Set<Capability> capset = capabilityCache.get(key);
if (capset == null) {
capset = new LinkedHashSet<Capability>();
capabilityCache.put(key, capset);
}
return capset;
}
private synchronized Set<Capability> findCachedCapabilities(CacheKey key) {
Set<Capability> capset = capabilityCache.get(key);
if (capset == null) {
capset = new LinkedHashSet<Capability>();
// do not add this to the capabilityCache
}
if (capset.isEmpty() && (key.value == null)) {
for (Entry<CacheKey, Set<Capability>> entry : capabilityCache.entrySet()) {
CacheKey auxkey = entry.getKey();
if (auxkey.namespace.equals(key.namespace)) {
capset.addAll(entry.getValue());
}
}
}
return Collections.unmodifiableSet(capset);
}
@Override
public String toString() {
String prefix = getClass() != AbstractResourceStore.class ? getClass().getSimpleName() : ResourceStore.class.getSimpleName();
return prefix + "[" + storeName + "]";
}
private static class CacheKey {
private final String namespace;
private final String value;
private final String keyspec;
static CacheKey create(Capability cap) {
String namespace = cap.getNamespace();
String nsvalue = (String) cap.getAttributes().get(namespace);
return new CacheKey(namespace, nsvalue);
}
static CacheKey create(Requirement req) {
String namespace = req.getNamespace();
String nsvalue = (String) req.getAttributes().get(namespace);
return new CacheKey(namespace, nsvalue);
}
private CacheKey(String namespace, String value) {
this.namespace = namespace;
this.value = value;
this.keyspec = namespace + ":" + value;
}
@Override
public int hashCode() {
return keyspec.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof CacheKey))
return false;
CacheKey other = (CacheKey) obj;
return keyspec.equals(other.keyspec);
}
@Override
public String toString() {
return "[" + keyspec + "]";
}
}
}
|
9239ff94a50a6a3dc5515ae1e4f7262ccee878bd | 8,059 | java | Java | surefire-provider/src/test/java/org/arquillian/smart/testing/surefire/provider/SmartTestingProviderTest.java | arquillian/smart-testing | f7bf280120e745298bb8a39a37ca408ff205bcd6 | [
"Apache-2.0"
] | 27 | 2017-06-14T14:16:52.000Z | 2021-02-10T10:52:32.000Z | surefire-provider/src/test/java/org/arquillian/smart/testing/surefire/provider/SmartTestingProviderTest.java | arquillian/smart-testing | f7bf280120e745298bb8a39a37ca408ff205bcd6 | [
"Apache-2.0"
] | 395 | 2017-04-07T16:28:51.000Z | 2021-07-08T11:13:54.000Z | surefire-provider/src/test/java/org/arquillian/smart/testing/surefire/provider/SmartTestingProviderTest.java | arquillian/smart-testing | f7bf280120e745298bb8a39a37ca408ff205bcd6 | [
"Apache-2.0"
] | 15 | 2017-04-28T10:29:00.000Z | 2021-05-13T06:56:53.000Z | 40.094527 | 131 | 0.738181 | 999,042 | package org.arquillian.smart.testing.surefire.provider;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import net.jcip.annotations.NotThreadSafe;
import org.apache.maven.surefire.providerapi.ProviderParameters;
import org.apache.maven.surefire.providerapi.SurefireProvider;
import org.apache.maven.surefire.report.DefaultConsoleReporter;
import org.apache.maven.surefire.testset.ResolvedTest;
import org.apache.maven.surefire.testset.TestListResolver;
import org.apache.maven.surefire.testset.TestRequest;
import org.apache.maven.surefire.testset.TestSetFailedException;
import org.apache.maven.surefire.util.TestsToRun;
import org.arquillian.smart.testing.TestSelection;
import org.arquillian.smart.testing.configuration.ConfigurationLoader;
import org.arquillian.smart.testing.surefire.provider.custom.assertions.SurefireProviderSoftAssertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@Category(NotThreadSafe.class)
public class SmartTestingProviderTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@Rule
public final SurefireProviderSoftAssertions softly = new SurefireProviderSoftAssertions();
private final Set<Class<?>> expectedClassesToRun = new LinkedHashSet<>(asList(ATest.class, BTest.class));
private ProviderParameters providerParameters;
private TestRequest testRequest;
private SurefireProviderFactory providerFactory;
private SurefireProvider surefireProvider;
@Before
public void setupMocksAndDumpConfiguration() throws IOException {
providerParameters = mock(ProviderParameters.class);
surefireProvider = mock(SurefireProvider.class);
when(surefireProvider.getSuites()).thenReturn(new TestsToRun(expectedClassesToRun));
providerFactory = mock(SurefireProviderFactory.class);
when(providerFactory.createInstance(Mockito.any())).thenReturn(surefireProvider);
testRequest = new TestRequest(null, temporaryFolder.getRoot(), TestListResolver.getEmptyTestListResolver());
when(providerParameters.getTestRequest()).thenReturn(testRequest);
temporaryFolder.newFile("pom.xml");
ConfigurationLoader.load(Paths.get("").toFile()).dump(temporaryFolder.getRoot());
System.setProperty("basedir", temporaryFolder.getRoot().toString());
when(providerParameters.getConsoleLogger()).thenReturn(new DefaultConsoleReporter(new PrintStream(System.out)));
}
@Test
public void when_get_suites_is_called_then_same_list_of_classes_will_be_returned() {
// given
SmartTestingSurefireProvider provider = new SmartTestingSurefireProvider(providerParameters, providerFactory);
// when
Iterable<Class<?>> suites = provider.getSuites();
// then
verify(surefireProvider, times(1)).getSuites();
assertThat(suites).containsExactlyElementsOf(expectedClassesToRun);
}
@Test
public void test_when_invoke_is_called_with_null() throws Exception {
// given
SmartTestingSurefireProvider provider = new SmartTestingSurefireProvider(providerParameters, providerFactory);
// when
provider.invoke(null);
// then
verify(surefireProvider, times(1)).getSuites();
verify(surefireProvider, times(1)).invoke(argThat((ArgumentMatcher<Iterable<Class>>)
iterable -> iterableContains(iterable, expectedClassesToRun)));
}
@Test
public void test_when_invoke_is_called_with_one_class() throws Exception {
// given
SmartTestingSurefireProvider provider = new SmartTestingSurefireProvider(providerParameters, providerFactory);
// when
provider.invoke(ATest.class);
// then
verify(surefireProvider, times(0)).getSuites();
verify(surefireProvider, times(1)).invoke(argThat((ArgumentMatcher<Iterable<Class>>)
iterable -> iterableContains(iterable, new LinkedHashSet(Collections.singletonList(ATest.class)))));
}
@Test
public void test_when_invoke_is_called_with_whole_set_of_classes() throws Exception {
// given
SmartTestingSurefireProvider provider = new SmartTestingSurefireProvider(providerParameters, providerFactory);
// when
provider.invoke(new TestsToRun(expectedClassesToRun));
// then
verify(surefireProvider, times(0)).getSuites();
verify(surefireProvider, times(1)).invoke(argThat((ArgumentMatcher<Iterable<Class>>)
iterable -> iterableContains(iterable, expectedClassesToRun)));
}
@Test
public void should_add_test_method_selection_to_test_list_resolver() throws TestSetFailedException, InvocationTargetException {
// given
TestSelection strategy =
new TestSelection(ATest.class.getName(), Arrays.asList("firstMethod", "secondMethod"), "strategy");
prepareTestListResolver();
SmartTestingInvoker smartTestingInvoker = prepareSTInvoker(Arrays.asList(strategy));
SmartTestingSurefireProvider provider =
new SmartTestingSurefireProvider(providerParameters, providerFactory, smartTestingInvoker);
// when
provider.invoke(null);
// then
softly.assertThat(testRequest.getTestListResolver())
.hasMethodPatterns(true)
.hasIncludedMethodPatterns(true)
.hasExcludedMethodPatterns(true)
.includedPatterns()
.containsExactlyInAnyOrder(
new ResolvedTest(ATest.class.getName(), "firstMethod", false),
new ResolvedTest(ATest.class.getName(), "secondMethod", false));
softly.assertThat(testRequest.getTestListResolver())
.excludedPatterns()
.containsExactly(new ResolvedTest(ATest.class.getName(), "thirdMethod", false));
}
private SmartTestingInvoker prepareSTInvoker(List<TestSelection> selectionToReturn) {
SmartTestingInvoker smartTestingInvoker = mock(SmartTestingInvoker.class);
when(smartTestingInvoker.invokeSmartTestingAPI(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(
new HashSet<>(selectionToReturn));
return smartTestingInvoker;
}
private void prepareTestListResolver(){
TestListResolver testListResolver =
new TestListResolver(Arrays.asList("*Test*", "!" + ATest.class.getName() + "#thirdMethod"));
testRequest = new TestRequest(null, temporaryFolder.getRoot(), testListResolver);
when(providerParameters.getTestRequest()).thenReturn(testRequest);
}
private boolean iterableContains(Iterable<Class> iterable, Set expectedClasses) {
List<Class> actualCall = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
return actualCall.size() == expectedClasses.size() && actualCall.containsAll(expectedClasses);
}
private static class ATest {
void firstMethod() {
}
void secondMethod() {
}
void thirdMethod() {
}
}
private static class BTest {}
}
|
923a0119b592425be122db061119fab145592c91 | 1,657 | java | Java | src/spelling/DictionaryLL.java | stevenanhle/TextEditor | 830c47c6cba355005a4402e40f817bdcc63c7b3e | [
"BSD-2-Clause"
] | null | null | null | src/spelling/DictionaryLL.java | stevenanhle/TextEditor | 830c47c6cba355005a4402e40f817bdcc63c7b3e | [
"BSD-2-Clause"
] | null | null | null | src/spelling/DictionaryLL.java | stevenanhle/TextEditor | 830c47c6cba355005a4402e40f817bdcc63c7b3e | [
"BSD-2-Clause"
] | null | null | null | 21.519481 | 71 | 0.583585 | 999,043 | package spelling;
import java.util.LinkedList;
import com.sun.corba.se.impl.orbutil.graph.Node;
/**
* A class that implements the Dictionary interface using a LinkedList
*
*/
public class DictionaryLL implements Dictionary
{
private LinkedList<String> dict;
// TODO: Add a constructor
public DictionaryLL()
{
this.dict = new LinkedList<String>();
}
/** Add this word to the dictionary. Convert it to lowercase first
* for the assignment requirements.
* @param word The word to add
* @return true if the word was added to the dictionary
* (it wasn't already there). */
public boolean addWord(String word) {
// TODO: Implement this method
String lowCase = word.toLowerCase();
if(!isWord(word))
{
dict.add(lowCase);
return true;
}
else
return false;
}
/** Return the number of words in the dictionary */
public int size()
{
// TODO: Implement this method
int size = dict.size();
return size;
}
/** Is this a word according to this dictionary? */
public boolean isWord(String s) {
//TODO: Implement this method
String lowCase = s.toLowerCase();
boolean isHas = true;
if(dict.size()==0)
isHas=false;
for(int i=0; i<dict.size(); i++)
{
//System.out.println(dict.get(i));
if(dict.get(i).equals(lowCase))
{
isHas=true;// s is in the list already
break;
}
else
isHas=false; // s is not in the list
}
//System.out.println(isHas);
return isHas;//
}
}
|
923a01d69b7b48b861c2a36e74be4f7bda7781c4 | 390 | java | Java | app/src/main/java/com/wanbo/werb/ui/view/IMessageTabFgView.java | Werb/Werb | d7b0b43f2ee8cb362ebebb07acf3f3338edfb7f0 | [
"Apache-2.0"
] | 308 | 2016-09-11T13:55:53.000Z | 2018-12-24T11:33:10.000Z | app/src/main/java/com/wanbo/werb/ui/view/IMessageTabFgView.java | syc8622374github/Werb | d7b0b43f2ee8cb362ebebb07acf3f3338edfb7f0 | [
"Apache-2.0"
] | 4 | 2016-09-18T03:16:21.000Z | 2017-07-19T11:53:06.000Z | app/src/main/java/com/wanbo/werb/ui/view/IMessageTabFgView.java | syc8622374github/Werb | d7b0b43f2ee8cb362ebebb07acf3f3338edfb7f0 | [
"Apache-2.0"
] | 101 | 2016-09-12T02:45:36.000Z | 2018-10-15T04:43:49.000Z | 23.117647 | 53 | 0.75827 | 999,044 | package com.wanbo.werb.ui.view;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
/**
* Created by Werb on 2016/8/13.
* Werb is Wanbo.
* Contact Me : hzdkv@example.com
*/
public interface IMessageTabFgView {
void setDataRefresh(Boolean refresh);
RecyclerView getRecyclerView();
LinearLayoutManager getLayoutManager();
}
|
923a04633828114c37eda3fffc8cbb4b1005e9b5 | 1,557 | java | Java | hibernate-search/hsearch-elasticsearch-wikipedia/src/main/java/org/hibernate/search/demos/wikipedia/data/dao/hibernate/HibernatePageDaoImpl.java | duschata/hibernate-demos | 3f5eb8e170296e2217f94bd56fdf8dc73ec8d669 | [
"Apache-2.0"
] | 265 | 2015-01-15T06:08:22.000Z | 2022-03-20T13:34:39.000Z | hibernate-search/hsearch-elasticsearch-wikipedia/src/main/java/org/hibernate/search/demos/wikipedia/data/dao/hibernate/HibernatePageDaoImpl.java | duschata/hibernate-demos | 3f5eb8e170296e2217f94bd56fdf8dc73ec8d669 | [
"Apache-2.0"
] | 39 | 2015-01-09T14:21:07.000Z | 2022-01-25T06:19:22.000Z | hibernate-search/hsearch-elasticsearch-wikipedia/src/main/java/org/hibernate/search/demos/wikipedia/data/dao/hibernate/HibernatePageDaoImpl.java | duschata/hibernate-demos | 3f5eb8e170296e2217f94bd56fdf8dc73ec8d669 | [
"Apache-2.0"
] | 256 | 2015-01-07T11:33:52.000Z | 2022-01-25T05:28:46.000Z | 23.590909 | 86 | 0.668593 | 999,045 | package org.hibernate.search.demos.wikipedia.data.dao.hibernate;
import org.hibernate.search.demos.wikipedia.data.Page;
import org.hibernate.search.demos.wikipedia.data.dao.PageDao;
import org.hibernate.search.demos.wikipedia.data.dao.PageSort;
import org.hibernate.search.demos.wikipedia.util.SearchResult;
import org.hibernate.search.mapper.orm.Search;
import org.hibernate.search.mapper.orm.session.SearchSession;
import org.springframework.stereotype.Repository;
@Repository
public class HibernatePageDaoImpl extends AbstractHibernateDao implements PageDao {
@Override
public void create(Page page) {
getEm().persist( page );
}
@Override
public void update(Page page) {
getEm().merge( page );
}
@Override
public void delete(Page page) {
getEm().remove( page );
}
@Override
public Page getById(Long id) {
return getEm().find( Page.class, id );
}
@Override
public SearchResult<Page> search(String term, PageSort sort, int offset, int limit) {
SearchSession searchSession = Search.session( getEm() );
return new SearchResult<>( searchSession.search( Page.class )
.where( f -> {
if ( term == null || term.isEmpty() ) {
return f.matchAll();
}
else {
return f.match()
.field( "title" ).boost( 2.0f )
.field( "content" )
.matching( term );
}
} )
.sort( f -> {
switch ( sort ) {
case TITLE:
return f.field( "title_sort" );
case RELEVANCE:
default:
return f.score();
}
} )
.fetch( offset, limit )
);
}
}
|
923a046602787d1bdf2253553c29aea5be5d0557 | 1,281 | java | Java | mllib/target/java/org/apache/spark/ml/source/libsvm/LibSVMOptions.java | jessicarychen/598project | 0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | mllib/target/java/org/apache/spark/ml/source/libsvm/LibSVMOptions.java | jessicarychen/598project | 0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | mllib/target/java/org/apache/spark/ml/source/libsvm/LibSVMOptions.java | jessicarychen/598project | 0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | 58.227273 | 144 | 0.741608 | 999,046 | package org.apache.spark.ml.source.libsvm;
/**
* Options for the LibSVM data source.
*/
class LibSVMOptions implements scala.Serializable {
static public java.lang.String NUM_FEATURES () { throw new RuntimeException(); }
static public java.lang.String VECTOR_TYPE () { throw new RuntimeException(); }
static public java.lang.String DENSE_VECTOR_TYPE () { throw new RuntimeException(); }
static public java.lang.String SPARSE_VECTOR_TYPE () { throw new RuntimeException(); }
private org.apache.spark.sql.catalyst.util.CaseInsensitiveMap<java.lang.String> parameters () { throw new RuntimeException(); }
// not preceding
public LibSVMOptions (org.apache.spark.sql.catalyst.util.CaseInsensitiveMap<java.lang.String> parameters) { throw new RuntimeException(); }
public LibSVMOptions (scala.collection.immutable.Map<java.lang.String, java.lang.String> parameters) { throw new RuntimeException(); }
/**
* Number of features. If unspecified or nonpositive, the number of features will be determined
* automatically at the cost of one additional pass.
* @return (undocumented)
*/
public scala.Option<java.lang.Object> numFeatures () { throw new RuntimeException(); }
public boolean isSparse () { throw new RuntimeException(); }
}
|
923a0503d1b96fb20911590a253992345bf3adb0 | 17,541 | java | Java | spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java | izeye/spring-restdocs | 17d05f2750791acb4755fd0690df73183db46825 | [
"Apache-2.0"
] | null | null | null | spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java | izeye/spring-restdocs | 17d05f2750791acb4755fd0690df73183db46825 | [
"Apache-2.0"
] | null | null | null | spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java | izeye/spring-restdocs | 17d05f2750791acb4755fd0690df73183db46825 | [
"Apache-2.0"
] | null | null | null | 39.241611 | 91 | 0.661023 | 999,047 | /*
* Copyright 2014-2017 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 org.springframework.restdocs.payload;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.restdocs.AbstractSnippetTests;
import org.springframework.restdocs.templates.TemplateEngine;
import org.springframework.restdocs.templates.TemplateFormat;
import org.springframework.restdocs.templates.TemplateFormats;
import org.springframework.restdocs.templates.TemplateResourceResolver;
import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.restdocs.snippet.Attributes.attributes;
import static org.springframework.restdocs.snippet.Attributes.key;
/**
* Tests for {@link RequestFieldsSnippet}.
*
* @author Andy Wilkinson
*/
public class RequestFieldsSnippetTests extends AbstractSnippetTests {
public RequestFieldsSnippetTests(String name, TemplateFormat templateFormat) {
super(name, templateFormat);
}
@Test
public void mapRequestWithFields() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two")
.row("`a`", "`Object`", "three"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"),
fieldWithPath("a.c").description("two"),
fieldWithPath("a").description("three")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
}
@Test
public void mapRequestWithNullField() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`Null`", "one"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": null}}").build());
}
@Test
public void entireSubsectionsCanBeDocumented() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`a`",
"`Object`", "one"));
new RequestFieldsSnippet(
Arrays.asList(subsectionWithPath("a").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
}
@Test
public void subsectionOfMapRequest() throws IOException {
this.snippets.expect("request-fields-beneath-a")
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "one").row("`c`", "`String`", "two"));
requestFields(beneathPath("a"), fieldWithPath("b").description("one"),
fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
}
@Test
public void arrayRequestWithFields() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`[]`", "`Array`", "one").row("`[]a.b`", "`Number`", "two")
.row("`[]a.c`", "`String`", "three")
.row("`[]a`", "`Object`", "four"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"),
fieldWithPath("[]a.b").description("two"),
fieldWithPath("[]a.c").description("three"),
fieldWithPath("[]a").description("four")))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}},"
+ "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]")
.build());
}
@Test
public void arrayRequestWithAlwaysNullField() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`[]a.b`", "`Null`", "one"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one")))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]")
.build());
}
@Test
public void subsectionOfArrayRequest() throws IOException {
this.snippets.expect("request-fields-beneath-[].a")
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "one").row("`c`", "`String`", "two"));
requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"),
fieldWithPath("c").description("two"))
.document(this.operationBuilder.request("http://localhost")
.content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]")
.build());
}
@Test
public void ignoredRequestField() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`b`",
"`Number`", "Field b"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(),
fieldWithPath("b").description("Field b")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5, \"b\": 4}").build());
}
@Test
public void entireSubsectionCanBeIgnored() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`c`",
"`Number`", "Field c"));
new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").ignored(),
fieldWithPath("c").description("Field c")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5}, \"c\": 4}").build());
}
@Test
public void allUndocumentedRequestFieldsCanBeIgnored() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`b`",
"`Number`", "Field b"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")),
true).document(
this.operationBuilder.request("http://localhost")
.content("{\"a\": 5, \"b\": 4}").build());
}
@Test
public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors()
throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`b`", "`Number`", "Field b")
.row("`c.d`", "`Number`", "Field d"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")),
true).andWithPrefix("c.", fieldWithPath("d").description("Field d"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build());
}
@Test
public void missingOptionalRequestField() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`String`", "one"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")
.type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{}").build());
}
@Test
public void missingIgnoredOptionalRequestFieldDoesNotRequireAType()
throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description"));
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a.b").description("one").ignored().optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{}").build());
}
@Test
public void presentOptionalRequestField() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`",
"`String`", "one"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one")
.type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": { \"b\": \"bravo\"}}").build());
}
@Test
public void requestFieldsWithCustomAttributes() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-fields"))
.willReturn(snippetResource("request-fields-with-title"));
this.snippets.expectRequestFields().withContents(containsString("Custom title"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")),
attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.content("{\"a\": \"foo\"}").build());
}
@Test
public void requestFieldsWithCustomDescriptorAttributes() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-fields"))
.willReturn(snippetResource("request-fields-with-extra-column"));
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description", "Foo")
.row("a.b", "Number", "one", "alpha")
.row("a.c", "String", "two", "bravo")
.row("a", "Object", "three", "charlie"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a.b").description("one")
.attributes(key("foo").value("alpha")),
fieldWithPath("a.c").description("two")
.attributes(key("foo").value("bravo")),
fieldWithPath("a").description("three")
.attributes(key("foo").value("charlie"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.content(
"{\"a\": {\"b\": 5, \"c\": \"charlie\"}}")
.build());
}
@Test
public void fieldWithExplictExactlyMatchingType() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`a`",
"`Number`", "one"));
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER)))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5 }").build());
}
@Test
public void fieldWithExplictVariesType() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row("`a`",
"`Varies`", "one"));
new RequestFieldsSnippet(Arrays
.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES)))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": 5 }").build());
}
@Test
public void applicationXmlRequestFields() throws IOException {
xmlRequestFields(MediaType.APPLICATION_XML);
}
@Test
public void textXmlRequestFields() throws IOException {
xmlRequestFields(MediaType.TEXT_XML);
}
@Test
public void customXmlRequestFields() throws IOException {
xmlRequestFields(MediaType.parseMediaType("application/vnd.com.example+xml"));
}
private void xmlRequestFields(MediaType contentType) throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two")
.row("`a`", "`a`", "three"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a/b").description("one").type("b"),
fieldWithPath("a/c").description("two").type("c"),
fieldWithPath("a").description("three").type("a")))
.document(this.operationBuilder.request("http://localhost")
.content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE, contentType.toString())
.build());
}
@Test
public void entireSubsectionOfXmlPayloadCanBeDocumented() throws IOException {
this.snippets.expectRequestFields().withContents(
tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one"));
new RequestFieldsSnippet(
Arrays.asList(subsectionWithPath("a").description("one").type("a")))
.document(this.operationBuilder.request("http://localhost")
.content("<a><b>5</b><c>charlie</c></a>")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_VALUE)
.build());
}
@Test
public void additionalDescriptors() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two")
.row("`a`", "`Object`", "three"));
PayloadDocumentation
.requestFields(fieldWithPath("a.b").description("one"),
fieldWithPath("a.c").description("two"))
.and(fieldWithPath("a").description("three"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
}
@Test
public void prefixedAdditionalDescriptors() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two")
.row("`a.c`", "`String`", "three"));
PayloadDocumentation.requestFields(fieldWithPath("a").description("one"))
.andWithPrefix("a.", fieldWithPath("b").description("two"),
fieldWithPath("c").description("three"))
.document(this.operationBuilder.request("http://localhost")
.content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build());
}
@Test
public void requestWithFieldsWithEscapedContent() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description").row(
escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"),
escapeIfNecessary("three|four")));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("Foo|Bar").type("one|two").description("three|four")))
.document(this.operationBuilder.request("http://localhost")
.content("{\"Foo|Bar\": 5}").build());
}
@Test
public void mapRequestWithVaryingKeysMatchedUsingWildcard() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`things.*.size`", "`String`", "one")
.row("`things.*.type`", "`String`", "two"));
new RequestFieldsSnippet(
Arrays.asList(fieldWithPath("things.*.size").description("one"),
fieldWithPath("things.*.type").description("two"))).document(
this.operationBuilder.request("http://localhost")
.content("{\"things\": {\"12abf\": {\"type\":"
+ "\"Whale\", \"size\": \"HUGE\"},"
+ "\"gzM33\" : {\"type\": \"Screw\","
+ "\"size\": \"SMALL\"}}}")
.build());
}
@Test
public void requestWithArrayContainingFieldThatIsSometimesNull() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`assets[].name`", "`String`", "one"));
new RequestFieldsSnippet(Arrays.asList(fieldWithPath("assets[].name")
.description("one").type(JsonFieldType.STRING).optional()))
.document(this.operationBuilder.request("http://localhost")
.content("{\"assets\": [" + "{\"name\": \"sample1\"}, "
+ "{\"name\": null}, "
+ "{\"name\": \"sample2\"}]}")
.build());
}
@Test
public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException {
this.snippets.expectRequestFields()
.withContents(tableWithHeader("Path", "Type", "Description")
.row("`a[].b`", "`Number`", "one")
.row("`a[].c`", "`Number`", "two"));
new RequestFieldsSnippet(Arrays.asList(
fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER)
.optional(),
fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER)))
.document(
this.operationBuilder.request("http://localhost")
.content("{\"a\":[{\"b\": 1,\"c\": 2}, "
+ "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}")
.build());
}
private String escapeIfNecessary(String input) {
if (this.templateFormat.equals(TemplateFormats.markdown())) {
return input;
}
return input.replace("|", "\\|");
}
}
|
923a07219a6b8224f6ad9d2cacc0a3f5b2320dd7 | 486 | java | Java | src/main/java/com/br/zupacademy/hugo/proposta/proposta/consulta/ConsultaPropostaClient.java | hugovallada/orange-talents-04-template-proposta | 2fff159173a21a3008722562d5cb368c365b0b76 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/br/zupacademy/hugo/proposta/proposta/consulta/ConsultaPropostaClient.java | hugovallada/orange-talents-04-template-proposta | 2fff159173a21a3008722562d5cb368c365b0b76 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/br/zupacademy/hugo/proposta/proposta/consulta/ConsultaPropostaClient.java | hugovallada/orange-talents-04-template-proposta | 2fff159173a21a3008722562d5cb368c365b0b76 | [
"Apache-2.0"
] | null | null | null | 37.384615 | 90 | 0.825103 | 999,048 | package com.br.zupacademy.hugo.proposta.proposta.consulta;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@FeignClient(name = "consultaProposta", url = "${consulta.solicitacao.url}")
public interface ConsultaPropostaClient {
@PostMapping("/api/solicitacao")
ConsultaPropostaResponse solicitacao(ConsultaPropostaRequest consultaPropostaRequest);
}
|
923a0912aa0f928638f9f9ac60ebd6e76060ac10 | 728 | java | Java | mall-product/src/main/java/personal/skyxt/mallproduct/entity/SpuImagesEntity.java | skyxt/skymail | 8c8dd874967522eb11bed1572018b0827724d4f2 | [
"Apache-2.0"
] | null | null | null | mall-product/src/main/java/personal/skyxt/mallproduct/entity/SpuImagesEntity.java | skyxt/skymail | 8c8dd874967522eb11bed1572018b0827724d4f2 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:11:48.000Z | 2021-09-20T21:01:32.000Z | mall-product/src/main/java/personal/skyxt/mallproduct/entity/SpuImagesEntity.java | skyxt/sky-mall | 8c8dd874967522eb11bed1572018b0827724d4f2 | [
"Apache-2.0"
] | null | null | null | 14.918367 | 54 | 0.683995 | 999,049 | package personal.skyxt.mallproduct.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* spu图片
*
* @author skyxt
* @email efpyi@example.com
* @date 2020-08-05 14:25:48
*/
@Data
@TableName("pms_spu_images")
public class SpuImagesEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* spu_id
*/
private Long spuId;
/**
* 图片名
*/
private String imgName;
/**
* 图片地址
*/
private String imgUrl;
/**
* 顺序
*/
private Integer imgSort;
/**
* 是否默认图
*/
private Integer defaultImg;
}
|
923a0996c4e868f4900776021aba7a8cdcac5d6f | 1,603 | java | Java | jodd-joy/src/testInt/java/jodd/joy/action/AppDao.java | xun404/jodd | d5c7e9cb61842aee2ba7800e4b7a10ba7f0162a1 | [
"BSD-2-Clause"
] | 3,937 | 2015-01-02T14:21:57.000Z | 2022-03-31T09:03:33.000Z | jodd-joy/src/testInt/java/jodd/joy/action/AppDao.java | xun404/jodd | d5c7e9cb61842aee2ba7800e4b7a10ba7f0162a1 | [
"BSD-2-Clause"
] | 584 | 2015-01-02T20:58:08.000Z | 2022-03-29T02:10:35.000Z | jodd-joy/src/testInt/java/jodd/joy/action/AppDao.java | xun404/jodd | d5c7e9cb61842aee2ba7800e4b7a10ba7f0162a1 | [
"BSD-2-Clause"
] | 800 | 2015-01-02T06:44:42.000Z | 2022-02-16T08:28:49.000Z | 41.102564 | 78 | 0.769183 | 999,050 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.joy.action;
import jodd.db.DbOom;
import jodd.db.oom.dao.GenericDao;
import jodd.petite.meta.PetiteBean;
@PetiteBean
public class AppDao extends GenericDao {
public AppDao() {
super(DbOom.get());
}
}
|
923a09e49537dd83ffb3f55ffaa6e81b03ba5329 | 1,014 | java | Java | sample/src/main/java/com/idealista/android/sample/app/model/MovieModel.java | idealista/Elves-Android | 83e3e27ef0dc96e024d0f20ce2fe64b1e696897e | [
"BSD-3-Clause"
] | 5 | 2017-04-18T13:55:52.000Z | 2018-05-29T22:52:15.000Z | sample/src/main/java/com/idealista/android/sample/app/model/MovieModel.java | idealista-tech/Elves-Android | 83e3e27ef0dc96e024d0f20ce2fe64b1e696897e | [
"BSD-3-Clause"
] | 1 | 2017-03-28T11:03:26.000Z | 2017-03-28T11:03:26.000Z | sample/src/main/java/com/idealista/android/sample/app/model/MovieModel.java | idealista-tech/Elves-Android | 83e3e27ef0dc96e024d0f20ce2fe64b1e696897e | [
"BSD-3-Clause"
] | 2 | 2017-05-11T07:58:09.000Z | 2017-12-04T10:42:53.000Z | 21.574468 | 103 | 0.638067 | 999,051 | package com.idealista.android.sample.app.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.idealista.android.elves.view.mvp.view.View;
public class MovieModel implements View, Parcelable {
private String title;
public MovieModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
}
protected MovieModel(Parcel in) {
this.title = in.readString();
}
public static final Parcelable.Creator<MovieModel> CREATOR = new Parcelable.Creator<MovieModel>() {
@Override
public MovieModel createFromParcel(Parcel source) {
return new MovieModel(source);
}
@Override
public MovieModel[] newArray(int size) {
return new MovieModel[size];
}
};
}
|
923a0a2577315eadc1fede98177a7ee7d52b6aaf | 940 | java | Java | src/main/java/cn/vonce/sql/android/util/PackageUtil.java | Jovilam77/vonce-sqlbean-android | 6e8256c122ee7d3171f7f1c9ab8239c060d4c040 | [
"MIT"
] | 10 | 2020-06-30T11:17:29.000Z | 2022-01-06T03:09:32.000Z | src/main/java/cn/vonce/sql/android/util/PackageUtil.java | Jovilam77/vonce-sqlbean-android | 6e8256c122ee7d3171f7f1c9ab8239c060d4c040 | [
"MIT"
] | null | null | null | src/main/java/cn/vonce/sql/android/util/PackageUtil.java | Jovilam77/vonce-sqlbean-android | 6e8256c122ee7d3171f7f1c9ab8239c060d4c040 | [
"MIT"
] | null | null | null | 30.322581 | 81 | 0.598936 | 999,052 | package cn.vonce.sql.android.util;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import dalvik.system.DexFile;
public class PackageUtil {
public static List<String> getClasses(Context mContext, String packageName) {
List<String> classes = new ArrayList<>();
try {
String packageCodePath = mContext.getPackageCodePath();
DexFile df = new DexFile(packageCodePath);
String regExp = "^" + packageName + ".\\w+$";
for (Enumeration iter = df.entries(); iter.hasMoreElements(); ) {
String className = (String) iter.nextElement();
if (className.matches(regExp)) {
classes.add(className);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
}
|
923a0bbf2c2d86e1a68aca787df2769af087cb18 | 1,952 | java | Java | clouddriver-core/src/main/java/com/netflix/spinnaker/clouddriver/cache/CustomSchedulableAgentIntervalProvider.java | SusmithaGU/clouddriver | 3287f7a01d96a5841ad10964932ce31baa9e27f4 | [
"Apache-2.0"
] | null | null | null | clouddriver-core/src/main/java/com/netflix/spinnaker/clouddriver/cache/CustomSchedulableAgentIntervalProvider.java | SusmithaGU/clouddriver | 3287f7a01d96a5841ad10964932ce31baa9e27f4 | [
"Apache-2.0"
] | null | null | null | clouddriver-core/src/main/java/com/netflix/spinnaker/clouddriver/cache/CustomSchedulableAgentIntervalProvider.java | SusmithaGU/clouddriver | 3287f7a01d96a5841ad10964932ce31baa9e27f4 | [
"Apache-2.0"
] | null | null | null | 39.04 | 98 | 0.755635 | 999,053 | /*
* Copyright 2015 Netflix, 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.netflix.spinnaker.clouddriver.cache;
import com.netflix.spinnaker.cats.agent.Agent;
import com.netflix.spinnaker.cats.cluster.AgentIntervalProvider;
import com.netflix.spinnaker.cats.cluster.DefaultAgentIntervalProvider;
public class CustomSchedulableAgentIntervalProvider extends DefaultAgentIntervalProvider {
public CustomSchedulableAgentIntervalProvider(long interval, long errorInterval, long timeout) {
super(interval, errorInterval, timeout);
}
@Override
public AgentIntervalProvider.Interval getInterval(Agent agent) {
if (agent instanceof CustomScheduledAgent) {
CustomScheduledAgent customAgent = (CustomScheduledAgent) agent;
return getCustomInterval(customAgent);
}
return super.getInterval(agent);
}
AgentIntervalProvider.Interval getCustomInterval(CustomScheduledAgent agent) {
final long pollInterval =
agent.getPollIntervalMillis() == -1 ? super.getInterval() : agent.getPollIntervalMillis();
final long errorInterval =
agent.getErrorIntervalMillis() == -1
? super.getErrorInterval()
: agent.getErrorIntervalMillis();
final long timeoutMillis =
agent.getTimeoutMillis() == -1 ? super.getTimeout() : agent.getTimeoutMillis();
return new AgentIntervalProvider.Interval(pollInterval, errorInterval, timeoutMillis);
}
}
|
923a0bc33c9a12c6193225b111875a8fd28eaf97 | 4,696 | java | Java | src/no/ntnu/acp142/chatapp/Chat.java | libjpmul/pmulchat | 4b60acee27eb1a93021e1c87e081d389bab59b6c | [
"BSD-3-Clause"
] | 1 | 2019-04-19T14:30:23.000Z | 2019-04-19T14:30:23.000Z | src/no/ntnu/acp142/chatapp/Chat.java | libjpmul/pmulchat | 4b60acee27eb1a93021e1c87e081d389bab59b6c | [
"BSD-3-Clause"
] | null | null | null | src/no/ntnu/acp142/chatapp/Chat.java | libjpmul/pmulchat | 4b60acee27eb1a93021e1c87e081d389bab59b6c | [
"BSD-3-Clause"
] | null | null | null | 28.460606 | 78 | 0.632666 | 999,054 | package no.ntnu.acp142.chatapp;
import no.ntnu.acp142.Configuration;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
/*
* Copyright (c) 2013, Thomas Martin Schmid
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* (3) The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Chat<br>
* Chat container. Contains a list of all messages in order of reception. Each
* container also has a reference to the topic.
*
* @author Thomas Martin Schmid
*/
public class Chat extends AbstractListModel<Message> {
/**
* Dictates how many messages it keeps in its history.
*/
private int capacity;
/**
* List of all messages in this chat.
*/
private ArrayList<Message> messageList;
/**
* Topic name for this chat.
*/
private final Topic topic;
/**
* Reference to our own subscriber object.
*/
private Subscriber self;
/**
* Creates a new chat
*
* @param topic
* Topic of this chat
* @param self
* Subscriber reference of the user.
*/
public Chat(Topic topic, Subscriber self) {
this.topic = topic;
this.messageList = new ArrayList<Message>();
this.self = self;
this.capacity = 100;
}
/**
* Gets the list of all the messages received for this chat.
*
* @return The list of all messages.
*/
public ArrayList<Message> getMessageList() {
if ( this.messageList == null ) {
this.messageList = new ArrayList<Message>();
}
return this.messageList;
}
/**
* Gets the topic for this chat
*
* @return Reference to the topic of this chat.
*/
public Topic getTopic() {
return this.topic;
}
/**
* Gets the subscriber object of the current user.
*
* @return Reference to user's subscriber object.
*/
public Subscriber getSelf() {
return this.self;
}
/**
* Adds a message to the message list, removing the oldest messages while
* capacity is exceeded.
*
* @param message
* to add
*/
public void addMessage(Message message) {
while (this.messageList.size() >= this.capacity) {
this.messageList.remove(0);
}
this.messageList.add(message);
}
@Override
public Message getElementAt(int index) {
return this.messageList.get(index);
}
@Override
public int getSize() {
return this.messageList.size();
}
@Override
public String toString() {
return this.topic == null ? "" : this.topic.getName();
}
/**
* Sets the maximum number of messages to keep in its history.
*
* @param max
* Number of messages to keep.
*/
public void setCapacity(int max) {
this.capacity = max;
}
/**
* Resets the Self subscriber instance with default values
*
* @param newUserName
* New username to use. Null uses a standard username.
*/
public void resetSelf(String newUserName) {
if ( newUserName == null ) {
newUserName = "User_" + Configuration.getNodeId();
}
this.self = new Subscriber(Configuration.getNodeId(), newUserName);
}
}
|
923a0bdc69ce3f94bda64bb82955c5c32634ab5f | 13,442 | java | Java | src/main/java/SageOneIntegration/SA/V1_1_2/SageOneApiEntities/SageOneCustomerReceipt.java | Carabaw9000/sageOneApiLibrary-GLOBAL | 3e01a2044cd6338557369863e3c720fa8c547e4d | [
"Apache-2.0"
] | 3 | 2017-08-07T13:34:06.000Z | 2017-08-26T17:23:46.000Z | src/main/java/SageOneIntegration/SA/V1_1_2/SageOneApiEntities/SageOneCustomerReceipt.java | Carabaw9000/sageOneApiLibrary-GLOBAL | 3e01a2044cd6338557369863e3c720fa8c547e4d | [
"Apache-2.0"
] | 10 | 2017-06-02T17:58:48.000Z | 2017-06-22T20:37:08.000Z | src/main/java/SageOneIntegration/SA/V1_1_2/SageOneApiEntities/SageOneCustomerReceipt.java | Carabaw9000/sageOneApiLibrary-GLOBAL | 3e01a2044cd6338557369863e3c720fa8c547e4d | [
"Apache-2.0"
] | 2 | 2017-08-04T14:30:27.000Z | 2017-08-31T15:33:40.000Z | 29.542857 | 97 | 0.634429 | 999,055 | /**
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 SageOneIntegration.SA.V1_1_2.SageOneApiEntities;
import SageOneIntegration.SA.V1_1_2.SageOneEnumEntities.SageOnePaymentMethod;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
@JsonDeserialize(builder = SageOneCustomerReceipt.Builder.class)
public final class SageOneCustomerReceipt {
private final Integer ID;
private final Integer CustomerId;
private final Date Date;
private final String Payee;
//String length: inclusive between 0 and 100
private final String DocumentNumber;
//String length: inclusive between 0 and 100
private final String Reference;
//String length: inclusive between 0 and 100
private final String Description;
//String length: inclusive between 0 and 8000
private final String Comments;
private final Double Total;
private final Double Discount;
private final Double TotalUnallocated;
private final Boolean Reconciled;
private final Integer BankAccountId;
private final SageOnePaymentMethod SageOnePaymentMethod;
private final Integer TaxPeriodId;
private final Boolean Editable;
private final Boolean Accepted;
private final Boolean Locked;
//Gets or sets the Analysis Category identifier. This needs to be a valid AnalysisCategoryId.
private final Integer AnalysisCategoryId1;
// Gets or sets the Analysis Category identifier. This needs to be a valid AnalysisCategoryId.
private final Integer AnalysisCategoryId2;
//Gets or sets the Analysis Category identifier. This needs to be a valid AnalysisCategoryId.
private final Integer AnalysisCategoryId3;
private final Boolean Printed;
private final String BankUniqueIdentifier;
private final Integer ImportTypeId;
private final Integer BankImportMappingId;
private final Integer BankAccountCurrencyId;
private final Double BankAccountExchangeRate;
private final Integer CustomerCurrencyId;
private final Double CustomerExchangeRate;
private final Date Modified;
private final Date Created;
private final SageOneCustomer Customer;
private final SageOneSalesRepresentative SalesRepresentative;
private final SageOneBankAccount BankAccount;
public SageOneCustomerReceipt(Builder builder) {
ID = builder.ID;
CustomerId = builder.CustomerId;
Date = builder.Date;
Payee = builder.Payee;
DocumentNumber = builder.DocumentNumber;
Reference = builder.Reference;
Description = builder.Description;
Comments = builder.Comments;
Total = builder.Total;
Discount = builder.Discount;
TotalUnallocated = builder.TotalUnallocated;
Reconciled = builder.Reconciled;
BankAccountId = builder.BankAccountId;
SageOnePaymentMethod = builder.SageOnePaymentMethod;
TaxPeriodId = builder.TaxPeriodId;
Editable = builder.Editable;
Accepted = builder.Accepted;
Locked = builder.Locked;
AnalysisCategoryId1 = builder.AnalysisCategoryId1;
AnalysisCategoryId2 = builder.AnalysisCategoryId2;
AnalysisCategoryId3 = builder.AnalysisCategoryId3;
Printed = builder.Printed;
BankUniqueIdentifier = builder.BankUniqueIdentifier;
ImportTypeId = builder.ImportTypeId;
BankImportMappingId = builder.BankImportMappingId;
BankAccountCurrencyId = builder.BankAccountCurrencyId;
BankAccountExchangeRate = builder.BankAccountExchangeRate;
CustomerCurrencyId = builder.CustomerCurrencyId;
CustomerExchangeRate = builder.CustomerExchangeRate;
Modified = builder.Modified;
Created = builder.Created;
Customer = builder.Customer;
SalesRepresentative = builder.SalesRepresentative;
BankAccount = builder.BankAccount;
}
public static class Builder {
private Integer ID;
private Integer CustomerId;
private Date Date;
private String Payee;
private String DocumentNumber;
private String Reference;
private String Description;
private String Comments;
private Double Total;
private Double Discount;
private Double TotalUnallocated;
private Boolean Reconciled;
private Integer BankAccountId;
private SageOnePaymentMethod SageOnePaymentMethod;
private Integer TaxPeriodId;
private Boolean Editable;
private Boolean Accepted;
private Boolean Locked;
private Integer AnalysisCategoryId1;
private Integer AnalysisCategoryId2;
private Integer AnalysisCategoryId3;
private Boolean Printed;
private String BankUniqueIdentifier;
private Integer ImportTypeId;
private Integer BankImportMappingId;
private Integer BankAccountCurrencyId;
private Double BankAccountExchangeRate;
private Integer CustomerCurrencyId;
private Double CustomerExchangeRate;
private Date Modified;
private Date Created;
private SageOneCustomer Customer;
private SageOneSalesRepresentative SalesRepresentative;
private SageOneBankAccount BankAccount;
public Builder withId(final Integer val){
ID = val;
return this;
}
public Builder withCustomerId(final Integer val) {
CustomerId = val;
return this;
}
public Builder withDate(final java.util.Date val){
Date = val;
return this;
}
public Builder withPayee(final String val){
Payee = val;
return this;
}
public Builder withDocumentNumber(final String val){
DocumentNumber = val;
return this;
}
public Builder withReference(final String val){
Reference = val;
return this;
}
public Builder withDescription(final String val){
Description = val;
return this;
}
public Builder withComments(final String val){
Comments = val;
return this;
}
public Builder withTotal(final Double val){
Total = val;
return this;
}
public Builder withDiscount(final Double val){
Discount = val;
return this;
}
public Builder withTotalUnallocated(final Double val){
TotalUnallocated = val;
return this;
}
public Builder withReconciled(final Boolean val){
Reconciled = val;
return this;
}
public Builder withBankAccountId(final Integer val){
BankAccountId = val;
return this;
}
public Builder withPaymentMethod(final SageOnePaymentMethod val){
SageOnePaymentMethod = val;
return this;
}
public Builder withTaxPeriodId(final Integer val){
TaxPeriodId = val;
return this;
}
public Builder withEditable(final Boolean val){
Editable = val;
return this;
}
public Builder withAccepted(final Boolean val){
Accepted = val;
return this;
}
public Builder withLocked(final Boolean val){
Locked = val;
return this;
}
public Builder withAnalysisCategoryId1(final Integer val){
AnalysisCategoryId1 = val;
return this;
}
public Builder withAnalysisCategoryId2(final Integer val){
AnalysisCategoryId2 = val;
return this;
}
public Builder withAnalysisCategoryId3(final Integer val){
AnalysisCategoryId3 = val;
return this;
}
public Builder withPrinted(final Boolean val){
Printed = val;
return this;
}
public Builder withBankUniqueIdentifier(final String val){
BankUniqueIdentifier = val;
return this;
}
public Builder withImportTypeId(final Integer val){
ImportTypeId = val;
return this;
}
public Builder withBankImportMappingId(final Integer val){
BankImportMappingId = val;
return this;
}
public Builder withBankAccountCurrencyId(final Integer val){
BankAccountCurrencyId = val;
return this;
}
public Builder withBankAccountExchangeRate(final Double val){
BankAccountExchangeRate = val;
return this;
}
public Builder withCustomerCurrencyId(final Integer val){
CustomerCurrencyId = val;
return this;
}
public Builder withCustomerExchangeRate(final Double val){
CustomerExchangeRate = val;
return this;
}
public Builder withModified(final Date val){
Modified = val;
return this;
}
public Builder withCreated(final Date val){
Created = val;
return this;
}
public Builder withCustomer(final SageOneCustomer val){
Customer = val;
return this;
}
public Builder withSalesRepresentative(final SageOneSalesRepresentative val){
SalesRepresentative = val;
return this;
}
public Builder withBankAccount(final SageOneBankAccount val){
BankAccount = val;
return this;
}
public SageOneCustomerReceipt build(){
return new SageOneCustomerReceipt(this);
}
}
public Integer getId() {
return ID;
}
public Integer getCustomerId() {
return CustomerId;
}
public java.util.Date getDate() {
return Date;
}
public String getPayee() {
return Payee;
}
public String getDocumentNumber() {
return DocumentNumber;
}
public String getReference() {
return Reference;
}
public String getDescription() {
return Description;
}
public String getComments() {
return Comments;
}
public double getTotal() {
return Total;
}
public Double getDiscount() {
return Discount;
}
public Double getTotalUnallocated() {
return TotalUnallocated;
}
public Boolean isReconciled() {
return Reconciled;
}
public Integer getBankAccountId() {
return BankAccountId;
}
public SageOnePaymentMethod getSageOnePaymentMethod() {
return SageOnePaymentMethod;
}
public Integer getTaxPeriodId() {
return TaxPeriodId;
}
public Boolean isEditable() {
return Editable;
}
public Boolean isAccepted() {
return Accepted;
}
public Boolean isLocked() {
return Locked;
}
public Integer getAnalysisCategoryId1() {
return AnalysisCategoryId1;
}
public Integer getAnalysisCategoryId2() {
return AnalysisCategoryId2;
}
public Integer getAnalysisCategoryId3() {
return AnalysisCategoryId3;
}
public Boolean getPrinted() {
return Printed;
}
public String getBankUniqueIdentifier() {
return BankUniqueIdentifier;
}
public Integer getImportTypeId() {
return ImportTypeId;
}
public Integer getBankImportMappingId() {
return BankImportMappingId;
}
public Integer getBankAccountCurrencyId() {
return BankAccountCurrencyId;
}
public Double getBankAccountExchangeRate() {
return BankAccountExchangeRate;
}
public Integer getCustomerCurrencyId() {
return CustomerCurrencyId;
}
public Double getCustomerExchangeRate() {
return CustomerExchangeRate;
}
public Date getModified() {
return Modified;
}
public Date getCreated() {
return Created;
}
public final SageOneCustomer getCustomer() {
return Customer;
}
public final SageOneSalesRepresentative getSalesRepresentative() {
return SalesRepresentative;
}
public final SageOneBankAccount getBankAccount() {
return BankAccount;
}
}
|
923a0d3c84b5697ae3c1232b33e753fe4a487b2d | 3,499 | java | Java | Taller_parte_1/server/src/main/java/co/taller2/api/TripControllers.java | monotera/MC-Taller2 | bee4c2deb09a88bb9a6237cb31966029934e7bb6 | [
"MIT"
] | null | null | null | Taller_parte_1/server/src/main/java/co/taller2/api/TripControllers.java | monotera/MC-Taller2 | bee4c2deb09a88bb9a6237cb31966029934e7bb6 | [
"MIT"
] | null | null | null | Taller_parte_1/server/src/main/java/co/taller2/api/TripControllers.java | monotera/MC-Taller2 | bee4c2deb09a88bb9a6237cb31966029934e7bb6 | [
"MIT"
] | null | null | null | 28.917355 | 100 | 0.580166 | 999,056 | package co.taller2.api;
import java.util.ArrayList;
import java.util.Random;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("API")
public class TripControllers {
DataController dc = new DataController();
Random random = new Random();
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
@GET
@Path("trips")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ArrayList<Trip> printtrips() {
ArrayList<Trip> trips = dc.getData();
return trips;
}
@GET
@Path("get_ids")
@Produces(MediaType.APPLICATION_JSON)
public Response getIds() {
ArrayList<Trip> trips = dc.getData();
ArrayList<Integer> ids = new ArrayList<>();
for (Trip trip : trips) {
ids.add(trip.getId());
}
return Response.ok(ids).build();
}
@GET
@Path("trip")
@Produces(MediaType.APPLICATION_JSON)
public Response findtripById(@QueryParam("id") int id) {
ArrayList<Trip> trips = dc.getData();
for (Trip trip : trips) {
if (trip.getId() == id)
return Response.status(200).entity(trip).build();
}
return Response.status(404).build();
}
@POST
@Path("create_trip")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createTrip(Trip trip) {
ArrayList<Trip> trips = dc.getData();
if (trips.size() == 0)
trip.setId(0);
else
trip.setId(trips.get(trips.size() - 1).getId() + 1);
trips.add(trip);
dc.writeData(trips);
return Response.status(201).entity(trip).build();
}
@DELETE
@Path("delete_trip/{id}")
public Response deleteTrip(@PathParam("id") int id) {
ArrayList<Trip> trips = dc.getData();
for (Trip trip : trips) {
if (trip.getId() == id) {
trips.remove(trip);
dc.writeData(trips);
return Response.status(200).entity(trip).build();
}
}
return Response.status(404).build();
}
@PUT
@Path("update_trip_name")
public Response updateTrip(@QueryParam("id") int id, @QueryParam("name") String name) {
ArrayList<Trip> trips = dc.getData();
for (Trip trip : trips) {
if (trip.getId() == id) {
trip.setName(name);
dc.writeData(trips);
return Response.status(200).entity(trip).build();
}
}
return Response.status(404).build();
}
@PUT
@Path("update_trip_place")
public Response updateTripPlace(@QueryParam("id") int id, @QueryParam("arrival") String arrival,
@QueryParam("depature") String depature) {
ArrayList<Trip> trips = dc.getData();
for (Trip trip : trips) {
if (trip.getId() == id) {
trip.setPlace_arrival(arrival);
trip.setPlace_departure(depature);
dc.writeData(trips);
return Response.status(200).entity(trip).build();
}
}
return Response.status(404).build();
}
}
|
923a0d7427f549bff7929c373345c9e0f578d094 | 12,165 | java | Java | usermodel-initial/src/test/java/com/lambdaschool/usermodel/controllers/UserControllerNoDBTest.java | aldenho52/java-testingusermodel | 41877ca817211dfe3c5838be5c9264525153ab46 | [
"MIT"
] | null | null | null | usermodel-initial/src/test/java/com/lambdaschool/usermodel/controllers/UserControllerNoDBTest.java | aldenho52/java-testingusermodel | 41877ca817211dfe3c5838be5c9264525153ab46 | [
"MIT"
] | null | null | null | usermodel-initial/src/test/java/com/lambdaschool/usermodel/controllers/UserControllerNoDBTest.java | aldenho52/java-testingusermodel | 41877ca817211dfe3c5838be5c9264525153ab46 | [
"MIT"
] | null | null | null | 29.52657 | 87 | 0.596777 | 999,057 | package com.lambdaschool.usermodel.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lambdaschool.usermodel.UserModelApplicationTest;
import com.lambdaschool.usermodel.models.Role;
import com.lambdaschool.usermodel.models.User;
import com.lambdaschool.usermodel.models.UserRoles;
import com.lambdaschool.usermodel.models.Useremail;
import com.lambdaschool.usermodel.services.UserService;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = UserModelApplicationTest.class,
properties = {
"command.line.runner.enabled=false"})
@AutoConfigureMockMvc
public class UserControllerNoDBTest
{
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@MockBean
private UserService userService;
private List<User> userList;
@Before
public void setUp() throws Exception
{
userList = new ArrayList<>();
Role r1 = new Role("admin");
Role r2 = new Role("user");
Role r3 = new Role("data");
r1.setRoleid(1);
r2.setRoleid(2);
r3.setRoleid(3);
// admin, data, user
User u1 = new User("admin",
"password",
"lyhxr@example.com");
u1.setUserid(10);
u1.getRoles()
.add(new UserRoles(u1,
r1));
u1.getRoles()
.add(new UserRoles(u1,
r2));
u1.getRoles()
.add(new UserRoles(u1,
r3));
u1.getUseremails()
.add(new Useremail(u1,
"hzdkv@example.com"));
u1.getUseremails()
.add(new Useremail(u1,
"kenaa@example.com"));
userList.add(u1);
// data, user
User u2 = new User("cinnamon",
"1234567",
"dycjh@example.com");
u2.setUserid(20);
u2.getRoles()
.add(new UserRoles(u2,
r2));
u2.getRoles()
.add(new UserRoles(u2,
r3));
u2.getUseremails()
.add(new Useremail(u2,
"anpch@example.com"));
u2.getUseremails()
.add(new Useremail(u2,
"lyhxr@example.com"));
u2.getUseremails()
.add(new Useremail(u2,
"hzdkv@example.com"));
userList.add(u2);
// user
User u3 = new User("barnbarn",
"ILuvM4th!",
"nnheo@example.com");
u3.setUserid(30);
u3.getRoles()
.add(new UserRoles(u3,
r2));
u3.getUseremails()
.add(new Useremail(u3,
"envkt@example.com"));
userList.add(u3);
RestAssuredMockMvc.webAppContextSetup(webApplicationContext);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
}
@After
public void tearDown() throws Exception
{
}
@Test
public void listAllUsers() throws Exception
{
String apiUrl = "/users/users";
Mockito.when(userService.findAll())
.thenReturn(userList);
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl)
.accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb)
.andReturn();
String tr = r.getResponse()
.getContentAsString();
ObjectMapper mapper = new ObjectMapper();
String er = mapper.writeValueAsString(userList);
System.out.println(er);
assertEquals(er,
tr);
}
@Test
public void getUserById() throws Exception
{
String apiUrl = "/users/user/10";
Mockito.when(userService.findUserById(10))
.thenReturn(userList.get(0));
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl)
.accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb)
.andReturn();
String tr = r.getResponse()
.getContentAsString();
ObjectMapper mapper = new ObjectMapper();
String er = mapper.writeValueAsString(userList.get(0));
System.out.println(tr);
assertEquals(er,
tr);
}
@Test
public void getUserByIdNotFound() throws Exception
{
String apiUrl = "/users/user/100";
Mockito.when(userService.findUserById(100))
.thenReturn(null);
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl)
.accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb)
.andReturn();
String tr = r.getResponse()
.getContentAsString();
String er = "";
System.out.println(tr);
assertEquals(er,
tr);
}
@Test
public void getUserByName() throws Exception
{
String apiUrl = "/users/user/name/admin";
Mockito.when(userService.findByName("admin"))
.thenReturn(userList.get(0));
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl)
.accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb)
.andReturn(); // this could throw an exception
String tr = r.getResponse()
.getContentAsString();
ObjectMapper mapper = new ObjectMapper();
String er = mapper.writeValueAsString(userList.get(0));
System.out.println("Expect: " + er);
System.out.println("Actual: " + tr);
Assert.assertEquals("Rest API Returns List",
er,
tr);
}
@Test
public void getUserByNameNotFound() throws Exception
{
String apiUrl = "/users/user/name/admin";
Mockito.when(userService.findByName("Turtle"))
.thenReturn(null);
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl)
.accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb)
.andReturn(); // this could throw an exception
String tr = r.getResponse()
.getContentAsString();
String er = "";
System.out.println("Expect: " + er);
System.out.println("Actual: " + tr);
Assert.assertEquals(
er,
tr);
}
@Test
public void getUserLikeName() throws Exception
{
String apiUrl = "/users/user/name/like/adm";
Mockito.when(userService.findByNameContaining("adm"))
.thenReturn(userList);
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl)
.accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb)
.andReturn(); // this could throw an exception
String tr = r.getResponse()
.getContentAsString();
ObjectMapper mapper = new ObjectMapper();
String er = mapper.writeValueAsString(userList);
System.out.println("Expect: " + er);
System.out.println("Actual: " + tr);
Assert.assertEquals("Rest API Returns List",
er,
tr);
}
@Test
public void addNewUser() throws Exception
{
String apiUrl = "/users/user";
User u1 = new User("alden",
"password",
"lyhxr@example.com");
u1.setUserid(12);
Role r1 = new Role("admin");
r1.setRoleid(1);
u1.getRoles()
.add(new UserRoles(u1,
r1));
u1.getUseremails()
.add(new Useremail(u1,
"hzdkv@example.com"));
u1.getUseremails()
.add(new Useremail(u1,
"kenaa@example.com"));
ObjectMapper mapper = new ObjectMapper();
String userString = mapper.writeValueAsString(u1);
Mockito.when(userService.save(any(User.class)))
.thenReturn(u1);
RequestBuilder rb = MockMvcRequestBuilders.post(apiUrl)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(userString);
mockMvc.perform(rb)
.andExpect(status().isCreated())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void updateFullUser() throws Exception
{
String apiUrl = "/users/user/{userid}";
User u1 = new User("alden",
"password",
"lyhxr@example.com");
u1.setUserid(12);
Role r1 = new Role("admin");
r1.setRoleid(1);
u1.getRoles()
.add(new UserRoles(u1,
r1));
u1.getUseremails()
.add(new Useremail(u1,
"hzdkv@example.com"));
u1.getUseremails()
.add(new Useremail(u1,
"kenaa@example.com"));
Mockito.when(userService.update(u1,
10L))
.thenReturn(u1);
ObjectMapper mapper = new ObjectMapper();
String userString = mapper.writeValueAsString(u1);
RequestBuilder rb = MockMvcRequestBuilders.put(apiUrl,
10L)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(userString);
mockMvc.perform(rb)
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void updateUser() throws Exception
{
String apiUrl = "/users/user/{userid}";
User u1 = new User("alden",
"password",
"lyhxr@example.com");
u1.setUserid(12);
// Role r1 = new Role("admin");
// r1.setRoleid(1);
//
// u1.getRoles()
// .add(new UserRoles(u1,
// r1));
// u1.getUseremails()
// .add(new Useremail(u1,
// "hzdkv@example.com"));
// u1.getUseremails()
// .add(new Useremail(u1,
// "kenaa@example.com"));
Mockito.when(userService.update(u1,
10L))
.thenReturn(u1);
ObjectMapper mapper = new ObjectMapper();
String userString = mapper.writeValueAsString(u1);
RequestBuilder rb = MockMvcRequestBuilders.patch(apiUrl,
10L)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(userString);
mockMvc.perform(rb)
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void deleteUserById() throws Exception
{
String apiUrl = "/users/user/{id}";
RequestBuilder rb = MockMvcRequestBuilders.delete(apiUrl,
"12")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
mockMvc.perform(rb)
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print());
}
} |
923a0f5efe195d69108577ac5a4994ca897bdae3 | 5,380 | java | Java | fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauConfigurationWritePlatformServiceImpl.java | Azeemudeen101/fineract | 764b98b202c050a68c59909bd867c9b6de5fea14 | [
"ECL-2.0",
"Apache-2.0"
] | 668 | 2017-05-17T15:41:24.000Z | 2022-03-24T15:00:37.000Z | fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauConfigurationWritePlatformServiceImpl.java | Azeemudeen101/fineract | 764b98b202c050a68c59909bd867c9b6de5fea14 | [
"ECL-2.0",
"Apache-2.0"
] | 1,114 | 2017-05-22T13:48:25.000Z | 2022-03-31T09:49:53.000Z | fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauConfigurationWritePlatformServiceImpl.java | Azeemudeen101/fineract | 764b98b202c050a68c59909bd867c9b6de5fea14 | [
"ECL-2.0",
"Apache-2.0"
] | 918 | 2017-05-17T13:28:06.000Z | 2022-03-31T20:09:01.000Z | 48.468468 | 127 | 0.784015 | 999,058 | /**
* 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.fineract.infrastructure.creditbureau.service;
import java.util.Map;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder;
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfiguration;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepository;
import org.apache.fineract.infrastructure.creditbureau.domain.OrganisationCreditBureau;
import org.apache.fineract.infrastructure.creditbureau.domain.OrganisationCreditBureauRepository;
import org.apache.fineract.infrastructure.creditbureau.exception.CreditReportNotFoundException;
import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauConfigurationCommandFromApiJsonDeserializer;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CreditBureauConfigurationWritePlatformServiceImpl implements CreditBureauConfigurationWritePlatformService {
private final PlatformSecurityContext context;
private final CreditBureauConfigurationCommandFromApiJsonDeserializer fromApiJsonDeserializer;
private final CreditBureauConfigurationRepository creditBureauConfigurationRepository;
private final OrganisationCreditBureauRepository organisationCreditBureauRepository;
@Autowired
public CreditBureauConfigurationWritePlatformServiceImpl(final PlatformSecurityContext context,
final CreditBureauConfigurationCommandFromApiJsonDeserializer fromApiJsonDeserializer,
final CreditBureauConfigurationRepository creditBureauConfigurationRepository,
OrganisationCreditBureauRepository organisationCreditBureauRepository) {
this.context = context;
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.creditBureauConfigurationRepository = creditBureauConfigurationRepository;
this.organisationCreditBureauRepository = organisationCreditBureauRepository;
}
@Transactional
@Override
public CommandProcessingResult addCreditBureauConfiguration(Long creditBureauId, JsonCommand command) {
this.context.authenticatedUser();
this.fromApiJsonDeserializer.validateForCreate(command.json(), creditBureauId);
final OrganisationCreditBureau orgcb = this.organisationCreditBureauRepository.getById(creditBureauId);
final CreditBureauConfiguration cb_config = CreditBureauConfiguration.fromJson(command, orgcb);
this.creditBureauConfigurationRepository.save(cb_config);
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(cb_config.getId()).build();
}
@Transactional
@Override
public CommandProcessingResult updateCreditBureauConfiguration(Long configurationId, JsonCommand command) {
try {
this.context.authenticatedUser();
this.fromApiJsonDeserializer.validateForUpdate(command.json());
final CreditBureauConfiguration config = retrieveConfigBy(configurationId);
final Map<String, Object> changes = config.update(command);
if (!changes.isEmpty()) {
this.creditBureauConfigurationRepository.save(config);
}
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) //
.withEntityId(configurationId) //
.with(changes) //
.build();
} catch (final JpaSystemException | DataIntegrityViolationException dve) {
throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue",
"Unknown data integrity issue with resource: " + dve.getMostSpecificCause(), dve);
}
}
private CreditBureauConfiguration retrieveConfigBy(final Long creditBureauId) {
return this.creditBureauConfigurationRepository.findById(creditBureauId)
.orElseThrow(() -> new CreditReportNotFoundException(creditBureauId));
}
}
|
923a0fe1f1654fcc545bd8b7a9abcd7dc80819c3 | 4,435 | java | Java | vlcandroid/src/org/videolan/vlc/gui/audio/AlbumAdapter.java | skylarklxlong/vlc-android | b06be3606ab62e7444464f08ddd22ce63f9df163 | [
"Apache-2.0"
] | 1 | 2020-12-30T21:46:01.000Z | 2020-12-30T21:46:01.000Z | vlcandroid/src/org/videolan/vlc/gui/audio/AlbumAdapter.java | skylarklxlong/vlc-android | b06be3606ab62e7444464f08ddd22ce63f9df163 | [
"Apache-2.0"
] | null | null | null | vlcandroid/src/org/videolan/vlc/gui/audio/AlbumAdapter.java | skylarklxlong/vlc-android | b06be3606ab62e7444464f08ddd22ce63f9df163 | [
"Apache-2.0"
] | null | null | null | 31.906475 | 114 | 0.655017 | 999,059 | /*
* *************************************************************************
* AlbumAdapter.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.audio;
import android.content.Context;
import android.database.DataSetObserver;
import android.databinding.DataBindingUtil;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import org.videolan.medialibrary.media.MediaWrapper;
import org.videolan.vlc.R;
import org.videolan.vlc.databinding.AudioBrowserItemBinding;
import org.videolan.vlc.gui.helpers.MediaComparators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class AlbumAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<MediaWrapper> mMediaList;
private ContextPopupMenuListener mContextPopupMenuListener;
public AlbumAdapter(Context context, MediaWrapper[] tracks) {
mContext = context;
addAll(tracks);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
MediaWrapper mw = mMediaList.get(position);
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
holder.binding = DataBindingUtil.inflate(inflater, R.layout.audio_browser_item, parent, false);
v = holder.binding.getRoot();
v.setTag(R.layout.audio_browser_item, holder);
} else
holder = (ViewHolder) v.getTag(R.layout.audio_browser_item);
holder.binding.setItem(mw);
holder.binding.executePendingBindings();
return v;
}
@MainThread
public void addMedia(int position, MediaWrapper media) {
mMediaList.add(position, media);
notifyDataSetChanged();
}
@MainThread void removeMedia(int position) {
mMediaList.remove(position);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mMediaList == null ? 0 : mMediaList.size();
}
public MediaWrapper getItem(int position) {
return mMediaList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Nullable
public String getLocation(int position) {
if (position >= 0 && position < mMediaList.size())
return mMediaList.get(position).getLocation();
else
return null;
}
public void addAll(MediaWrapper[] tracks){
if (tracks != null) {
mMediaList = new ArrayList<>(Arrays.asList(tracks));
Collections.sort(mMediaList, MediaComparators.byTrackNumber);
notifyDataSetChanged();
}
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null)
super.unregisterDataSetObserver(observer);
}
public void clear() {
mMediaList.clear();
}
static class ViewHolder {
AudioBrowserItemBinding binding;
}
public interface ContextPopupMenuListener {
void onPopupMenu(View anchor, final int position);
}
void setContextPopupMenuListener(ContextPopupMenuListener l) {
mContextPopupMenuListener = l;
}
}
|
923a11ae6a9fb5c337fae30cc279a457809e94d0 | 13,692 | java | Java | generated-test-cases/RecordTypeMessage/13-run/Evosuite_RecordTypeMessage_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | null | null | null | generated-test-cases/RecordTypeMessage/13-run/Evosuite_RecordTypeMessage_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | 1 | 2017-05-11T21:18:17.000Z | 2017-05-11T21:18:17.000Z | generated-test-cases/RecordTypeMessage/13-run/Evosuite_RecordTypeMessage_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | null | null | null | 44.31068 | 234 | 0.726483 | 999,060 | /*
* This file was automatically generated by EvoSuite
* Sun Dec 20 01:37:55 GMT 2015
*/
package net.sf.xbus.protocol.records;
import static org.junit.Assert.*;
import org.junit.Test;
import net.sf.xbus.base.bytearraylist.ByteArrayList;
import net.sf.xbus.base.xbussystem.XBUSSystem;
import net.sf.xbus.protocol.records.RecordTypeMessage;
import org.apache.html.dom.HTMLDocumentImpl;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.EvoSuiteLocalAddress;
import org.evosuite.runtime.testdata.EvoSuiteRemoteAddress;
import org.evosuite.runtime.testdata.EvoSuiteURL;
import org.junit.runner.RunWith;
import org.w3c.dom.Document;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true)
public class RecordTypeMessage_ESTest extends RecordTypeMessage_ESTest_scaffolding {
//Test case number: 0
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseObject()Ljava/lang/Object;: I15 Branch 11 IFNULL L279 - false
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseObject()Ljava/lang/Object;: I21 Branch 12 IFNULL L279 - true
*/
@Test
public void test00() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("h", (XBUSSystem) null, "h");
HTMLDocumentImpl hTMLDocumentImpl0 = new HTMLDocumentImpl();
recordTypeMessage0.setResponseDocument((Document) hTMLDocumentImpl0, (XBUSSystem) null);
Object object0 = recordTypeMessage0.getResponseObject();
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
}
//Test case number: 1
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseObject()Ljava/lang/Object;: I15 Branch 11 IFNULL L279 - true
*/
@Test
public void test01() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("+'x fA/4Z9&z0", (XBUSSystem) null, "+'x fA/4Z9&z0");
Object object0 = recordTypeMessage0.getResponseObject();
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 2
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I44 Branch 10 IFNE L247 - true
*/
@Test
public void test02() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("zd/qk_;<I", (XBUSSystem) null, "zd/qk_;<I");
byte[] byteArray0 = new byte[4];
ByteArrayList byteArrayList0 = ByteArrayList.createByteArrayList(byteArray0, (int) (byte) (-116));
// Undeclared exception!
try {
recordTypeMessage0.setResponseObject((Object) byteArrayList0, (XBUSSystem) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 3
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 9 IFNONNULL L239 - false
*/
@Test
public void test03() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("", (XBUSSystem) null, "");
recordTypeMessage0.setResponseObject((Object) null, (XBUSSystem) null);
assertEquals(0, recordTypeMessage0.getErrorcode());
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
}
//Test case number: 4
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getRequestObject(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Ljava/lang/Object;: I16 Branch 8 IFNULL L216 - true
*/
@Test
public void test04() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("", (XBUSSystem) null, "");
Object object0 = recordTypeMessage0.getRequestObject((XBUSSystem) null);
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 5
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I29 Branch 7 IFNE L181 - true
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.parseRecordsFromByteArrayList(Lnet/sf/xbus/base/bytearraylist/ByteArrayList;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Lorg/w3c/dom/Document;: I10 Branch 14 IFNULL L360 - false
*/
@Test
public void test05() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
byte[] byteArray0 = new byte[11];
ByteArrayList byteArrayList0 = ByteArrayList.createByteArrayList(byteArray0, (int) (byte)0);
// Undeclared exception!
try {
recordTypeMessage0.setRequestObject((Object) byteArrayList0, (XBUSSystem) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 6
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 6 IFNONNULL L173 - false
*/
@Test
public void test06() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("+'x fA/4Z9&z0", (XBUSSystem) null, "+'x fA/4Z9&z0");
recordTypeMessage0.setRequestObject((Object) null, (XBUSSystem) null);
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 7
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 6 IFNONNULL L173 - true
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I29 Branch 7 IFNE L181 - false
*/
@Test
public void test07() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
byte[] byteArray0 = new byte[14];
ByteArrayList byteArrayList0 = ByteArrayList.createByteArrayList(byteArray0, (int) (byte)16);
recordTypeMessage0.setRequestObject((Object) byteArrayList0, (XBUSSystem) null);
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 8
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseText()Ljava/lang/String;: I15 Branch 4 IFNULL L153 - false
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseText()Ljava/lang/String;: I21 Branch 5 IFNULL L153 - true
*/
@Test
public void test08() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("h", (XBUSSystem) null, "h");
HTMLDocumentImpl hTMLDocumentImpl0 = new HTMLDocumentImpl();
recordTypeMessage0.setResponseDocument((Document) hTMLDocumentImpl0, (XBUSSystem) null);
String string0 = recordTypeMessage0.getResponseText();
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
}
//Test case number: 9
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseText()Ljava/lang/String;: I15 Branch 4 IFNULL L153 - true
*/
@Test
public void test09() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("", (XBUSSystem) null, "");
String string0 = recordTypeMessage0.getResponseText();
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 10
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 3 IFNONNULL L132 - true
*/
@Test
public void test10() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("+'x fA/4Z9&z0", (XBUSSystem) null, "+'x fA/4Z9&z0");
// Undeclared exception!
try {
recordTypeMessage0.setResponseText("+'x fA/4Z9&z0", (XBUSSystem) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 11
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getRequestText(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Ljava/lang/String;: I16 Branch 2 IFNULL L110 - true
*/
@Test
public void test11() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
String string0 = recordTypeMessage0.getRequestText((XBUSSystem) null);
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 12
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 1 IFNONNULL L87 - true
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.parseRecordsFromString(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Lorg/w3c/dom/Document;: I10 Branch 13 IFNULL L336 - false
*/
@Test
public void test12() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("c", (XBUSSystem) null, "c");
// Undeclared exception!
try {
recordTypeMessage0.setRequestText("c", (XBUSSystem) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 13
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getRequestTextAsXML(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Ljava/lang/String;: root-Branch
*/
@Test
public void test13() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("h", (XBUSSystem) null, "h");
String string0 = recordTypeMessage0.getRequestTextAsXML((XBUSSystem) null);
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 14
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.<init>(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: root-Branch
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 1 IFNONNULL L87 - false
*/
@Test
public void test14() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
recordTypeMessage0.setRequestText((String) null, (XBUSSystem) null);
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 15
/*
* 3 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.synchronizeRequestFields(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: root-Branch
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 9 IFNONNULL L239 - true
* Goal 3. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I44 Branch 10 IFNE L247 - false
*/
@Test
public void test15() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("", (XBUSSystem) null, "");
ByteArrayList byteArrayList0 = new ByteArrayList();
recordTypeMessage0.setResponseObject((Object) byteArrayList0, (XBUSSystem) null);
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
assertEquals(0, recordTypeMessage0.getErrorcode());
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 16
/*
* 4 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseDocument(Lorg/w3c/dom/Document;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: root-Branch
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.synchronizeResponseFields(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: root-Branch
* Goal 3. net.sf.xbus.protocol.records.RecordTypeMessage.<init>(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;Ljava/lang/String;)V: root-Branch
* Goal 4. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 3 IFNONNULL L132 - false
*/
@Test
public void test16() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("", (XBUSSystem) null, "");
recordTypeMessage0.setResponseText((String) null, (XBUSSystem) null);
assertEquals(0, recordTypeMessage0.getErrorcode());
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
}
|
923a1290f2381a91693e69abe855c36d33362ac4 | 3,070 | java | Java | test/com/thetransactioncompany/cors/OriginTest.java | LuisSala/CORS-Java-Servlet-Filter | 919897dc6d5719cbcd7518317e141382a689793e | [
"Apache-2.0"
] | 3 | 2015-07-03T23:08:14.000Z | 2017-06-07T10:02:50.000Z | test/com/thetransactioncompany/cors/OriginTest.java | LuisSala/CORS-Java-Servlet-Filter | 919897dc6d5719cbcd7518317e141382a689793e | [
"Apache-2.0"
] | null | null | null | test/com/thetransactioncompany/cors/OriginTest.java | LuisSala/CORS-Java-Servlet-Filter | 919897dc6d5719cbcd7518317e141382a689793e | [
"Apache-2.0"
] | 2 | 2017-07-06T09:38:49.000Z | 2017-07-06T09:39:06.000Z | 15.19802 | 60 | 0.580456 | 999,061 | package com.thetransactioncompany.cors;
import java.util.*;
import junit.framework.*;
/**
* Tests the origin class.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2010-09-24)
*/
public class OriginTest extends TestCase {
public void testConstructorUnknown() {
Origin o = new Origin();
assertTrue(o.equals(Origin.UNKNOWN));
}
public void testConstructor1() {
String uri = "http://example.com";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertEquals(uri, o.toString());
}
public void testConstructor2() {
String uri = "HTTP://example.com";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertEquals("http://example.com", o.toString());
}
public void testConstructor3() {
String uri = "https://example.com";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertEquals(uri, o.toString());
}
public void testConstructor4() {
String uri = "file:///data/file.xml";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertEquals(uri, o.toString());
}
public void testConstructor5() {
String uri = "http://192.168.0.1:8080";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertEquals(uri, o.toString());
}
public void testConstructor6() {
String uri = "https://LOCALHOST:8080/my-app/upload.php";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertEquals("https://localhost:8080", o.toString());
}
public void testConstructor7() {
String uri = "ftp://ftp.example.com";
Origin o = null;
try {
o = new Origin(uri);
fail("Failed to raise bad protocol exception on FTP://");
} catch (OriginException e) {
// ok
}
}
public void testEquality1() {
String uri1 = "http://MY.service.com";
String uri2 = "HTTP://my.service.com/my-app";
Origin o1 = null;
Origin o2 = null;
try {
o1 = new Origin(uri1);
o2 = new Origin(uri2);
} catch (OriginException e) {
fail(e.getMessage());
}
assertTrue(o1.equals(o2));
}
public void testEquality2() {
String uri1 = "http://MY.service.com";
String uri2 = "HTTPS://my.service.com/my-app";
Origin o1 = null;
Origin o2 = null;
try {
o1 = new Origin(uri1);
o2 = new Origin(uri2);
} catch (OriginException e) {
fail(e.getMessage());
}
assertFalse(o1.equals(o2));
}
public void testEqualityWithString() {
String uri = "http://my.service.com";
Origin o = null;
try {
o = new Origin(uri);
} catch (OriginException e) {
fail(e.getMessage());
}
assertTrue(o.equals(uri));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.