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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0f630951d69c362d4246dace731bfbcdd86d73 | 2,090 | java | Java | frontend/frontend-core/src/main/java/org/bloomreach/forge/settings/management/config/eventlog/EventLogConfigPanel.java | onehippo-forge/settings-management | 520e3fffded50a92d3ae4065f31806e50c30548f | [
"Apache-2.0"
] | null | null | null | frontend/frontend-core/src/main/java/org/bloomreach/forge/settings/management/config/eventlog/EventLogConfigPanel.java | onehippo-forge/settings-management | 520e3fffded50a92d3ae4065f31806e50c30548f | [
"Apache-2.0"
] | null | null | null | frontend/frontend-core/src/main/java/org/bloomreach/forge/settings/management/config/eventlog/EventLogConfigPanel.java | onehippo-forge/settings-management | 520e3fffded50a92d3ae4065f31806e50c30548f | [
"Apache-2.0"
] | 2 | 2019-02-22T20:10:31.000Z | 2020-03-25T18:01:31.000Z | 38 | 108 | 0.743541 | 6,529 | /*
* Copyright 2013-2020 Bloomreach Inc. (http://www.bloomreach.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.bloomreach.forge.settings.management.config.eventlog;
import javax.jcr.RepositoryException;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.hippoecm.frontend.plugin.IPluginContext;
import org.hippoecm.frontend.plugin.config.IPluginConfig;
import org.bloomreach.forge.settings.management.FeatureConfigPanel;
import org.bloomreach.forge.settings.management.config.CMSFeatureConfig;
public class EventLogConfigPanel extends FeatureConfigPanel {
private EventLogConfigModel detachableEventLogConfig = new EventLogConfigModel();
public EventLogConfigPanel(IPluginContext context, IPluginConfig config) {
super(context, config, new ResourceModel("title"));
add(new TextField("cronexpression", new PropertyModel(detachableEventLogConfig, "cronexpression")));
add(new TextField("minutestolive", new PropertyModel(detachableEventLogConfig, "minutestolive")));
add(new TextField("maxitems", new PropertyModel(detachableEventLogConfig, "maxitems")));
}
public void save() {
CMSFeatureConfig config = detachableEventLogConfig.getConfig();
try {
config.save();
} catch (RepositoryException e) {
error("An error occurred while trying to save event log configuration: " + e);
}
}
public void cancel() {
// do nothing.
}
}
|
3e0f63383620b0b8b13076751bda9d8247e36da0 | 1,202 | java | Java | skygear/src/main/java/io/skygear/skygear/SetAdminRoleRequest.java | SkygearIO/skygear-SDK-Android | f28f34852c32eb325b90a83b92e920d7f41c5033 | [
"Apache-2.0"
] | 16 | 2016-06-24T03:26:57.000Z | 2019-07-04T18:05:19.000Z | skygear/src/main/java/io/skygear/skygear/SetAdminRoleRequest.java | SkygearIO/skygear-SDK-Android | f28f34852c32eb325b90a83b92e920d7f41c5033 | [
"Apache-2.0"
] | 224 | 2016-05-30T00:48:21.000Z | 2019-05-03T09:32:10.000Z | skygear/src/main/java/io/skygear/skygear/SetAdminRoleRequest.java | SkygearIO/skygear-SDK-Android | f28f34852c32eb325b90a83b92e920d7f41c5033 | [
"Apache-2.0"
] | 43 | 2016-06-03T09:46:52.000Z | 2021-10-12T14:38:41.000Z | 27.318182 | 75 | 0.661398 | 6,530 | /*
* Copyright 2017 Oursky Ltd.
*
* 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.skygear.skygear;
import java.util.HashMap;
/**
* The Skygear Admin Role Setup Request.
*/
public class SetAdminRoleRequest extends Request {
/**
* Instantiates a new Set Admin Role Request.
*
* @param roles the roles array
*/
public SetAdminRoleRequest(Role[] roles) {
super("role:admin");
this.data = new HashMap<>();
String[] roleNames = new String[roles.length];
for (int idx = 0; idx < roles.length; idx++) {
roleNames[idx] = roles[idx].getName();
}
this.data.put("roles", roleNames);
}
}
|
3e0f637794b43f1238d5eb291dd14330bbef8aac | 2,631 | java | Java | app/src/main/java/ch/abertschi/loris/TabHostDetails.java | abertschi/loris | 92fa082098892862c944b4fc45e41a4ee141ce3d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/ch/abertschi/loris/TabHostDetails.java | abertschi/loris | 92fa082098892862c944b4fc45e41a4ee141ce3d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/ch/abertschi/loris/TabHostDetails.java | abertschi/loris | 92fa082098892862c944b4fc45e41a4ee141ce3d | [
"Apache-2.0"
] | null | null | null | 36.041096 | 103 | 0.582288 | 6,531 | package ch.abertschi.loris;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import com.afollestad.materialdialogs.MaterialDialog;
/**
* Created by abertschi on 19.11.16.
*/
public class TabHostDetails extends Fragment {
@Override
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
View confirmHostName = view.findViewById(R.id.confirm_hostname);
confirmHostName.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
System.out.println("button pressed");
EditText hostname = (EditText) view.findViewById(R.id.editText);
Editable text = hostname.getText();
if (text.toString().trim().isEmpty()) {
MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
.title("Hold on!")
.content("Enter a valid host name to continue.")
.positiveText("Got it")
.show();
} else {
final Handler h = new Handler(Looper.getMainLooper());
final Runnable r = new Runnable() {
public void run() {
FullscreenActivity.getInstance()
.getViewPager().setCurrentItem(2, true);
}
};
h.postDelayed(r, 500);
}
return false;
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_hostname, container, false);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if (getActivity() != null) {
ImageView img = (ImageView) getActivity().findViewById(R.id.face);
if (img != null) {
img.setImageResource(R.mipmap.suspicious);
}
}
}
}
}
|
3e0f63ac75e59c466c1e91ef72ecbf1c98a32ef9 | 535 | java | Java | aoc01/src/main/java/net/aoc/InverseCaptcha.java | abmmrusso/advent-of-code-2017 | 6eab571357b2afbd18995b165fb243eaaafb2c3d | [
"MIT"
] | null | null | null | aoc01/src/main/java/net/aoc/InverseCaptcha.java | abmmrusso/advent-of-code-2017 | 6eab571357b2afbd18995b165fb243eaaafb2c3d | [
"MIT"
] | null | null | null | aoc01/src/main/java/net/aoc/InverseCaptcha.java | abmmrusso/advent-of-code-2017 | 6eab571357b2afbd18995b165fb243eaaafb2c3d | [
"MIT"
] | null | null | null | 25.47619 | 110 | 0.579439 | 6,532 | package net.aoc;
import java.util.stream.IntStream;
public class InverseCaptcha {
public int captchaSolution(int[] captcha, int captchaCycleFactor) {
if(captcha == null || captcha.length == 0) {
return 0;
}
if(captcha.length % 2 != 0) {
throw new IllegalArgumentException();
}
return IntStream.range(0, captcha.length)
.map(idx -> captcha[idx] == captcha[(idx + captchaCycleFactor)%captcha.length]?captcha[idx]:0)
.sum();
}
}
|
3e0f63d527cd32b3abe2ad5c689d56eb8a9e79bd | 1,868 | java | Java | src/jazari/utils/JOptionPaneExample.java | hakmesyo/OpenJazariLibrary | 20b45c855b6c5d950575d4122aa55b49a58ba41d | [
"MIT"
] | 1 | 2022-03-15T10:59:39.000Z | 2022-03-15T10:59:39.000Z | src/jazari/utils/JOptionPaneExample.java | hakmesyo/OpenJazariLibrary | 20b45c855b6c5d950575d4122aa55b49a58ba41d | [
"MIT"
] | null | null | null | src/jazari/utils/JOptionPaneExample.java | hakmesyo/OpenJazariLibrary | 20b45c855b6c5d950575d4122aa55b49a58ba41d | [
"MIT"
] | null | null | null | 25.589041 | 79 | 0.614026 | 6,533 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jazari.utils;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JOptionPaneExample {
private JLabel label;
private JTextField tfield;
private JLabel statusLabel;
private static final int GAP = 5;
private void displayGUI() {
JOptionPane.showMessageDialog(null, getPanel());
}
private JPanel getPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
label = new JLabel("Enter something: ", JLabel.CENTER);
tfield = new JTextField(10);
tfield.getDocument().addDocumentListener(new MyDocumentListener());
JPanel controlPanel = new JPanel();
controlPanel.add(label);
controlPanel.add(tfield);
panel.add(controlPanel);
statusLabel = new JLabel("", JLabel.CENTER);
panel.add(statusLabel);
return panel;
}
private class MyDocumentListener implements DocumentListener {
@Override
public void changedUpdate(DocumentEvent de) {
updateStatus();
}
@Override
public void insertUpdate(DocumentEvent de) {
updateStatus();
}
@Override
public void removeUpdate(DocumentEvent de) {
updateStatus();
}
private void updateStatus() {
statusLabel.setText(tfield.getText());
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new JOptionPaneExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
|
3e0f6418ffdbc471c2fa37286b8986590be07644 | 4,981 | java | Java | loglib/src/main/java/com/simpalm/loglib/FileLogger.java | ramsimpalm/SplLib | f68b07b5fd70dff13a946810feaad74e78be127c | [
"Apache-2.0"
] | null | null | null | loglib/src/main/java/com/simpalm/loglib/FileLogger.java | ramsimpalm/SplLib | f68b07b5fd70dff13a946810feaad74e78be127c | [
"Apache-2.0"
] | null | null | null | loglib/src/main/java/com/simpalm/loglib/FileLogger.java | ramsimpalm/SplLib | f68b07b5fd70dff13a946810feaad74e78be127c | [
"Apache-2.0"
] | null | null | null | 28.462857 | 85 | 0.453323 | 6,534 | package com.simpalm.loglib;
import android.content.Context;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Utility class to write logs in cache file
*/
public class FileLogger {
public static final String FILE_BEGIN_MARKER = " ******************** ";
public static final String NEW_LINE = "\n";
private final String COLUMN_DIVIDER = "\t";
private final String LOG_DIR = "logs";
private final String FILE_EXT = ".log";
private final SimpleDateFormat SDF = new SimpleDateFormat("yyMMdd-HH:mm:ss.SSS");
public enum LogType {
V, D, I, W, E, EX, EI;
@Override
public String toString() {
switch (this) {
case V:
return "V";
case D:
return "D";
case I:
return "I";
case W:
return "W";
case E:
return "E";
case EX:
return "EX";
case EI:
return "EI";
default:
return "V";
}
}
public static LogType fromString(String type) {
switch (type) {
case "V":
return V;
case "D":
return D;
case "I":
return I;
case "W":
return W;
case "E":
return E;
case "EX":
return EX;
case "EI":
return EI;
default:
return V;
}
}
}
private File dir, file;
public FileLogger(Context context) {
dir = new File(context.getCacheDir(), LOG_DIR);
if (!dir.exists()) {
dir.mkdir();
}
file = new File(dir, SDF.format(new Date()) + FILE_EXT);
}
/**
* Delete all log files
*/
public void clearLogs() {
for (File file : dir.listFiles()) {
file.delete();
}
}
/**
* Append log in log in this session's log file
* @param tag the tag
* @param logType the log type
* @param message the message
*/
public void appendLog(String tag, LogType logType, String message) {
StringBuilder builder = new StringBuilder();
builder
.append(SDF.format(new Date()))
.append(COLUMN_DIVIDER)
.append(tag)
.append(COLUMN_DIVIDER)
.append(logType.toString())
.append(COLUMN_DIVIDER)
.append(message)
.append(NEW_LINE);
FileOutputStream stream = null;
OutputStreamWriter writer = null;
try {
stream = new FileOutputStream(file, true);
writer = new OutputStreamWriter(stream);
writer.append(builder.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
if (stream != null) {
stream.flush();
stream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Gets all text logged until now
* @return logs
*/
public String getAllLogs() {
StringBuilder builder = new StringBuilder();
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[files.length - i - 1];
builder.append(FILE_BEGIN_MARKER)
.append(file.getName())
.append(FILE_BEGIN_MARKER)
.append(NEW_LINE)
.append(getFileContent(file))
.append(NEW_LINE);
}
return builder.toString();
}
/**
* Read file in string
* @param file the file to read
* @return file content
*/
private String getFileContent(File file) {
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append(NEW_LINE);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}
}
|
3e0f64b740461201c9a33b5fc19c055c6cce1cf9 | 3,400 | java | Java | spring-context/src/test/java/example/scannable/FooServiceImpl.java | LMDreamFree/spring-framework | 3940d2a952cf7b914cd7b1aab737f3996f54ac6b | [
"Apache-2.0"
] | 49,076 | 2015-01-01T07:23:26.000Z | 2022-03-31T23:57:00.000Z | spring-context/src/test/java/example/scannable/FooServiceImpl.java | LMDreamFree/spring-framework | 3940d2a952cf7b914cd7b1aab737f3996f54ac6b | [
"Apache-2.0"
] | 7,918 | 2015-01-06T17:17:21.000Z | 2022-03-31T20:10:05.000Z | spring-context/src/test/java/example/scannable/FooServiceImpl.java | LMDreamFree/spring-framework | 3940d2a952cf7b914cd7b1aab737f3996f54ac6b | [
"Apache-2.0"
] | 37,778 | 2015-01-01T08:25:16.000Z | 2022-03-31T17:25:08.000Z | 30.630631 | 116 | 0.8 | 6,535 | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.scannable;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Future;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
/**
* @author Mark Fisher
* @author Juergen Hoeller
*/
@Service @Lazy @DependsOn("myNamedComponent")
public abstract class FooServiceImpl implements FooService {
// Just to test ASM5's bytecode parsing of INVOKESPECIAL/STATIC on interfaces
@SuppressWarnings("unused")
private static final Comparator<MessageBean> COMPARATOR_BY_MESSAGE = Comparator.comparing(MessageBean::getMessage);
@Autowired private FooDao fooDao;
@Autowired public BeanFactory beanFactory;
@Autowired public List<ListableBeanFactory> listableBeanFactory;
@Autowired public ResourceLoader resourceLoader;
@Autowired public ResourcePatternResolver resourcePatternResolver;
@Autowired public ApplicationEventPublisher eventPublisher;
@Autowired public MessageSource messageSource;
@Autowired public ApplicationContext context;
@Autowired public ConfigurableApplicationContext[] configurableContext;
@Autowired public AbstractApplicationContext genericContext;
private boolean initCalled = false;
@PostConstruct
private void init() {
if (this.initCalled) {
throw new IllegalStateException("Init already called");
}
this.initCalled = true;
}
@Override
public String foo(int id) {
return this.fooDao.findFoo(id);
}
public String lookupFoo(int id) {
return fooDao().findFoo(id);
}
@Override
public Future<String> asyncFoo(int id) {
System.out.println(Thread.currentThread().getName());
Assert.state(ServiceInvocationCounter.getThreadLocalCount() != null, "Thread-local counter not exposed");
return new AsyncResult<>(fooDao().findFoo(id));
}
@Override
public boolean isInitCalled() {
return this.initCalled;
}
@Lookup
protected abstract FooDao fooDao();
}
|
3e0f64e07a3639951542c7a9005065201619c161 | 410 | java | Java | src/main/java/be/intecbrussel/testy/repository/ExamRepository.java | intec-brussel-vzw/testy-backend | e33c5ddcc87b8a0770b729c8513c440fc12ede66 | [
"Unlicense"
] | null | null | null | src/main/java/be/intecbrussel/testy/repository/ExamRepository.java | intec-brussel-vzw/testy-backend | e33c5ddcc87b8a0770b729c8513c440fc12ede66 | [
"Unlicense"
] | null | null | null | src/main/java/be/intecbrussel/testy/repository/ExamRepository.java | intec-brussel-vzw/testy-backend | e33c5ddcc87b8a0770b729c8513c440fc12ede66 | [
"Unlicense"
] | null | null | null | 34.166667 | 111 | 0.858537 | 6,536 | package be.intecbrussel.testy.repository;
import be.intecbrussel.testy.model.entity.ExamEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface ExamRepository extends JpaRepository<ExamEntity, Long>, JpaSpecificationExecutor<ExamEntity> {
}
|
3e0f650f7f4a861621efdc4646c2dfd7bbe271c9 | 544 | java | Java | compiler/src/main/java/tk/doraneko/domain/node/statement/ReturnStatement.java | tranphuquy19/Kinomo-JVM-Language | be06927dad1db3323e8545a7838e29795bf23fa1 | [
"MIT"
] | null | null | null | compiler/src/main/java/tk/doraneko/domain/node/statement/ReturnStatement.java | tranphuquy19/Kinomo-JVM-Language | be06927dad1db3323e8545a7838e29795bf23fa1 | [
"MIT"
] | null | null | null | compiler/src/main/java/tk/doraneko/domain/node/statement/ReturnStatement.java | tranphuquy19/Kinomo-JVM-Language | be06927dad1db3323e8545a7838e29795bf23fa1 | [
"MIT"
] | 1 | 2019-07-16T04:56:34.000Z | 2019-07-16T04:56:34.000Z | 23.652174 | 67 | 0.738971 | 6,537 | package tk.doraneko.domain.node.statement;
import tk.doraneko.bytecodegeneration.statement.StatementGenerator;
import tk.doraneko.domain.node.expression.Expression;
public class ReturnStatement implements Statement {
private final Expression expression;
public ReturnStatement(Expression expression) {
this.expression = expression;
}
@Override
public void accept(StatementGenerator generator) {
generator.generate(this);
}
public Expression getExpression() {
return expression;
}
}
|
3e0f654a84c8c75d148c4ab96e0927e106a19a9f | 4,896 | java | Java | rest-app/src/main/java/org/ednovo/gooru/controllers/v1/api/UnitRestController.java | saravanab/Gooru-Core-API-1 | f659734b8cf746566c6c62c9ee2a8ed3db1dc875 | [
"MIT"
] | null | null | null | rest-app/src/main/java/org/ednovo/gooru/controllers/v1/api/UnitRestController.java | saravanab/Gooru-Core-API-1 | f659734b8cf746566c6c62c9ee2a8ed3db1dc875 | [
"MIT"
] | null | null | null | rest-app/src/main/java/org/ednovo/gooru/controllers/v1/api/UnitRestController.java | saravanab/Gooru-Core-API-1 | f659734b8cf746566c6c62c9ee2a8ed3db1dc875 | [
"MIT"
] | null | null | null | 56.930233 | 290 | 0.816993 | 6,538 | package org.ednovo.gooru.controllers.v1.api;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.ednovo.gooru.controllers.BaseController;
import org.ednovo.gooru.core.api.model.ActionResponseDTO;
import org.ednovo.gooru.core.api.model.Collection;
import org.ednovo.gooru.core.api.model.RequestMappingUri;
import org.ednovo.gooru.core.api.model.User;
import org.ednovo.gooru.core.constant.ConstantProperties;
import org.ednovo.gooru.core.constant.Constants;
import org.ednovo.gooru.core.constant.GooruOperationConstants;
import org.ednovo.gooru.core.constant.ParameterProperties;
import org.ednovo.gooru.core.security.AuthorizeOperations;
import org.ednovo.gooru.domain.service.collection.UnitService;
import org.ednovo.goorucore.application.serializer.JsonDeserializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@RequestMapping(value = { RequestMappingUri.UNIT })
@Controller
public class UnitRestController extends BaseController implements ConstantProperties, ParameterProperties {
@Autowired
private UnitService unitService;
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_ADD })
@RequestMapping(method = RequestMethod.POST)
public ModelAndView createUnit(@PathVariable(value = COURSE_ID) final String courseId, @RequestBody final String data, final HttpServletRequest request, final HttpServletResponse response) {
final User user = (User) request.getAttribute(Constants.USER);
final ActionResponseDTO<Collection> responseDTO = this.getUnitService().createUnit(courseId, buildUnit(data), user);
if (responseDTO.getErrors().getErrorCount() > 0) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
} else {
response.setStatus(HttpServletResponse.SC_CREATED);
responseDTO.getModel().setUri(generateUri(request.getRequestURI(), responseDTO.getModel().getGooruOid()));
}
String includes[] = (String[]) ArrayUtils.addAll(CREATE_INCLUDES, ERROR_INCLUDE);
return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes);
}
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_UPDATE })
@RequestMapping(value = RequestMappingUri.ID, method = RequestMethod.PUT)
public void updateUnit(@PathVariable(value = COURSE_ID) final String courseId, @PathVariable(value = ID) final String unitId, @RequestBody final String data, final HttpServletRequest request, final HttpServletResponse response) {
final User user = (User) request.getAttribute(Constants.USER);
this.getUnitService().updateUnit(courseId, unitId, buildUnit(data), user);
}
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_READ })
@RequestMapping(value = RequestMappingUri.ID, method = RequestMethod.GET)
public ModelAndView getUnit(@PathVariable(value = COURSE_ID) final String courseId, @PathVariable(value = ID) final String unitId, final HttpServletRequest request, final HttpServletResponse response) {
return toModelAndViewWithIoFilter(getUnitService().getUnit(unitId), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, "*");
}
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_READ })
@RequestMapping(method = RequestMethod.GET)
public ModelAndView getUnits(@PathVariable(value = COURSE_ID) final String courseId, @RequestParam(value = OFFSET_FIELD, required = false, defaultValue = "0") int offset, @RequestParam(value = LIMIT_FIELD, required = false, defaultValue = "10") int limit, final HttpServletRequest request,
final HttpServletResponse response) {
return toModelAndViewWithIoFilter(getUnitService().getUnits(courseId, limit, offset), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, "*");
}
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_DELETE })
@RequestMapping(value = RequestMappingUri.ID, method = RequestMethod.DELETE)
public void deleteUnit(@PathVariable(value = COURSE_ID) final String courseId, @PathVariable(value = ID) final String unitId, final HttpServletRequest request, final HttpServletResponse response) {
final User user = (User) request.getAttribute(Constants.USER);
this.getUnitService().deleteUnit(courseId, unitId, user);
}
private Collection buildUnit(final String data) {
return JsonDeserializer.deserialize(data, Collection.class);
}
public UnitService getUnitService() {
return unitService;
}
}
|
3e0f65960311ee0ba7205d23a25555df59403962 | 1,026 | java | Java | WinterEE-Core-Serve/src/main/java/com/winteree/core/dao/QrtzQausedTriggerGrpsDOMapper.java | renfei-net/WinterEE | 5625638421726c956168c68b162ef6a6665c6a5b | [
"Apache-2.0"
] | 3 | 2020-07-07T09:30:50.000Z | 2020-09-08T02:52:29.000Z | WinterEE-Core-Serve/src/main/java/com/winteree/core/dao/QrtzQausedTriggerGrpsDOMapper.java | renfei-net/WinterEE | 5625638421726c956168c68b162ef6a6665c6a5b | [
"Apache-2.0"
] | 121 | 2020-06-24T12:43:04.000Z | 2020-11-03T21:28:32.000Z | WinterEE-Core-Serve/src/main/java/com/winteree/core/dao/QrtzQausedTriggerGrpsDOMapper.java | renfei/WinterEE | 5625638421726c956168c68b162ef6a6665c6a5b | [
"Apache-2.0"
] | 2 | 2020-07-01T15:41:00.000Z | 2020-07-11T15:06:21.000Z | 38 | 143 | 0.834308 | 6,539 | package com.winteree.core.dao;
import com.winteree.core.dao.entity.QrtzQausedTriggerGrpsDOExample;
import com.winteree.core.dao.entity.QrtzQausedTriggerGrpsDOKey;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface QrtzQausedTriggerGrpsDOMapper {
long countByExample(QrtzQausedTriggerGrpsDOExample example);
int deleteByExample(QrtzQausedTriggerGrpsDOExample example);
int deleteByPrimaryKey(QrtzQausedTriggerGrpsDOKey key);
int insert(QrtzQausedTriggerGrpsDOKey record);
int insertSelective(QrtzQausedTriggerGrpsDOKey record);
List<QrtzQausedTriggerGrpsDOKey> selectByExample(QrtzQausedTriggerGrpsDOExample example);
int updateByExampleSelective(@Param("record") QrtzQausedTriggerGrpsDOKey record, @Param("example") QrtzQausedTriggerGrpsDOExample example);
int updateByExample(@Param("record") QrtzQausedTriggerGrpsDOKey record, @Param("example") QrtzQausedTriggerGrpsDOExample example);
} |
3e0f65a734db46c6aca0a340a998bf635fdfd56a | 5,686 | java | Java | src/main/java/com/twilio/rest/media/v1/PlayerStreamerReader.java | sullis/twilio-java | 841cd25abd53dccaca6f913df3cda90131d11852 | [
"MIT"
] | 295 | 2015-01-04T17:00:48.000Z | 2022-03-29T21:51:49.000Z | src/main/java/com/twilio/rest/media/v1/PlayerStreamerReader.java | sullis/twilio-java | 841cd25abd53dccaca6f913df3cda90131d11852 | [
"MIT"
] | 349 | 2015-01-14T19:08:16.000Z | 2022-03-09T15:50:13.000Z | src/main/java/com/twilio/rest/media/v1/PlayerStreamerReader.java | sullis/twilio-java | 841cd25abd53dccaca6f913df3cda90131d11852 | [
"MIT"
] | 376 | 2015-01-03T22:31:01.000Z | 2022-03-31T08:23:17.000Z | 31.94382 | 113 | 0.629441 | 6,540 | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.media.v1;
import com.twilio.base.Page;
import com.twilio.base.Reader;
import com.twilio.base.ResourceSet;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
public class PlayerStreamerReader extends Reader<PlayerStreamer> {
private PlayerStreamer.Order order;
private PlayerStreamer.Status status;
/**
* The sort order of the list by `date_created`. Can be: `asc` (ascending) or
* `desc` (descending) with `desc` as the default..
*
* @param order The sort order of the list
* @return this
*/
public PlayerStreamerReader setOrder(final PlayerStreamer.Order order) {
this.order = order;
return this;
}
/**
* Status to filter by, with possible values `created`, `started`, `ended`, or
* `failed`..
*
* @param status Status to filter by
* @return this
*/
public PlayerStreamerReader setStatus(final PlayerStreamer.Status status) {
this.status = status;
return this;
}
/**
* Make the request to the Twilio API to perform the read.
*
* @param client TwilioRestClient with which to make the request
* @return PlayerStreamer ResourceSet
*/
@Override
public ResourceSet<PlayerStreamer> read(final TwilioRestClient client) {
return new ResourceSet<>(this, client, firstPage(client));
}
/**
* Make the request to the Twilio API to perform the read.
*
* @param client TwilioRestClient with which to make the request
* @return PlayerStreamer ResourceSet
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public Page<PlayerStreamer> firstPage(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
Domains.MEDIA.toString(),
"/v1/PlayerStreamers"
);
addQueryParams(request);
return pageForRequest(client, request);
}
/**
* Retrieve the target page from the Twilio API.
*
* @param targetUrl API-generated URL for the requested results page
* @param client TwilioRestClient with which to make the request
* @return PlayerStreamer ResourceSet
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public Page<PlayerStreamer> getPage(final String targetUrl, final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
targetUrl
);
return pageForRequest(client, request);
}
/**
* Retrieve the next page from the Twilio API.
*
* @param page current page
* @param client TwilioRestClient with which to make the request
* @return Next Page
*/
@Override
public Page<PlayerStreamer> nextPage(final Page<PlayerStreamer> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(Domains.MEDIA.toString())
);
return pageForRequest(client, request);
}
/**
* Retrieve the previous page from the Twilio API.
*
* @param page current page
* @param client TwilioRestClient with which to make the request
* @return Previous Page
*/
@Override
public Page<PlayerStreamer> previousPage(final Page<PlayerStreamer> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(Domains.MEDIA.toString())
);
return pageForRequest(client, request);
}
/**
* Generate a Page of PlayerStreamer Resources for a given request.
*
* @param client TwilioRestClient with which to make the request
* @param request Request to generate a page for
* @return Page for the Request
*/
private Page<PlayerStreamer> pageForRequest(final TwilioRestClient client, final Request request) {
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("PlayerStreamer read failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(restException);
}
return Page.fromJson(
"player_streamers",
response.getContent(),
PlayerStreamer.class,
client.getObjectMapper()
);
}
/**
* Add the requested query string arguments to the Request.
*
* @param request Request to add query string arguments to
*/
private void addQueryParams(final Request request) {
if (order != null) {
request.addQueryParam("Order", order.toString());
}
if (status != null) {
request.addQueryParam("Status", status.toString());
}
if (getPageSize() != null) {
request.addQueryParam("PageSize", Integer.toString(getPageSize()));
}
}
} |
3e0f6630a07f1be9c9f37beda81964d0c6519142 | 800 | java | Java | TripleT/ControllableSprite.java | ohjay/TripleTGame | 5aaee6b4dca517dd020fc7ce40d3d0903d388f04 | [
"MIT"
] | null | null | null | TripleT/ControllableSprite.java | ohjay/TripleTGame | 5aaee6b4dca517dd020fc7ce40d3d0903d388f04 | [
"MIT"
] | 1 | 2015-06-25T07:56:05.000Z | 2015-06-25T07:56:05.000Z | TripleT/ControllableSprite.java | ohjay/TripleTGame | 5aaee6b4dca517dd020fc7ce40d3d0903d388f04 | [
"MIT"
] | null | null | null | 32 | 86 | 0.55375 | 6,541 | package TripleT;
/**
* A sprite that can be controlled by the player (via the keyboard).
* @author Owen Jow
*/
abstract class ControllableSprite extends Sprite {
protected boolean leftKeyPressed, rightKeyPressed, upKeyPressed, downKeyPressed;
//================================================================================
// Action methods (to be overridden by the actual sprite)
//================================================================================
abstract void rightPressed();
abstract void leftPressed();
abstract void downPressed();
abstract void upPressed();
abstract void aPressed();
abstract void rightReleased();
abstract void leftReleased();
abstract void downReleased();
abstract void upReleased();
}
|
3e0f66aeacb06db8948e2ed8f6b3e2adc5a052eb | 4,472 | java | Java | collection_pro/src/main/java/ru/job4j/map/SimpleHashMap.java | Daniil56/DEmelyanov2 | 8e6bffdb5459f14c6f28feb01f46a43334c792c2 | [
"Apache-2.0"
] | 3 | 2018-07-23T14:03:44.000Z | 2020-10-16T22:05:53.000Z | collection_pro/src/main/java/ru/job4j/map/SimpleHashMap.java | Daniil56/DEmelyanov2 | 8e6bffdb5459f14c6f28feb01f46a43334c792c2 | [
"Apache-2.0"
] | null | null | null | collection_pro/src/main/java/ru/job4j/map/SimpleHashMap.java | Daniil56/DEmelyanov2 | 8e6bffdb5459f14c6f28feb01f46a43334c792c2 | [
"Apache-2.0"
] | null | null | null | 26.461538 | 99 | 0.478757 | 6,542 | package ru.job4j.map;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
public class SimpleHashMap<K, V> {
private static final int DEFAULT_SIZE = 16;
private Node[] container;
public int getSize() {
return size;
}
private int size;
private int modCount;
public SimpleHashMap() {
this.container = new Node[DEFAULT_SIZE];
}
private static class Node<K, V> {
private K key;
private V value;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return this.key;
}
@Override
public int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
}
public boolean put(K key, V value) {
boolean result = false;
int factor = this.container.length;
if (this.container[position(key)] == null) {
if (this.size > factor * 2 / 3) {
resize();
}
this.container[position(key)] = new Node(key, value);
this.size++;
result = true;
this.modCount++;
}
return result;
}
public V get(K key) {
V result = null;
int index = position(key);
if (this.container[index] != null && this.container[index].key.equals(key)) {
result = (V) this.container[index].value;
}
return result;
}
public boolean delete(K key) {
boolean result = false;
int index = this.position(key);
if (this.container[index] != null
&& this.container[index].getKey().equals(key)) {
this.container[index] = null;
result = true;
this.size--;
this.modCount++;
}
return result;
}
private int position(K key) {
int h = key.hashCode();
return h % Math.abs(hash(key, this.container.length) % this.container.length);
}
private int hash(K key, int newSize) {
int h = key.hashCode();
h = h ^ h >>> 16;
return (31 * h) % newSize;
}
private void resize() {
Node<K, V>[] newContainer = (Node<K, V>[]) new Node[this.container.length * 2];
for (Node<K, V> entry : this.container) {
if (entry != null) {
newContainer[hash(entry.getKey(), newContainer.length)] = entry;
}
}
this.container = newContainer;
}
class HashIterator {
Node<K, V> next;
int expectedModcount;
int index;
HashIterator() {
expectedModcount = modCount;
Node<K, V>[] t = container;
index = 0;
if (t != null && size > 0) {
while (index < t.length && next == null) {
next = t[index++];
}
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K, V> nextNode() {
Node<K, V>[] t = container;
Node<K, V> e = next;
if (modCount != expectedModcount) {
throw new ConcurrentModificationException("mod exception");
}
if (e == null) {
throw new NoSuchElementException("no such");
}
next = container[index++];
if ((next == null && t != null)) {
while (index < t.length && next == null) {
next = t[index++];
}
}
return e;
}
}
final class KeyIterator extends HashIterator implements Iterator<K> {
@Override
public K next() {
return nextNode().key;
}
}
final class ValueIterator extends HashIterator implements Iterator<V> {
@Override
public V next() {
return nextNode().value;
}
}
final class EntryIterator extends HashIterator implements Iterator<SimpleHashMap.Node<K, V>> {
@Override
public Node<K, V> next() {
return nextNode();
}
}
} |
3e0f66fa9e31150ffe521971c4f5d90f7017ea3a | 11,197 | java | Java | common/src/main/java/com/serenegiant/dialog/ConfirmDialogV4.java | kaushikrw/libcommon | a496f84efc8732225938001b393db744558737c8 | [
"Apache-2.0"
] | 170 | 2017-01-06T02:21:05.000Z | 2022-03-25T09:30:30.000Z | common/src/main/java/com/serenegiant/dialog/ConfirmDialogV4.java | kaushikrw/libcommon | a496f84efc8732225938001b393db744558737c8 | [
"Apache-2.0"
] | 8 | 2018-01-13T10:35:54.000Z | 2021-03-04T05:54:10.000Z | common/src/main/java/com/serenegiant/dialog/ConfirmDialogV4.java | kaushikrw/libcommon | a496f84efc8732225938001b393db744558737c8 | [
"Apache-2.0"
] | 154 | 2016-10-23T08:26:37.000Z | 2022-03-16T11:18:46.000Z | 29.872 | 97 | 0.760936 | 6,543 | package com.serenegiant.dialog;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2021 saki efpyi@example.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import com.serenegiant.system.BuildCheck;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
/**
* ユーザー確認用ダイアログ
* 表示要求するActivity/FragmentはConfirmDialogListenerを実装していないといけない
*/
public class ConfirmDialogV4 extends DialogFragmentEx {
// private static final boolean DEBUG = false; // FIXME 実働時はfalseにすること
private static final String TAG = ConfirmDialogV4.class.getSimpleName();
private static final String ARGS_KEY_CANCELED_ON_TOUCH_OUTSIDE
= "ARGS_KEY_CANCELED_ON_TOUCH_OUTSIDE";
private static final String ARGS_KEY_MESSAGE_STRING
= "ARGS_KEY_MESSAGE_STRING";
private static final String ARGS_KEY_ARGS
= "ARGS_KEY_ARGS";
/**
* ダイアログの表示結果を受け取るためのコールバックリスナー
*/
public static interface ConfirmDialogListener {
/**
* 確認結果を引き渡すためのコールバックメソッド
* @param dialog
* @param requestCode
* @param result DialogInterface#BUTTONxxx
*/
public void onConfirmResult(
@NonNull final ConfirmDialogV4 dialog,
final int requestCode, final int result,
@Nullable final Bundle userArgs);
}
/**
* ダイアログ表示のためのヘルパーメソッド
* @param parent
* @param requestCode
* @param id_title
* @param id_message
* @param canceledOnTouchOutside
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final FragmentActivity parent, final int requestCode,
@StringRes final int id_title, @StringRes final int id_message,
final boolean canceledOnTouchOutside) throws IllegalStateException {
return showDialog(parent, requestCode, id_title, id_message, canceledOnTouchOutside, null);
}
/**
* ダイアログ表示のためのヘルパーメソッド
* @param parent
* @param requestCode
* @param id_title
* @param id_message
* @param canceledOnTouchOutside
* @param userArgs
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final FragmentActivity parent, final int requestCode,
@StringRes final int id_title, @StringRes final int id_message,
final boolean canceledOnTouchOutside,
@Nullable final Bundle userArgs) throws IllegalStateException {
final ConfirmDialogV4 dialog
= newInstance(requestCode,
id_title, id_message, null,
canceledOnTouchOutside,
userArgs);
dialog.show(parent.getSupportFragmentManager(), TAG);
return dialog;
}
/**
* ダイアログ表示のためのヘルパーメソッド
* こっちはCharSequenceとしてメッセージ内容を指定
* @param parent
* @param requestCode
* @param id_title
* @param message
* @param canceledOnTouchOutside
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final FragmentActivity parent, final int requestCode,
@StringRes final int id_title, @NonNull final CharSequence message,
final boolean canceledOnTouchOutside) throws IllegalStateException {
return showDialog(parent, requestCode, id_title, message, canceledOnTouchOutside, null);
}
/**
* ダイアログ表示のためのヘルパーメソッド
* こっちはCharSequenceとしてメッセージ内容を指定
* @param parent
* @param requestCode
* @param id_title
* @param message
* @param canceledOnTouchOutside
* @param userArgs
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final FragmentActivity parent, final int requestCode,
@StringRes final int id_title, @NonNull final CharSequence message,
final boolean canceledOnTouchOutside,
@Nullable final Bundle userArgs) throws IllegalStateException {
final ConfirmDialogV4 dialog
= newInstance(requestCode,
id_title, 0, message,
canceledOnTouchOutside,
userArgs);
dialog.show(parent.getSupportFragmentManager(), TAG);
return dialog;
}
/**
* ダイアログ表示のためのヘルパーメソッド
* @param parent
* @param requestCode
* @param id_title
* @param id_message
* @param canceledOnTouchOutside
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final Fragment parent, final int requestCode,
@StringRes final int id_title, @StringRes final int id_message,
final boolean canceledOnTouchOutside) throws IllegalStateException {
return showDialog(parent, requestCode, id_title, id_message, canceledOnTouchOutside, null);
}
/**
* ダイアログ表示のためのヘルパーメソッド
* @param parent
* @param requestCode
* @param id_title
* @param id_message
* @param canceledOnTouchOutside
* @param userArgs
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final Fragment parent, final int requestCode,
@StringRes final int id_title, @StringRes final int id_message,
final boolean canceledOnTouchOutside,
@Nullable final Bundle userArgs) throws IllegalStateException {
final ConfirmDialogV4 dialog
= newInstance(requestCode,
id_title, id_message, null,
canceledOnTouchOutside,
userArgs);
dialog.setTargetFragment(parent, parent.getId());
dialog.show(parent.getParentFragmentManager(), TAG);
return dialog;
}
/**
* ダイアログ表示のためのヘルパーメソッド
* こっちはCharSequenceとしてメッセージ内容を指定
* @param parent
* @param requestCode
* @param id_title
* @param message
* @param canceledOnTouchOutside
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final Fragment parent, final int requestCode,
@StringRes final int id_title, @NonNull final CharSequence message,
final boolean canceledOnTouchOutside) throws IllegalStateException {
return showDialog(parent, requestCode, id_title, message, canceledOnTouchOutside, null);
}
/**
* ダイアログ表示のためのヘルパーメソッド
* こっちはCharSequenceとしてメッセージ内容を指定
* @param parent
* @param requestCode
* @param id_title
* @param message
* @param canceledOnTouchOutside
* @param userArgs
* @return
* @throws IllegalStateException
*/
public static ConfirmDialogV4 showDialog(
@NonNull final Fragment parent, final int requestCode,
@StringRes final int id_title, @NonNull final CharSequence message,
final boolean canceledOnTouchOutside,
@Nullable final Bundle userArgs) throws IllegalStateException {
final ConfirmDialogV4 dialog
= newInstance(requestCode,
id_title, 0, message,
canceledOnTouchOutside,
userArgs);
dialog.setTargetFragment(parent, parent.getId());
dialog.show(parent.getParentFragmentManager(), TAG);
return dialog;
}
/**
* ダイアログ生成のためのヘルパーメソッド
* ダイアログ自体を直接生成せずにこのメソッドを呼び出すこと
* @param requestCode
* @param id_title
* @param id_message
* @param message
* @param canceledOnTouchOutside
* @param userArgs
* @return
*/
public static ConfirmDialogV4 newInstance(
final int requestCode,
@StringRes final int id_title, @StringRes final int id_message,
@Nullable final CharSequence message,
final boolean canceledOnTouchOutside,
@Nullable final Bundle userArgs) {
final ConfirmDialogV4 fragment = new ConfirmDialogV4();
final Bundle args = new Bundle();
// ここでパラメータをセットする
args.putInt(ARGS_KEY_REQUEST_CODE, requestCode);
args.putInt(ARGS_KEY_ID_TITLE, id_title);
args.putInt(ARGS_KEY_ID_MESSAGE, id_message);
args.putCharSequence(ARGS_KEY_MESSAGE_STRING, message);
args.putBoolean(ARGS_KEY_CANCELED_ON_TOUCH_OUTSIDE, canceledOnTouchOutside);
args.putBundle(ARGS_KEY_ARGS, userArgs);
fragment.setArguments(args);
return fragment;
}
private ConfirmDialogListener mListener;
/**
* コンストラクタ, 直接生成せずに#newInstanceを使うこと
*/
public ConfirmDialogV4() {
super();
// デフォルトコンストラクタが必要
}
@Override
public void onAttach(@NonNull final Context context) {
super.onAttach(context);
// コールバックインターフェースを取得
if (context instanceof ConfirmDialogListener) {
mListener = (ConfirmDialogListener)context;
}
if (mListener == null) {
final Fragment fragment = getTargetFragment();
if (fragment instanceof ConfirmDialogListener) {
mListener = (ConfirmDialogListener)fragment;
}
}
if (mListener == null) {
if (BuildCheck.isAndroid4_2()) {
final Fragment target = getParentFragment();
if (target instanceof ConfirmDialogListener) {
mListener = (ConfirmDialogListener)target;
}
}
}
if (mListener == null) {
// Log.w(TAG, "caller activity/fragment must implement ConfirmDialogV4#ConfirmDialogListener");
throw new ClassCastException(context.toString());
}
}
@NonNull
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
final Bundle args = savedInstanceState != null ? savedInstanceState : requireArguments();
final int id_title = args.getInt(ARGS_KEY_ID_TITLE);
final int id_message = args.getInt(ARGS_KEY_ID_MESSAGE);
final CharSequence message = args.getCharSequence(ARGS_KEY_MESSAGE_STRING);
final boolean canceledOnTouchOutside = args.getBoolean(ARGS_KEY_CANCELED_ON_TOUCH_OUTSIDE);
final AlertDialog.Builder builder = new AlertDialog.Builder(requireContext(), getTheme())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(id_title)
.setPositiveButton(android.R.string.ok, mOnClickListener)
.setNegativeButton(android.R.string.cancel, mOnClickListener);
if (id_message != 0) {
builder.setMessage(id_message);
} else {
builder.setMessage(message);
}
final AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
return dialog;
}
private final DialogInterface.OnClickListener mOnClickListener
= new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
// 本当はここでパーミッション要求をしたいだけどこのダイアログがdismissしてしまって結果を受け取れないので
// 呼び出し側へ返してそこでパーミッション要求する。なのでこのダイアログは単にメッセージを表示するだけ
callOnMessageDialogResult(which);
}
};
@Override
public void onCancel(@NonNull final DialogInterface dialog) {
super.onCancel(dialog);
callOnMessageDialogResult(DialogInterface.BUTTON_NEGATIVE);
}
/**
* コールバックリスナー呼び出しのためのヘルパーメソッド
* @param result DialogInterface#BUTTONxxx
*/
private void callOnMessageDialogResult(final int result)
throws IllegalStateException {
final Bundle args = requireArguments();
final Bundle userArgs = args.getBundle(ARGS_KEY_ARGS);
final int requestCode = args.getInt(ARGS_KEY_REQUEST_CODE);
try {
mListener.onConfirmResult(
ConfirmDialogV4.this, requestCode, result, userArgs);
} catch (final Exception e) {
Log.w(TAG, e);
}
}
}
|
3e0f671e39a8973439696491fd4e7d221713fd9e | 12,618 | java | Java | netreflected/src/net5.0/presentationcore_version_5.0.10.0_culture_neutral_publickeytoken_31bf3856ad364e35/system/windows/input/KeyboardDevice.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 35 | 2020-08-30T03:19:42.000Z | 2022-03-12T09:22:23.000Z | netreflected/src/net5.0/presentationcore_version_5.0.10.0_culture_neutral_publickeytoken_31bf3856ad364e35/system/windows/input/KeyboardDevice.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 50 | 2020-06-22T17:03:18.000Z | 2022-03-30T21:19:05.000Z | netreflected/src/net5.0/presentationcore_version_5.0.10.0_culture_neutral_publickeytoken_31bf3856ad364e35/system/windows/input/KeyboardDevice.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 12 | 2020-08-30T03:19:45.000Z | 2022-03-05T02:22:37.000Z | 46.733333 | 639 | 0.701775 | 6,544 | /*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.windows.input;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.windows.input.InputDevice;
import system.windows.input.Key;
import system.windows.IInputElement;
import system.windows.IInputElementImplementation;
import system.windows.input.KeyStates;
import system.windows.input.ModifierKeys;
import system.windows.input.RestoreFocusMode;
import system.windows.PresentationSource;
/**
* The base .NET class managing System.Windows.Input.KeyboardDevice, PresentationCore, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Input.KeyboardDevice" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Input.KeyboardDevice</a>
*/
public class KeyboardDevice extends InputDevice {
/**
* Fully assembly qualified name: PresentationCore, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "PresentationCore, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: PresentationCore
*/
public static final String assemblyShortName = "PresentationCore";
/**
* Qualified class name: System.Windows.Input.KeyboardDevice
*/
public static final String className = "System.Windows.Input.KeyboardDevice";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public KeyboardDevice(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link KeyboardDevice}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link KeyboardDevice} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static KeyboardDevice cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new KeyboardDevice(from.getJCOInstance());
}
// Constructors section
public KeyboardDevice() throws Throwable {
}
// Methods section
public boolean IsKeyDown(Key key) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.globalization.CultureNotFoundException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.FormatException, system.IndexOutOfRangeException, system.componentmodel.InvalidEnumArgumentException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Invoke("IsKeyDown", key == null ? null : key.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean IsKeyToggled(Key key) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.globalization.CultureNotFoundException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.FormatException, system.IndexOutOfRangeException, system.componentmodel.InvalidEnumArgumentException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Invoke("IsKeyToggled", key == null ? null : key.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean IsKeyUp(Key key) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.globalization.CultureNotFoundException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.FormatException, system.IndexOutOfRangeException, system.componentmodel.InvalidEnumArgumentException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Invoke("IsKeyUp", key == null ? null : key.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IInputElement Focus(IInputElement element) throws Throwable, system.ArgumentException, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.ObjectDisposedException, system.InvalidOperationException, system.OutOfMemoryException, system.runtime.interopservices.ExternalException, system.NotSupportedException, system.IndexOutOfRangeException, system.RankException, system.ArrayTypeMismatchException, system.componentmodel.InvalidEnumArgumentException, system.security.SecurityException, system.componentmodel.Win32Exception {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objFocus = (JCObject)classInstance.Invoke("Focus", element == null ? null : element.getJCOInstance());
return new IInputElementImplementation(objFocus);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public KeyStates GetKeyStates(Key key) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.globalization.CultureNotFoundException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.FormatException, system.IndexOutOfRangeException, system.componentmodel.InvalidEnumArgumentException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objGetKeyStates = (JCObject)classInstance.Invoke("GetKeyStates", key == null ? null : key.getJCOInstance());
return new KeyStates(objGetKeyStates);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void ClearFocus() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.NotSupportedException, system.IndexOutOfRangeException, system.PlatformNotSupportedException, system.RankException, system.ArrayTypeMismatchException, system.componentmodel.InvalidEnumArgumentException, system.ObjectDisposedException, system.security.SecurityException, system.componentmodel.Win32Exception {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("ClearFocus");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Properties section
public IInputElement getFocusedElement() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("FocusedElement");
return new IInputElementImplementation(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public ModifierKeys getModifiers() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Modifiers");
return new ModifierKeys(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public RestoreFocusMode getDefaultRestoreFocusMode() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("DefaultRestoreFocusMode");
return new RestoreFocusMode(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setDefaultRestoreFocusMode(RestoreFocusMode DefaultRestoreFocusMode) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("DefaultRestoreFocusMode", DefaultRestoreFocusMode == null ? null : DefaultRestoreFocusMode.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
} |
3e0f678d4e7eebe88770150a621ccc1df0d92236 | 2,779 | java | Java | server/protocols/jmap-draft/src/main/java/org/apache/james/jmap/draft/model/message/view/MetaMessageViewFactory.java | brokenshoebox/james-project | a2a77ad247330ceb148ee0c7751cbe7e347467bd | [
"Apache-2.0"
] | 634 | 2015-12-21T20:24:06.000Z | 2022-03-24T09:57:48.000Z | server/protocols/jmap-draft/src/main/java/org/apache/james/jmap/draft/model/message/view/MetaMessageViewFactory.java | brokenshoebox/james-project | a2a77ad247330ceb148ee0c7751cbe7e347467bd | [
"Apache-2.0"
] | 4,148 | 2015-09-14T15:59:06.000Z | 2022-03-31T10:29:10.000Z | server/protocols/jmap-draft/src/main/java/org/apache/james/jmap/draft/model/message/view/MetaMessageViewFactory.java | brokenshoebox/james-project | a2a77ad247330ceb148ee0c7751cbe7e347467bd | [
"Apache-2.0"
] | 392 | 2015-07-16T07:04:59.000Z | 2022-03-28T09:37:53.000Z | 49.625 | 137 | 0.63656 | 6,545 | /****************************************************************
* 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.james.jmap.draft.model.message.view;
import javax.inject.Inject;
import org.apache.james.jmap.draft.model.MessageProperties;
public class MetaMessageViewFactory {
private final MessageFullViewFactory messageFullViewFactory;
private final MessageHeaderViewFactory messageHeaderViewFactory;
private final MessageMetadataViewFactory messageMetadataViewFactory;
private final MessageFastViewFactory messageFastViewFactory;
@Inject
public MetaMessageViewFactory(MessageFullViewFactory messageFullViewFactory, MessageHeaderViewFactory messageHeaderViewFactory,
MessageMetadataViewFactory messageMetadataViewFactory, MessageFastViewFactory messageFastViewFactory) {
this.messageFullViewFactory = messageFullViewFactory;
this.messageHeaderViewFactory = messageHeaderViewFactory;
this.messageMetadataViewFactory = messageMetadataViewFactory;
this.messageFastViewFactory = messageFastViewFactory;
}
public MessageViewFactory<? extends MessageView> getFactory(MessageProperties.ReadProfile readProfile) {
switch (readProfile) {
case Full:
return messageFullViewFactory;
case Header:
return messageHeaderViewFactory;
case Fast:
return messageFastViewFactory;
case Metadata:
return messageMetadataViewFactory;
default:
throw new IllegalArgumentException(readProfile + " is not a James JMAP draft supported view");
}
}
}
|
3e0f68e9a72decb7538ad25e4343ef082398c621 | 876 | java | Java | src/com/sqrch/chocosheep/Const.java | junhg0211/Chocosheep | 24f7ab202e00c1fce0e3b392d93d4b6d5d6f8008 | [
"MIT"
] | null | null | null | src/com/sqrch/chocosheep/Const.java | junhg0211/Chocosheep | 24f7ab202e00c1fce0e3b392d93d4b6d5d6f8008 | [
"MIT"
] | null | null | null | src/com/sqrch/chocosheep/Const.java | junhg0211/Chocosheep | 24f7ab202e00c1fce0e3b392d93d4b6d5d6f8008 | [
"MIT"
] | null | null | null | 35.04 | 68 | 0.714612 | 6,546 | package com.sqrch.chocosheep;
import java.awt.*;
public class Const {
public static Color BLACK = new Color(0x1F2226);
public static Color WHITE = new Color(0xFFF4E0);
public static Color YELLOW = new Color(0xF8B500);
public static Color LIME = new Color(0x38B52E);
public static Color RED = new Color(0xD6231E);
public static Color SOY = new Color(0xFFE9AC);
public static Color GREEN = new Color(0x097B00);
public static Color PURPLE = new Color(0x971ED6);
public static Color CYAN = new Color(0x2EB584);
public static Color BLUE = new Color(0x2E5AB5);
public static Color AQUA = new Color(0x2E94B5);
public static Color COFFEE = new Color(0x591500);
public static String FONT_PATH = "./res/font/NANUMSQUAREEB.ttf";
public static String SERVER_HOST = "shtelo.kro.kr";
public static int SERVER_PORT = 31685;
}
|
3e0f6a3107af6044c78a4b1990d7f69e1999f153 | 3,443 | java | Java | src/main/java/com/github/jnidzwetzki/bitfinex/v2/manager/BiConsumerCallbackManager.java | alexkarezin/bitfinex-v2-wss-api-java | 97c1ef6c0b272d1ca3efd1afb172e8a0e250db05 | [
"Apache-2.0"
] | 105 | 2018-01-01T20:08:09.000Z | 2021-07-17T18:24:36.000Z | src/main/java/com/github/jnidzwetzki/bitfinex/v2/manager/BiConsumerCallbackManager.java | alexkarezin/bitfinex-v2-wss-api-java | 97c1ef6c0b272d1ca3efd1afb172e8a0e250db05 | [
"Apache-2.0"
] | 218 | 2018-01-07T05:24:27.000Z | 2022-03-25T07:38:11.000Z | src/main/java/com/github/jnidzwetzki/bitfinex/v2/manager/BiConsumerCallbackManager.java | alexkarezin/bitfinex-v2-wss-api-java | 97c1ef6c0b272d1ca3efd1afb172e8a0e250db05 | [
"Apache-2.0"
] | 70 | 2018-01-07T19:28:24.000Z | 2022-03-25T00:58:36.000Z | 27.99187 | 112 | 0.674993 | 6,547 | /*******************************************************************************
*
* Copyright (C) 2015-2018 Jan Kristof Nidzwetzki
*
* 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.jnidzwetzki.bitfinex.v2.manager;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import com.github.jnidzwetzki.bitfinex.v2.BitfinexWebsocketClient;
import com.github.jnidzwetzki.bitfinex.v2.exception.BitfinexClientException;
public class BiConsumerCallbackManager<S, T> extends AbstractManager {
/**
* The callbacks
*/
private final Map<S, List<BiConsumer<S, T>>> callbacks;
public BiConsumerCallbackManager(final ExecutorService executorService,
final BitfinexWebsocketClient client) {
super(client, executorService);
this.callbacks = new ConcurrentHashMap<>();
}
/**
* Register a new callback
* @param symbol
* @param callback
* @throws BitfinexClientException
*/
public void registerCallback(final S symbol, final BiConsumer<S, T> callback) throws BitfinexClientException {
final List<BiConsumer<S, T>> callbackList
= callbacks.computeIfAbsent(symbol, (k) -> new CopyOnWriteArrayList<>());
callbackList.add(callback);
}
/**
* Remove the a callback
* @param symbol
* @param callback
* @return
* @throws BitfinexClientException
*/
public boolean removeCallback(final S symbol, final BiConsumer<S, T> callback) throws BitfinexClientException {
final List<BiConsumer<S, T>> callbackList = callbacks.get(symbol);
if(callbackList == null) {
throw new BitfinexClientException("Unknown ticker string: " + symbol);
}
return callbackList.remove(callback);
}
/**
* Process a list with event
* @param symbol
* @param ticksArray
*/
public void handleEventsCollection(final S symbol, final Collection<T> elements) {
final List<BiConsumer<S, T>> callbackList = callbacks.get(symbol);
if(callbackList == null) {
return;
}
if(callbackList.isEmpty()) {
return;
}
// Notify callbacks synchronously, to preserve the order of events
for (final T element : elements) {
callbackList.forEach((c) -> {
c.accept(symbol, element);
});
}
}
/**
* Handle a new tick
* @param symbol
* @param element
*/
public void handleEvent(final S symbol, final T element) {
final List<BiConsumer<S, T>> callbackList = callbacks.get(symbol);
if(callbackList == null) {
return;
}
if(callbackList.isEmpty()) {
return;
}
callbackList.forEach((c) -> {
final Runnable runnable = () -> c.accept(symbol, element);
executorService.submit(runnable);
});
}
}
|
3e0f6b68c5703be95364aff02df71962657ef503 | 256 | java | Java | crocok/src/main/java/croc/messager/server/Server.java | nikita220399/job4j | 1fbcb40cb232b72c6a853a3e7081951efa604947 | [
"Apache-2.0"
] | 2 | 2019-02-28T15:20:58.000Z | 2019-05-02T16:41:17.000Z | crocok/src/main/java/croc/messager/server/Server.java | nikita220399/job4j | 1fbcb40cb232b72c6a853a3e7081951efa604947 | [
"Apache-2.0"
] | null | null | null | crocok/src/main/java/croc/messager/server/Server.java | nikita220399/job4j | 1fbcb40cb232b72c6a853a3e7081951efa604947 | [
"Apache-2.0"
] | null | null | null | 17.066667 | 49 | 0.6875 | 6,548 | package croc.messager.server;
import croc.messager.common.Chat;
import java.util.ArrayList;
import java.util.List;
public class Server {
private List<Chat> chats = new ArrayList<>();
public List<Chat> getChats() {
return chats;
}
}
|
3e0f6ce8364fd7c51f50603cfc3d361c10219ef9 | 2,374 | java | Java | gulimall-product/src/main/java/com/zhou/gulimall/product/controller/SkuSaleAttrValueController.java | 15738383930/gulimail | d249c0cb614253529970568baba89d24ea2430d3 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/zhou/gulimall/product/controller/SkuSaleAttrValueController.java | 15738383930/gulimail | d249c0cb614253529970568baba89d24ea2430d3 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/zhou/gulimall/product/controller/SkuSaleAttrValueController.java | 15738383930/gulimail | d249c0cb614253529970568baba89d24ea2430d3 | [
"Apache-2.0"
] | null | null | null | 26.411111 | 80 | 0.714767 | 6,549 | package com.zhou.gulimall.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zhou.gulimall.product.entity.SkuSaleAttrValueEntity;
import com.zhou.gulimall.product.service.SkuSaleAttrValueService;
import com.zhou.common.utils.PageUtils;
import com.zhou.common.utils.R;
/**
* sku销售属性&值
*
* @author zh
* @email lyhxr@example.com
* @date 2021-06-01 19:01:26
*/
@RestController
@RequestMapping("product/skusaleattrvalue")
public class SkuSaleAttrValueController {
@Autowired
private SkuSaleAttrValueService skuSaleAttrValueService;
/**
* 列表
*/
@RequestMapping("/list")
// @RequiresPermissions("product:skusaleattrvalue:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = skuSaleAttrValueService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
// @RequiresPermissions("product:skusaleattrvalue:info")
public R info(@PathVariable("id") Long id){
SkuSaleAttrValueEntity skuSaleAttrValue = skuSaleAttrValueService.getById(id);
return R.ok().put("skuSaleAttrValue", skuSaleAttrValue);
}
/**
* 保存
*/
@RequestMapping("/save")
// @RequiresPermissions("product:skusaleattrvalue:save")
public R save(@RequestBody SkuSaleAttrValueEntity skuSaleAttrValue){
skuSaleAttrValueService.save(skuSaleAttrValue);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
// @RequiresPermissions("product:skusaleattrvalue:update")
public R update(@RequestBody SkuSaleAttrValueEntity skuSaleAttrValue){
skuSaleAttrValueService.updateById(skuSaleAttrValue);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
// @RequiresPermissions("product:skusaleattrvalue:delete")
public R delete(@RequestBody Long[] ids){
skuSaleAttrValueService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
3e0f6cefe54c87459d78bd5c0ef2d2ce27c08d53 | 1,825 | java | Java | src/main/java/sonar/core/recipes/RecipeOreStack.java | SonarSonic/Sonar-Core | f5b64e033e2c07af55c2d5f474052fb83fba5ca1 | [
"MIT"
] | 19 | 2015-06-09T21:36:13.000Z | 2021-07-01T19:01:50.000Z | src/main/java/sonar/core/recipes/RecipeOreStack.java | SonarSonic/Sonar-Core | f5b64e033e2c07af55c2d5f474052fb83fba5ca1 | [
"MIT"
] | 70 | 2016-03-09T16:57:30.000Z | 2019-08-05T10:10:23.000Z | src/main/java/sonar/core/recipes/RecipeOreStack.java | SonarSonic/Sonar-Core | f5b64e033e2c07af55c2d5f474052fb83fba5ca1 | [
"MIT"
] | 20 | 2015-11-06T16:56:50.000Z | 2021-07-01T19:01:50.000Z | 24.662162 | 110 | 0.71726 | 6,550 | package sonar.core.recipes;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.ArrayList;
import java.util.List;
public class RecipeOreStack implements ISonarRecipeObject, ISonarRecipeItem {
public String oreType;
public List<ItemStack> cachedRegister;
public int stackSize;
public RecipeOreStack(String oreType, int stackSize) {
this.oreType = oreType;
this.stackSize = stackSize;
}
@Override
public Object getValue() {
return getJEIValue();
}
@Override
public boolean isNull() {
return getJEIValue().isEmpty();
}
@Override
public ItemStack getOutputStack() {
return getJEIValue().get(0).copy();
}
@Override
public boolean matches(Object object, RecipeObjectType type) {
if(object instanceof RecipeItemStack){
object = ((RecipeItemStack)object).stack;
}
if (object instanceof RecipeOreStack) {
RecipeOreStack oreStack = (RecipeOreStack) object;
return oreStack.oreType.equals(oreType) && oreStack.stackSize >= stackSize;
} else if (object instanceof String) {
return oreType.equals(object);
} else if (object instanceof ItemStack && type.checkStackSize(stackSize, ((ItemStack) object).getCount())) {
int oreID = OreDictionary.getOreID(oreType);
for (int id : OreDictionary.getOreIDs((ItemStack) object)) {
if (oreID == id) {
return true;
}
}
}
return false;
}
@Override
public List<ItemStack> getJEIValue() {
if(cachedRegister == null){
List<ItemStack> stacks = new ArrayList<>();
for (ItemStack ore : OreDictionary.getOres(oreType)) {
ItemStack newStack = ore.copy();
newStack.setCount(stackSize);
stacks.add(newStack);
}
this.cachedRegister = stacks;
}
return cachedRegister;
}
@Override
public int getStackSize() {
return stackSize;
}
} |
3e0f6d125b11ceddffb71c3ec2914db051db0b94 | 1,638 | java | Java | rdf4j-learning/src/main/java/com/earasoft/rdf4j/sail/rocksDbStore/rockdb/iterator/RockRegIterator.java | mannyrivera2010/rdf4j-learning | ef5bc6aeac0c16265605f4e7b577255fb48f96f7 | [
"Apache-2.0"
] | null | null | null | rdf4j-learning/src/main/java/com/earasoft/rdf4j/sail/rocksDbStore/rockdb/iterator/RockRegIterator.java | mannyrivera2010/rdf4j-learning | ef5bc6aeac0c16265605f4e7b577255fb48f96f7 | [
"Apache-2.0"
] | null | null | null | rdf4j-learning/src/main/java/com/earasoft/rdf4j/sail/rocksDbStore/rockdb/iterator/RockRegIterator.java | mannyrivera2010/rdf4j-learning | ef5bc6aeac0c16265605f4e7b577255fb48f96f7 | [
"Apache-2.0"
] | null | null | null | 26.852459 | 123 | 0.631868 | 6,551 | package com.earasoft.rdf4j.sail.rocksDbStore.rockdb.iterator;
import org.rocksdb.ColumnFamilyHandle;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksIterator;
import java.util.Iterator;
import java.util.function.Function;
public class RockRegIterator<S> implements Iterator {
final RocksIterator innerRocksIterator;
boolean seek = false;
final Function<RockDbIteratorEntry, S> func;
public RockRegIterator(ColumnFamilyHandle columnFamilyHandle, RocksDB rocksDB, Function<RockDbIteratorEntry, S> func) {
this.innerRocksIterator = rocksDB.newIterator(columnFamilyHandle);
this.func = func;
}
@Override
public boolean hasNext() {
if(!seek) {
this.innerRocksIterator.seekToFirst();
seek = true;
}
return innerRocksIterator.isValid();
}
@Override
public S next() {
// Iterator.next(); // this causes seg fault handle this
byte[] keyBytes = innerRocksIterator.key();
byte[] valueBytes = innerRocksIterator.value();
S ns = this.func.apply(new RockDbIteratorEntry(keyBytes, valueBytes));
innerRocksIterator.next();
return ns;
}
public void handleClose(){
if (this.innerRocksIterator.isOwningHandle()) {
this.innerRocksIterator.close();
}
}
// @Override
// public long count() {
// long count = 0L;
// while (this.hasNext()) {
// this.iter.next();
// this.matched = false;
// count++;
// BackendEntryIterator.checkInterrupted();
// }
// return count;
// }
}
|
3e0f6d9c6befacf94a40791d1f0b52c0b2f641a0 | 770 | java | Java | Lab4/src/main/java/ru/nsu/gorin/lab4/factory/suppliers/EngineSupplier.java | tarihay/java_labs | 8708cb05a2b8597c2cef8b29c8c89e43b008111b | [
"MIT"
] | null | null | null | Lab4/src/main/java/ru/nsu/gorin/lab4/factory/suppliers/EngineSupplier.java | tarihay/java_labs | 8708cb05a2b8597c2cef8b29c8c89e43b008111b | [
"MIT"
] | null | null | null | Lab4/src/main/java/ru/nsu/gorin/lab4/factory/suppliers/EngineSupplier.java | tarihay/java_labs | 8708cb05a2b8597c2cef8b29c8c89e43b008111b | [
"MIT"
] | null | null | null | 26.551724 | 84 | 0.679221 | 6,552 | package ru.nsu.gorin.lab4.factory.suppliers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.gorin.lab4.factory.parts.Engine;
/**
* Класс-поставщик двигателя
* Расширяет абстрактный класс поставщика с задержкой
* @see DelaySupplier
*/
public class EngineSupplier extends DelaySupplier<Engine> {
private static final Logger logger = LogManager.getLogger(EngineSupplier.class);
public EngineSupplier(int delay) {
super(delay);
}
public Engine get() {
try {
Thread.sleep(getDelay());
} catch (InterruptedException e) {
logger.info("Caught InterruptedException, returning null");
return null;
}
return new Engine();
}
}
|
3e0f6dd512a0d05d58407eea822ba0f375d2ca92 | 4,397 | java | Java | src/WebTest.java | sanxyzhang/Selenium | 15d9e04706c1566aa41757b7ae966228af9ca05a | [
"MIT"
] | null | null | null | src/WebTest.java | sanxyzhang/Selenium | 15d9e04706c1566aa41757b7ae966228af9ca05a | [
"MIT"
] | null | null | null | src/WebTest.java | sanxyzhang/Selenium | 15d9e04706c1566aa41757b7ae966228af9ca05a | [
"MIT"
] | null | null | null | 41.87619 | 135 | 0.548328 | 6,553 | //import java.util.concurrent.TimeUnit;
//import org.openqa.selenium.WebDriver;
//import org.openqa.selenium.chrome.ChromeDriver;
//
//public class WebTest {
// public static void main(String[] args) {
// System.setProperty("webdriver.chrome.driver","/Users/apple/Downloads/chromedriver");//chromedriver�务地�
// WebDriver driver = new ChromeDriver(); //新建一个WebDriver 的对象,但是new 的是FirefoxDriver的驱动
// driver.get("https://psych.liebes.top/st");//打开指定的网站
// //driver.findElement(By.id("kw")).sendKeys(new String[] {"hello"});//找到kwå…ƒç´ çš„id,然å�Žè¾“å…¥hello
// //driver.findElement(By.id("su")).click(); //点击按æ‰
// try {
// /**
// * WebDriver自带了一个智能ç‰å¾…的方法。
// dr.manage().timeouts().implicitlyWait(arg0, arg1);
// Arg0:ç‰å¾…的时间长度,int 类型 ï¼›
// Arg1:ç‰å¾…æ—¶é—´çš„å�•ä½� TimeUnit.SECONDS 一般用秒作为å�•ä½�。
// */
// driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
// } catch (Exception e) {
// e.printStackTrace();
// }
// /**
// * dr.quit()和dr.close()都�以退出�览器,简�的说一下两者的区别:第一个close,
// * 如果打开了多个页é�¢æ˜¯å…³ä¸�干净的,它å�ªå…³é—当å‰�的一个页é�¢ã€‚第二个quit,
// * 是退出了所有Webdriver所有的窗�,退的�常干净,所以推�使用quit最为一个case退出的方法。
// */
// driver.quit();//退出�览器
// }
//}
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class WebTest {
private String baseUrl;
private WebDriver driver;
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver","chromedriver");//chromedriver�务地�
driver = new ChromeDriver(); //新建一个WebDriver 的对象,但是new 的是FirefoxDriver的驱动
baseUrl = "https://psych.liebes.top/st";//打开指定的网站
try {
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void Test1() throws Exception {
//直接从本地文件创建Workbook
InputStream instream = new FileInputStream("input.xls");
Workbook readwb = Workbook.getWorkbook(instream);
//Sheetçš„ä¸‹æ ‡æ˜¯ä»Ž0开始
//获å�–ç¬¬ä¸€å¼ Sheet表
Sheet readsheet = readwb.getSheet(0);
//获å�–Sheetè¡¨ä¸æ‰€åŒ…å�«çš„æ€»åˆ—æ•°
int rsColumns = readsheet.getColumns();
//获å�–Sheetè¡¨ä¸æ‰€åŒ…å�«çš„æ€»è¡Œæ•°
int rsRows = readsheet.getRows();
//获å�–指定å�•å…ƒæ ¼çš„å¯¹è±¡å¼•ç”¨
for (int i = 0; i < rsRows; i++)
{
driver.get(baseUrl);
Cell cell = readsheet.getCell(0, i);
String username = cell.getContents();
String password = username.substring(4, 10);
// 通过 id 找到 input 的 DOM
WebElement element = driver.findElement(By.id("username"));
WebElement element1 = driver.findElement(By.id("password"));
//System.out.println(element.getSize());
// 输入关键å—
element.sendKeys(username);
element1.sendKeys(password);
// �交 input 所在的form
element.submit();
//获�得到的邮箱
WebElement element2 = driver.findElement(By.xpath("html/body/div/div/a/p"));
String mailByWeb = element2.getText();
String mailByInfo = readsheet.getCell(1,i).getContents();
assertEquals(mailByInfo, mailByWeb);
System.out.println(element2.getText());
System.out.println(username);
}
//å…³é—读入æµ�
readwb.close();
}
} |
3e0f6e9f0a378023d5a6f5468937097143ce2071 | 1,016 | java | Java | TheFirstModule/src/LeetCode/Solution813Ex.java | xiongEd/TheFirstModule | 4016ed2ff327e5c51e3ee2434cee5536ebe40ae1 | [
"Apache-2.0"
] | 1 | 2020-01-09T09:59:23.000Z | 2020-01-09T09:59:23.000Z | TheFirstModule/src/LeetCode/Solution813Ex.java | xiongEd/TheFirstModule | 4016ed2ff327e5c51e3ee2434cee5536ebe40ae1 | [
"Apache-2.0"
] | null | null | null | TheFirstModule/src/LeetCode/Solution813Ex.java | xiongEd/TheFirstModule | 4016ed2ff327e5c51e3ee2434cee5536ebe40ae1 | [
"Apache-2.0"
] | null | null | null | 23.627907 | 76 | 0.409449 | 6,554 | package LeetCode;
public class Solution813Ex {
private static double[]sums;
public static double largestSumOfAverages(int[] A, int K) {
if (A.length == 0 || K > A.length)
return 0;
int sum = 0;
sums = new double[A.length];
for (int i = 0; i < A.length; i ++){
sum += A[i];
sums[i] = sum;
}
double[] dp = new double[A.length];
for (int i = 0; i < A.length; i ++){
dp[i] = getAvevage(i, A.length - 1);
}
for (int i = 0; i < K - 1; i ++){
for (int j = 0; j < A.length; j ++){
for (int k = j + 1; k < A.length; k ++){
dp[j] = Math.max(dp[j], (getAvevage(j, k - 1) + dp[k]));
}
}
}
return dp[0];
}
private static double getAvevage(int i, int j){
if (i == 0)
return sums[j] / (j + 1);
else
return (sums[j] - sums[i - 1]) / (j - i + 1);
}
}
|
3e0f6f2d8f72bb6d2e912af3bc0ec8a85c1bee46 | 1,498 | java | Java | src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/filtering/DuplicatedAltReadFilter.java | slzhao/gatk | 2e27f693bbea5b22eca809eb104a5df8a0a2d381 | [
"Apache-2.0"
] | 1,273 | 2015-10-13T18:11:50.000Z | 2022-03-28T09:25:13.000Z | src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/filtering/DuplicatedAltReadFilter.java | slzhao/gatk | 2e27f693bbea5b22eca809eb104a5df8a0a2d381 | [
"Apache-2.0"
] | 6,471 | 2015-10-08T02:31:06.000Z | 2022-03-31T17:55:25.000Z | src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/filtering/DuplicatedAltReadFilter.java | slzhao/gatk | 2e27f693bbea5b22eca809eb104a5df8a0a2d381 | [
"Apache-2.0"
] | 598 | 2015-10-14T19:16:14.000Z | 2022-03-29T10:03:03.000Z | 40.486486 | 152 | 0.794393 | 6,555 | package org.broadinstitute.hellbender.tools.walkers.mutect.filtering;
import htsjdk.variant.variantcontext.VariantContext;
import org.broadinstitute.hellbender.engine.ReferenceContext;
import org.broadinstitute.hellbender.tools.walkers.annotator.UniqueAltReadCount;
import org.broadinstitute.hellbender.utils.variant.GATKVCFConstants;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
// This filter checks for the case in which PCR-duplicates with unique UMIs (which we assume is caused by false adapter priming)
// amplify the erroneous signal for an alternate allele.
public class DuplicatedAltReadFilter extends HardAlleleFilter {
private final int uniqueAltReadCount;
public DuplicatedAltReadFilter(final int uniqueAltReadCount) {
this.uniqueAltReadCount = uniqueAltReadCount;
}
@Override
public ErrorType errorType() { return ErrorType.ARTIFACT; }
@Override
public List<Boolean> areAllelesArtifacts(final VariantContext vc, final Mutect2FilteringEngine filteringEngine, ReferenceContext referenceContext) {
return vc.getAttributeAsIntList(UniqueAltReadCount.KEY, 1).stream().map(count -> count <= uniqueAltReadCount).collect(Collectors.toList());
}
@Override
public String filterName() {
return GATKVCFConstants.DUPLICATED_EVIDENCE_FILTER_NAME;
}
@Override
protected List<String> requiredInfoAnnotations() { return Collections.singletonList(UniqueAltReadCount.KEY); }
}
|
3e0f6faea528dcc7b7796c9de8f18462a0cda8d5 | 2,216 | java | Java | repose-aggregator/components/filters/client-auth/src/main/java/org/openrepose/filters/clientauth/common/EndpointsCache.java | olacabs/repose | 795b009edc46bcd10d4b337622239155749a92dd | [
"Apache-2.0"
] | null | null | null | repose-aggregator/components/filters/client-auth/src/main/java/org/openrepose/filters/clientauth/common/EndpointsCache.java | olacabs/repose | 795b009edc46bcd10d4b337622239155749a92dd | [
"Apache-2.0"
] | null | null | null | repose-aggregator/components/filters/client-auth/src/main/java/org/openrepose/filters/clientauth/common/EndpointsCache.java | olacabs/repose | 795b009edc46bcd10d4b337622239155749a92dd | [
"Apache-2.0"
] | 1 | 2021-03-29T09:35:51.000Z | 2021-03-29T09:35:51.000Z | 34.625 | 101 | 0.670578 | 6,556 | /*
* _=_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_=
* Repose
* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
* Copyright (C) 2010 - 2015 Rackspace US, 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 org.openrepose.filters.clientauth.common;
import org.openrepose.core.services.datastore.Datastore;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* This class manages the caching of endpoints.
*/
public class EndpointsCache implements DeleteableCache {
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(AuthenticationHandler.class);
private final Datastore store;
private final String cachePrefix;
public EndpointsCache(Datastore store, String cachePrefix) {
this.store = store;
this.cachePrefix = cachePrefix;
}
public String getEndpoints(String token) {
String candidate = (String) store.get(cachePrefix + "." + token);
return candidate;
}
public void storeEndpoints(String tokenId, String endpoints, int ttl) throws IOException {
if (endpoints == null || tokenId == null || ttl < 0) {
LOG.warn("Null values passed into cache when attempting to store endpoints.");
return;
}
store.put(cachePrefix + "." + tokenId, endpoints, ttl, TimeUnit.MILLISECONDS);
}
@Override
public boolean deleteCacheItem(String userId) {
return store.remove(userId);
}
}
|
3e0f705dbeb472a33c6e04ad0e229a6512c3525d | 18,015 | java | Java | apollo-compiler/src/test/graphql/com/example/nested_inline_fragment/fragment/TestSetting.java | xrd/apollo-android | 8b3e8a52b647b2853cf4813812de614009d169a6 | [
"MIT"
] | 1 | 2019-03-22T16:21:11.000Z | 2019-03-22T16:21:11.000Z | apollo-compiler/src/test/graphql/com/example/nested_inline_fragment/fragment/TestSetting.java | xrd/apollo-android | 8b3e8a52b647b2853cf4813812de614009d169a6 | [
"MIT"
] | 1 | 2018-10-08T14:35:43.000Z | 2018-10-08T14:35:43.000Z | apollo-compiler/src/test/graphql/com/example/nested_inline_fragment/fragment/TestSetting.java | xrd/apollo-android | 8b3e8a52b647b2853cf4813812de614009d169a6 | [
"MIT"
] | null | null | null | 32.6951 | 263 | 0.642631 | 6,557 | package com.example.nested_inline_fragment.fragment;
import com.apollographql.apollo.api.GraphqlFragment;
import com.apollographql.apollo.api.ResponseField;
import com.apollographql.apollo.api.ResponseFieldMapper;
import com.apollographql.apollo.api.ResponseFieldMarshaller;
import com.apollographql.apollo.api.ResponseReader;
import com.apollographql.apollo.api.ResponseWriter;
import com.apollographql.apollo.api.internal.Optional;
import com.apollographql.apollo.api.internal.Utils;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Generated;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Generated("Apollo GraphQL")
public interface TestSetting extends GraphqlFragment {
String FRAGMENT_DEFINITION = "fragment TestSetting on Setting {\n"
+ " __typename\n"
+ " value {\n"
+ " __typename\n"
+ " ... on StringListSettingValue {\n"
+ " list\n"
+ " }\n"
+ " }\n"
+ " ... on SelectSetting {\n"
+ " options {\n"
+ " __typename\n"
+ " allowFreeText\n"
+ " id\n"
+ " label\n"
+ " }\n"
+ " }\n"
+ "}";
List<String> POSSIBLE_TYPES = Collections.unmodifiableList(Arrays.asList( "BooleanSetting", "SelectSetting", "StringListSetting", "TextSetting", "TypedStringListSetting"));
@NotNull String __typename();
Optional<? extends Value> value();
ResponseFieldMarshaller marshaller();
final class Mapper implements ResponseFieldMapper<TestSetting> {
final AsSelectSetting.Mapper asSelectSettingFieldMapper = new AsSelectSetting.Mapper();
@Override
public TestSetting map(ResponseReader reader) {
final AsSelectSetting asSelectSetting = reader.readConditional(ResponseField.forInlineFragment("__typename", "__typename", Arrays.asList("SelectSetting")), new ResponseReader.ConditionalTypeReader<AsSelectSetting>() {
@Override
public AsSelectSetting read(String conditionalType, ResponseReader reader) {
return asSelectSettingFieldMapper.map(reader);
}
});
if (asSelectSetting != null) {
return asSelectSetting;
}
return null;
}
}
interface Value {
@NotNull String __typename();
ResponseFieldMarshaller marshaller();
final class Mapper implements ResponseFieldMapper<Value> {
final AsStringListSettingValue.Mapper asStringListSettingValueFieldMapper = new AsStringListSettingValue.Mapper();
@Override
public Value map(ResponseReader reader) {
final AsStringListSettingValue asStringListSettingValue = reader.readConditional(ResponseField.forInlineFragment("__typename", "__typename", Arrays.asList("StringListSettingValue")), new ResponseReader.ConditionalTypeReader<AsStringListSettingValue>() {
@Override
public AsStringListSettingValue read(String conditionalType, ResponseReader reader) {
return asStringListSettingValueFieldMapper.map(reader);
}
});
if (asStringListSettingValue != null) {
return asStringListSettingValue;
}
return null;
}
}
}
class AsStringListSettingValue implements Value {
static final ResponseField[] $responseFields = {
ResponseField.forString("__typename", "__typename", null, false, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forList("list", "list", null, true, Collections.<ResponseField.Condition>emptyList())
};
final @NotNull String __typename;
final Optional<List<String>> list;
private volatile String $toString;
private volatile int $hashCode;
private volatile boolean $hashCodeMemoized;
public AsStringListSettingValue(@NotNull String __typename, @Nullable List<String> list) {
this.__typename = Utils.checkNotNull(__typename, "__typename == null");
this.list = Optional.fromNullable(list);
}
public @NotNull String __typename() {
return this.__typename;
}
public Optional<List<String>> list() {
return this.list;
}
public ResponseFieldMarshaller marshaller() {
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
writer.writeString($responseFields[0], __typename);
writer.writeList($responseFields[1], list.isPresent() ? list.get() : null, new ResponseWriter.ListWriter() {
@Override
public void write(Object value, ResponseWriter.ListItemWriter listItemWriter) {
listItemWriter.writeString(value);
}
});
}
};
}
@Override
public String toString() {
if ($toString == null) {
$toString = "AsStringListSettingValue{"
+ "__typename=" + __typename + ", "
+ "list=" + list
+ "}";
}
return $toString;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof AsStringListSettingValue) {
AsStringListSettingValue that = (AsStringListSettingValue) o;
return this.__typename.equals(that.__typename)
&& this.list.equals(that.list);
}
return false;
}
@Override
public int hashCode() {
if (!$hashCodeMemoized) {
int h = 1;
h *= 1000003;
h ^= __typename.hashCode();
h *= 1000003;
h ^= list.hashCode();
$hashCode = h;
$hashCodeMemoized = true;
}
return $hashCode;
}
public static final class Mapper implements ResponseFieldMapper<AsStringListSettingValue> {
@Override
public AsStringListSettingValue map(ResponseReader reader) {
final String __typename = reader.readString($responseFields[0]);
final List<String> list = reader.readList($responseFields[1], new ResponseReader.ListReader<String>() {
@Override
public String read(ResponseReader.ListItemReader listItemReader) {
return listItemReader.readString();
}
});
return new AsStringListSettingValue(__typename, list);
}
}
}
class AsSelectSetting implements TestSetting {
static final ResponseField[] $responseFields = {
ResponseField.forString("__typename", "__typename", null, false, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forObject("value", "value", null, true, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forList("options", "options", null, true, Collections.<ResponseField.Condition>emptyList())
};
final @NotNull String __typename;
final Optional<Value1> value;
final Optional<List<Option>> options;
private volatile String $toString;
private volatile int $hashCode;
private volatile boolean $hashCodeMemoized;
public AsSelectSetting(@NotNull String __typename, @Nullable Value1 value,
@Nullable List<Option> options) {
this.__typename = Utils.checkNotNull(__typename, "__typename == null");
this.value = Optional.fromNullable(value);
this.options = Optional.fromNullable(options);
}
public @NotNull String __typename() {
return this.__typename;
}
public Optional<Value1> value() {
return this.value;
}
public Optional<List<Option>> options() {
return this.options;
}
public ResponseFieldMarshaller marshaller() {
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
writer.writeString($responseFields[0], __typename);
writer.writeObject($responseFields[1], value.isPresent() ? value.get().marshaller() : null);
writer.writeList($responseFields[2], options.isPresent() ? options.get() : null, new ResponseWriter.ListWriter() {
@Override
public void write(Object value, ResponseWriter.ListItemWriter listItemWriter) {
listItemWriter.writeObject(((Option) value).marshaller());
}
});
}
};
}
@Override
public String toString() {
if ($toString == null) {
$toString = "AsSelectSetting{"
+ "__typename=" + __typename + ", "
+ "value=" + value + ", "
+ "options=" + options
+ "}";
}
return $toString;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof AsSelectSetting) {
AsSelectSetting that = (AsSelectSetting) o;
return this.__typename.equals(that.__typename)
&& this.value.equals(that.value)
&& this.options.equals(that.options);
}
return false;
}
@Override
public int hashCode() {
if (!$hashCodeMemoized) {
int h = 1;
h *= 1000003;
h ^= __typename.hashCode();
h *= 1000003;
h ^= value.hashCode();
h *= 1000003;
h ^= options.hashCode();
$hashCode = h;
$hashCodeMemoized = true;
}
return $hashCode;
}
public static final class Mapper implements ResponseFieldMapper<AsSelectSetting> {
final Value1.Mapper value1FieldMapper = new Value1.Mapper();
final Option.Mapper optionFieldMapper = new Option.Mapper();
@Override
public AsSelectSetting map(ResponseReader reader) {
final String __typename = reader.readString($responseFields[0]);
final Value1 value = reader.readObject($responseFields[1], new ResponseReader.ObjectReader<Value1>() {
@Override
public Value1 read(ResponseReader reader) {
return value1FieldMapper.map(reader);
}
});
final List<Option> options = reader.readList($responseFields[2], new ResponseReader.ListReader<Option>() {
@Override
public Option read(ResponseReader.ListItemReader listItemReader) {
return listItemReader.readObject(new ResponseReader.ObjectReader<Option>() {
@Override
public Option read(ResponseReader reader) {
return optionFieldMapper.map(reader);
}
});
}
});
return new AsSelectSetting(__typename, value, options);
}
}
}
interface Value1 extends Value {
@NotNull String __typename();
ResponseFieldMarshaller marshaller();
final class Mapper implements ResponseFieldMapper<Value1> {
final AsStringListSettingValue1.Mapper asStringListSettingValue1FieldMapper = new AsStringListSettingValue1.Mapper();
@Override
public Value1 map(ResponseReader reader) {
final AsStringListSettingValue1 asStringListSettingValue = reader.readConditional(ResponseField.forInlineFragment("__typename", "__typename", Arrays.asList("StringListSettingValue")), new ResponseReader.ConditionalTypeReader<AsStringListSettingValue1>() {
@Override
public AsStringListSettingValue1 read(String conditionalType, ResponseReader reader) {
return asStringListSettingValue1FieldMapper.map(reader);
}
});
if (asStringListSettingValue != null) {
return asStringListSettingValue;
}
return null;
}
}
}
class AsStringListSettingValue1 implements Value1 {
static final ResponseField[] $responseFields = {
ResponseField.forString("__typename", "__typename", null, false, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forList("list", "list", null, true, Collections.<ResponseField.Condition>emptyList())
};
final @NotNull String __typename;
final Optional<List<String>> list;
private volatile String $toString;
private volatile int $hashCode;
private volatile boolean $hashCodeMemoized;
public AsStringListSettingValue1(@NotNull String __typename, @Nullable List<String> list) {
this.__typename = Utils.checkNotNull(__typename, "__typename == null");
this.list = Optional.fromNullable(list);
}
public @NotNull String __typename() {
return this.__typename;
}
public Optional<List<String>> list() {
return this.list;
}
public ResponseFieldMarshaller marshaller() {
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
writer.writeString($responseFields[0], __typename);
writer.writeList($responseFields[1], list.isPresent() ? list.get() : null, new ResponseWriter.ListWriter() {
@Override
public void write(Object value, ResponseWriter.ListItemWriter listItemWriter) {
listItemWriter.writeString(value);
}
});
}
};
}
@Override
public String toString() {
if ($toString == null) {
$toString = "AsStringListSettingValue1{"
+ "__typename=" + __typename + ", "
+ "list=" + list
+ "}";
}
return $toString;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof AsStringListSettingValue1) {
AsStringListSettingValue1 that = (AsStringListSettingValue1) o;
return this.__typename.equals(that.__typename)
&& this.list.equals(that.list);
}
return false;
}
@Override
public int hashCode() {
if (!$hashCodeMemoized) {
int h = 1;
h *= 1000003;
h ^= __typename.hashCode();
h *= 1000003;
h ^= list.hashCode();
$hashCode = h;
$hashCodeMemoized = true;
}
return $hashCode;
}
public static final class Mapper implements ResponseFieldMapper<AsStringListSettingValue1> {
@Override
public AsStringListSettingValue1 map(ResponseReader reader) {
final String __typename = reader.readString($responseFields[0]);
final List<String> list = reader.readList($responseFields[1], new ResponseReader.ListReader<String>() {
@Override
public String read(ResponseReader.ListItemReader listItemReader) {
return listItemReader.readString();
}
});
return new AsStringListSettingValue1(__typename, list);
}
}
}
class Option {
static final ResponseField[] $responseFields = {
ResponseField.forString("__typename", "__typename", null, false, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forBoolean("allowFreeText", "allowFreeText", null, false, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forString("id", "id", null, false, Collections.<ResponseField.Condition>emptyList()),
ResponseField.forString("label", "label", null, false, Collections.<ResponseField.Condition>emptyList())
};
final @NotNull String __typename;
final boolean allowFreeText;
final @NotNull String id;
final @NotNull String label;
private volatile String $toString;
private volatile int $hashCode;
private volatile boolean $hashCodeMemoized;
public Option(@NotNull String __typename, boolean allowFreeText, @NotNull String id,
@NotNull String label) {
this.__typename = Utils.checkNotNull(__typename, "__typename == null");
this.allowFreeText = allowFreeText;
this.id = Utils.checkNotNull(id, "id == null");
this.label = Utils.checkNotNull(label, "label == null");
}
public @NotNull String __typename() {
return this.__typename;
}
public boolean allowFreeText() {
return this.allowFreeText;
}
public @NotNull String id() {
return this.id;
}
public @NotNull String label() {
return this.label;
}
public ResponseFieldMarshaller marshaller() {
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
writer.writeString($responseFields[0], __typename);
writer.writeBoolean($responseFields[1], allowFreeText);
writer.writeString($responseFields[2], id);
writer.writeString($responseFields[3], label);
}
};
}
@Override
public String toString() {
if ($toString == null) {
$toString = "Option{"
+ "__typename=" + __typename + ", "
+ "allowFreeText=" + allowFreeText + ", "
+ "id=" + id + ", "
+ "label=" + label
+ "}";
}
return $toString;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof Option) {
Option that = (Option) o;
return this.__typename.equals(that.__typename)
&& this.allowFreeText == that.allowFreeText
&& this.id.equals(that.id)
&& this.label.equals(that.label);
}
return false;
}
@Override
public int hashCode() {
if (!$hashCodeMemoized) {
int h = 1;
h *= 1000003;
h ^= __typename.hashCode();
h *= 1000003;
h ^= Boolean.valueOf(allowFreeText).hashCode();
h *= 1000003;
h ^= id.hashCode();
h *= 1000003;
h ^= label.hashCode();
$hashCode = h;
$hashCodeMemoized = true;
}
return $hashCode;
}
public static final class Mapper implements ResponseFieldMapper<Option> {
@Override
public Option map(ResponseReader reader) {
final String __typename = reader.readString($responseFields[0]);
final boolean allowFreeText = reader.readBoolean($responseFields[1]);
final String id = reader.readString($responseFields[2]);
final String label = reader.readString($responseFields[3]);
return new Option(__typename, allowFreeText, id, label);
}
}
}
}
|
3e0f70f5f1b5ffc5a28a15b9561f5a65a887132b | 2,259 | java | Java | src/test/java/org/opensaml/saml2/core/validator/AttributeStatementSchemaTest.java | danpal/OpenSAML | 8297262c7ef649249f84750a6c197f4359669f97 | [
"Apache-2.0"
] | 3 | 2016-04-19T09:11:40.000Z | 2020-01-21T14:47:34.000Z | src/test/java/org/opensaml/saml2/core/validator/AttributeStatementSchemaTest.java | danpal/OpenSAML | 8297262c7ef649249f84750a6c197f4359669f97 | [
"Apache-2.0"
] | 2 | 2015-05-05T13:30:56.000Z | 2017-07-27T07:33:07.000Z | src/test/java/org/opensaml/saml2/core/validator/AttributeStatementSchemaTest.java | danpal/OpenSAML | 8297262c7ef649249f84750a6c197f4359669f97 | [
"Apache-2.0"
] | 10 | 2016-01-07T12:23:40.000Z | 2022-02-23T03:24:07.000Z | 38.948276 | 133 | 0.75166 | 6,558 | /*
* Copyright [2005] [University Corporation for Advanced Internet Development, 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 org.opensaml.saml2.core.validator;
import javax.xml.namespace.QName;
import org.opensaml.common.BaseSAMLObjectValidatorTestCase;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.xml.validation.ValidationException;
/**
* Test case for {@link org.opensaml.saml2.core.validator.AttributeStatementSchemaValidator}.
*/
public class AttributeStatementSchemaTest extends BaseSAMLObjectValidatorTestCase {
/** Constructor */
public AttributeStatementSchemaTest() {
targetQName = new QName(SAMLConstants.SAML20_NS, AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX);
validator = new AttributeStatementSchemaValidator();
}
/** {@inheritDoc} */
protected void populateRequiredData() {
super.populateRequiredData();
AttributeStatement attributeStatement = (AttributeStatement) target;
Attribute attribute = (Attribute) buildXMLObject(new QName(SAMLConstants.SAML20_NS, Attribute.DEFAULT_ELEMENT_LOCAL_NAME,
SAMLConstants.SAML20_PREFIX));
attributeStatement.getAttributes().add(attribute);
}
/**
* Tests absent Attribute failure.
*
* @throws ValidationException
*/
public void testAttributeFailure() throws ValidationException {
AttributeStatement attributeStatement = (AttributeStatement) target;
attributeStatement.getAttributes().clear();
assertValidationFail("Attribute list empty, should raise a Validation Exception");
}
} |
3e0f7103d76d13c55ad99b252b8f1bda43f10407 | 2,833 | java | Java | edexOsgi/com.raytheon.uf.common.archive/src/com/raytheon/uf/common/archive/config/select/CategorySelect.java | drjoeycadieux/awips2 | 3b467b15915cba23d9216eefd97a21758e66c748 | [
"Apache-2.0"
] | null | null | null | edexOsgi/com.raytheon.uf.common.archive/src/com/raytheon/uf/common/archive/config/select/CategorySelect.java | drjoeycadieux/awips2 | 3b467b15915cba23d9216eefd97a21758e66c748 | [
"Apache-2.0"
] | null | null | null | edexOsgi/com.raytheon.uf.common.archive/src/com/raytheon/uf/common/archive/config/select/CategorySelect.java | drjoeycadieux/awips2 | 3b467b15915cba23d9216eefd97a21758e66c748 | [
"Apache-2.0"
] | 1 | 2021-10-30T00:03:05.000Z | 2021-10-30T00:03:05.000Z | 27.77451 | 79 | 0.625838 | 6,559 | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.archive.config.select;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Select configuration class that contains a list of selected display labels
* for a given category. It is assumed this is associated with a given archive.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 19, 2013 2221 rferrel Initial creation
* Dec 11, 2013 2603 rferrel Selected now a Set.
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "archive")
public class CategorySelect {
/**
* The category name.
*/
@XmlElement(name = "name")
private String name;
/**
* List of selected labels.
*/
@XmlElement(name = "selectedDisplayName")
private final Set<String> selectSet = new HashSet<String>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getSelectSet() {
return selectSet;
}
public void setSelectSet(Set<String> selectList) {
this.selectSet.clear();
this.selectSet.addAll(selectList);
}
public void add(String displayName) {
selectSet.add(displayName);
}
public boolean isEmpty() {
return selectSet.isEmpty();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CategorySelect [ name: ").append(getName());
sb.append("[ ");
for (String select : getSelectSet()) {
sb.append("\"").append(select).append("\", ");
}
sb.append("]");
return sb.toString();
}
}
|
3e0f71147134539a0c77d3001b62384a2e3ecd1b | 4,991 | java | Java | presto-common/src/main/java/com/facebook/presto/common/array/AdaptiveLongBigArray.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 9,782 | 2016-03-18T15:16:19.000Z | 2022-03-31T07:49:41.000Z | presto-common/src/main/java/com/facebook/presto/common/array/AdaptiveLongBigArray.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 10,310 | 2016-03-18T01:03:00.000Z | 2022-03-31T23:54:08.000Z | presto-common/src/main/java/com/facebook/presto/common/array/AdaptiveLongBigArray.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 3,803 | 2016-03-18T22:54:24.000Z | 2022-03-31T07:49:46.000Z | 32.2 | 103 | 0.621118 | 6,560 | /*
* 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.facebook.presto.common.array;
import org.openjdk.jol.info.ClassLayout;
import java.util.Arrays;
import static io.airlift.slice.SizeOf.sizeOf;
import static io.airlift.slice.SizeOf.sizeOfLongArray;
/**
* This variation of BigArray is designed to expand segments up to some reasonable extend
* and add more segments if the maximum segment capacity is reached
* This implementation allows to keep the redirection table small so it does fit into L1 CPU cache
*/
public class AdaptiveLongBigArray
{
// visible for testing
static final int INSTANCE_SIZE = ClassLayout.parseClass(AdaptiveLongBigArray.class).instanceSize();
// settings are constants due to efficiency considerations
static final int INITIAL_SEGMENT_LENGTH = 16 * 1024; // 128KB
static final int MAX_SEGMENT_LENGTH = 32 * 1024 * 1024; // 256MB
static final long MAX_SEGMENT_SIZE_IN_BYTES = sizeOfLongArray(MAX_SEGMENT_LENGTH);
static final int INITIAL_SEGMENTS = 10;
static final int SEGMENT_SHIFT = 25;
static final int SEGMENT_MASK = MAX_SEGMENT_LENGTH - 1;
// segments are allocated lazily in ensureCapacity
// The first segment is allocated initially with INITIAL_SEGMENT_LENGTH
// and then gradually expanded until it reaches MAX_SEGMENT_LENGTH
// Second and subsequent segments are directly allocated with MAX_SEGMENT_LENGTH
private long[][] array;
// number of allocated segments
private int segments;
// number of elements that currently can be stored in the container
private int capacity;
public AdaptiveLongBigArray()
{
array = new long[INITIAL_SEGMENTS][];
}
public long getRetainedSizeInBytes()
{
long result = INSTANCE_SIZE + sizeOf(array);
if (segments == 1) {
result += sizeOfLongArray(array[0].length);
}
else if (segments > 1) {
result += segments * MAX_SEGMENT_SIZE_IN_BYTES;
}
return result;
}
public long get(int index)
{
return array[segment(index)][offset(index)];
}
public void set(int index, long value)
{
array[segment(index)][offset(index)] = value;
}
public void swap(int first, int second)
{
long[] firstSegment = array[segment(first)];
int firstOffset = offset(first);
long[] secondSegment = array[segment(second)];
int secondOffset = offset(second);
long tmp = firstSegment[firstOffset];
firstSegment[firstOffset] = secondSegment[secondOffset];
secondSegment[secondOffset] = tmp;
}
public void ensureCapacity(int length)
{
if (capacity >= length) {
return;
}
int lastIndex = length - 1;
int segment = segment(lastIndex);
int offset = offset(lastIndex);
// expand segments array if needed
if (segment >= array.length) {
int segmentsArrayCapacity = array.length;
while (segment >= segmentsArrayCapacity) {
segmentsArrayCapacity *= 2;
}
array = Arrays.copyOf(array, segmentsArrayCapacity);
}
if (segment == 0) {
if (array[0] == null) {
array[0] = new long[INITIAL_SEGMENT_LENGTH];
}
// expand segment if needed
if (offset >= array[0].length) {
int segmentLength = array[0].length;
while (offset >= segmentLength) {
segmentLength *= 2;
}
array[0] = Arrays.copyOf(array[0], segmentLength);
}
}
else {
for (int i = 0; i <= segment; i++) {
if (array[i] == null) {
array[i] = new long[MAX_SEGMENT_LENGTH];
}
if (i == 0 && array[0].length < MAX_SEGMENT_LENGTH) {
array[0] = Arrays.copyOf(array[0], MAX_SEGMENT_LENGTH);
}
}
}
segments = segment + 1;
capacity = segments == 1 ? array[0].length : MAX_SEGMENT_LENGTH * segments;
}
private static int segment(int index)
{
return index >>> SEGMENT_SHIFT;
}
private static int offset(int index)
{
return index & SEGMENT_MASK;
}
public void clear()
{
array = new long[INITIAL_SEGMENTS][];
segments = 0;
capacity = 0;
}
}
|
3e0f717669a9da863b01e683cbcc94f2590a933b | 402 | java | Java | lamp-public/lamp-common/src/main/java/com/tangyh/lamp/common/cache/gateway/RateLimiterCacheKeyBuilder.java | Yimn/lamp-cloud | 510d18143303039cf01df9ad55226cf43aa5b7bb | [
"Apache-2.0"
] | 1 | 2022-03-19T03:28:16.000Z | 2022-03-19T03:28:16.000Z | lamp-public/lamp-common/src/main/java/com/tangyh/lamp/common/cache/gateway/RateLimiterCacheKeyBuilder.java | Yimn/lamp-cloud | 510d18143303039cf01df9ad55226cf43aa5b7bb | [
"Apache-2.0"
] | null | null | null | lamp-public/lamp-common/src/main/java/com/tangyh/lamp/common/cache/gateway/RateLimiterCacheKeyBuilder.java | Yimn/lamp-cloud | 510d18143303039cf01df9ad55226cf43aa5b7bb | [
"Apache-2.0"
] | 2 | 2021-02-25T09:40:25.000Z | 2022-03-19T03:28:15.000Z | 20.1 | 68 | 0.726368 | 6,561 | package com.tangyh.lamp.common.cache.gateway;
import com.tangyh.basic.cache.model.CacheKeyBuilder;
import com.tangyh.lamp.common.cache.CacheKeyDefinition;
/**
* 限流 KEY
* <p>
*
* @author zuihou
* @date 2020/9/20 6:45 下午
*/
public class RateLimiterCacheKeyBuilder implements CacheKeyBuilder {
@Override
public String getPrefix() {
return CacheKeyDefinition.RATE_LIMITER;
}
}
|
3e0f717c083e256f8d1e846a0386f9f3d1e1c594 | 1,921 | java | Java | src/main/java/com/stryphic/stryphiccore/proxy/ClientProxy.java | Stryphic-Team/StryphicCore | 89082e9b143b530ee2031928df2243560c2f9cd7 | [
"MIT"
] | 1 | 2019-11-11T00:25:50.000Z | 2019-11-11T00:25:50.000Z | src/main/java/com/stryphic/stryphiccore/proxy/ClientProxy.java | Stryphic-Team/StryphicCore | 89082e9b143b530ee2031928df2243560c2f9cd7 | [
"MIT"
] | null | null | null | src/main/java/com/stryphic/stryphiccore/proxy/ClientProxy.java | Stryphic-Team/StryphicCore | 89082e9b143b530ee2031928df2243560c2f9cd7 | [
"MIT"
] | null | null | null | 34.927273 | 131 | 0.750651 | 6,562 | package com.stryphic.stryphiccore.proxy;
import com.stryphic.stryphiccore.StryphicCore;
import com.stryphic.stryphiccore.util.handlers.ClientEventHandler;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
public class ClientProxy extends CommonProxy{
public void registerItemRenderer(Item item, int meta, String id)
{
ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(item.getRegistryName(), id));
}
@Override
public void registerModel(Item item, int metadata)
{
ModelLoader.setCustomModelResourceLocation(item, metadata, new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
public void registerEntityRenderer(){
}
//Run before Minecraft initializes
@Override
public void preInit(FMLPreInitializationEvent event){
super.preInit(event);
StryphicCore.logger.debug("Client: Pre Intializing");
}
//Run when the client connects to a server or starts a new single player world
@Override
public void init(FMLInitializationEvent event) {
super.init(event);
StryphicCore.logger.debug("Client: Intializing");
}
//Run after Minecraft initializes
@Override
public void postInit(FMLPostInitializationEvent event) {
super.postInit(event);//You need one of these oops...
StryphicCore.logger.debug("Client: Pre Intializing");
//MinecraftForge.EVENT_BUS.register(new KeyHandler());
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
}
}
|
3e0f720a628aec2da12471b23a9b185453a9e8ac | 3,272 | java | Java | source/main/java/org/openbakery/racecontrol/plugin/tracker/web/LapListView.java | openbakery/LFS-Racecontrol | d98a2d5f4f51d95fe71ddc06b4deb70ccb8ec5b9 | [
"Apache-2.0"
] | null | null | null | source/main/java/org/openbakery/racecontrol/plugin/tracker/web/LapListView.java | openbakery/LFS-Racecontrol | d98a2d5f4f51d95fe71ddc06b4deb70ccb8ec5b9 | [
"Apache-2.0"
] | null | null | null | source/main/java/org/openbakery/racecontrol/plugin/tracker/web/LapListView.java | openbakery/LFS-Racecontrol | d98a2d5f4f51d95fe71ddc06b4deb70ccb8ec5b9 | [
"Apache-2.0"
] | null | null | null | 26.819672 | 88 | 0.681235 | 6,563 | package org.openbakery.racecontrol.plugin.tracker.web;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import org.openbakery.jinsim.Track;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.openbakery.racecontrol.data.Lap;
import org.openbakery.racecontrol.persistence.bean.Profile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LapListView extends ListView<Lap> {
private static Logger log = LoggerFactory.getLogger(LapListView.class);
private static SimpleDateFormat dateFormat = new SimpleDateFormat("m:ss.SSS");
private static SimpleDateFormat dateFormatShort = new SimpleDateFormat("s.SSS");
private List<Profile> profiles;
private Track track;
public LapListView(String id, List<Lap> lapList, List<Profile> profiles, Track track) {
super(id, lapList);
this.profiles = profiles;
this.track = track;
}
/**
*
*/
private static final long serialVersionUID = -9188867995949564845L;
@Override
protected void populateItem(ListItem<Lap> item) {
if (!(item.getModelObject() instanceof Lap)) {
log.info("is " + item.getModelObject().getClass().getName());
}
Lap lap = (Lap) item.getModelObject();
final int index = item.getIndex();
int gapPrevious = 0;
int gapFirst = 0;
if (index > 0) {
gapPrevious = lap.getTime() - getList().get(index - 1).getTime();
gapFirst = lap.getTime() - getList().get(0).getTime();
}
item.add(new Label("position", Integer.toString(index + 1)));
String name = null;
for (Profile profile : profiles) {
if (profile.getLfsworldName().equalsIgnoreCase(lap.getDriver().getName())) {
name = profile.getFullName();
}
}
if (name == null) {
name = lap.getDriver().getName();
}
item.add(new Label("name", name).setEscapeModelStrings(false));
item.add(new Label("car", lap.getDriver().getCarName()));
item.add(new Label("time", getTime(lap.getTime())));
item.add(new Label("number", lap.getNumber() + "/" + lap.getAttempt()));
if (lap.getTime() == 0) {
item.add(new Label("gapPrevious", "-"));
item.add(new Label("gapAll", "-"));
} else {
item.add(new Label("gapPrevious", getTime(gapPrevious)));
item.add(new Label("gapAll", getTime(gapFirst)));
}
LinkedList<String> splits = new LinkedList<String>();
for (int i = 0; i < track.getSplits(); i++) {
StringBuilder text = new StringBuilder(getTime(lap.getSplit(i)));
if (i > 0 && i < track.getSplits() - 1) {
text.append(" (");
int time = 0;
for (int j = 0; j <= i; j++) {
time += lap.getSplit(j);
}
text.append(getTime(time));
text.append(")");
}
splits.add(text.toString());
}
item.add(new ListView<String>("splits", splits) {
@Override
protected void populateItem(ListItem<String> splitItem) {
splitItem.add(new Label("split", splitItem.getModelObject()));
}
});
}
private String getTime(int time) {
if (time == 0) {
return "-";
}
if (time < 60000) {
return dateFormatShort.format(time);
}
return dateFormat.format(time);
}
}
|
3e0f721dc5adea77467497fd0aa5ae9546431180 | 2,088 | java | Java | src/main/java/com/github/f4b6a3/uuid/codec/base/Base32UCodec.java | lbruun/uuid-creator | 74018f0c5c193a404e22cdb16c2f189faeef7d86 | [
"MIT"
] | 153 | 2019-04-20T22:48:01.000Z | 2022-03-28T15:48:00.000Z | src/main/java/com/github/f4b6a3/uuid/codec/base/Base32UCodec.java | lbruun/uuid-creator | 74018f0c5c193a404e22cdb16c2f189faeef7d86 | [
"MIT"
] | 59 | 2019-04-14T08:14:29.000Z | 2022-03-22T18:28:08.000Z | src/main/java/com/github/f4b6a3/uuid/codec/base/Base32UCodec.java | lbruun/uuid-creator | 74018f0c5c193a404e22cdb16c2f189faeef7d86 | [
"MIT"
] | 23 | 2019-04-13T21:18:17.000Z | 2022-03-09T00:19:07.000Z | 37.963636 | 81 | 0.749042 | 6,564 | /*
* MIT License
*
* Copyright (c) 2018-2021 Fabio Lima
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.f4b6a3.uuid.codec.base;
import com.github.f4b6a3.uuid.codec.base.function.Base32Decoder;
import com.github.f4b6a3.uuid.codec.base.function.Base32Encoder;
/**
* Codec for UPPER CASE base-32 as defined in RFC-4648.
*
* It is case insensitive, so it decodes from lower and upper case, but encodes
* to UPPER CASE only.
*
* This codec complies with RFC-4648, encoding a byte array sequentially. If you
* need a codec that encodes integers using the remainder operator (modulus),
* use the static factory {@link BaseNCodec#newInstance(BaseN)}.
*
* See: https://tools.ietf.org/html/rfc4648
*/
public final class Base32UCodec extends BaseNCodec {
private static final BaseN BASE_N = new BaseN("A-Z2-7");
/**
* A shared immutable instance.
*/
public static final Base32UCodec INSTANCE = new Base32UCodec();
public Base32UCodec() {
super(BASE_N, new Base32Encoder(BASE_N), new Base32Decoder(BASE_N));
}
}
|
3e0f73394e43788f5363a5582ff5d27a4fdff798 | 3,018 | java | Java | rvs2.0/src/com/osh/rvs/form/inline/MaterialProcessAssignForm.java | fangke-ray/RVS-OGZ | 733365cb6af455c7bc977eb6867b21c41d25fc42 | [
"Apache-2.0"
] | null | null | null | rvs2.0/src/com/osh/rvs/form/inline/MaterialProcessAssignForm.java | fangke-ray/RVS-OGZ | 733365cb6af455c7bc977eb6867b21c41d25fc42 | [
"Apache-2.0"
] | null | null | null | rvs2.0/src/com/osh/rvs/form/inline/MaterialProcessAssignForm.java | fangke-ray/RVS-OGZ | 733365cb6af455c7bc977eb6867b21c41d25fc42 | [
"Apache-2.0"
] | 2 | 2019-03-01T02:27:57.000Z | 2019-06-13T12:32:34.000Z | 22.355556 | 100 | 0.729622 | 6,565 | package com.osh.rvs.form.inline;
import java.io.Serializable;
import org.apache.struts.action.ActionForm;
import framework.huiqing.bean.annotation.BeanField;
/**
*
* @Title MaterialProcessAssignForm.java
* @Project rvs
* @Package com.osh.rvs.form.inline
* @ClassName: MaterialProcessAssignForm
* @Description:维修对象独有修理流程
* @author lxb
* @date 2015-8-19 下午3:32:26
*/
public class MaterialProcessAssignForm extends ActionForm implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5047655885281548998L;
@BeanField(title = "维修对象 ID", name = "material_id", length = 11, notNull = true, primaryKey = true)
private String material_id;// 维修对象 ID
@BeanField(title = "分枝", name = "line_id", length = 11, notNull = true)
private String line_id;// 分枝
@BeanField(title = "工位 ID", name = "position_id", length = 11, notNull = true, primaryKey = true)
private String position_id;// 工位 ID
@BeanField(title = "顺位标记", name = "sign_position_id", length = 11, notNull = true)
private String sign_position_id;// 顺位标记
@BeanField(title = "先决标记", name = "prev_position_id", length = 11, notNull = true)
private String prev_position_id;// 先决标记
@BeanField(title = "后位标记", name = "next_position_id", length = 11)
private String next_position_id;// 后位标记
@BeanField(title = "小修理标准编制 ID", name = "light_fix_id", length = 11)
private String light_fix_id;//
@BeanField(title = "维修流程模板ID", name = "pad_id", length = 11)
private String pad_id;//维修流程模板ID
private String level;
private String fix_type;
public String getMaterial_id() {
return material_id;
}
public void setMaterial_id(String material_id) {
this.material_id = material_id;
}
public String getLine_id() {
return line_id;
}
public void setLine_id(String line_id) {
this.line_id = line_id;
}
public String getPosition_id() {
return position_id;
}
public void setPosition_id(String position_id) {
this.position_id = position_id;
}
public String getSign_position_id() {
return sign_position_id;
}
public void setSign_position_id(String sign_position_id) {
this.sign_position_id = sign_position_id;
}
public String getPrev_position_id() {
return prev_position_id;
}
public void setPrev_position_id(String prev_position_id) {
this.prev_position_id = prev_position_id;
}
public String getNext_position_id() {
return next_position_id;
}
public void setNext_position_id(String next_position_id) {
this.next_position_id = next_position_id;
}
public String getLight_fix_id() {
return light_fix_id;
}
public void setLight_fix_id(String light_fix_id) {
this.light_fix_id = light_fix_id;
}
public String getPad_id() {
return pad_id;
}
public void setPad_id(String pad_id) {
this.pad_id = pad_id;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getFix_type() {
return fix_type;
}
public void setFix_type(String fix_type) {
this.fix_type = fix_type;
}
}
|
3e0f73e960ffb0c6ff9e19bad967fcf57aa7ddde | 10,520 | java | Java | app/src/main/java/com/aqinn/actmanagersysandroid/ShowManager.java | Aqinn/activity_manager_sys-android | e4801353169d4bdac2eacc116708d37a92512b1d | [
"MIT"
] | 1 | 2021-04-20T12:35:00.000Z | 2021-04-20T12:35:00.000Z | app/src/main/java/com/aqinn/actmanagersysandroid/ShowManager.java | Aqinn/activity_manager_sys-android | e4801353169d4bdac2eacc116708d37a92512b1d | [
"MIT"
] | null | null | null | app/src/main/java/com/aqinn/actmanagersysandroid/ShowManager.java | Aqinn/activity_manager_sys-android | e4801353169d4bdac2eacc116708d37a92512b1d | [
"MIT"
] | null | null | null | 29.8017 | 133 | 0.552376 | 6,566 | package com.aqinn.actmanagersysandroid;
import android.content.ContentValues;
import android.util.Log;
import com.aqinn.actmanagersysandroid.data.DataSource;
import com.aqinn.actmanagersysandroid.entity.show.ActIntroItem;
import com.aqinn.actmanagersysandroid.entity.show.CreateAttendIntroItem;
import com.aqinn.actmanagersysandroid.entity.show.ParticipateAttendIntroItem;
import com.aqinn.actmanagersysandroid.qualifiers.ActCreateDataSource;
import com.aqinn.actmanagersysandroid.qualifiers.ActPartDataSource;
import com.aqinn.actmanagersysandroid.qualifiers.AttendCreateDataSource;
import com.aqinn.actmanagersysandroid.qualifiers.AttendPartDataSource;
import com.aqinn.actmanagersysandroid.qualifiers.UserDescDataSource;
import org.litepal.LitePal;
import java.util.List;
import javax.inject.Inject;
/**
* 管理数据的展示
*
* @author Aqinn
* @date 2020/12/18 5:33 PM
*/
public class ShowManager {
private static final String TAG = "ShowManager";
@Inject
@ActCreateDataSource
public DataSource actC;
@Inject
@ActPartDataSource
public DataSource actP;
@Inject
@AttendCreateDataSource
public DataSource attC;
@Inject
@AttendPartDataSource
public DataSource attP;
@Inject
@UserDescDataSource
public DataSource users;
public ShowManager() {
MyApplication.getApplicationComponent().inject(this);
}
/**
* 停止创建的活动
*
* @param id
* @return
*/
public boolean stopCreateAct(Long id) {
ContentValues values = new ContentValues();
values.put("status", 3);
int res = LitePal.update(ActIntroItem.class, values, id);
if (res <= 0)
return false;
boolean success = false;
for (ActIntroItem aii : (List<ActIntroItem>) actC.getDatas()) {
if (aii.getId().equals(id)) {
aii.setStatus(3);
actC.notifyAllObserver();
success = true;
break;
}
}
return success;
}
/**
* 退出参与的活动
*
* @param id
* @return
*/
public boolean quitPartAct(Long id) {
int res = LitePal.delete(ActIntroItem.class, id);
if (res <= 0)
return false;
boolean success = false;
Long actId = -1L;
for (ActIntroItem aii : (List<ActIntroItem>) actP.getDatas()) {
if (aii.getId().equals(id)) {
actP.getDatas().remove(aii);
actP.notifyAllObserver();
success = true;
actId = aii.getActId();
break;
}
}
if (success) {
for (ParticipateAttendIntroItem paii : (List<ParticipateAttendIntroItem>) attP.getDatas()) {
if (paii.getActId().equals(actId)) {
attP.getDatas().remove(paii);
paii.delete();
}
}
attP.notifyAllObserver();
}
return success;
}
/**
* 编辑创建的活动
*
* @param newAii
* @return
*/
public boolean editCreateAct(ActIntroItem newAii) {
int res = newAii.update(newAii.getId());
if (res <= 0)
return false;
boolean success = false;
for (ActIntroItem aii : (List<ActIntroItem>) actC.getDatas()) {
if (aii.getId().equals(newAii.getId())) {
aii.setOwnerId(newAii.getOwnerId());
aii.setActId(newAii.getActId());
aii.setCreator(newAii.getCreator());
aii.setName(newAii.getTime());
aii.setStatus(newAii.getStatus());
aii.setIntro(newAii.getIntro());
aii.setLocation(newAii.getLocation());
aii.setTime(newAii.getTime());
actC.notifyAllObserver();
success = true;
break;
}
}
return success;
}
/**
* 开始创建的活动
*
* @param id
* @return
*/
public boolean startCreateAct(Long id) {
ContentValues values = new ContentValues();
values.put("status", 2);
int res = LitePal.update(ActIntroItem.class, values, id);
if (res <= 0)
return false;
boolean success = false;
for (ActIntroItem aii : (List<ActIntroItem>) actC.getDatas()) {
if (aii.getId().equals(id)) {
aii.setStatus(2);
actC.notifyAllObserver();
success = true;
break;
}
}
return success;
}
/**
* 更改创建的签到的签到方式
*
* @param id
* @param type
* @return
*/
public boolean changeCreateAttendType(Long id, Integer type) {
ContentValues values = new ContentValues();
values.put("type", type);
int res = LitePal.update(CreateAttendIntroItem.class, values, id);
if (res <= 0)
return false;
boolean success = false;
for (CreateAttendIntroItem caii_ : (List<CreateAttendIntroItem>) attC.getDatas()) {
if (caii_.getId().equals(id)) {
caii_.setType(type);
attC.notifyAllObserver();
success = true;
break;
}
}
return success;
}
/**
* 更改创建的签到的签到时间
*
* @param id
* @return
*/
public boolean changeCreateAttendTime(Long id, String newTime) {
ContentValues values = new ContentValues();
values.put("time", newTime);
int res = LitePal.update(CreateAttendIntroItem.class, values, id);
if (res <= 0)
return false;
boolean success = false;
for (CreateAttendIntroItem caii : (List<CreateAttendIntroItem>) attC.getDatas()) {
if (caii.getId().equals(id)) {
caii.setTime(newTime);
attC.notifyAllObserver();
success = true;
break;
}
}
return success;
}
/**
* 开启创建的签到
*
* @param id
* @return
*/
public boolean startCreateAttend(Long id) {
ContentValues values = new ContentValues();
values.put("status", 2);
int res = LitePal.update(CreateAttendIntroItem.class, values, id);
if (res <= 0)
return false;
boolean success = false;
for (CreateAttendIntroItem caii : (List<CreateAttendIntroItem>) attC.getDatas()) {
if (caii.getId().equals(id)) {
success = true;
caii.setStatus(2);
attC.notifyAllObserver();
break;
}
}
return success;
}
/**
* 结束创建的签到
*
* @param id
* @return
*/
public boolean stopCreateAttend(Long id) {
ContentValues values = new ContentValues();
values.put("status", 3);
int res = LitePal.update(CreateAttendIntroItem.class, values, id);
if (res <= 0)
return false;
boolean success = false;
for (CreateAttendIntroItem caii : (List<CreateAttendIntroItem>) attC.getDatas()) {
if (caii.getId().equals(id)) {
if (caii.getStatus() == 2) {
success = true;
caii.setStatus(3);
attC.notifyAllObserver();
}
break;
}
}
return success;
}
/**
* 创建一个活动
*
* @param newAii
* @return
*/
public boolean createAct(ActIntroItem newAii) {
boolean res = newAii.save();
if (!res)
return false;
ActIntroItem dbAii = LitePal.findLast(ActIntroItem.class);
actC.getDatas().add(0, dbAii);
actC.notifyAllObserver();
return true;
}
/**
* 创建一个签到
*
* @param newCaii
* @return
*/
public boolean createAttend(CreateAttendIntroItem newCaii) {
boolean success = false;
success = newCaii.save();
if (!success)
return success;
success = attC.getDatas().add(newCaii);
if (success)
attC.notifyAllObserver();
return success;
}
/**
* 加入活动
*
* @param aii
* @return
*/
public boolean joinAct(ActIntroItem aii) {
boolean res = aii.save();
if (!res)
return false;
ActIntroItem dbAii = LitePal.findLast(ActIntroItem.class);
actP.getDatas().add(0, dbAii);
actP.notifyAllObserver();
return true;
}
public boolean refreshAttendCount(CreateAttendIntroItem newCaii) {
boolean success = false;
List<CreateAttendIntroItem> list = attC.getDatas();
for (CreateAttendIntroItem caii: list) {
if (caii.getId().equals(newCaii.getId())) {
caii.setShouldAttendCount(newCaii.getShouldAttendCount());
caii.setHaveAttendCount(newCaii.getHaveAttendCount());
caii.setNotAttendCount(newCaii.getNotAttendCount());
success = true;
break;
}
}
attC.notifyAllObserver();
return success;
}
// 不要用这个,是有问题的,懒得删
@Deprecated
public boolean refreshAttendCount_old(CreateAttendIntroItem newCaii) {
boolean success = false;
for (int i = 0; i < attC.getDatas().size(); i++) {
if (((CreateAttendIntroItem) attC.getDatas().get(i)).getAttendId().equals(newCaii.getAttendId())) {
ContentValues values = new ContentValues();
if (((CreateAttendIntroItem) attC.getDatas().get(i)).getShouldAttendCount().equals(newCaii.getShouldAttendCount()) &&
((CreateAttendIntroItem) attC.getDatas().get(i)).getHaveAttendCount().equals(newCaii.getHaveAttendCount()))
return true;
values.put("shouldAttendCount", newCaii.getShouldAttendCount());
values.put("haveAttendCount", newCaii.getHaveAttendCount());
values.put("notAttendCount", newCaii.getNotAttendCount());
String attendId = String.valueOf(newCaii.getAttendId());
int res = LitePal.updateAll(CreateAttendIntroItem.class, values, "attendId = ?", attendId);
if (res > 0)
success = true;
break;
}
}
if (success)
attC.notifyAllObserver();
return success;
}
}
|
3e0f75a74304524969737ec899164f6e0e77ea26 | 1,780 | java | Java | arrow/src/gen/java/org/bytedeco/arrow/TakeOptions.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 2,132 | 2015-01-14T10:02:38.000Z | 2022-03-31T07:51:08.000Z | arrow/src/gen/java/org/bytedeco/arrow/TakeOptions.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 1,024 | 2015-01-11T18:35:03.000Z | 2022-03-31T14:52:22.000Z | arrow/src/gen/java/org/bytedeco/arrow/TakeOptions.java | oxisto/javacpp-presets | a70841e089cbe4269cd3e1b1e6de2005c3b4aa16 | [
"Apache-2.0"
] | 759 | 2015-01-15T08:41:48.000Z | 2022-03-29T17:05:57.000Z | 42.380952 | 113 | 0.738202 | 6,567 | // Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.arrow;
import org.bytedeco.arrow.Function;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.arrow.global.arrow.*;
@Namespace("arrow::compute") @NoOffset @Properties(inherit = org.bytedeco.arrow.presets.arrow.class)
public class TakeOptions extends FunctionOptions {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public TakeOptions(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public TakeOptions(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public TakeOptions position(long position) {
return (TakeOptions)super.position(position);
}
@Override public TakeOptions getPointer(long i) {
return new TakeOptions((Pointer)this).offsetAddress(i);
}
public TakeOptions(@Cast("bool") boolean boundscheck/*=true*/) { super((Pointer)null); allocate(boundscheck); }
private native void allocate(@Cast("bool") boolean boundscheck/*=true*/);
public TakeOptions() { super((Pointer)null); allocate(); }
private native void allocate();
@MemberGetter public static native byte kTypeName(int i);
@MemberGetter public static native String kTypeName();
public static native @ByVal TakeOptions BoundsCheck();
public static native @ByVal TakeOptions NoBoundsCheck();
public static native @ByVal TakeOptions Defaults();
public native @Cast("bool") boolean boundscheck(); public native TakeOptions boundscheck(boolean setter);
}
|
3e0f75bfaa54f63dac9069d4269c9ee154e34b24 | 7,454 | java | Java | src/main/java/com/conversantmedia/util/estimation/Percentile.java | sullis/disruptor | a5448ae2b742047abdf793066e40ebe2c59b1392 | [
"Apache-2.0"
] | 276 | 2016-02-19T00:36:22.000Z | 2022-03-22T05:41:16.000Z | src/main/java/com/conversantmedia/util/estimation/Percentile.java | sullis/disruptor | a5448ae2b742047abdf793066e40ebe2c59b1392 | [
"Apache-2.0"
] | 20 | 2016-08-22T16:36:50.000Z | 2021-10-04T00:52:44.000Z | src/main/java/com/conversantmedia/util/estimation/Percentile.java | sullis/disruptor | a5448ae2b742047abdf793066e40ebe2c59b1392 | [
"Apache-2.0"
] | 47 | 2016-08-30T14:49:52.000Z | 2022-03-25T07:20:50.000Z | 26.062937 | 108 | 0.465254 | 6,568 | package com.conversantmedia.util.estimation;
/*
* #%L
* Conversant Disruptor
* ~~
* Conversantmedia.com © 2016, Conversant, Inc. Conversant® is a trademark of Conversant, 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.
* #L%
*/
import java.io.PrintStream;
import java.util.Arrays;
/**
* Implementation of "Simulatenous Estimation of Several Persentiles," by Kimmo E. E. Raatikainen
*
* This is very useful for profiling the performance of timing characteristics
*
* Created by jcairns on 5/28/14.
*/
public class Percentile {
private static float[] DEFAULT_PERCENTILE = { 0.05F, 0.5F, 0.683F, 0.75F, 0.85F, 0.954F, 0.99F};
private final float[] quantiles;
private final int m;
private final float[] q; // heights
private final int[] n; // actual positions
private final float[] f; // increments of desired positions
private final float[] d; // desired positions
private final float[] e; // estimates
private boolean isInitializing;
private int ni; // which x is initialized so far
public Percentile() {
this(DEFAULT_PERCENTILE);
}
public Percentile(final float[] quantiles) {
m = quantiles.length;
this.quantiles = Arrays.copyOf(quantiles, m);
final int N = 2*m+3;
q = new float[N+1];
n = new int[N+1];
f = new float[N+1];
d = new float[N+1];
e = new float[m];
clear();
}
/**
* clear existing samples
*/
public void clear() {
for(int i=1; i<=2*m+3; i++) {
n[i] = i+1;
}
f[1] = 0F;
f[2*m+3] = 1F;
for(int i=1; i<=m; i++) {
f[2*i+1] = quantiles[i-1];
}
for(int i=1; i<=m+1; i++) {
f[2*i] = (f[2*i-1] + f[2*i+1])/2F;
}
for(int i=1; i<=2*m+3; i++) {
d[i] = 1F + 2*(m+1)*f[i];
}
isInitializing = true;
ni = 1;
}
/**
* Add a measurement to estimate
*
* @param x - the value of the measurement
*/
public void add(final float x) {
if(isInitializing) {
q[ni++] = x;
if(ni == 2*m+3+1) {
Arrays.sort(q);
isInitializing=false;
}
} else {
addMeasurement(x);
}
}
/**
* @return float[] - percentiles requested at initialization
*/
public float[] getQuantiles() {
return quantiles;
}
/**
* @return boolean - true if sufficient samples have been seen to form an estimate
*/
public boolean isReady() {
return !isInitializing;
}
/**
* @return int - the number of samples in the estimate
*/
public int getNSamples() {
if(!isInitializing)
return n[2*m+3]-1;
else {
return ni-1;
}
}
/**
* get the estimates based on the last sample
*
* @return float[]
*
* @throws InsufficientSamplesException - if no estimate is currently available due to insufficient data
*/
public float[] getEstimates() throws InsufficientSamplesException {
if(!isInitializing) {
for (int i = 1; i <= m; i++) {
e[i-1] = q[2*i+1];
}
return e;
} else {
throw new InsufficientSamplesException();
}
}
/**
* @return float - the minimum sample seen in the distribution
*/
public float getMin() {
return q[1];
}
/**
* @return float - the maximum sample seen in the distribution
*/
public float getMax() {
return q[2*m+3];
}
private void addMeasurement(final float x) {
int k=1;
if(x < q[1]) {
k = 1;
q[1] = x;
} else if(x >= q[2*m+3]) {
k = 2*m+2;
q[2*m+3] = x;
} else {
for(int i=1; i<=2*m+2; i++) {
if((q[i] <= x) && (x < q[i+1])) {
k=i;
break;
}
}
}
for(int i=k+1; i<=2*m+3; i++) {
n[i] = n[i]+1;
}
for(int i=1; i<=2*m+3; i++) {
d[i] = d[i] + f[i];
}
for(int i=2; i<=2*m+2; i++) {
final float dval = d[i] - n[i];
final float dp = n[i+1] - n[i];
final float dm = n[i-1] - n[i];
final float qp = (q[i+1] - q[i])/dp;
final float qm = (q[i-1] - q[i])/dm;
if((dval >= 1F) && (dp > 1F)) {
final float qt = q[i] + ((1F - dm) * qp
+(dp - 1F)*qm)/(dp - dm);
if((q[i-1] < qt) && (qt < q[i+1])) {
q[i] = qt;
} else {
q[i] = q[i] + qp;
}
n[i] = n[i]+1;
} else if((dval <= -1) && dm < -1) {
final float qt = q[i] - ((1F + dp)*qm -
(dm + 1F)*qp)/(dp - dm);
if((q[i-1] < qt) && (qt < q[i+1])) {
q[i] = qt;
} else {
q[i] = q[i] - qm;
}
n[i] = n[i]-1;
}
}
}
/**
* print a nice histogram of percentiles
*
* @param out - output stream
* @param name - data set name
* @param p - percentile
*
*/
public static void print(final PrintStream out, final String name, final Percentile p) {
if(p.isReady()) {
try {
final StringBuilder sb = new StringBuilder(512);
final float[] q = p.getQuantiles();
final float[] e = p.getEstimates();
final int SCREENWIDTH = 80;
sb.append(name);
sb.append(", min(");
sb.append(p.getMin());
sb.append("), max(");
sb.append(p.getMax());
sb.append(')');
sb.append("\n");
final float max = e[e.length-1];
for(int i = 0; i<q.length; i++) {
sb.append(String.format("%4.3f", q[i]));
sb.append(": ");
final int len = (int) (e[i]/max*SCREENWIDTH);
for(int j = 0; j<len; j++) {
sb.append('#');
}
sb.append(" ");
sb.append(String.format("%4.3f\n", e[i]));
}
out.println(sb.toString());
} catch(InsufficientSamplesException e) {
// this can never occur
}
}
}
/**
* Indicates too few measurements have been added to compute the requested
* estimation
*/
public class InsufficientSamplesException extends Exception {
private InsufficientSamplesException() {
}
}
}
|
3e0f760585da3e5509d0e779a248a2b2f7dd958b | 2,611 | java | Java | portfolio/src/main/java/com/google/sps/servlets/AuthServlet.java | Richie78321/google-step | 4dba4f5a875e7572bc8b699f512cc750a8593e8d | [
"Apache-2.0"
] | 1 | 2020-06-09T03:53:17.000Z | 2020-06-09T03:53:17.000Z | portfolio/src/main/java/com/google/sps/servlets/AuthServlet.java | Richie78321/google-step | 4dba4f5a875e7572bc8b699f512cc750a8593e8d | [
"Apache-2.0"
] | 18 | 2020-05-21T20:38:01.000Z | 2020-06-19T00:56:03.000Z | portfolio/src/main/java/com/google/sps/servlets/AuthServlet.java | Richie78321/google-step | 4dba4f5a875e7572bc8b699f512cc750a8593e8d | [
"Apache-2.0"
] | null | null | null | 31.083333 | 102 | 0.734584 | 6,569 | // Copyright 2019 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.sps.servlets;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/auth")
public class AuthServlet extends HttpServlet {
public static final String AUTH_URL_REDIRECT = "/";
public Gson gson = new Gson();
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
JsonObject responseObject = new JsonObject();
UserService userService = UserServiceFactory.getUserService();
String loginUrl = userService.createLoginURL(AUTH_URL_REDIRECT);
String logoutUrl = userService.createLogoutURL(AUTH_URL_REDIRECT);
responseObject.addProperty("loginUrl", loginUrl);
responseObject.addProperty("logoutUrl", logoutUrl);
if (userService.isUserLoggedIn()) {
responseObject.addProperty("authorized", true);
UserData userData = new UserData(userService.getCurrentUser());
responseObject.add("user", gson.toJsonTree(userData));
} else {
responseObject.addProperty("authorized", false);
}
String responseJson = gson.toJson(responseObject);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json;");
response.getWriter().println(responseJson);
}
private class UserData {
private final String email;
private final String id;
/**
* Creates a user data object intended for JSON serialization.
*/
public UserData(User user) {
this.email = user.getEmail();
this.id = user.getUserId();
}
public String getEmail() {
return this.email;
}
public String getId() {
return this.id;
}
}
}
|
3e0f76992667032f094b80fcf10357a31b1331a7 | 24,097 | java | Java | migration-client/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/APIMMigrationService.java | CrowleyRajapakse/apim-migration-resources | 2f66204ecda5920b02d4d5be29f40b644dc5e743 | [
"Apache-2.0"
] | null | null | null | migration-client/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/APIMMigrationService.java | CrowleyRajapakse/apim-migration-resources | 2f66204ecda5920b02d4d5be29f40b644dc5e743 | [
"Apache-2.0"
] | 64 | 2020-04-16T13:35:27.000Z | 2022-03-31T04:37:41.000Z | migration-client/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/APIMMigrationService.java | CrowleyRajapakse/apim-migration-resources | 2f66204ecda5920b02d4d5be29f40b644dc5e743 | [
"Apache-2.0"
] | 39 | 2020-04-16T12:40:12.000Z | 2022-03-23T04:55:28.000Z | 57.786571 | 170 | 0.63344 | 6,570 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.apimgt.migration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil;
import org.wso2.carbon.apimgt.migration.client.*;
import org.wso2.carbon.apimgt.migration.client.internal.ServiceHolder;
import org.wso2.carbon.apimgt.migration.client.sp_migration.APIMStatMigrationClient;
import org.wso2.carbon.apimgt.migration.client.sp_migration.APIMStatMigrationConstants;
import org.wso2.carbon.apimgt.migration.client.sp_migration.DBManager;
import org.wso2.carbon.apimgt.migration.client.sp_migration.DBManagerImpl;
import org.wso2.carbon.apimgt.migration.util.Constants;
import org.wso2.carbon.apimgt.migration.util.RegistryServiceImpl;
import org.wso2.carbon.apimgt.migration.util.SharedDBUtil;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.tenant.TenantManager;
import java.sql.SQLException;
public class APIMMigrationService implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(APIMMigrationService.class);
private final String V200 = "2.0.0";
private final String V210 = "2.1.0";
private final String V220 = "2.2.0";
private final String V250 = "2.5.0";
private final String V260 = "2.6.0";
private final String V310 = "3.1.0";
private final String V300 = "3.0.0";
private final String V320 = "3.2.0";
private final String V400 = "4.0.0";
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
try {
APIMgtDBUtil.initialize();
SharedDBUtil.initialize();
} catch (Exception e) {
//APIMgtDBUtil.initialize() throws generic exception
log.error("Error occurred while initializing DB Util ", e);
}
String migrateFromVersion = System.getProperty(Constants.ARG_MIGRATE_FROM_VERSION);
log.info("Starting APIM Migration from APIM " + migrateFromVersion + " ..............");
String options = System.getProperty(Constants.ARG_OPTIONS);
String specificVersion = System.getProperty(Constants.ARG_RUN_SPECIFIC_VERSION);
String component = System.getProperty(Constants.ARG_COMPONENT);
String tenants = System.getProperty(Constants.ARG_MIGRATE_TENANTS);
String tenantRange = System.getProperty(Constants.ARG_MIGRATE_TENANTS_RANGE);
String blackListTenants = System.getProperty(Constants.ARG_MIGRATE_BLACKLIST_TENANTS);
boolean migrateAll = Boolean.parseBoolean(System.getProperty(Constants.ARG_MIGRATE_ALL));
boolean cleanupNeeded = Boolean.parseBoolean(System.getProperty(Constants.ARG_CLEANUP));
boolean isDBMigration = Boolean.parseBoolean(System.getProperty(Constants.ARG_MIGRATE_DB));
boolean isRegistryMigration = Boolean.parseBoolean(System.getProperty(Constants.ARG_MIGRATE_REG));
boolean isFileSystemMigration = Boolean.parseBoolean(System.getProperty(Constants.ARG_MIGRATE_FILE_SYSTEM));
boolean isTriggerAPIIndexer = Boolean.parseBoolean(System.getProperty(Constants.ARG_TRIGGER_API_INDEXER));
boolean isAccessControlMigration = Boolean.parseBoolean(System.getProperty(Constants.ARG_MIGRATE_ACCESS_CONTROL));
boolean isStatMigration = Boolean.parseBoolean(System.getProperty(Constants.ARG_MIGRATE_STATS));
boolean removeDecryptionFailedKeysFromDB = Boolean.parseBoolean(
System.getProperty(Constants.ARG_REMOVE_DECRYPTION_FAILED_CONSUMER_KEYS_FROM_DB));
boolean isSPMigration = Boolean.parseBoolean(System.getProperty(APIMStatMigrationConstants.ARG_MIGRATE_SP));
boolean isSP_APP_Population = Boolean.parseBoolean(System.getProperty(Constants.ARG_POPULATE_SPAPP));
boolean isScopeRoleMappingPopulation = Boolean.parseBoolean(System.getProperty(Constants.ARG_POPULATE_SCOPE_ROLE_MAPPING));
try {
RegistryServiceImpl registryService = new RegistryServiceImpl();
TenantManager tenantManager = ServiceHolder.getRealmService().getTenantManager();
MigrateUUIDToDB commonMigrationClient = new MigrateUUIDToDB(tenants, blackListTenants, tenantRange,
tenantManager);
IdentityScopeMigration identityScopeMigration = new IdentityScopeMigration();
//Check SP-Migration enabled
if (isSPMigration) {
log.info("----------------Migrating to WSO2 API Manager analytics 3.2.0");
// Create a thread and wait till the APIManager DBUtils is initialized
MigrationClient migrateStatDB = new APIMStatMigrationClient(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
DBManager dbManager = new DBManagerImpl();
dbManager.initialize(migrateFromVersion);
if(migrateFromVersion.equals(V310)){
dbManager.sortGraphQLOperation();
} else if (migrateFromVersion.equals(V200) || migrateFromVersion.equals(V210) ||
migrateFromVersion.equals(V220) || migrateFromVersion.equals(V250)){
migrateStatDB.statsMigration();
}
log.info("------------------------------Stat migration completed----------------------------------");
if (log.isDebugEnabled()) {
log.debug("----------------API Manager 3.2.0 Stat migration successfully completed------------");
}
//Check AccessControl-Migration enabled
} else if (V200.equals(migrateFromVersion)) {
MigrationClient migrateFrom200 = new MigrateFrom200(tenants, blackListTenants, tenantRange, registryService, tenantManager);
log.info("Start Migrating WSO2 API Manager " + migrateFromVersion +" registry resources ..........");
migrateFrom200.registryResourceMigration();
log.info("Successfully migrated WSO2 API Manager " + migrateFromVersion +" registry resources.");
MigrationClient scopeRoleMappingPopulation = new ScopeRoleMappingPopulationClient(tenants, blackListTenants, tenantRange, registryService, tenantManager);
log.info("Populating WSO2 API Manager Scope-Role Mapping from APIM " + migrateFromVersion +
" ..........");
scopeRoleMappingPopulation.updateScopeRoleMappings();
log.info("Successfully updated the Scope Role Mappings..........");
scopeRoleMappingPopulation.populateScopeRoleMapping();
log.info("Successfully populated the Scope Role Mappings ..........");
MigrationClient migrateFrom310 = new MigrateFrom310(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
log.info("Start scope migration from APIM 3.1.0 ..........");
migrateFrom310.scopeMigration();
log.info("Successfully migrated the Scopes from APIM 3.1.0 ..........");
log.info("Start SP migration from APIM 3.1.0 ..........");
migrateFrom310.spMigration();
log.info("Successfully migrated the SP from APIM 3.1.0 ..........");
log.info("Starting Migration from API Manager 3.2 to 4.0");
log.info("Start moving UUIDs to DB from registry ..........");
commonMigrationClient.moveUUIDToDBFromRegistry();
log.info("Successfully moved the UUIDs to DB from registry ..........");
log.info("Start identity scope migration ..........");
identityScopeMigration.migrateScopes();
log.info("Successfully migrated the identity scopes. ");
MigrateFrom320 migrateFrom320 = new MigrateFrom320(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
log.info("Start migrating WebSocket APIs ..........");
migrateFrom320.migrateWebSocketAPI();
log.info("Successfully migrated WebSocket APIs ..........");
log.info("Start migrating API Product Mappings ..........");
migrateFrom320.migrateProductMappingTable();
log.info("Successfully migrated API Product Mappings ..........");
log.info("Start migrating registry paths of Icon and WSDLs ..........");
migrateFrom320.updateRegistryPathsOfIconAndWSDL();
log.info("Successfully migrated API registry paths of Icon and WSDLs.");
log.info("Start removing unnecessary fault handlers from fault sequences ..........");
migrateFrom320.removeUnnecessaryFaultHandlers();
log.info("Successfully removed the unnecessary fault handlers from fault sequences.");
log.info("Start API Revision related migration ..........");
migrateFrom320.apiRevisionRelatedMigration();
log.info("API Revision related migration is successful.");
log.info("Start migrating Endpoint Certificates ..........");
migrateFrom320.migrateEndpointCertificates();
log.info("Successfully migrated Endpoint Certificates.");
log.info("Start replacing KM name by UUID ..........");
migrateFrom320.replaceKMNamebyUUID();
log.info("Successfully replaced KM name by UUID.");
log.info("Migrated Successfully to APIM 4.0.0");
MigrateFrom400 migrateFrom400 = new MigrateFrom400(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
migrateFrom400.migrateTenantConfToDB();
log.info("Successfully migrated Tenant Conf to Database.");
log.info("Migrated Successfully to 4.1.0");
} else if (V210.equals(migrateFromVersion) || V220.equals(migrateFromVersion) ||
V250.equals(migrateFromVersion) || V260.equals(migrateFromVersion)) {
log.info("Start migration from APIM " + migrateFromVersion + " ..........");
MigrationClient migrateFrom210 = new MigrateFrom210(tenants, blackListTenants, tenantRange, registryService, tenantManager);
log.info("Migrating WSO2 API Manager registry resources ..........");
migrateFrom210.registryResourceMigration();
log.info("Successfully migrated registry resources .");
MigrationClient scopeRoleMappingPopulation = new ScopeRoleMappingPopulationClient(tenants, blackListTenants, tenantRange, registryService, tenantManager);
log.info("Populating WSO2 API Manager Scope-Role Mapping to migrate from APIM " + migrateFromVersion);
scopeRoleMappingPopulation.updateScopeRoleMappings();
log.info("Successfully updated the Scope Role Mappings ..........");
scopeRoleMappingPopulation.populateScopeRoleMapping();
log.info("Successfully populated the Scope Role Mappings ..........");
log.info("Migrated Successfully to API Manager 3.1");
log.info("Starting Migration from API Manager 3.1 to 3.2");
MigrationClient migrateFrom310 = new MigrateFrom310(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
migrateFrom310.scopeMigration();
log.info("Successfully migrated the Scopes from APIM " + migrateFromVersion);
migrateFrom310.spMigration();
log.info("Successfully migrated the SPs from APIM " + migrateFromVersion);
log.info("Migrated Successfully to APIM 3.2.0 ");
log.info("Starting Migration from API Manager 3.2.0 to 4.0.0 .................");
log.info("Start moving UUIDs to DB from registry ..........");
commonMigrationClient.moveUUIDToDBFromRegistry();
log.info("Successfully moved the UUIDs to DB from registry ..........");
log.info("Start identity scope migration ..........");
identityScopeMigration.migrateScopes();
log.info("Successfully migrated the identity scopes. ");
MigrateFrom320 migrateFrom320 = new MigrateFrom320(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
log.info("Start migrating WebSocket APIs ..........");
migrateFrom320.migrateWebSocketAPI();
log.info("Successfully migrated WebSocket APIs ..........");
if (V250.equals(migrateFromVersion) || V260.equals(migrateFromVersion)) {
log.info("Migrating lables to vhosts in APIM " + migrateFromVersion);
migrateFrom320.migrateLabelsToVhosts();
log.info("Successfully Migrated lables to vhosts in APIM " + migrateFromVersion);
}
log.info("Start migrating API Product Mappings ..........");
migrateFrom320.migrateProductMappingTable();
log.info("Successfully migrated API Product Mappings ..........");
log.info("Start migrating registry paths of Icon and WSDLs ..........");
migrateFrom320.updateRegistryPathsOfIconAndWSDL();
log.info("Successfully migrated API registry paths of Icon and WSDLs.");
log.info("Start removing unnecessary fault handlers from fault sequences ..........");
migrateFrom320.removeUnnecessaryFaultHandlers();
log.info("Successfully removed the unnecessary fault handlers from fault sequences.");
log.info("Start API Revision related migration ..........");
migrateFrom320.apiRevisionRelatedMigration();
log.info("API Revision related migration is successful.");
log.info("Start migrating Endpoint Certificates ..........");
migrateFrom320.migrateEndpointCertificates();
log.info("Successfully migrated Endpoint Certificates.");
log.info("Start replacing KM name by UUID ..........");
migrateFrom320.replaceKMNamebyUUID();
log.info("Successfully replaced KM name by UUID.");
log.info("Migrated Successfully to 4.0.0");
MigrateFrom400 migrateFrom400 = new MigrateFrom400(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
migrateFrom400.migrateTenantConfToDB();
log.info("Successfully migrated Tenant Conf to Database.");
log.info("Migrated Successfully to 4.1.0");
} else if (isScopeRoleMappingPopulation) {
MigrationClient scopeRoleMappingPopulation = new ScopeRoleMappingPopulationClient(tenants, blackListTenants, tenantRange, registryService, tenantManager);
log.info("Populating WSO2 API Manager Scope-Role Mapping");
scopeRoleMappingPopulation.populateScopeRoleMapping();
} else if(V310.equals(migrateFromVersion) || V300.equals(migrateFromVersion)) {
MigrationClient migrateFrom310 = new MigrateFrom310(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
migrateFrom310.registryResourceMigration();
migrateFrom310.scopeMigration();
migrateFrom310.spMigration();
log.info("Migrated Successfully to 3.2");
log.info("Starting Migration from API Manager 3.2 to 4.0");
log.info("Start moving UUIDs to DB from registry ..........");
commonMigrationClient.moveUUIDToDBFromRegistry();
log.info("Successfully moved the UUIDs to DB from registry ..........");
log.info("Start identity scope migration ..........");
identityScopeMigration.migrateScopes();
log.info("Successfully migrated the identity scopes. ");
MigrateFrom320 migrateFrom320 = new MigrateFrom320(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
log.info("Start migrating WebSocket APIs ..........");
migrateFrom320.migrateWebSocketAPI();
log.info("Successfully migrated WebSocket APIs ..........");
migrateFrom320.migrateLabelsToVhosts();
log.info("Start migrating API Product Mappings ..........");
migrateFrom320.migrateProductMappingTable();
log.info("Successfully migrated API Product Mappings ..........");
log.info("Start migrating registry paths of Icon and WSDLs ..........");
migrateFrom320.updateRegistryPathsOfIconAndWSDL();
log.info("Successfully migrated API registry paths of Icon and WSDLs.");
log.info("Start removing unnecessary fault handlers from fault sequences ..........");
migrateFrom320.removeUnnecessaryFaultHandlers();
log.info("Successfully removed the unnecessary fault handlers from fault sequences.");
log.info("Start API Revision related migration ..........");
migrateFrom320.apiRevisionRelatedMigration();
log.info("Successfully done the API Revision related migration.");
log.info("Start migrating Endpoint Certificates ..........");
migrateFrom320.migrateEndpointCertificates();
log.info("Successfully migrated Endpoint Certificates.");
log.info("Start replacing KM name by UUID ..........");
migrateFrom320.replaceKMNamebyUUID();
log.info("Successfully replaced KM name by UUID.");
log.info("Migrated Successfully to 4.0.0");
MigrateFrom400 migrateFrom400 = new MigrateFrom400(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
migrateFrom400.migrateTenantConfToDB();
log.info("Successfully migrated Tenant Conf to Database.");
log.info("Migrated Successfully to 4.1.0");
} else if (V320.equals(migrateFromVersion)) {
commonMigrationClient.moveUUIDToDBFromRegistry();
MigrateFrom320 migrateFrom320 = new MigrateFrom320(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
log.info("Start migrating WebSocket APIs ..........");
migrateFrom320.migrateWebSocketAPI();
log.info("Successfully migrated WebSocket APIs ..........");
migrateFrom320.migrateLabelsToVhosts();
log.info("Start migrating API Product Mappings ..........");
migrateFrom320.migrateProductMappingTable();
log.info("Successfully migrated API Product Mappings ..........");
log.info("Start migrating registry paths of Icon and WSDLs ..........");
migrateFrom320.updateRegistryPathsOfIconAndWSDL();
log.info("Successfully migrated API registry paths of Icon and WSDLs.");
log.info("Start removing unnecessary fault handlers from fault sequences ..........");
migrateFrom320.removeUnnecessaryFaultHandlers();
log.info("Successfully removed the unnecessary fault handlers from fault sequences.");
log.info("Start API Revision related migration ..........");
migrateFrom320.apiRevisionRelatedMigration();
log.info("Successfully done the API Revision related migration.");
log.info("Start migrating Endpoint Certificates ..........");
migrateFrom320.migrateEndpointCertificates();
log.info("Successfully migrated Endpoint Certificates.");
log.info("Start replacing KM name by UUID ..........");
migrateFrom320.replaceKMNamebyUUID();
log.info("Successfully replaced KM name by UUID.");
log.info("Migrated Successfully to 4.0.0");
MigrateFrom400 migrateFrom400 = new MigrateFrom400(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
migrateFrom400.migrateTenantConfToDB();
log.info("Successfully migrated Tenant Conf to Database.");
log.info("Migrated Successfully to 4.1.0");
} else if (V400.equals(migrateFromVersion)) {
MigrateFrom400 migrateFrom400 = new MigrateFrom400(tenants, blackListTenants,
tenantRange, registryService, tenantManager);
log.info("Start migrating databases ..........");
migrateFrom400.databaseMigration();
log.info("Successfully migrated databases.");
migrateFrom400.updateScopeRoleMappings();
log.info("Successfully migrated Role Scope Tenant Conf Mappings.");
migrateFrom400.migrateTenantConfToDB();
log.info("Successfully migrated Tenant Conf to Database.");
log.info("Migrated Successfully to 4.1.0");
} else {
MigrationClientFactory.initFactory(tenants, blackListTenants, tenantRange, registryService, tenantManager,
removeDecryptionFailedKeysFromDB);
MigrationExecutor.Arguments arguments = new MigrationExecutor.Arguments();
arguments.setMigrateFromVersion(migrateFromVersion);
arguments.setSpecificVersion(specificVersion);
arguments.setComponent(component);
arguments.setMigrateAll(migrateAll);
arguments.setCleanupNeeded(cleanupNeeded);
arguments.setDBMigration(isDBMigration);
arguments.setRegistryMigration(isRegistryMigration);
arguments.setFileSystemMigration(isFileSystemMigration);
arguments.setTriggerAPIIndexer(isTriggerAPIIndexer);
arguments.setStatMigration(isStatMigration);
arguments.setOptions(options);
arguments.setSP_APP_Migration(isSP_APP_Population);
MigrationExecutor.execute(arguments);
}
} catch (APIMigrationException e) {
log.error("API Management exception occurred while migrating", e);
} catch (UserStoreException e) {
log.error("User store exception occurred while migrating", e);
} catch (SQLException e) {
log.error("SQL exception occurred while migrating", e);
} catch (Exception e) {
log.error("Generic exception occurred while migrating", e);
} catch (Throwable t) {
log.error("Throwable error", t);
} finally {
MigrationClientFactory.clearFactory();
}
log.info("WSO2 API Manager migration component successfully activated.");
}
}
|
3e0f76ac9ec6ba0087b4ab77c5738ca7b261bed2 | 1,489 | java | Java | src/GUI/ButtonTest.java | ChenSir0795/TestDemo | 52e9598e45185bb32ed724e9527bcb761f685cda | [
"Apache-2.0"
] | null | null | null | src/GUI/ButtonTest.java | ChenSir0795/TestDemo | 52e9598e45185bb32ed724e9527bcb761f685cda | [
"Apache-2.0"
] | null | null | null | src/GUI/ButtonTest.java | ChenSir0795/TestDemo | 52e9598e45185bb32ed724e9527bcb761f685cda | [
"Apache-2.0"
] | null | null | null | 26.122807 | 58 | 0.736736 | 6,571 | package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JFrame;
public class ButtonTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ButtonFrame frame=new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame{
public ButtonFrame() {
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
ButtonPanel panel=new ButtonPanel();
add(panel);
}
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT=200;
}
class ButtonPanel extends JPanel{
public ButtonPanel() {
JButton yellowButton=new JButton("yellow");
JButton blueButton=new JButton("Bule");
JButton redButton=new JButton("Red");
add(yellowButton);
add(blueButton);
add(redButton);
colorAction yellowAction=new colorAction(Color.YELLOW);
colorAction bluewAction=new colorAction(Color.BLUE);
colorAction redowAction=new colorAction(Color.red);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(bluewAction);
redButton.addActionListener(redowAction);
}
private class colorAction implements ActionListener{
public colorAction(Color c) {
backgroundColor=c;
}
public void actionPerformed(ActionEvent event) {
setBackground(backgroundColor);
}
private Color backgroundColor;
}
}
|
3e0f77aedfde15a87ae7cfd3abde6f2589d85cb4 | 320 | java | Java | src/main/java/com/mmorpg/framework/net/session/GameSessionStatus.java | drugbean/Odin | 399c5b01a9042895373fea4a103d4f16c032e1b5 | [
"MIT"
] | 1 | 2021-01-21T15:53:12.000Z | 2021-01-21T15:53:12.000Z | src/main/java/com/mmorpg/framework/net/session/GameSessionStatus.java | Ariescat/game-seed.odin | 399c5b01a9042895373fea4a103d4f16c032e1b5 | [
"MIT"
] | 2 | 2021-12-10T01:55:48.000Z | 2021-12-14T21:58:33.000Z | src/main/java/com/mmorpg/framework/net/session/GameSessionStatus.java | Ariescat/game-seed.odin | 399c5b01a9042895373fea4a103d4f16c032e1b5 | [
"MIT"
] | null | null | null | 9.411765 | 41 | 0.56875 | 6,572 | package com.mmorpg.framework.net.session;
/**
* @author Ariescat
* @version 2020/2/19 11:46
*/
public enum GameSessionStatus {
/**
* 初始
*/
INIT,
/**
* 已验证
*/
LOGIN_AUTH,
/**
* 正在进入场景(还没初始化玩家数据)
*/
ENTERING_SCENE,
/**
* 已经进入场景(已经初始化玩家数据)
*/
ENTERED_SCENE,
/**
* 退出中
*/
LOGOUTING,
}
|
3e0f77f8a89e0b2c5fb04613c9a4b4094a460997 | 3,770 | java | Java | _plugin_cloud/qiniu-kodo-solon-plugin/src/main/java/org/noear/solon/cloud/extend/qiniu/kodo/service/CloudFileServiceKodoImp.java | noear/solon | e458cd1a045c4e5d0f7a89d98f9b746879647c48 | [
"Apache-2.0"
] | 232 | 2019-02-15T03:44:00.000Z | 2022-03-27T08:44:51.000Z | _plugin_cloud/qiniu-kodo-solon-plugin/src/main/java/org/noear/solon/cloud/extend/qiniu/kodo/service/CloudFileServiceKodoImp.java | noear/solon | e458cd1a045c4e5d0f7a89d98f9b746879647c48 | [
"Apache-2.0"
] | 26 | 2019-11-21T04:47:38.000Z | 2022-03-15T13:44:21.000Z | _plugin_cloud/qiniu-kodo-solon-plugin/src/main/java/org/noear/solon/cloud/extend/qiniu/kodo/service/CloudFileServiceKodoImp.java | noear/solon | e458cd1a045c4e5d0f7a89d98f9b746879647c48 | [
"Apache-2.0"
] | 31 | 2019-07-15T14:36:27.000Z | 2022-03-13T09:59:25.000Z | 30.650407 | 107 | 0.656499 | 6,573 | package org.noear.solon.cloud.extend.qiniu.kodo.service;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import okhttp3.ResponseBody;
import org.noear.solon.Utils;
import org.noear.solon.cloud.exception.CloudFileException;
import org.noear.solon.cloud.extend.qiniu.kodo.KodoProps;
import org.noear.solon.cloud.model.Media;
import org.noear.solon.cloud.service.CloudFileService;
import org.noear.solon.cloud.utils.http.HttpUtils;
import org.noear.solon.core.handle.Result;
import java.io.IOException;
import java.io.InputStream;
/**
* @author noear
*/
public class CloudFileServiceKodoImp implements CloudFileService {
private static CloudFileServiceKodoImp instance;
public static synchronized CloudFileServiceKodoImp getInstance() {
if (instance == null) {
instance = new CloudFileServiceKodoImp();
}
return instance;
}
protected final String bucketDef;
protected final String accessKey;
protected final String secretKey;
protected final String endpoint;
protected final Auth auth;
protected final UploadManager uploadManager;
protected final BucketManager bucketManager;
public CloudFileServiceKodoImp() {
bucketDef = KodoProps.instance.getFileBucket();
accessKey = KodoProps.instance.getFileAccessKey();
secretKey = KodoProps.instance.getFileSecretKey();
endpoint = KodoProps.instance.getFileEndpoint();
auth = Auth.create(accessKey, secretKey);
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释
uploadManager = new UploadManager(cfg);
bucketManager = new BucketManager(auth, cfg);
}
@Override
public Media get(String bucket, String key) throws CloudFileException {
if (Utils.isEmpty(bucket)) {
bucket = bucketDef;
}
String baseUrl = buildUrl(key);
String downUrl = auth.privateDownloadUrl(baseUrl);
try {
ResponseBody obj = HttpUtils.http(downUrl).exec("GET").body();
return new Media(obj.byteStream(), obj.contentType().toString());
} catch (IOException e) {
throw new CloudFileException(e);
}
}
@Override
public Result put(String bucket, String key, Media media) throws CloudFileException {
if (Utils.isEmpty(bucket)) {
bucket = bucketDef;
}
String streamMime = media.contentType();
if (Utils.isEmpty(streamMime)) {
streamMime = "text/plain; charset=utf-8";
}
String uploadToken = auth.uploadToken(bucket);
try {
Response resp = uploadManager.put(media.body(), key, uploadToken, new StringMap(), streamMime);
return Result.succeed(resp.bodyString());
} catch (QiniuException e) {
throw new CloudFileException(e);
}
}
@Override
public Result delete(String bucket, String key) throws CloudFileException {
if (Utils.isEmpty(bucket)) {
bucket = bucketDef;
}
try {
Response resp = bucketManager.delete(bucket, key);
return Result.succeed(resp.bodyString());
} catch (QiniuException e) {
return Result.failure(e.error());
}
}
private String buildUrl(String key) {
if (endpoint.contains("://")) {
return endpoint + "/" + key;
} else {
return "https://" + endpoint + "/" + key;
}
}
}
|
3e0f78409d3ea5cdd8ebd1b2570fcc1d8f40bdf9 | 784 | java | Java | Java/old/OpenGL-1.0(old_ver)/Loon-backend-JavaSE/src/loon/core/graphics/component/CollisionQuery.java | cping/LGame | 6ee0daf43841cbafc9638f73e35cbb1c30bf69ad | [
"Apache-2.0"
] | 428 | 2015-01-02T17:25:20.000Z | 2022-03-26T20:38:48.000Z | Java/JavaSE/OpenGL/source/core/src/loon/core/graphics/component/CollisionQuery.java | windows10207/LGame | 4599507d737a79b27d8f685f7aa542fd9f936cf7 | [
"Apache-2.0"
] | 26 | 2015-01-19T15:05:48.000Z | 2021-06-13T14:22:29.000Z | Java/JavaSE/OpenGL/source/core/src/loon/core/graphics/component/CollisionQuery.java | windows10207/LGame | 4599507d737a79b27d8f685f7aa542fd9f936cf7 | [
"Apache-2.0"
] | 153 | 2015-01-07T08:40:09.000Z | 2022-02-28T01:47:07.000Z | 28.392857 | 80 | 0.730818 | 6,574 | package loon.core.graphics.component;
/**
*
* Copyright 2008 - 2011
*
* 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.
*
* @project loon
* @author cping
* @dycjh@example.com
* @version 0.1
*/
public interface CollisionQuery {
boolean checkCollision(Actor actor);
}
|
3e0f78eaf25001ec2b995d4d492ab923f6d7855f | 1,636 | java | Java | p2p-core/src/test/java/com/bt/pi/core/application/resource/NoOpSharedResourceWatchingStrategyTest.java | barnyard/pi | 8dafc1d915e3b90b4cf79a4af76dd03a5b356fcd | [
"Apache-2.0"
] | 2 | 2016-02-22T22:38:27.000Z | 2017-10-29T07:18:55.000Z | p2p-core/src/test/java/com/bt/pi/core/application/resource/NoOpSharedResourceWatchingStrategyTest.java | barnyard/pi | 8dafc1d915e3b90b4cf79a4af76dd03a5b356fcd | [
"Apache-2.0"
] | null | null | null | p2p-core/src/test/java/com/bt/pi/core/application/resource/NoOpSharedResourceWatchingStrategyTest.java | barnyard/pi | 8dafc1d915e3b90b4cf79a4af76dd03a5b356fcd | [
"Apache-2.0"
] | null | null | null | 44.216216 | 106 | 0.809291 | 6,575 | package com.bt.pi.core.application.resource;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import com.bt.pi.core.application.resource.NoOpSharedResourceWatchingStrategy;
import rice.p2p.commonapi.Id;
public class NoOpSharedResourceWatchingStrategyTest {
private NoOpSharedResourceWatchingStrategy<Id> noOpSharedResourceWatchingStrategy;
private Id resourceId;
private String consumerId;
@Before
public void before() {
noOpSharedResourceWatchingStrategy = new NoOpSharedResourceWatchingStrategy<Id>();
}
@Test
public void coverage() {
// assert
assertEquals(null, noOpSharedResourceWatchingStrategy.getSharedResourceRefreshRunner(resourceId));
assertEquals(null, noOpSharedResourceWatchingStrategy.getConsumerWatcher(resourceId, consumerId));
assertEquals(0, noOpSharedResourceWatchingStrategy.getInitialResourceRefreshIntervalMillis());
assertEquals(0, noOpSharedResourceWatchingStrategy.getRepeatingResourceRefreshIntervalMillis());
assertEquals(0, noOpSharedResourceWatchingStrategy.getInitialConsumerWatcherIntervalMillis());
assertEquals(0, noOpSharedResourceWatchingStrategy.getRepeatingConsumerWatcherIntervalMillis());
noOpSharedResourceWatchingStrategy.setInitialResourceRefreshIntervalMillis(0);
noOpSharedResourceWatchingStrategy.setRepeatingResourceRefreshIntervalMillis(0);
noOpSharedResourceWatchingStrategy.setInitialConsumerWatcherIntervalMillis(0);
noOpSharedResourceWatchingStrategy.setRepeatingConsumerWatcherIntervalMillis(0);
}
}
|
3e0f792c096a63be7f05773dbe19bf346d7c95b2 | 1,076 | java | Java | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/errors/Operation.java | datayangl/kafka | 40db072e5418f9b437b0d2719cb7bdd542635b8d | [
"Apache-2.0"
] | 126 | 2018-08-31T21:47:30.000Z | 2022-03-11T10:01:31.000Z | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/errors/Operation.java | datayangl/kafka | 40db072e5418f9b437b0d2719cb7bdd542635b8d | [
"Apache-2.0"
] | 75 | 2019-03-07T20:24:18.000Z | 2022-03-31T02:14:37.000Z | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/errors/Operation.java | datayangl/kafka | 40db072e5418f9b437b0d2719cb7bdd542635b8d | [
"Apache-2.0"
] | 88 | 2016-11-27T02:16:11.000Z | 2020-02-28T05:10:26.000Z | 37.103448 | 75 | 0.756506 | 6,576 | /*
* 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.kafka.connect.runtime.errors;
import java.util.concurrent.Callable;
/**
* A recoverable operation evaluated in the connector pipeline.
*
* @param <V> return type of the result of the operation.
*/
public interface Operation<V> extends Callable<V> {
}
|
3e0f796fba85ece31d0f781b4cc0c241185bdbdf | 310 | java | Java | lbn-gtt-template-tpo/GTT-V2-Sample-TrackPurchaseOrders-Service/srv/src/main/java/com/sap/gtt/v2/sample/pof/rest/domain/fulfillmentprocessflow/FulfillmentProcessFlow.java | zenonkowalewski/logistics-business-network-gtt-samples | c34ddff27f339768ae61a6dc8eb4330ecc5ca320 | [
"Apache-2.0"
] | 12 | 2020-09-25T07:54:40.000Z | 2021-09-27T12:29:34.000Z | lbn-gtt-template-tpo/GTT-V2-Sample-TrackPurchaseOrders-Service/srv/src/main/java/com/sap/gtt/v2/sample/pof/rest/domain/fulfillmentprocessflow/FulfillmentProcessFlow.java | zenonkowalewski/logistics-business-network-gtt-samples | c34ddff27f339768ae61a6dc8eb4330ecc5ca320 | [
"Apache-2.0"
] | 2 | 2020-10-15T05:20:41.000Z | 2022-02-14T09:28:02.000Z | lbn-gtt-template-tpo/GTT-V2-Sample-TrackPurchaseOrders-Service/srv/src/main/java/com/sap/gtt/v2/sample/pof/rest/domain/fulfillmentprocessflow/FulfillmentProcessFlow.java | zenonkowalewski/logistics-business-network-gtt-samples | c34ddff27f339768ae61a6dc8eb4330ecc5ca320 | [
"Apache-2.0"
] | 50 | 2020-09-29T03:06:01.000Z | 2022-03-28T16:04:45.000Z | 18.235294 | 69 | 0.670968 | 6,577 | package com.sap.gtt.v2.sample.pof.rest.domain.fulfillmentprocessflow;
import java.util.List;
public class FulfillmentProcessFlow {
private List<Lane> lanes;
public List<Lane> getLanes() {
return lanes;
}
public void setLanes(List<Lane> lanes) {
this.lanes = lanes;
}
}
|
3e0f7a3441e388cd6e56cae53e34ba2c46c3d38e | 1,936 | java | Java | src/main/java/com/zx/sms/common/util/DefaultSequenceNumberUtil.java | thinwonton/SMSGate | cefe271ed99ba6557ba6c16af80d7fae673dc0b3 | [
"Apache-2.0"
] | 537 | 2018-04-24T13:56:04.000Z | 2022-03-31T03:36:46.000Z | src/main/java/com/zx/sms/common/util/DefaultSequenceNumberUtil.java | thinwonton/SMSGate | cefe271ed99ba6557ba6c16af80d7fae673dc0b3 | [
"Apache-2.0"
] | 21 | 2018-05-31T08:12:15.000Z | 2022-01-21T08:36:11.000Z | src/main/java/com/zx/sms/common/util/DefaultSequenceNumberUtil.java | thinwonton/SMSGate | cefe271ed99ba6557ba6c16af80d7fae673dc0b3 | [
"Apache-2.0"
] | 260 | 2018-04-28T07:33:41.000Z | 2022-03-19T15:12:19.000Z | 30.730159 | 123 | 0.731405 | 6,578 | /**
*
*/
package com.zx.sms.common.util;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
/**
* @author huzorro(dycjh@example.com)
*
*/
public class DefaultSequenceNumberUtil {
public static byte[] sequenceN2Bytes(SequenceNumber sn) {
byte[] bytes = new byte[12];
long t = Long.parseLong(sn.getTimeString());
ByteBuffer.wrap(bytes).putInt((int) sn.getNodeIds()).putInt((int) t).putInt((int) sn.getSequenceId());
return bytes;
}
private static final String[] datePattern = new String[]{"yyyyMMddHHmmss"};
public static SequenceNumber bytes2SequenceN(byte[] bytes) {
long nodeIds = ByteBuffer.wrap(Arrays.copyOfRange(bytes, 0, 4)).getInt() & 0xFFFFFFFFL;
//sgip协议里时间不带年份信息,这里判断下年份信息
String year = DateFormatUtils.format(CachedMillisecondClock.INS.now(), "yyyy");
String t =year + StringUtils.leftPad(String.valueOf(ByteBuffer.wrap(Arrays.copyOfRange(bytes, 4, 8)).getInt()), 10, '0');
Date d ;
try {
d = DateUtils.parseDate(t, datePattern);
//如果正好是年末,这个时间有可能差一年,则必须取上一年
//这里判断取200天,防止因不同主机时间不同步造成误差
if(d.getTime() - CachedMillisecondClock.INS.now() > 86400000L * 200){
d = DateUtils.addYears(d, -1);
}
} catch (ParseException e) {
d = new Date();
e.printStackTrace();
}
int sequenceId = ByteBuffer.wrap(Arrays.copyOfRange(bytes, 8, 12)).getInt();
SequenceNumber sn = new SequenceNumber(d.getTime(),nodeIds,sequenceId);
return sn;
}
public static int getSequenceNo() {
return sequenceId.incrementAndGet();
}
private final static AtomicInteger sequenceId = new AtomicInteger(RandomUtils.nextInt());
}
|
3e0f7a8f8b46c3062c7d46e5606a080c45e76e41 | 548 | java | Java | src/test/java/com/insightfullogic/java8/exercises/chapter2/Question2Test.java | zhiyongwang/java-8-lambdas-exercises | 3513bf094d215d8bd6402d502c2af62f16455c2f | [
"MIT"
] | 1,822 | 2015-01-13T15:36:24.000Z | 2022-03-28T18:47:17.000Z | src/test/java/com/insightfullogic/java8/exercises/chapter2/Question2Test.java | zhiyongwang/java-8-lambdas-exercises | 3513bf094d215d8bd6402d502c2af62f16455c2f | [
"MIT"
] | 26 | 2015-01-05T10:55:18.000Z | 2021-09-16T15:11:59.000Z | src/test/java/com/insightfullogic/java8/exercises/chapter2/Question2Test.java | zhiyongwang/java-8-lambdas-exercises | 3513bf094d215d8bd6402d502c2af62f16455c2f | [
"MIT"
] | 1,390 | 2015-01-09T05:12:24.000Z | 2022-03-28T18:46:50.000Z | 24.909091 | 87 | 0.687956 | 6,579 | package com.insightfullogic.java8.exercises.chapter2;
import org.junit.Test;
import java.util.Calendar;
import static org.junit.Assert.assertEquals;
public class Question2Test {
@Test
public void exampleInB() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
String formatted = Question2.formatter.get().getFormat().format(cal.getTime());
assertEquals("01-Jan-1970", formatted);
}
}
|
3e0f7b916090bcdcc24ae6212ace23327cfd6af1 | 5,199 | java | Java | reactivesocket-transport-local/src/main/java/io/reactivesocket/local/LocalServer.java | carrot-garden/stream_reactivesocket-java | f419554bdec5c115a682bde69f7b324b9d1474d5 | [
"Apache-2.0"
] | null | null | null | reactivesocket-transport-local/src/main/java/io/reactivesocket/local/LocalServer.java | carrot-garden/stream_reactivesocket-java | f419554bdec5c115a682bde69f7b324b9d1474d5 | [
"Apache-2.0"
] | null | null | null | reactivesocket-transport-local/src/main/java/io/reactivesocket/local/LocalServer.java | carrot-garden/stream_reactivesocket-java | f419554bdec5c115a682bde69f7b324b9d1474d5 | [
"Apache-2.0"
] | null | null | null | 32.905063 | 114 | 0.650894 | 6,580 | /*
* Copyright 2016 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 io.reactivesocket.local;
import io.reactivesocket.DuplexConnection;
import io.reactivesocket.local.internal.PeerConnector;
import io.reactivesocket.reactivestreams.extensions.DefaultSubscriber;
import io.reactivesocket.reactivestreams.extensions.Px;
import io.reactivesocket.reactivestreams.extensions.internal.subscribers.Subscribers;
import io.reactivesocket.transport.TransportServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.SocketAddress;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* A {@link TransportServer} using local transport. Only {@link LocalClient} instances can connect to this server.
*/
public final class LocalServer implements TransportServer {
private static final Logger logger = LoggerFactory.getLogger(LocalServer.class);
private final String name;
private volatile StartedImpl started;
/**
* Active connections, to close when server is shutdown.
*/
private final ConcurrentLinkedQueue<DuplexConnection> activeConnections = new ConcurrentLinkedQueue<>();
private LocalServer(String name) {
this.name = name;
}
@Override
public StartedServer start(ConnectionAcceptor acceptor) {
synchronized (this) {
if (started != null) {
throw new IllegalStateException("Server already started.");
}
}
started = new StartedImpl(acceptor);
return started;
}
public String getName() {
return name;
}
/**
* Creates a new {@link LocalServer} with the passed {@code name}.
*
* @param name Name of this server. This is the unique identifier to connect to this server.
*
* @return A new {@link LocalServer} instance.
*/
public static LocalServer create(String name) {
final LocalServer toReturn = new LocalServer(name);
LocalPeersManager.register(toReturn);
return toReturn;
}
void accept(PeerConnector peerConnector) {
if (null == started) {
throw new IllegalStateException(String.format("Local server %s not started.", name));
}
DuplexConnection serverConn = peerConnector.forServer();
activeConnections.add(serverConn);
serverConn.onClose().subscribe(Subscribers.doOnTerminate(() -> activeConnections.remove(serverConn)));
Px.from(started.acceptor.apply(serverConn))
.subscribe(Subscribers.cleanup(() -> {
serverConn.close().subscribe(Subscribers.empty());
}));
}
boolean isActive() {
return null != started && started.shutdownLatch.getCount() != 0;
}
void shutdown() {
StartedImpl s;
synchronized (this) {
s = started;
}
if (s != null) {
s.shutdown();
}
}
private final class StartedImpl implements StartedServer {
private final ConnectionAcceptor acceptor;
private final SocketAddress serverAddr;
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
private StartedImpl(ConnectionAcceptor acceptor) {
this.acceptor = acceptor;
serverAddr = new LocalSocketAddress(name);
}
@Override
public SocketAddress getServerAddress() {
return serverAddr;
}
@Override
public int getServerPort() {
return 0; // Local server
}
@Override
public void awaitShutdown() {
try {
shutdownLatch.await();
} catch (InterruptedException e) {
logger.error("Interrupted while waiting for shutdown.", e);
Thread.currentThread().interrupt(); // reset the interrupt flag.
}
}
@Override
public void awaitShutdown(long duration, TimeUnit durationUnit) {
try {
shutdownLatch.await(duration, durationUnit);
} catch (InterruptedException e) {
logger.error("Interrupted while waiting for shutdown.", e);
Thread.currentThread().interrupt(); // reset the interrupt flag.
}
}
@Override
public void shutdown() {
shutdownLatch.countDown();
for (DuplexConnection activeConnection : activeConnections) {
activeConnection.close().subscribe(DefaultSubscriber.defaultInstance());
}
LocalPeersManager.unregister(name);
}
}
}
|
3e0f7bba0634ede2151548665857ab6913e8c632 | 2,423 | java | Java | src/echowand/sample/RemoteObjectAnnoSample.java | ymakino/echowand | 4b3b51aaf47bb3f553dfd557529469082555340e | [
"BSD-2-Clause"
] | 7 | 2015-09-14T23:45:29.000Z | 2020-04-13T03:25:10.000Z | src/echowand/sample/RemoteObjectAnnoSample.java | ymakino/echowand | 4b3b51aaf47bb3f553dfd557529469082555340e | [
"BSD-2-Clause"
] | null | null | null | src/echowand/sample/RemoteObjectAnnoSample.java | ymakino/echowand | 4b3b51aaf47bb3f553dfd557529469082555340e | [
"BSD-2-Clause"
] | 2 | 2018-05-25T05:55:01.000Z | 2019-11-09T14:05:59.000Z | 39.721311 | 137 | 0.650021 | 6,581 | package echowand.sample;
import echowand.common.EOJ;
import echowand.common.EPC;
import echowand.info.NodeProfileInfo;
import echowand.logic.MainLoop;
import echowand.logic.RequestDispatcher;
import echowand.logic.TransactionManager;
import echowand.net.Inet4Subnet;
import echowand.net.Node;
import echowand.object.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Yoshiki Makino
*/
public class RemoteObjectAnnoSample {
public static void main(String[] args) {
try {
final Inet4Subnet subnet = Inet4Subnet.startSubnet();
final TransactionManager transactionManager = new TransactionManager(subnet);
RemoteObjectManager remoteManager = new RemoteObjectManager();
LocalObjectManager localManager = new LocalObjectManager();
final RequestDispatcher dispatcher = new RequestDispatcher();
dispatcher.addRequestProcessor(new AnnounceRequestProcessor(localManager, remoteManager));
LocalObject nodeProfileObject = new LocalObject(new NodeProfileInfo());
nodeProfileObject.addDelegate(new NodeProfileObjectDelegate(localManager));
localManager.add(nodeProfileObject);
MainLoop mainLoop = new MainLoop();
mainLoop.setSubnet(subnet);
mainLoop.addListener(transactionManager);
mainLoop.addListener(dispatcher);
Thread mainThread = new Thread(mainLoop);
mainThread.start();
InstanceListRequestExecutor instanceListRequest = new InstanceListRequestExecutor(subnet, transactionManager, remoteManager);
instanceListRequest.execute();
instanceListRequest.join();
for (Node node : remoteManager.getNodes()) {
RemoteObject remoteObject = remoteManager.get(node, new EOJ("001101"));
remoteObject.addObserver(new RemoteObjectObserver() {
@Override
public void notifyData(RemoteObject object, EPC epc, ObjectData data) {
System.out.println(object.getNode() + " " + object.getEOJ() + " " + epc + " " + data);
}
});
}
} catch (Exception ex) {
Logger.getLogger(RemoteObjectGetSample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
3e0f7c801b5aec185aced233e4fa21c6175780ba | 6,995 | java | Java | src/com/droid/activitys/setting/SettingFragment.java | sunglasscat/android-tv-launcher | d4af57bb18c8c91e316a51122786312fe67b30a0 | [
"MIT"
] | 165 | 2015-04-09T02:13:45.000Z | 2021-11-16T12:49:59.000Z | src/com/droid/activitys/setting/SettingFragment.java | lambdalang/android-tv-launcher | d4af57bb18c8c91e316a51122786312fe67b30a0 | [
"MIT"
] | 2 | 2016-04-07T11:09:51.000Z | 2019-09-12T07:57:02.000Z | src/com/droid/activitys/setting/SettingFragment.java | lambdalang/android-tv-launcher | d4af57bb18c8c91e316a51122786312fe67b30a0 | [
"MIT"
] | 117 | 2015-04-09T02:13:48.000Z | 2021-08-12T02:35:31.000Z | 38.224044 | 86 | 0.659185 | 6,582 | package com.droid.activitys.setting;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.droid.R;
import com.droid.activitys.WoDouGameBaseFragment;
import com.droid.activitys.app.AppAutoRun;
import com.droid.activitys.app.AppUninstall;
import com.droid.application.ClientApplication;
import com.droid.cache.ImageCache;
import com.droid.cache.loader.ImageFetcher;
import com.droid.cache.loader.ImageWorker;
import com.droid.activitys.eliminateprocess.EliminateMainActivity;
import com.droid.activitys.garbageclear.GarbageClear;
import com.droid.activitys.speedtest.SpeedTestActivity;
import java.util.List;
/**
* Created by Administrator on 2014/9/9.
*/
public class SettingFragment extends WoDouGameBaseFragment implements
View.OnClickListener {
private ImageWorker mImageLoader;
private ImageButton Setting_Clean;// 垃圾清理
private ImageButton Setting_Accelerate;// 一键加速
private ImageButton appUninstall;
private ImageButton setNet;
private ImageButton setMore;
private ImageButton netSpeed;
private ImageButton sysUpdate;
private ImageButton fileManage;
private ImageButton about;
private ImageButton autoRun;
private View view;// 视图
private Intent JumpIntent;
private static final boolean d = ClientApplication.debug;
private Context context;
/**
* 用来存放
*/
private List<ContentValues> datas;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this.getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = LayoutInflater.from(getActivity()).inflate(
R.layout.fragment_setting, null);
initView(view);
setListener();
// Bundle bundle = this.getArguments();
// String data = bundle.getString("url_data");
// UIResponseParam uiResponseParam = null;
// try {
// uiResponseParam = new UIResponseParam(data);
// datas = uiResponseParam.getUIInfo();
// showImages();
// } catch (JSONException e) {
// e.printStackTrace();
// }
return view;
}
private void initView(View view) {
// FocusedRelativeLayout focus = (FocusedRelativeLayout) view
// .findViewById(R.id.setting_focus_rl);
// focus.setFocusResId(R.drawable.focus_bg);
// focus.setFocusShadowResId(R.drawable.focus_shadow);
// focus.setFocusable(true);
// focus.setFocusableInTouchMode(true);
// focus.requestFocus();
// focus.requestFocusFromTouch();
appUninstall = (ImageButton) view.findViewById(R.id.setting_uninstall);
setNet = (ImageButton) view.findViewById(R.id.setting_net);
setMore = (ImageButton) view.findViewById(R.id.setting_more);
netSpeed = (ImageButton) view.findViewById(R.id.setting_net_speed);
sysUpdate = (ImageButton) view.findViewById(R.id.setting_update);
fileManage = (ImageButton) view.findViewById(R.id.setting_file);
about = (ImageButton) view.findViewById(R.id.setting_about);
Setting_Clean = (ImageButton) view.findViewById(R.id.setting_clean);
Setting_Accelerate = (ImageButton) view.findViewById(R.id.setting_accelerate);
autoRun = (ImageButton) view.findViewById(R.id.setting_autorun);
appUninstall.setOnFocusChangeListener(mFocusChangeListener);
setNet.setOnFocusChangeListener(mFocusChangeListener);
setMore.setOnFocusChangeListener(mFocusChangeListener);
netSpeed.setOnFocusChangeListener(mFocusChangeListener);
sysUpdate.setOnFocusChangeListener(mFocusChangeListener);
fileManage.setOnFocusChangeListener(mFocusChangeListener);
about.setOnFocusChangeListener(mFocusChangeListener);
Setting_Clean.setOnFocusChangeListener(mFocusChangeListener);
Setting_Accelerate.setOnFocusChangeListener(mFocusChangeListener);
autoRun.setOnFocusChangeListener(mFocusChangeListener);
}
private void setListener() {
Setting_Clean.setOnClickListener(this);
Setting_Accelerate.setOnClickListener(this);
about.setOnClickListener(this);
setMore.setOnClickListener(this);
appUninstall.setOnClickListener(this);
setNet.setOnClickListener(this);
fileManage.setOnClickListener(this);
netSpeed.setOnClickListener(this);
sysUpdate.setOnClickListener(this);
autoRun.setOnClickListener(this);
}
private void showImages() {
mImageLoader = new ImageFetcher(this.getActivity());
mImageLoader.setImageCache(ImageCache.getInstance(this.getActivity()));
datas = datas.subList(11, 17);
for (int i = 0; i < datas.size(); i++) {
int picPosition = datas.get(i).getAsInteger("picPosition");
String picPath = datas.get(i).getAsString("picPath");
switch (picPosition) {
case 1:
// mImageLoader.loadImage(picPath, iv_1,
// R.drawable.where_is_father);
break;
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.setting_clean:
JumpIntent = new Intent(context, GarbageClear.class);
startActivity(JumpIntent);
break;
case R.id.setting_accelerate:
JumpIntent = new Intent(context, EliminateMainActivity.class);
startActivity(JumpIntent);
break;
case R.id.setting_about:
break;
case R.id.setting_more:
JumpIntent = new Intent(Settings.ACTION_SETTINGS);
startActivity(JumpIntent);
break;
case R.id.setting_file:
break;
case R.id.setting_update:
break;
case R.id.setting_net:
JumpIntent = new Intent(context, SettingCustom.class);
startActivity(JumpIntent);
break;
case R.id.setting_uninstall:
JumpIntent = new Intent(context, AppUninstall.class);
startActivity(JumpIntent);
break;
case R.id.setting_autorun:
JumpIntent = new Intent(context, AppAutoRun.class);
startActivity(JumpIntent);
break;
case R.id.setting_net_speed:
JumpIntent = new Intent(context, SpeedTestActivity.class);
startActivity(JumpIntent);
break;
}
}
}
|
3e0f7d1ee982e199a21633f996599988a0af9c8b | 749 | java | Java | app/src/main/java/com/happytimes/alisha/model/TaskReaderContract.java | alishaalam/ToDoAppCodePath | c8e1e8172c2bae9dbbb50740a41036ca8b89de1c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/happytimes/alisha/model/TaskReaderContract.java | alishaalam/ToDoAppCodePath | c8e1e8172c2bae9dbbb50740a41036ca8b89de1c | [
"Apache-2.0"
] | 1 | 2016-06-25T04:28:09.000Z | 2016-07-07T03:58:59.000Z | app/src/main/java/com/happytimes/alisha/model/TaskReaderContract.java | alishaalam/ToDoAppCodePath | c8e1e8172c2bae9dbbb50740a41036ca8b89de1c | [
"Apache-2.0"
] | null | null | null | 31.208333 | 75 | 0.720961 | 6,583 | package com.happytimes.alisha.model;
import android.provider.BaseColumns;
/**
* Created by alishaalam on 6/26/16.
*/
public class TaskReaderContract {
public TaskReaderContract(){
}
public static abstract class TaskEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_DESCRIPTION = "description";
public static final String COLUMN_NAME_DEADLINE = "deadline";
public static final String COLUMN_NAME_PRIORITY = "priority";
public static final String COLUMN_NAME_NULLABLE = "nullHack";
}
}
|
3e0f7d7b3d2c923e73704c365ad8a5fee44bbb08 | 648 | java | Java | src/com/zyx1011/mobilesafe002/entity/FlowInfo.java | zhongyuxin1011/MobileSafe002 | 0a13f6f4907567b2ae4271420ff06852dee4e14f | [
"Apache-2.0"
] | null | null | null | src/com/zyx1011/mobilesafe002/entity/FlowInfo.java | zhongyuxin1011/MobileSafe002 | 0a13f6f4907567b2ae4271420ff06852dee4e14f | [
"Apache-2.0"
] | null | null | null | src/com/zyx1011/mobilesafe002/entity/FlowInfo.java | zhongyuxin1011/MobileSafe002 | 0a13f6f4907567b2ae4271420ff06852dee4e14f | [
"Apache-2.0"
] | null | null | null | 24 | 113 | 0.654321 | 6,584 | package com.zyx1011.mobilesafe002.entity;
import android.graphics.drawable.Drawable;
public class FlowInfo implements Comparable<FlowInfo> {
public String packageName;
public String name;
public Drawable icon;
public int uid;
public long rcv;
public long snd;
@Override
public String toString() {
return "FlowInfo [packageName=" + packageName + ", name=" + name + ", icon=" + icon + ", uid=" + uid + ", rcv="
+ rcv + ", snd=" + snd + "]";
}
@Override
public int compareTo(FlowInfo another) {
int a = (int) (another.rcv - this.rcv); // 以接收数为主
int b = a == 0 ? (int) (another.snd - this.snd) : a; // 以发送数为辅
return b;
}
} |
3e0f7eec035f44999195d4a7d876da5ee4b2d939 | 6,714 | java | Java | src/main/java/jp/ossc/nimbus/beans/dataset/RecordPropertySchema.java | nimbus-org/nimbus | 43a511499e9cd7f27515ddb8d493b2af44346abc | [
"BSD-3-Clause"
] | 26 | 2018-01-16T10:21:31.000Z | 2021-09-10T02:28:47.000Z | src/main/java/jp/ossc/nimbus/beans/dataset/RecordPropertySchema.java | nimbus-org/nimbus | 43a511499e9cd7f27515ddb8d493b2af44346abc | [
"BSD-3-Clause"
] | 473 | 2018-02-08T06:51:43.000Z | 2021-09-08T07:35:59.000Z | src/main/java/jp/ossc/nimbus/beans/dataset/RecordPropertySchema.java | nimbus-org/nimbus | 43a511499e9cd7f27515ddb8d493b2af44346abc | [
"BSD-3-Clause"
] | 1 | 2018-05-31T14:30:33.000Z | 2018-05-31T14:30:33.000Z | 30.243243 | 104 | 0.60426 | 6,585 | /*
* This software is distributed under following license based on modified BSD
* style license.
* ----------------------------------------------------------------------
*
* Copyright 2003 The Nimbus Project. 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 NIMBUS PROJECT ``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 NIMBUS PROJECT 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the Nimbus Project.
*/
package jp.ossc.nimbus.beans.dataset;
import java.util.List;
/**
* ネストした{@link Record}のプロパティのスキーマ定義。<p>
* このクラスには、プロパティのスキーマ情報として、以下の情報が定義できる。<br>
* <ul>
* <li>名前</li>
* <li>ネストレコード名</li>
* <li>型</li>
* </ul>
* プロパティスキーマ定義のフォーマットは、<br>
* <pre>
* 名前,ネストレコード名,型
* </pre>
* となっており、型以外は全て必須である。<br>
* <p>
* 次に、各項目の詳細を説明する。<br>
* <p>
* 名前は、プロパティの名前を意味し、{@link Record レコード}からプロパティ値を取得する際のキーとなる。<br>
* <p>
* ネストレコード名は、ネストされたRecordの名前で、{@link DataSet#setNestedRecordSchema(String, String)}で設定したレコード名を指定する。<br>
* <p>
* 型は、プロパティの型を意味し、Javaの完全修飾クラス名で指定する。<br>
*
* @author M.Takata
*/
public class RecordPropertySchema implements PropertySchema, java.io.Serializable{
private static final long serialVersionUID = -6689975898690899203L;
/**
* スキーマ文字列。<p>
*/
protected String schema;
/**
* プロパティの名前。<p>
*/
protected String name;
/**
* ネストしたレコード名。<p>
*/
protected String recordName;
/**
* プロパティの型。<p>
*/
protected Class type = Record.class;
/**
* 空のプロパティスキーマを生成する。<p>
*/
public RecordPropertySchema(){
}
/**
* プロパティスキーマを生成する。<p>
*
* @param schema プロパティのスキーマ定義
* @exception PropertySchemaDefineException プロパティのスキーマ定義に失敗した場合
*/
public RecordPropertySchema(String schema) throws PropertySchemaDefineException{
setSchema(schema);
}
/**
* プロパティのスキーマ定義を設定する。<p>
*
* @param schema プロパティのスキーマ定義
* @exception PropertySchemaDefineException プロパティのスキーマ定義に失敗した場合
*/
public void setSchema(String schema) throws PropertySchemaDefineException{
final List schemata = DefaultPropertySchema.parseCSV(schema);
if(schemata.size() < 2){
throw new PropertySchemaDefineException("Name and Schema must be specified.");
}
this.schema = schema;
name = (String)schemata.get(0);
recordName = (String)schemata.get(1);
if(schemata.size() > 2){
parseType(schema, (String)schemata.get(2));
}
}
/**
* プロパティスキーマの型の項目をパースする。<p>
*
* @param schema プロパティスキーマ全体
* @param val スキーマ項目
* @exception PropertySchemaDefineException プロパティのスキーマ定義に失敗した場合
*/
protected void parseType(String schema, String val)
throws PropertySchemaDefineException{
if(val != null && val.length() != 0){
try{
type = jp.ossc.nimbus.core.Utility.convertStringToClass(val, false);
}catch(ClassNotFoundException e){
throw new PropertySchemaDefineException(
schema,
"The type is illegal.",
e
);
}
}
}
// PropertySchemaのJavaDoc
public String getSchema(){
return schema;
}
// PropertySchemaのJavaDoc
public String getName(){
return name;
}
// PropertySchemaのJavaDoc
public Class getType(){
return type;
}
// PropertySchemaのJavaDoc
public boolean isPrimaryKey(){
return false;
}
// PropertySchemaのJavaDoc
public Object set(Object val) throws PropertySetException{
if(val == null){
return null;
}
if(!(val instanceof Record)){
throw new PropertySchemaCheckException(
this,
"The type is unmatch. type=" + val.getClass().getName()
);
}
return val;
}
// PropertySchemaのJavaDoc
public Object get(DataSet ds, Record rec, Object val) throws PropertyGetException{
return val;
}
// PropertySchemaのJavaDoc
public Object format(Object val) throws PropertyGetException{
return val;
}
// PropertySchemaのJavaDoc
public Object parse(Object val) throws PropertySetException{
return val;
}
// PropertySchemaのJavaDoc
public boolean validate(Object val) throws PropertyValidateException{
if(val != null && val instanceof Record){
return ((Record)val).validate();
}
return true;
}
/**
* ネストしたレコード名を取得する。<p>
*
* @return ネストしたレコード名
*/
public String getRecordName(){
return recordName;
}
/**
* このスキーマの文字列表現を取得する。<p>
*
* @return 文字列表現
*/
public String toString(){
final StringBuilder buf = new StringBuilder(getClass().getName());
buf.append('{');
buf.append("name=").append(name);
buf.append(",recordName=").append(recordName);
buf.append(",type=").append(type);
buf.append('}');
return buf.toString();
}
}
|
3e0f7fc25cd219f8889bf90045657f927b50cf96 | 1,214 | java | Java | src/test/java/com/dua3/meja/test/XlsxWorkbookTest.java | xzel23/meja | 9e68ad180649828adeeffebc6e3097c35f5b6a1a | [
"Apache-2.0"
] | 7 | 2015-05-06T21:53:45.000Z | 2018-05-17T03:50:13.000Z | src/test/java/com/dua3/meja/test/XlsxWorkbookTest.java | xzel23/meja | 9e68ad180649828adeeffebc6e3097c35f5b6a1a | [
"Apache-2.0"
] | 16 | 2015-04-08T17:01:59.000Z | 2022-01-02T07:18:04.000Z | src/test/java/com/dua3/meja/test/XlsxWorkbookTest.java | xzel23/meja | 9e68ad180649828adeeffebc6e3097c35f5b6a1a | [
"Apache-2.0"
] | null | null | null | 23.346154 | 62 | 0.688633 | 6,586 | package com.dua3.meja.test;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.dua3.meja.model.Workbook;
import com.dua3.meja.model.poi.PoiWorkbookFactory;
public class XlsxWorkbookTest {
private Workbook workbook;
@BeforeEach
public void initialize() throws IOException {
workbook = PoiWorkbookFactory.instance().createXlsx();
workbook.copy(WorkbookTestHelper.loadWorkbook());
}
@AfterEach
public void cleanup() throws IOException {
workbook.close();
workbook = null;
}
/**
* @see WorkbookTestHelper#testFormat_getAsText(Workbook)
*/
@Test
public void testFormat_getAsText() {
WorkbookTestHelper.testFormat_getAsText(workbook);
}
/**
* @see WorkbookTestHelper#testFormat_toString(Workbook)
*/
@Test
public void testFormat_toString() {
WorkbookTestHelper.testFormat_toString(workbook);
}
/**
* @see WorkbookTestHelper#testMergeUnmerge(Workbook)
*/
@Test
public void testMergeUnmerge() {
WorkbookTestHelper.testMergeUnmerge(workbook);
}
}
|
3e0f805c8b24bd7e5a62edbf285b5f008c45939c | 3,048 | java | Java | Chapter_002/Lesson_4/Tracker/src/main/java/ru/sbulygin/models/Item.java | sergeyBulygin/Java_a_to_z | b7b3469d726d95aa51d61dab8c23bbf0d31fad39 | [
"Apache-2.0"
] | 2 | 2017-05-28T10:31:45.000Z | 2017-07-08T09:29:00.000Z | Chapter_002/Lesson_4/Tracker/src/main/java/ru/sbulygin/models/Item.java | sergeyBulygin/Java_a_to_z | b7b3469d726d95aa51d61dab8c23bbf0d31fad39 | [
"Apache-2.0"
] | 26 | 2017-04-09T10:17:55.000Z | 2017-10-22T07:46:10.000Z | Chapter_005/Generalizations/ChangeTracker/src/main/java/ru/sbulygin/models/Item.java | sergeyBulygin/Java_a_to_z | b7b3469d726d95aa51d61dab8c23bbf0d31fad39 | [
"Apache-2.0"
] | null | null | null | 22.086957 | 70 | 0.524606 | 6,587 | package ru.sbulygin.models;
/**
* Class Item.
*
* @author sbulygin.
* @since 09.01.2017.
* @version 1.0.
*/
public class Item {
/**
* The id field.
*/
private String id;
/**
* The name field.
*/
private String name;
/**
* Description field.
*/
private String description;
/**
* Creation date field.
*/
private long dateCreation;
/**
* The comment field of the array.
*/
private Comment comments = new Comment();
/**
* Constructor of Item class.
* @param name name of item.
* @param description description of item.
* @param dateCreation create time of item.
*/
public Item(String name, String description, long dateCreation) {
this.name = name;
this.description = description;
this.dateCreation = dateCreation;
}
/**
* Getter method for name field.
* @return name.
*/
public String getName() {
return this.name;
}
/**
* Getter method for description field.
* @return description.
*/
public String getDescription() {
return this.description;
}
/**
* Getter method for dateCreation field.
* @return dateCreation.
*/
public long getDateCreation() {
return this.dateCreation;
}
/**
* Getter method for id field.
* @return id.
*/
public String getId() {
return this.id;
}
/**
* Getter method for comment array field.
* @return result result sting line comments.
*/
public String getComment() {
String result = "";
String[] allRemarks = this.comments.getRemark();
if (allRemarks != null) {
for (String temp : allRemarks) {
if (result != "") {
result += System.lineSeparator();
}
result += temp;
}
}
return result;
}
/**
* Setter method for comment array field.
* @param comment comments.
*/
public void setComment(String comment) {
this.comments.addComment(comment);
}
/**
* Setter method for name field.
* @param name string for set name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Setter method for description field.
* @param description string for set description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Setter method for dateCreation field.
* @param dateCreation number for set create.
*/
public void setDateCreation(long dateCreation) {
this.dateCreation = dateCreation;
}
/**
* Setter method for id field.
* @param id string for set id.
*/
public void setId(String id) {
this.id = id;
}
}
|
3e0f8074f1f47b7c903cd7152784ae52ab84ccc8 | 1,076 | java | Java | src/main/java/com/gin/gof/design/patterns/factory/simple/SimpleFactory.java | soulasuna/java-design-patterns | eb7248587089cef885c785335f52547dcc770715 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/gin/gof/design/patterns/factory/simple/SimpleFactory.java | soulasuna/java-design-patterns | eb7248587089cef885c785335f52547dcc770715 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/gin/gof/design/patterns/factory/simple/SimpleFactory.java | soulasuna/java-design-patterns | eb7248587089cef885c785335f52547dcc770715 | [
"Apache-2.0"
] | null | null | null | 24.454545 | 75 | 0.660781 | 6,588 | /*
* Copyright 2013-2018 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 com.gin.gof.design.patterns.factory.simple;
/**
* <p>
* Description: 简单工厂接口
* </p>
* InterfaceName: SimpleFactory
*
* @author dnt
* @version V1.0.0
* @date 2020/4/13、11:04
* @since jdk1.8
*/
public interface SimpleFactory<T> {
/**
* <p>
* Description: 根据名称获得对象
* </p>
* @param name 对象名称
* @return 获得对象
*
* @author dnt
* @date 2020/4/13 11:05
*/
T getProduct(String name);
}
|
3e0f820aeab79f57690139c883ea8500dbdb4ab6 | 1,307 | java | Java | plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java | aleskxyz/cloudstack | 2700beb4fb1206f93829b8c4085479a8f416833d | [
"Apache-2.0"
] | 1,131 | 2015-01-08T18:59:06.000Z | 2022-03-29T11:31:10.000Z | plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java | aleskxyz/cloudstack | 2700beb4fb1206f93829b8c4085479a8f416833d | [
"Apache-2.0"
] | 5,908 | 2015-01-13T15:28:37.000Z | 2022-03-31T20:31:07.000Z | plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java | Rostov1991/cloudstack | 4abe8385e0721793d5dae8f195303d010c8ff8d2 | [
"Apache-2.0"
] | 1,083 | 2015-01-05T01:16:52.000Z | 2022-03-31T12:14:10.000Z | 38.441176 | 63 | 0.764346 | 6,589 | // 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.cloudstack.api.response.solidfire;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class ApiPathForVolumeResponse extends BaseResponse {
@SerializedName(ApiConstants.PATH)
@Param(description = "The path field for the volume")
private String path;
public ApiPathForVolumeResponse(String path) {
this.path = path;
}
}
|
3e0f835ccb2872c5110c9d760232563f7fc7c84c | 6,032 | java | Java | java/src/main/java/com/genexus/db/DBConnection.java | dalvarellos/JavaClasses | 6fe9e9643c91ff5f101a78ab6334c3e60c932e57 | [
"Apache-2.0"
] | 21 | 2019-06-01T02:25:26.000Z | 2022-01-13T02:20:18.000Z | java/src/main/java/com/genexus/db/DBConnection.java | dalvarellos/JavaClasses | 6fe9e9643c91ff5f101a78ab6334c3e60c932e57 | [
"Apache-2.0"
] | 415 | 2019-05-03T23:09:08.000Z | 2022-03-31T22:08:16.000Z | java/src/main/java/com/genexus/db/DBConnection.java | dalvarellos/JavaClasses | 6fe9e9643c91ff5f101a78ab6334c3e60c932e57 | [
"Apache-2.0"
] | 17 | 2019-05-21T16:02:28.000Z | 2022-02-06T17:39:59.000Z | 20.871972 | 143 | 0.679045 | 6,590 | package com.genexus.db;
import java.sql.SQLException;
import com.genexus.Application;
import com.genexus.ApplicationContext;
import com.genexus.db.driver.DataSource;
import com.genexus.db.driver.GXDBMS;
import com.genexus.util.ReorgSubmitThreadPool;
public class DBConnection
{
protected DataSource dataSource;
private int handle;
private String errMsg = "";
private int errCode = 0;
private short showPrompt = 3;
public static DBConnection getDataStore(String dataSourceName, int handle)
{
return new DBConnection(DBConnectionManager.getInstance().getDataSource(handle, dataSourceName), handle);
}
public DBConnection()
{
errMsg = "Invalid DBConnection instance";
errCode = 1;
}
public DBConnection(DataSource dataSource, int handle)
{
if (dataSource == null)
{
errMsg = "Invalid DBConnection instance";
errCode = 1;
}
else
{
this.dataSource = dataSource;
this.handle = handle;
}
}
public String getJdbcdrivername()
{
clearErr();
return dataSource.jdbcDriver;
}
public String getSchema()
{
return dataSource.schema;
}
public String getDatabasename()
{
return dataSource.jdbcDBName;
}
public void setDatabasename(String dbName)
{
String url = getJdbcdriverurl();
if (url != null)
{
int index = 0;
if (dataSource.dbms.getId() == GXDBMS.DBMS_INFORMIX && getDatabasename().equals(""))
{
index = url.lastIndexOf(":");
}
else
{
index = url.lastIndexOf(dataSource.jdbcDBName);
}
if (index >= 0)
{
if (dataSource.dbms.getId() == GXDBMS.DBMS_INFORMIX && dbName.equals(""))
{
url = url.substring(0, index-1) + url.substring(index + dataSource.jdbcDBName.length());
}
else
{
if (dataSource.dbms.getId() == GXDBMS.DBMS_INFORMIX && getDatabasename().equals(""))
{
url = url.substring(0, index) + "/" + dbName + url.substring(index + dataSource.jdbcDBName.length());
}
else
{
url = url.substring(0, index) + dbName + url.substring(index + dataSource.jdbcDBName.length());
}
}
setJdbcdriverurl(url);
}
}
dataSource.jdbcDBName = dbName;
dataSource.dbms.setDatabaseName(dbName);
}
public void setJdbcdrivername(String driverName)
{
dataSource.jdbcDriver = driverName;
}
public String getJdbcdriverurl()
{
clearErr();
return dataSource.jdbcUrl;
}
public void setJdbcdriverurl(String url)
{
dataSource.jdbcUrl = url;
}
public boolean getUseexternaldatasource()
{
return dataSource.usesJdbcDataSource();
}
public void setUseexternaldatasource(int value)
{
if (value==1)
dataSource.useJdbcDataSource = true;
else
dataSource.useJdbcDataSource = false;
}
public String getExternaldatasourcename()
{
return dataSource.jdbcDataSource;
}
public void setExternaldatasourcename(String value)
{
dataSource.jdbcDataSource = value;
}
public String getDatastorename()
{
clearErr();
return dataSource.name;
}
private void clearErr()
{
errMsg = "";
errCode = 0;
}
public void setUserName(String userName)
{
clearErr();
dataSource.defaultUser = userName;
}
public String getUserName()
{
clearErr();
return dataSource.defaultUser;
}
public void setUserpassword(String userPassword)
{
clearErr();
dataSource.defaultPassword = userPassword;
}
public String getUserpassword()
{
clearErr();
return dataSource.defaultPassword;
}
public void setShowprompt(short showPrompt)
{
clearErr();
this.showPrompt = showPrompt;
dataSource.loginInServer = (showPrompt == 2);
}
public short getShowprompt()
{
return showPrompt;
}
public String getErrDescription()
{
return errMsg;
}
public short getErrCode()
{
return (short)errCode;
}
public short disconnect()
{
clearErr();
try
{
DBConnectionManager.getInstance().getUserInformation(handle).disconnect();
}catch(SQLException e)
{
errMsg = e.getMessage();
errCode = e.getErrorCode();
}
return (short)errCode;
}
public short connectDontShowErrors()
{
Application.setShowConnectError(false);
short errCode = connect();
Application.setShowConnectError(true);
return errCode;
}
public short connect()
{
if (ReorgSubmitThreadPool.hasAnyError())
{
errCode = 3;
return (short)errCode;
}
clearErr();
try
{
UserInformation info = DBConnectionManager.getInstance().getUserInformation(handle);
if (info instanceof LocalUserInformation || (info instanceof ServerUserInformation && ApplicationContext.getInstance().getReorganization()))
{
((UserInformation)info).createConnectionBatch(null, this);
}
else
{
((UserInformation)info).testConnectionBatch(null, handle, this);
}
}catch(SQLException e)
{
errMsg = e.getMessage() + " - code:" + e.getErrorCode();
errCode = 3;
}catch(RuntimeException e)
{
errMsg = e.getMessage();
errCode = 3;
}
if (errCode != 0 && Application.getShowConnectError() && ApplicationContext.getInstance().getReorganization())
{
ReorgSubmitThreadPool.setAnError();
}
return (short)errCode;
}
public DataSource getDataSource()
{
return dataSource;
}
// Metodos que solo aplican a AS/400
public void setConnectiondata(String asLibName)
{
clearErr();
dataSource.jdbcDBName = asLibName;
dataSource.dbms.setDatabaseName(asLibName);
}
public String getConnectiondata()
{
return dataSource.jdbcDBName;
}
// Metodos que no aplican a Java
public void setConnectionmethod(short method) { ; }
public short getConnectionmethod(){ return 0; }
public void setOdbcdatasourcename(String ds){ ; }
public String getOdbcdatasourcename(){ return ""; }
public void setOdbcdrivername(String dn){ ; }
public String getOdbcdrivername(){ return ""; }
public void setOdbcfiledatasourcename(String ds){ ; }
public String getOdbcfiledatasourcename(){ return ""; }
}
|
3e0f83777e8f1a39ddfb2b5e409d151e33a45766 | 1,846 | java | Java | src/test/java/com/google/pubsub/proxy/server/HealthCheckTest.java | GoogleCloudPlatform/solutions-pubsub-proxy-rest | a48ea851dadf3e61095e0c82358985a37a8853e0 | [
"Apache-2.0"
] | 4 | 2020-02-12T10:47:34.000Z | 2021-10-09T02:50:01.000Z | src/test/java/com/google/pubsub/proxy/server/HealthCheckTest.java | GoogleCloudPlatform/solutions-pubsub-proxy-rest | a48ea851dadf3e61095e0c82358985a37a8853e0 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/google/pubsub/proxy/server/HealthCheckTest.java | GoogleCloudPlatform/solutions-pubsub-proxy-rest | a48ea851dadf3e61095e0c82358985a37a8853e0 | [
"Apache-2.0"
] | 3 | 2020-11-21T20:57:54.000Z | 2021-10-09T02:49:54.000Z | 36.196078 | 90 | 0.77844 | 6,591 | /* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
package com.google.pubsub.proxy.server;
import static javax.ws.rs.core.Response.Status.OK;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Assert;
import org.junit.Test;
public class HealthCheckTest extends JerseyTest {
@Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forServlet(
new ServletContainer(new ResourceConfig(HealthCheck.class)))
.build();
}
@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
@Test
public void HealthCheckAlwaysReturnsStatusOK() {
Response response = target("/").request().get();
Assert.assertEquals(OK.getStatusCode(), response.getStatus());
}
}
|
3e0f840aee3d131f7cf2ba3ed63601aa8f13111a | 1,071 | java | Java | src/main/java/com/ddlab/rnd/type2/AcceptEither1.java | debjava/completableFuture1 | 1caa1a251a13edee3e93d7f441fbfef68a6e5143 | [
"MIT"
] | null | null | null | src/main/java/com/ddlab/rnd/type2/AcceptEither1.java | debjava/completableFuture1 | 1caa1a251a13edee3e93d7f441fbfef68a6e5143 | [
"MIT"
] | null | null | null | src/main/java/com/ddlab/rnd/type2/AcceptEither1.java | debjava/completableFuture1 | 1caa1a251a13edee3e93d7f441fbfef68a6e5143 | [
"MIT"
] | null | null | null | 26.121951 | 82 | 0.603175 | 6,592 | package com.ddlab.rnd.type2;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class AcceptEither1 {
private static void sleep(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String task1() {
System.out.println("Started executing task-1");
sleep(5);
System.out.println("task-1 completed");
return "task-1";
}
public static String task2() {
System.out.println("Started executing task-2");
sleep(3);
System.out.println("task-2 completed");
return "task-2";
}
public static void main(String[] args) {
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> task1());
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> task2());
CompletableFuture<Void> cf =
cf1.acceptEither(
cf2,
a -> {
System.out.println("Result = " + a);
});
cf.join();
}
}
|
3e0f84c9ca9dceb8845642c39f84b37811c40984 | 832 | java | Java | src/main/java/com/memorynotfound/spring/security/config/CustomAuthorizer.java | tannguyen3489/mySpringStartKit1 | f6a2da23e52f19ec5331d292cbac7535d1f17d06 | [
"MIT"
] | null | null | null | src/main/java/com/memorynotfound/spring/security/config/CustomAuthorizer.java | tannguyen3489/mySpringStartKit1 | f6a2da23e52f19ec5331d292cbac7535d1f17d06 | [
"MIT"
] | null | null | null | src/main/java/com/memorynotfound/spring/security/config/CustomAuthorizer.java | tannguyen3489/mySpringStartKit1 | f6a2da23e52f19ec5331d292cbac7535d1f17d06 | [
"MIT"
] | null | null | null | 33.28 | 113 | 0.754808 | 6,593 | package com.memorynotfound.spring.security.config;
import org.apache.commons.lang3.StringUtils;
import org.pac4j.core.authorization.authorizer.ProfileAuthorizer;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.profile.CommonProfile;
import java.util.List;
public class CustomAuthorizer extends ProfileAuthorizer<CommonProfile> {
@Override
public boolean isAuthorized(final WebContext context, final List<CommonProfile> profiles) throws HttpAction {
return isAnyAuthorized(context, profiles);
}
@Override
public boolean isProfileAuthorized(final WebContext context, final CommonProfile profile) {
if (profile == null) {
return false;
}
return StringUtils.startsWith(profile.getUsername(), "jle");
}
} |
3e0f8685219d892d40d532bb4efe65f8ab0ecd0c | 1,098 | java | Java | dsl/org.sodalite.IDE.parent/org.sodalite.dsl.optimization.ide/src-gen/org/sodalite/dsl/optimization/ide/contentassist/antlr/PartialOptimizationContentAssistParser.java | SODALITE-EU/ide | a80c562e5d7d7928423d42dbcd328c76700bfbb1 | [
"Apache-2.0"
] | 5 | 2021-01-20T12:13:43.000Z | 2021-08-09T10:34:13.000Z | dsl/org.sodalite.IDE.parent/org.sodalite.dsl.optimization.ide/src-gen/org/sodalite/dsl/optimization/ide/contentassist/antlr/PartialOptimizationContentAssistParser.java | SODALITE-EU/ide | a80c562e5d7d7928423d42dbcd328c76700bfbb1 | [
"Apache-2.0"
] | 105 | 2020-04-22T16:27:32.000Z | 2022-02-08T15:39:58.000Z | dsl/org.sodalite.IDE.parent/org.sodalite.dsl.optimization.ide/src-gen/org/sodalite/dsl/optimization/ide/contentassist/antlr/PartialOptimizationContentAssistParser.java | SODALITE-EU/ide | a80c562e5d7d7928423d42dbcd328c76700bfbb1 | [
"Apache-2.0"
] | 4 | 2020-08-13T07:35:58.000Z | 2021-11-20T16:08:26.000Z | 32.294118 | 109 | 0.801457 | 6,594 | /*
* generated by Xtext 2.25.0
*/
package org.sodalite.dsl.optimization.ide.contentassist.antlr;
import java.util.Collection;
import java.util.Collections;
import org.eclipse.xtext.AbstractRule;
import org.eclipse.xtext.ide.editor.contentassist.antlr.FollowElement;
import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser;
import org.eclipse.xtext.util.PolymorphicDispatcher;
public class PartialOptimizationContentAssistParser extends OptimizationParser {
private AbstractRule rule;
@Override
public void initializeFor(AbstractRule rule) {
this.rule = rule;
}
@Override
protected Collection<FollowElement> getFollowElements(AbstractInternalContentAssistParser parser) {
if (rule == null || rule.eIsProxy())
return Collections.emptyList();
String methodName = "entryRule" + rule.getName();
PolymorphicDispatcher<Collection<FollowElement>> dispatcher =
new PolymorphicDispatcher<Collection<FollowElement>>(methodName, 0, 0, Collections.singletonList(parser));
dispatcher.invoke();
return parser.getFollowElements();
}
}
|
3e0f8792e8491cd3887b241882713bb13cfc76ee | 1,202 | java | Java | library/src/main/java/com/pengrad/telegrambot/model/request/InputMediaAudio.java | viwy/java-telegram-bot-api | 194741d43c0781a7aeb21b646a5b57161ba26cc6 | [
"Apache-2.0"
] | 1,283 | 2015-10-16T07:06:31.000Z | 2022-03-31T23:31:56.000Z | library/src/main/java/com/pengrad/telegrambot/model/request/InputMediaAudio.java | viwy/java-telegram-bot-api | 194741d43c0781a7aeb21b646a5b57161ba26cc6 | [
"Apache-2.0"
] | 258 | 2015-09-17T14:38:29.000Z | 2022-03-18T12:45:06.000Z | library/src/main/java/com/pengrad/telegrambot/model/request/InputMediaAudio.java | viwy/java-telegram-bot-api | 194741d43c0781a7aeb21b646a5b57161ba26cc6 | [
"Apache-2.0"
] | 357 | 2015-09-27T21:41:33.000Z | 2022-03-31T05:30:05.000Z | 21.854545 | 90 | 0.668053 | 6,595 | package com.pengrad.telegrambot.model.request;
import com.pengrad.telegrambot.request.ContentTypes;
import java.io.File;
import java.io.Serializable;
/**
* Stas Parshin
* 28 July 2018
*/
public class InputMediaAudio extends InputMedia<InputMediaAudio> implements Serializable {
private final static long serialVersionUID = 0L;
private Integer duration;
private String performer, title;
public InputMediaAudio(String media) {
super("audio", media);
}
public InputMediaAudio(File media) {
super("audio", media);
}
public InputMediaAudio(byte[] media) {
super("audio", media);
}
public InputMediaAudio duration(Integer duration) {
this.duration = duration;
return this;
}
public InputMediaAudio performer(String performer) {
this.performer = performer;
return this;
}
public InputMediaAudio title(String title) {
this.title = title;
return this;
}
@Override
public String getDefaultFileName() {
return ContentTypes.AUDIO_FILE_NAME;
}
@Override
public String getContentType() {
return ContentTypes.AUDIO_MIME_TYPE;
}
}
|
3e0f87e79a58e010fbd6992b4cb9dc49b392278b | 17,005 | java | Java | smallrye-reactive-messaging-kafka/src/main/java/io/smallrye/reactive/messaging/kafka/impl/KafkaSink.java | pcasaes/smallrye-reactive-messaging | 135d593b7850242abf5ea0b47dd032fe051c41fa | [
"Apache-2.0"
] | null | null | null | smallrye-reactive-messaging-kafka/src/main/java/io/smallrye/reactive/messaging/kafka/impl/KafkaSink.java | pcasaes/smallrye-reactive-messaging | 135d593b7850242abf5ea0b47dd032fe051c41fa | [
"Apache-2.0"
] | null | null | null | smallrye-reactive-messaging-kafka/src/main/java/io/smallrye/reactive/messaging/kafka/impl/KafkaSink.java | pcasaes/smallrye-reactive-messaging | 135d593b7850242abf5ea0b47dd032fe051c41fa | [
"Apache-2.0"
] | null | null | null | 43.714653 | 124 | 0.636989 | 6,596 | package io.smallrye.reactive.messaging.kafka.impl;
import static io.smallrye.reactive.messaging.kafka.KafkaConnector.TRACER;
import static io.smallrye.reactive.messaging.kafka.i18n.KafkaLogging.log;
import java.time.Duration;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.*;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.apache.kafka.common.serialization.StringSerializer;
import org.eclipse.microprofile.reactive.messaging.Message;
import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams;
import org.eclipse.microprofile.reactive.streams.operators.SubscriberBuilder;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes;
import io.smallrye.mutiny.Uni;
import io.smallrye.mutiny.subscription.UniEmitter;
import io.smallrye.reactive.messaging.TracingMetadata;
import io.smallrye.reactive.messaging.ce.OutgoingCloudEventMetadata;
import io.smallrye.reactive.messaging.health.HealthReport;
import io.smallrye.reactive.messaging.kafka.KafkaCDIEvents;
import io.smallrye.reactive.messaging.kafka.KafkaConnectorOutgoingConfiguration;
import io.smallrye.reactive.messaging.kafka.OutgoingKafkaRecordMetadata;
import io.smallrye.reactive.messaging.kafka.Record;
import io.smallrye.reactive.messaging.kafka.health.KafkaSinkReadinessHealth;
import io.smallrye.reactive.messaging.kafka.impl.ce.KafkaCloudEventHelper;
import io.smallrye.reactive.messaging.kafka.tracing.HeaderInjectAdapter;
import io.vertx.core.AsyncResult;
import io.vertx.core.json.JsonObject;
import io.vertx.kafka.client.producer.KafkaWriteStream;
import io.vertx.mutiny.core.Vertx;
public class KafkaSink {
private final KafkaWriteStream<?, ?> stream;
private final int partition;
private final String topic;
private final String key;
private final SubscriberBuilder<? extends Message<?>, Void> subscriber;
private final long retries;
private final KafkaConnectorOutgoingConfiguration configuration;
private final List<Throwable> failures = new ArrayList<>();
private final KafkaSenderProcessor processor;
private final boolean writeAsBinaryCloudEvent;
private final boolean writeCloudEvents;
private final boolean mandatoryCloudEventAttributeSet;
private final boolean isTracingEnabled;
private final KafkaSinkReadinessHealth health;
private final boolean isHealthEnabled;
public KafkaSink(Vertx vertx, KafkaConnectorOutgoingConfiguration config, KafkaCDIEvents kafkaCDIEvents) {
JsonObject kafkaConfiguration = extractProducerConfiguration(config);
Map<String, Object> kafkaConfigurationMap = kafkaConfiguration.getMap();
stream = KafkaWriteStream.create(vertx.getDelegate(), kafkaConfigurationMap);
stream.exceptionHandler(e -> {
if (config.getTopic().isPresent()) {
log.unableToWrite(config.getChannel(), config.getTopic().get(), e);
} else {
log.unableToWrite(config.getChannel(), e);
}
});
// fire producer event (e.g. bind metrics)
kafkaCDIEvents.producer().fire(stream.unwrap());
partition = config.getPartition();
retries = config.getRetries();
topic = config.getTopic().orElseGet(config::getChannel);
key = config.getKey().orElse(null);
isTracingEnabled = config.getTracingEnabled();
writeCloudEvents = config.getCloudEvents();
writeAsBinaryCloudEvent = config.getCloudEventsMode().equalsIgnoreCase("binary");
boolean waitForWriteCompletion = config.getWaitForWriteCompletion();
this.configuration = config;
this.mandatoryCloudEventAttributeSet = configuration.getCloudEventsType().isPresent()
&& configuration.getCloudEventsSource().isPresent();
// Validate the serializer for structured Cloud Events
if (configuration.getCloudEvents() &&
configuration.getCloudEventsMode().equalsIgnoreCase("structured") &&
!configuration.getValueSerializer().equalsIgnoreCase(StringSerializer.class.getName())) {
log.invalidValueSerializerForStructuredCloudEvent(configuration.getValueSerializer());
throw new IllegalStateException("Invalid value serializer to write a structured Cloud Event. "
+ StringSerializer.class.getName() + " must be used, found: "
+ configuration.getValueSerializer());
}
this.isHealthEnabled = configuration.getHealthEnabled();
if (isHealthEnabled && this.configuration.getHealthReadinessEnabled()) {
this.health = new KafkaSinkReadinessHealth(vertx, config, kafkaConfigurationMap, stream.unwrap());
} else {
this.health = null;
}
long requests = config.getMaxInflightMessages();
if (requests <= 0) {
requests = Long.MAX_VALUE;
}
processor = new KafkaSenderProcessor(requests, waitForWriteCompletion,
writeMessageToKafka());
subscriber = ReactiveStreams.<Message<?>> builder()
.via(processor)
.onError(f -> {
log.unableToDispatch(f);
reportFailure(f);
})
.ignore();
}
private synchronized void reportFailure(Throwable failure) {
// Don't keep all the failures, there are only there for reporting.
if (failures.size() == 10) {
failures.remove(0);
}
failures.add(failure);
}
/**
* List exception for which we should not retry - they are fatal.
* The list comes from https://kafka.apache.org/25/javadoc/org/apache/kafka/clients/producer/Callback.html.
* <p>
* Also included: SerializationException (as the chances to serialize the payload correctly one retry are almost 0).
*/
private static final Set<Class<? extends Throwable>> NOT_RECOVERABLE = new HashSet<>(Arrays.asList(
InvalidTopicException.class,
OffsetMetadataTooLarge.class,
RecordBatchTooLargeException.class,
RecordTooLargeException.class,
UnknownServerException.class,
SerializationException.class));
private Function<Message<?>, Uni<Void>> writeMessageToKafka() {
return message -> {
try {
Optional<OutgoingKafkaRecordMetadata<?>> om = getOutgoingKafkaRecordMetadata(message);
OutgoingKafkaRecordMetadata<?> metadata = om.orElse(null);
String actualTopic = metadata == null || metadata.getTopic() == null ? this.topic : metadata.getTopic();
ProducerRecord<?, ?> record;
OutgoingCloudEventMetadata<?> ceMetadata = message.getMetadata(OutgoingCloudEventMetadata.class)
.orElse(null);
// We encode the outbound record as Cloud Events if:
// - cloud events are enabled -> writeCloudEvents
// - the incoming message contains Cloud Event metadata (OutgoingCloudEventMetadata -> ceMetadata)
// - or if the message does not contain this metadata, the type and source are configured on the channel
if (writeCloudEvents && (ceMetadata != null || mandatoryCloudEventAttributeSet)) {
if (writeAsBinaryCloudEvent) {
record = KafkaCloudEventHelper.createBinaryRecord(message, actualTopic, metadata, ceMetadata,
configuration);
} else {
record = KafkaCloudEventHelper
.createStructuredRecord(message, actualTopic, metadata, ceMetadata,
configuration);
}
} else {
record = getProducerRecord(message, metadata, actualTopic);
}
log.sendingMessageToTopic(message, actualTopic);
//noinspection unchecked,rawtypes
Uni<Void> uni = Uni.createFrom()
.emitter(
e -> stream.send((ProducerRecord) record, ar -> handleWriteResult(ar, message, record, e)));
if (this.retries > 0) {
uni = uni.onFailure(this::isRecoverable).retry()
.withBackOff(Duration.ofSeconds(1), Duration.ofSeconds(20)).atMost(this.retries);
}
return uni
.onFailure().recoverWithUni(t -> {
// Log and nack the messages on failure.
log.nackingMessage(message, actualTopic, t);
return Uni.createFrom().completionStage(message.nack(t));
});
} catch (RuntimeException e) {
log.unableToSendRecord(e);
return Uni.createFrom().failure(e);
}
};
}
private boolean isRecoverable(Throwable f) {
return !NOT_RECOVERABLE.contains(f.getClass());
}
private void handleWriteResult(AsyncResult<?> ar, Message<?> message, ProducerRecord<?, ?> record,
UniEmitter<? super Void> emitter) {
String actualTopic = record.topic();
if (ar.succeeded()) {
log.successfullyToTopic(message, actualTopic);
message.ack().whenComplete((x, f) -> {
if (f != null) {
emitter.fail(f);
} else {
emitter.complete(null);
}
});
} else {
// Fail, there will be retry.
emitter.fail(ar.cause());
}
}
private Optional<OutgoingKafkaRecordMetadata<?>> getOutgoingKafkaRecordMetadata(Message<?> message) {
return message.getMetadata(OutgoingKafkaRecordMetadata.class).map(x -> (OutgoingKafkaRecordMetadata<?>) x);
}
@SuppressWarnings("rawtypes")
private ProducerRecord<?, ?> getProducerRecord(Message<?> message, OutgoingKafkaRecordMetadata<?> om,
String actualTopic) {
int actualPartition = om == null || om.getPartition() <= -1 ? this.partition : om.getPartition();
Object actualKey = getKey(message, om);
long actualTimestamp;
if ((om == null) || (om.getTimestamp() == null)) {
actualTimestamp = -1;
} else {
actualTimestamp = (om.getTimestamp() != null) ? om.getTimestamp().toEpochMilli() : -1;
}
Headers kafkaHeaders = om == null || om.getHeaders() == null ? new RecordHeaders() : om.getHeaders();
createOutgoingTrace(message, actualTopic, actualPartition, kafkaHeaders);
Object payload = message.getPayload();
if (payload instanceof Record) {
payload = ((Record) payload).value();
}
return new ProducerRecord<>(
actualTopic,
actualPartition == -1 ? null : actualPartition,
actualTimestamp == -1L ? null : actualTimestamp,
actualKey,
payload,
kafkaHeaders);
}
@SuppressWarnings({ "rawtypes" })
private Object getKey(Message<?> message,
OutgoingKafkaRecordMetadata<?> metadata) {
// First, the message metadata
if (metadata != null && metadata.getKey() != null) {
return metadata.getKey();
}
// Then, check if the message payload is a record
if (message.getPayload() instanceof Record) {
return ((Record) message.getPayload()).key();
}
// Finally, check the configuration
return key;
}
private void createOutgoingTrace(Message<?> message, String topic, int partition, Headers headers) {
if (isTracingEnabled) {
Optional<TracingMetadata> tracingMetadata = TracingMetadata.fromMessage(message);
final SpanBuilder spanBuilder = TRACER.spanBuilder(topic + " send")
.setSpanKind(Span.Kind.PRODUCER);
if (tracingMetadata.isPresent()) {
// Handle possible parent span
final Context parentSpanContext = tracingMetadata.get().getPreviousContext();
if (parentSpanContext != null) {
spanBuilder.setParent(parentSpanContext);
} else {
spanBuilder.setNoParent();
}
// Handle possible adjacent spans
final SpanContext incomingSpan = tracingMetadata.get().getCurrentSpanContext();
if (incomingSpan != null && incomingSpan.isValid()) {
spanBuilder.addLink(incomingSpan);
}
} else {
spanBuilder.setNoParent();
}
final Span span = spanBuilder.startSpan();
Scope scope = span.makeCurrent();
// Set Span attributes
span.setAttribute("partition", partition);
span.setAttribute(SemanticAttributes.MESSAGING_SYSTEM, "kafka");
span.setAttribute(SemanticAttributes.MESSAGING_DESTINATION, topic);
span.setAttribute(SemanticAttributes.MESSAGING_DESTINATION_KIND, "topic");
// Set span onto headers
GlobalOpenTelemetry.getPropagators().getTextMapPropagator()
.inject(Context.current(), headers, HeaderInjectAdapter.SETTER);
span.end();
scope.close();
}
}
private JsonObject extractProducerConfiguration(KafkaConnectorOutgoingConfiguration config) {
JsonObject kafkaConfiguration = JsonHelper.asJsonObject(config.config());
// Acks must be a string, even when "1".
kafkaConfiguration.put(ProducerConfig.ACKS_CONFIG, config.getAcks());
if (!kafkaConfiguration.containsKey(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) {
log.configServers(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrapServers());
kafkaConfiguration.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrapServers());
}
if (!kafkaConfiguration.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
log.keyDeserializerOmitted();
kafkaConfiguration.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, config.getKeySerializer());
}
if (!kafkaConfiguration.containsKey(ProducerConfig.CLIENT_ID_CONFIG)) {
String id = "kafka-producer-" + config.getChannel();
log.setKafkaProducerClientId(id);
kafkaConfiguration.put(ProducerConfig.CLIENT_ID_CONFIG, id);
}
if (!kafkaConfiguration.containsKey(ProducerConfig.RECONNECT_BACKOFF_MAX_MS_CONFIG)) {
// If no backoff is set, use 10s, it avoids high load on disconnection.
kafkaConfiguration.put(ProducerConfig.RECONNECT_BACKOFF_MAX_MS_CONFIG, "10000");
}
return ConfigurationCleaner.cleanupProducerConfiguration(kafkaConfiguration);
}
public SubscriberBuilder<? extends Message<?>, Void> getSink() {
return subscriber;
}
public void isAlive(HealthReport.HealthReportBuilder builder) {
if (isHealthEnabled) {
List<Throwable> actualFailures;
synchronized (this) {
actualFailures = new ArrayList<>(failures);
}
if (!actualFailures.isEmpty()) {
builder.add(configuration.getChannel(), false,
actualFailures.stream().map(Throwable::getMessage).collect(Collectors.joining()));
} else {
builder.add(configuration.getChannel(), true);
}
}
// If health is disable do not add anything to the builder.
}
public void isReady(HealthReport.HealthReportBuilder builder) {
// This method must not be called from the event loop.
if (health != null) {
health.isReady(builder);
}
// If health is disable do not add anything to the builder.
}
public void closeQuietly() {
if (processor != null) {
processor.cancel();
}
try {
// close() blocks forever (Long.MAX).
this.stream.unwrap().close(Duration.ofMillis(configuration.getCloseTimeout()));
} catch (Throwable e) {
log.errorWhileClosingWriteStream(e);
}
if (health != null) {
health.close();
}
}
}
|
3e0f87efa8a6738328e79a4f7a4c8c4ba6c96314 | 2,385 | java | Java | ocraft-s2client-protocol/src/main/java/com/github/ocraft/s2client/protocol/action/ui/ActionUiSelectLarva.java | JasperGeurtz/ocraft-s2client | 868a86228129619d09431bef47a29b0d40c6fc78 | [
"MIT"
] | 45 | 2017-11-18T15:31:56.000Z | 2022-02-20T11:26:16.000Z | ocraft-s2client-protocol/src/main/java/com/github/ocraft/s2client/protocol/action/ui/ActionUiSelectLarva.java | JasperGeurtz/ocraft-s2client | 868a86228129619d09431bef47a29b0d40c6fc78 | [
"MIT"
] | 44 | 2017-11-25T07:49:12.000Z | 2022-01-04T18:36:14.000Z | ocraft-s2client-protocol/src/main/java/com/github/ocraft/s2client/protocol/action/ui/ActionUiSelectLarva.java | JasperGeurtz/ocraft-s2client | 868a86228129619d09431bef47a29b0d40c6fc78 | [
"MIT"
] | 23 | 2018-05-23T22:17:36.000Z | 2021-11-12T20:03:10.000Z | 32.671233 | 92 | 0.732075 | 6,597 | package com.github.ocraft.s2client.protocol.action.ui;
/*-
* #%L
* ocraft-s2client-protocol
* %%
* Copyright (C) 2017 - 2018 Ocraft Project
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import SC2APIProtocol.Ui;
import com.github.ocraft.s2client.protocol.Sc2ApiSerializable;
import com.github.ocraft.s2client.protocol.Strings;
import static com.github.ocraft.s2client.protocol.Preconditions.require;
public final class ActionUiSelectLarva implements Sc2ApiSerializable<Ui.ActionSelectLarva> {
private static final long serialVersionUID = -5834863791532766043L;
private ActionUiSelectLarva() {
}
public static ActionUiSelectLarva from(Ui.ActionSelectLarva sc2ApiActionSelectLarva) {
require("sc2api action ui select larva", sc2ApiActionSelectLarva);
return new ActionUiSelectLarva();
}
public static ActionUiSelectLarva selectLarva() {
return new ActionUiSelectLarva();
}
@Override
public Ui.ActionSelectLarva toSc2Api() {
return Ui.ActionSelectLarva.newBuilder().build();
}
@Override
public boolean equals(Object o) {
return o == this || o instanceof ActionUiSelectLarva;
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return Strings.toJson(this);
}
}
|
3e0f88436c33bb7ee83d39b8eaf034cbcea24e64 | 2,564 | java | Java | argus/src/main/java/com/moldedbits/argus/LoginFragment.java | moldedbits/argus-android | 4e074bc975a3ba2d14d866cec972adc1e35eedad | [
"Apache-2.0"
] | 105 | 2017-06-23T10:54:13.000Z | 2021-07-17T13:04:54.000Z | argus/src/main/java/com/moldedbits/argus/LoginFragment.java | moldedbits/argus-android | 4e074bc975a3ba2d14d866cec972adc1e35eedad | [
"Apache-2.0"
] | 6 | 2017-06-28T12:42:35.000Z | 2017-12-11T13:04:21.000Z | argus/src/main/java/com/moldedbits/argus/LoginFragment.java | moldedbits/argus-android | 4e074bc975a3ba2d14d866cec972adc1e35eedad | [
"Apache-2.0"
] | 24 | 2017-07-11T06:46:53.000Z | 2021-07-19T19:17:46.000Z | 32.05 | 103 | 0.598674 | 6,598 | package com.moldedbits.argus;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.moldedbits.argus.provider.BaseProvider;
import java.util.List;
/**
* Login Fragment
*/
public class LoginFragment extends BaseFragment {
public static LoginFragment newInstance() {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = super.onCreateView(inflater, container, savedInstanceState);
if (Argus.getInstance().getSignupProviders() == null && rootView != null) {
View view2 = rootView.findViewById(R.id.tv_dont_have_account);
if (view2 != null) {
view2.setVisibility(View.GONE);
}
}
if (rootView != null) {
if (Argus.getInstance().isSkipLoginEnable()) {
TextView textView = (TextView) rootView.findViewById(R.id.tv_skip_login);
if (textView != null) {
String skipText = Argus.getInstance().getSkipLoginText();
if (Argus.getInstance().isSkipLoginEnable()) {
if (!TextUtils.isEmpty(skipText)) {
textView.setText(skipText);
}
}
textView.setVisibility(View.VISIBLE);
setSkipClick(textView);
}
}
}
return rootView;
}
private void setSkipClick(TextView textView) {
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSkipLogin();
}
});
}
public void onSkipLogin() {
//TODO if needed other activity for this we can also do that later
startActivity(Argus.getInstance().getNextScreenProvider().getNextScreen(getActivity()));
getActivity().finish();
}
public int getLayoutId() {
if (Argus.getInstance().getLoginLayout() != 0) {
return Argus.getInstance().getLoginLayout();
}
return R.layout.fragment_login;
}
@Override
protected List<BaseProvider> getProviders() {
return Argus.getInstance().getLoginProviders();
}
}
|
3e0f88db9f8d2ddebb839902b469dd1ad7a757fd | 701 | java | Java | src/main/java/net/metrosystems/mrc/stepdefinitions/LaunchPad.java | catalinmorariu/mrc-selenium-cucumber-java | 745b5a962d18c73c91e51df09f1f635fe7a3d55d | [
"Unlicense",
"MIT"
] | null | null | null | src/main/java/net/metrosystems/mrc/stepdefinitions/LaunchPad.java | catalinmorariu/mrc-selenium-cucumber-java | 745b5a962d18c73c91e51df09f1f635fe7a3d55d | [
"Unlicense",
"MIT"
] | null | null | null | src/main/java/net/metrosystems/mrc/stepdefinitions/LaunchPad.java | catalinmorariu/mrc-selenium-cucumber-java | 745b5a962d18c73c91e51df09f1f635fe7a3d55d | [
"Unlicense",
"MIT"
] | null | null | null | 30.478261 | 73 | 0.620542 | 6,599 | package net.metrosystems.mrc.stepdefinitions;
import com.codeborne.selenide.CollectionCondition;
import io.cucumber.java.en.Then;
import static com.codeborne.selenide.Selenide.$$;
import static com.codeborne.selenide.Selenide.open;
public class LaunchPad {
@Then("go to {string} tile at launchpad")
public void gotToTile(String tileName) {
String[] href = new String[1];
$$(".mrc-tile")
.shouldBe(CollectionCondition.anyMatch("reportTile",
webElement -> {
href[0] = webElement.getAttribute("href");
return href[0] != null && href[0].contains(tileName);
}));
open(href[0]);
}
}
|
3e0f88f0d0c3d101ef6ca293a89d520e437d06b4 | 1,692 | java | Java | lapr3-2019-g045/src/main/java/lapr/project/data/BDUtils.java | joaomfas/LAPR3-2019-2020 | 30360ebddab78a614c1f13721e5b2125c3114a97 | [
"MIT"
] | null | null | null | lapr3-2019-g045/src/main/java/lapr/project/data/BDUtils.java | joaomfas/LAPR3-2019-2020 | 30360ebddab78a614c1f13721e5b2125c3114a97 | [
"MIT"
] | null | null | null | lapr3-2019-g045/src/main/java/lapr/project/data/BDUtils.java | joaomfas/LAPR3-2019-2020 | 30360ebddab78a614c1f13721e5b2125c3114a97 | [
"MIT"
] | null | null | null | 36.782609 | 100 | 0.634752 | 6,600 | package lapr.project.data;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BDUtils {
DataHandler dh = new DataHandler();
String folderPath = System.getProperty("user.dir");
public void startBD() {
try {
dh.scriptRunner(folderPath + "/src/main/resources/BaseDeDados/tabelas.sql");
dh.scriptRunner(folderPath + "/src/main/resources/BaseDeDados/functions.sql");
dh.scriptRunner(folderPath + "/src/main/resources/BaseDeDados/inserts.sql");
dh.scriptRunner(folderPath + "/src/main/resources/BaseDeDados/triggers.sql");
} catch (SQLException | IOException ex) {
Logger.getLogger(BDUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void startBDFacade() {
try {
dh.scriptRunner("../lapr3-2019-g045" + "/src/main/resources/BaseDeDados/tabelas.sql");
dh.scriptRunner("../lapr3-2019-g045" + "/src/main/resources/BaseDeDados/functions.sql");
dh.scriptRunner("../lapr3-2019-g045" + "/src/main/resources/BaseDeDados/inserts.sql");
dh.scriptRunner("../lapr3-2019-g045" + "/src/main/resources/BaseDeDados/triggers.sql");
} catch (SQLException | IOException ex) {
Logger.getLogger(BDUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void runStript(String sript) {
try {
dh.scriptRunner(folderPath + sript);
} catch (SQLException | IOException ex) {
Logger.getLogger(BDUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
3e0f8b07c268b8a3df4b92e777ba53e3bd2bf628 | 95 | java | Java | oops/Interfaces/Student.java | tripathisharad/JAVA-WITH-DS-ALGO | abd40f9abbc44af698d877bd13d1b0b9924e5251 | [
"Apache-2.0"
] | null | null | null | oops/Interfaces/Student.java | tripathisharad/JAVA-WITH-DS-ALGO | abd40f9abbc44af698d877bd13d1b0b9924e5251 | [
"Apache-2.0"
] | null | null | null | oops/Interfaces/Student.java | tripathisharad/JAVA-WITH-DS-ALGO | abd40f9abbc44af698d877bd13d1b0b9924e5251 | [
"Apache-2.0"
] | null | null | null | 13.571429 | 36 | 0.715789 | 6,601 | package oops.Interfaces;
public abstract interface Student {
abstract void study();
}
|
3e0f8b92dd7d9b9e772058f0e7d604d56269c33d | 1,450 | java | Java | guava-testlib/src/com/google/common/collect/testing/NavigableSetTestSuiteBuilder.java | omapzoom/platform-external-guava | 87ffc45d2619a0c178a058de887e3050bb577efe | [
"Apache-2.0"
] | 3 | 2015-06-21T12:37:25.000Z | 2021-05-11T08:08:07.000Z | guava-testlib/src/com/google/common/collect/testing/NavigableSetTestSuiteBuilder.java | omapzoom/platform-external-guava | 87ffc45d2619a0c178a058de887e3050bb577efe | [
"Apache-2.0"
] | null | null | null | guava-testlib/src/com/google/common/collect/testing/NavigableSetTestSuiteBuilder.java | omapzoom/platform-external-guava | 87ffc45d2619a0c178a058de887e3050bb577efe | [
"Apache-2.0"
] | 15 | 2015-11-19T15:16:30.000Z | 2019-07-05T22:39:02.000Z | 32.954545 | 78 | 0.743448 | 6,602 | /*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.testers.SetNavigationTester;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a NavigableSet implementation.
*/
public final class NavigableSetTestSuiteBuilder<E>
extends SetTestSuiteBuilder<E> {
public static <E> NavigableSetTestSuiteBuilder<E> using(
TestSetGenerator<E> generator) {
NavigableSetTestSuiteBuilder<E> builder =
new NavigableSetTestSuiteBuilder<E>();
builder.usingGenerator(generator);
return builder;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
Helpers.copyToList(super.getTesters());
testers.add(SetNavigationTester.class);
return testers;
}
}
|
3e0f8ba9ea0998e6552513b485fed2620bdad862 | 777 | java | Java | extension/kobdig/src/main/java/kobdig/gui/AgentFileFilter.java | AjroudRami/PFE | dfdc223ffb2db23d8173782fc5caa7f903479726 | [
"MIT"
] | null | null | null | extension/kobdig/src/main/java/kobdig/gui/AgentFileFilter.java | AjroudRami/PFE | dfdc223ffb2db23d8173782fc5caa7f903479726 | [
"MIT"
] | null | null | null | extension/kobdig/src/main/java/kobdig/gui/AgentFileFilter.java | AjroudRami/PFE | dfdc223ffb2db23d8173782fc5caa7f903479726 | [
"MIT"
] | null | null | null | 20.447368 | 78 | 0.6139 | 6,603 | package kobdig.gui;
import java.io.File;
/**
* A filter for the file chooser to visualize KOBDIG agent program files only.
* A KOBDIG agent file is recognized by the extension ".apl".
*
* @author Andrea G. B. Tettamanzi
*/
public class AgentFileFilter extends KobdigFileFilter
{
/**
* Accept all directories and all KOBDIG agent files.
*/
@Override
public boolean accept(File f)
{
if(f.isDirectory())
return true;
String extension = getExtension(f);
if(extension!=null)
return extension.equals("apl");
return false;
}
/**
* The description of this filter
*/
@Override
public String getDescription()
{
return "KOBDIG agent program files";
}
}
|
3e0f8be59ea02975e78603abbe1c28e96ae5a008 | 1,370 | java | Java | worf-log/src/main/java/orj/worf/log/dto/OpenAccountDTO.java | liu-project/worf | c4372bb17f44ac964631759104e71e106d8f703f | [
"Apache-2.0"
] | null | null | null | worf-log/src/main/java/orj/worf/log/dto/OpenAccountDTO.java | liu-project/worf | c4372bb17f44ac964631759104e71e106d8f703f | [
"Apache-2.0"
] | 7 | 2020-05-15T22:05:51.000Z | 2021-08-25T15:46:25.000Z | worf-log/src/main/java/orj/worf/log/dto/OpenAccountDTO.java | liu-project/worf | c4372bb17f44ac964631759104e71e106d8f703f | [
"Apache-2.0"
] | null | null | null | 21.076923 | 69 | 0.617518 | 6,604 | package orj.worf.log.dto;
/**
* 开户
* @author LiuZhenghua
* 2018年4月19日 下午3:53:12
*/
public class OpenAccountDTO extends ServiceLogDTO {
/** 用户编号*/
private Integer uid;
/** 用户角色
private Byte userRole;
/** IP地址 */
private String ip;
/** 开户类型,1:普通用户开户,2:合作方开户 */
private Byte flag;
/**是否开通集团账户 0未开通 1开通 */
private Byte isOpGroupAccount;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Byte getFlag() {
return flag;
}
public void setFlag(Byte flag) {
this.flag = flag;
}
public Byte getIsOpGroupAccount() {
return isOpGroupAccount;
}
public void setIsOpGroupAccount(Byte isOpGroupAccount) {
this.isOpGroupAccount = isOpGroupAccount;
}
public OpenAccountDTO(Integer uid, String ip, Byte flag,
Byte isOpGroupAccount) {
super();
this.uid = uid;
this.ip = ip;
this.flag = flag;
this.isOpGroupAccount = isOpGroupAccount;
}
public OpenAccountDTO() {
super();
}
@Override
public String toString() {
return "{\"uid\":\"" + uid + "\",\"ip\":\"" + ip + "\",\"flag\":\""
+ flag + "\",\"isOpGroupAccount\":\"" + isOpGroupAccount
+ "\",\"type\":\"" + type + "\",\"code\":\"" + code
+ "\",\"desc\":\"" + desc + "\",\"timestamp\":\"" + timestamp
+ "\"}";
}
}
|
3e0f8ef4784f32e8b5a44b1e46d31f312f875c69 | 4,260 | java | Java | Java/src/test/java/com/gildedrose/GildedRoseTest.java | sushi1215/GildedRose-Refactoring-Kata | 81bfdccf828ac6b807a3f1caef1515a9d515883a | [
"MIT"
] | null | null | null | Java/src/test/java/com/gildedrose/GildedRoseTest.java | sushi1215/GildedRose-Refactoring-Kata | 81bfdccf828ac6b807a3f1caef1515a9d515883a | [
"MIT"
] | null | null | null | Java/src/test/java/com/gildedrose/GildedRoseTest.java | sushi1215/GildedRose-Refactoring-Kata | 81bfdccf828ac6b807a3f1caef1515a9d515883a | [
"MIT"
] | null | null | null | 26.625 | 110 | 0.681925 | 6,605 | package com.gildedrose;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class GildedRoseTest {
@Test
void foo() {
Item[] items = new Item[] { new Item("foo", 0, 0) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertEquals("foo", app.items[0].name);
assertEquals(0, app.items[0].quality);
assertEquals(-1, app.items[0].sellIn);
}
@Test
public void shouldLowerBothValues() {
Item[] items = new Item[] { new Item("foobar", 1, 1) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertEquals(0, app.items[0].quality);
assertEquals(0, app.items[0].sellIn);
}
@Test
public void shouldDowngradeTwiceAsFastAfterSellDate() {
Item[] items = new Item[] { new Item("foobar", 1, 5) };
GildedRose app = new GildedRose(items);
// day 1, drop by 1
app.updateQuality();
assertEquals(4, app.items[0].quality);
assertEquals(0, app.items[0].sellIn);
// day 2, drop by 2
app.updateQuality();
assertEquals(2, app.items[0].quality);
assertEquals(-1, app.items[0].sellIn);
}
@Test
public void shouldNeverHaveANegativeQuality() {
Item[] items = new Item[] { new Item("foobar", 0, 0) };
GildedRose app = new GildedRose(items);
// day 1, drop by 1
app.updateQuality();
assertEquals(0, app.items[0].quality);
// day 2, drop by 1 => quality is still 0
app.updateQuality();
assertEquals(0, app.items[0].quality);
}
@Test
public void shouldSeeAgedBrieIncreasedQualityDayByDay() {
Item[] items = new Item[] { new Item("Aged Brie", 0, 0) };
GildedRose app = new GildedRose(items);
// day 1, add 2
app.updateQuality();
assertEquals(2, app.items[0].quality);
// day 2, add 2
app.updateQuality();
assertEquals(4, app.items[0].quality);
}
@Test
public void shouldNeverHaveQualityHigherThan50() {
Item[] items = new Item[] { new Item("Aged Brie", 0, 49) };
GildedRose app = new GildedRose(items);
// day 1, add 2
app.updateQuality();
assertEquals(50, app.items[0].quality);
// day 2, add 2
app.updateQuality();
assertEquals(50, app.items[0].quality);
}
@Test
public void shouldSulfrasNotChangeQty() {
Item[] items = new Item[] { new Item("Sulfuras, Hand of Ragnaros", 0, 10) };
GildedRose app = new GildedRose(items);
// day 1, don't impact quality
app.updateQuality();
assertEquals(10, app.items[0].quality);
assertEquals(0, app.items[0].sellIn);
}
@Test
public void checkForBackStagePasses() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 5, 10) };
GildedRose app = new GildedRose(items);
// day 1, increase by 3 the quality
app.updateQuality();
assertEquals(13, app.items[0].quality);
assertEquals(4, app.items[0].sellIn);
// day 1, increase by 3 the quality
app.updateQuality();
assertEquals(16, app.items[0].quality);
assertEquals(3, app.items[0].sellIn);
}
@Test
public void shouldIncreaseQualityBasedOnSellIn() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 10, 10),
new Item("Backstage passes to a TAFKAL80ETC concert", 5, 10) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertEquals(12, app.items[0].quality);
assertEquals(9, app.items[0].sellIn);
assertEquals(13, app.items[1].quality);
assertEquals(4, app.items[1].sellIn);
}
public void shouldSulfurasNeverAltersForSulfuras() {
Item[] items = new Item[] { new Item("Sulfuras, Hand of Ragnaros", 10, 80) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertEquals(80, app.items[0].quality);
}
@Test
public void shouldHaveQualityDroppingToZeroAfterConcert() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 0, 10) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertEquals(0, app.items[0].quality);
assertEquals(-1, app.items[0].sellIn);
}
@Test
public void shouldDegradeConjureItemsTwiceAsNormal() {
Item[] items = new Item[] { new Item("Conjured Mana Cake", 10, 10), new Item("Conjured Mana Cake", 0, 10) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertEquals(8, app.items[0].quality);
assertEquals(6, app.items[1].quality);
}
}
|
3e0f8f0669695f1aa494fd4fdab39fa93bdf94ee | 2,709 | java | Java | src/nl/vu/cs/ajira/examples/aurora/data/StreamTuple.java | karmaresearch/ajira | 7dc12a780c71e663b7c996f93a66da2d0dff6764 | [
"Apache-2.0"
] | 3 | 2017-10-23T22:03:55.000Z | 2018-11-18T09:58:09.000Z | src/nl/vu/cs/ajira/examples/aurora/data/StreamTuple.java | jrbn/ajira | 8f3b1583993b565bbaf4f1fddf70c88c3461fafc | [
"Apache-2.0"
] | null | null | null | src/nl/vu/cs/ajira/examples/aurora/data/StreamTuple.java | jrbn/ajira | 8f3b1583993b565bbaf4f1fddf70c88c3461fafc | [
"Apache-2.0"
] | null | null | null | 27.09 | 120 | 0.655223 | 6,606 | package nl.vu.cs.ajira.examples.aurora.data;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import nl.vu.cs.ajira.data.types.SimpleData;
import nl.vu.cs.ajira.data.types.TString;
import nl.vu.cs.ajira.data.types.Tuple;
import nl.vu.cs.ajira.data.types.TupleFactory;
/**
* Special kind of Tuple composed of <attribute, value> pairs.
*
* Given the restrictions of Ajira in extending the Tuple class, it is implemented as a wrapper of Tuple, which provides
* all the methods require to access and manipulate pairs' values.
*
* @author Alessandro Margara
*/
public class StreamTuple {
private final Tuple tuple;
private LinkedHashMap<String, SimpleData> attributes;
public StreamTuple(Tuple tuple) {
this.tuple = tuple;
}
public StreamTuple(SimpleData... data) {
tuple = TupleFactory.newTuple(data);
}
public StreamTuple(LinkedHashMap<String, SimpleData> attributes) {
int numElements = attributes.size() * 2;
SimpleData[] data = new SimpleData[numElements];
int pos = 0;
for (String name : attributes.keySet()) {
data[pos++] = new TString(name);
data[pos++] = attributes.get(name);
}
tuple = TupleFactory.newTuple(data);
this.attributes = attributes;
}
public Tuple getTuple() {
return tuple;
}
/**
* Return the list of attributes' names (in the order in which they appear in the tuple)
*/
public List<String> getAttributes() {
List<String> result = new ArrayList<String>();
for (int i = 0; i < tuple.getNElements(); i += 2) {
String elem = ((TString) tuple.get(i)).getValue();
result.add(elem);
}
return result;
}
/**
* Return the position of the value of attribute in the tuple, or -1 if the attribute is not found.
*/
public int getPositionOfValueFor(String attribute) {
for (int i = 0; i < tuple.getNElements(); i += 2) {
String elem = ((TString) tuple.get(i)).getValue();
if (elem.equals(attribute)) {
return i + 1;
}
}
return -1;
}
/**
* Return the value for the give attribute.
*/
public SimpleData getValueFor(String attribute) {
initAttributesMap();
return attributes.get(attribute);
}
/**
* Return the value in the given position.
*/
public SimpleData getValueIn(int pos) {
return tuple.get(pos);
}
private void initAttributesMap() {
if (attributes != null) {
return;
}
attributes = new LinkedHashMap<String, SimpleData>();
for (int i = 0; i < tuple.getNElements(); i += 2) {
String name = ((TString) tuple.get(i)).getValue();
SimpleData value = tuple.get(i + 1);
attributes.put(name, value);
}
}
} |
3e0f8fc67e0e63ac3e25d126e8e30bd830203d4f | 1,961 | java | Java | src/main/java/net/reflxction/impuritybot/data/minecraft/IgnManager.java | ReflxctionDev/ImpurityBotX | fdebb090c21ff2f2f657a06ec13e01beba529347 | [
"Apache-2.0"
] | 1 | 2018-06-18T15:09:41.000Z | 2018-06-18T15:09:41.000Z | src/main/java/net/reflxction/impuritybot/data/minecraft/IgnManager.java | ReflxctionDev/ImpurityBotX | fdebb090c21ff2f2f657a06ec13e01beba529347 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/reflxction/impuritybot/data/minecraft/IgnManager.java | ReflxctionDev/ImpurityBotX | fdebb090c21ff2f2f657a06ec13e01beba529347 | [
"Apache-2.0"
] | null | null | null | 32.147541 | 79 | 0.676186 | 6,607 | /*
* * Copyright 2017-2018 github.com/ReflxctionDev
*
* 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.reflxction.impuritybot.data.minecraft;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.User;
import net.reflxction.impuritybot.data.DataManager;
import net.reflxction.impuritybot.data.IDataManager;
import net.reflxction.impuritybot.main.ImpurityBot;
import net.reflxction.impuritybot.utils.guild.GuildUtils;
import java.util.ArrayList;
import java.util.List;
public class IgnManager implements IDataManager {
private ImpurityBot bot = ImpurityBot.getBot();
private DataManager du = new DataManager(bot);
public void setIGN(User u, String ign) {
bot.getIgnsFile().set("IGNs." + u.getId() + ".Name", u.getName());
bot.getIgnsFile().set("IGNs." + u.getId() + ".IGN", ign);
du.saveIgnsFile();
}
public String getIGN(User u) {
String ign = bot.getIgnsFile().getString("IGNs." + u.getId() + ".IGN");
return ign == null ? "NO IGN" : ign;
}
public List<User> getUserByIGN(String ign) {
List<User> users = new ArrayList<>();
for (Member m : GuildUtils.members()) {
if (getIGN(m.getUser()).equalsIgnoreCase(ign)) {
users.add(m.getUser());
}
}
return users;
}
public boolean hasAssignedIGN(User u) {
return !getIGN(u).equals("NO IGN");
}
}
|
3e0f904a3aa7f44933522463e7fa095ce8a09178 | 1,684 | java | Java | server-config/src/main/java/org/apache/directory/server/config/beans/DhcpServerBean.java | motoponk/directory-server | 2a7dc89e3e905fd7ea3ace9a04fac561af594f56 | [
"Apache-2.0"
] | 86 | 2015-02-03T04:58:06.000Z | 2022-03-08T10:55:45.000Z | server-config/src/main/java/org/apache/directory/server/config/beans/DhcpServerBean.java | motoponk/directory-server | 2a7dc89e3e905fd7ea3ace9a04fac561af594f56 | [
"Apache-2.0"
] | 21 | 2016-05-17T13:48:07.000Z | 2021-11-15T11:03:24.000Z | server-config/src/main/java/org/apache/directory/server/config/beans/DhcpServerBean.java | motoponk/directory-server | 2a7dc89e3e905fd7ea3ace9a04fac561af594f56 | [
"Apache-2.0"
] | 82 | 2015-03-29T03:16:06.000Z | 2022-02-20T04:59:19.000Z | 25.621212 | 81 | 0.644589 | 6,608 | /*
* 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.directory.server.config.beans;
/**
* A class used to store the DhcpServer configuration.
*
* @author <a href="mailto:efpyi@example.com">Apache Directory Project</a>
*/
public class DhcpServerBean extends DSBasedServerBean
{
/**
* Create a new DhcpServerBean instance
*/
public DhcpServerBean()
{
super();
// Enabled by default
setEnabled( true );
}
/**
* {@inheritDoc}
*/
@Override
public String toString( String tabs )
{
StringBuilder sb = new StringBuilder();
sb.append( tabs ).append( "DhcpServer :\n" );
sb.append( super.toString( tabs + " " ) );
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return toString( "" );
}
}
|
3e0f916862f8c0b34e55c78966e661a65c5c30c6 | 4,031 | java | Java | src/main/java/snownee/kiwi/tile/InventoryTile.java | jihuayu/Kiwi | 4620c22f2307bf709e28181d32f6bdfe8d04a16e | [
"MIT"
] | 1 | 2020-05-26T11:56:10.000Z | 2020-05-26T11:56:10.000Z | src/main/java/snownee/kiwi/tile/InventoryTile.java | jihuayu/Kiwi | 4620c22f2307bf709e28181d32f6bdfe8d04a16e | [
"MIT"
] | null | null | null | src/main/java/snownee/kiwi/tile/InventoryTile.java | jihuayu/Kiwi | 4620c22f2307bf709e28181d32f6bdfe8d04a16e | [
"MIT"
] | null | null | null | 26.873333 | 120 | 0.588936 | 6,609 | package snownee.kiwi.tile;
//package snownee.kiwi.tile;
//
//import java.util.List;
//
//import javax.annotation.Nonnull;
//import javax.annotation.Nullable;
//
//import net.minecraft.init.Items;
//import net.minecraft.item.ItemStack;
//import net.minecraft.nbt.NBTTagCompound;
//import net.minecraft.util.EnumFacing;
//import net.minecraftforge.common.capabilities.Capability;
//import net.minecraftforge.common.util.Constants;
//import net.minecraftforge.items.CapabilityItemHandler;
//import net.minecraftforge.items.ItemStackHandler;
//
//public class TileInventoryBase extends TileBase
//{
// public class StackHandler extends ItemStackHandler
// {
// private final int stackLimit;
//
// @Deprecated
// StackHandler(TileInventoryBase tile, int slot, int stackLimit)
// {
// this(slot, stackLimit);
// }
//
// StackHandler(int slot, int stackLimit)
// {
// super(slot);
// this.stackLimit = stackLimit;
// }
//
// @Override
// public int getSlotLimit(int slot)
// {
// return stackLimit;
// }
//
// public List<ItemStack> getStacks()
// {
// return stacks;
// }
//
// @Override
// public boolean isItemValid(int slot, ItemStack stack)
// {
// return isItemValidForSlot(slot, stack);
// }
//
// @Nonnull
// @Override
// public ItemStack insertItem(int slot, ItemStack stack, boolean simulate)
// {
// if (!isItemValid(slot, stack))
// {
// return stack;
// }
// return super.insertItem(slot, stack, simulate);
// }
//
// @Override
// protected void onContentsChanged(int slot)
// {
// TileInventoryBase.this.onContentsChanged(slot);
// }
// }
//
// public final StackHandler stacks;
//
// @SuppressWarnings("deprecation")
// public TileInventoryBase(int slot)
// {
// this(slot, Items.AIR.getItemStackLimit()); // Default to a standard stack
// }
//
// public TileInventoryBase(int slot, int stackLimit)
// {
// stacks = new StackHandler(slot, stackLimit);
// }
//
// @Override
// public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing)
// {
// return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
// }
//
// @Override
// public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing)
// {
// if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
// {
// return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(stacks);
// }
// return super.getCapability(capability, facing);
// }
//
// @Override
// public void readFromNBT(NBTTagCompound compound)
// {
// super.readFromNBT(compound);
// if (compound.hasKey("Items", Constants.NBT.TAG_COMPOUND))
// {
// stacks.deserializeNBT(compound.getCompoundTag("Items"));
// }
// }
//
// @Nonnull
// @Override
// public NBTTagCompound writeToNBT(NBTTagCompound compound)
// {
// super.writeToNBT(compound);
// compound.setTag("Items", stacks.serializeNBT());
// return compound;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// protected void readPacketData(NBTTagCompound data)
// {
// this.stacks.deserializeNBT(data.getCompoundTag("Items"));
// }
//
// /**
// * {@inheritDoc}
// */
// @Nonnull
// @Override
// protected NBTTagCompound writePacketData(NBTTagCompound data)
// {
// data.setTag("Items", this.stacks.serializeNBT());
// return data;
// }
//
// public boolean isItemValidForSlot(int index, ItemStack stack)
// {
// return true;
// }
//
// public void onContentsChanged(int slot)
// {
// refresh();
// }
//
//}
|
3e0f91fbf72626df2d0c3f3a59ca950a36fdb3f0 | 1,659 | java | Java | src/main/java/musee/LeBatch.java | Yirou/Musee | c6370099f0c527efd53cde831fa26002632c39a9 | [
"MIT"
] | null | null | null | src/main/java/musee/LeBatch.java | Yirou/Musee | c6370099f0c527efd53cde831fa26002632c39a9 | [
"MIT"
] | null | null | null | src/main/java/musee/LeBatch.java | Yirou/Musee | c6370099f0c527efd53cde831fa26002632c39a9 | [
"MIT"
] | null | null | null | 28.118644 | 129 | 0.553345 | 6,610 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package musee;
import java.util.logging.Level;
import java.util.logging.Logger;
import musee.etatDemande.EtatPrisEnCharge;
/**
*
* @author yirou
*/
public class LeBatch implements Runnable{
Thread t;
int tempsMaxi=20;
int tempsDebut=0;
Demande d;
Musee musee;
public LeBatch(Demande d,Musee musee) {
this.d=d;
this.musee=musee;
t=new Thread(this);
t.start();
}
public int nombreAlea(int min,int max){
return (int) (Math.random() * ( max - min ));
}
@Override
public void run() {
while(tempsDebut<=tempsMaxi){
try {
Thread.sleep(1000);
tempsDebut++;
// System.out.println("jatend sinon j'attribue automatiquement");
if(tempsDebut==tempsMaxi&& this.d.getEtat().getClass().getSimpleName().equalsIgnoreCase("EtatNonPrisEnCharge")){
int a=nombreAlea(0, musee.listePhotoGraphe.size()-1);
Photographe p=musee.listePhotoGraphe.get(a);
p.demandePrisEnCharge.add(d);
d.setIdHistorien(a);
d.setEtat(new EtatPrisEnCharge(d));
}
} catch (InterruptedException ex) {
Logger.getLogger(LeBatch.class.getName()).log(Level.SEVERE, null, ex);
}
}
tempsDebut=0;
}
}
|
3e0f9258a175f90a6d3ab7232c891f3d4fe836e0 | 1,717 | java | Java | app/src/main/java/com/fidesmo/ble/client/models/Capabilities.java | fidesmo/apdu-over-ble-android | b79af50e030e266f4e99fe61055625a2b10addc1 | [
"MIT"
] | 11 | 2017-04-19T12:22:52.000Z | 2021-01-19T19:16:57.000Z | app/src/main/java/com/fidesmo/ble/client/models/Capabilities.java | fidesmo/apdu-over-ble-android | b79af50e030e266f4e99fe61055625a2b10addc1 | [
"MIT"
] | 2 | 2018-04-04T13:35:58.000Z | 2018-05-21T12:54:43.000Z | app/src/main/java/com/fidesmo/ble/client/models/Capabilities.java | fidesmo/apdu-over-ble-android | b79af50e030e266f4e99fe61055625a2b10addc1 | [
"MIT"
] | 1 | 2021-09-13T02:46:22.000Z | 2021-09-13T02:46:22.000Z | 30.122807 | 157 | 0.674432 | 6,611 | package com.fidesmo.ble.client.models;
public class Capabilities {
private final long platformVersion;
private final Integer mifareType;
private final Integer uidSize;
private final Integer jcVersion;
private final Integer osTypeVersion;
private final Integer globalPlatformVersion;
public Capabilities(long platformVersion, Integer mifareType, Integer uidSize, Integer jcVersion, Integer osTypeVersion, Integer globalPlatformVersion) {
this.platformVersion = platformVersion;
this.mifareType = mifareType;
this.uidSize = uidSize;
this.jcVersion = jcVersion;
this.osTypeVersion = osTypeVersion;
this.globalPlatformVersion = globalPlatformVersion;
}
public long getPlatformVersion() {
return platformVersion;
}
public Integer getMifareType() {
return mifareType;
}
public Integer getUidSize() {
return uidSize;
}
public Integer getJcVersion() {
return jcVersion;
}
public Integer getOsTypeVersion() {
return osTypeVersion;
}
public Integer getGlobalPlatformVersion() {
return globalPlatformVersion;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Capabilities{");
sb.append("platformVersion=").append(platformVersion);
sb.append(", mifareType=").append(mifareType);
sb.append(", uidSize=").append(uidSize);
sb.append(", jcVersion=").append(jcVersion);
sb.append(", osTypeVersion=").append(osTypeVersion);
sb.append(", globalPlatformVersion=").append(globalPlatformVersion);
sb.append('}');
return sb.toString();
}
}
|
3e0f9281962146bfe6f24229317bea663809c731 | 1,273 | java | Java | game/service/src/test/java/be/gerard/game/service/schema/GameSchemaExportTest.java | bartgerard/ubrew | c31b55ade55319e51801a73da83c697a577f5b4f | [
"Apache-2.0"
] | 1 | 2016-12-24T17:35:09.000Z | 2016-12-24T17:35:09.000Z | game/service/src/test/java/be/gerard/game/service/schema/GameSchemaExportTest.java | bartgerard/ubrew | c31b55ade55319e51801a73da83c697a577f5b4f | [
"Apache-2.0"
] | null | null | null | game/service/src/test/java/be/gerard/game/service/schema/GameSchemaExportTest.java | bartgerard/ubrew | c31b55ade55319e51801a73da83c697a577f5b4f | [
"Apache-2.0"
] | null | null | null | 33.5 | 131 | 0.819324 | 6,612 | package be.gerard.game.service.schema;
import be.gerard.common.db.config.EmbeddedDataSourceConfig;
import be.gerard.common.db.schema.SchemaExporter;
import be.gerard.game.service.config.GameDatabaseConfig;
import org.hibernate.dialect.MySQLDialect;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* CoreAuthenticationSchemaExportTest
*
* @author bartgerard
* @version 0.0.1
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
EmbeddedDataSourceConfig.class,
GameDatabaseConfig.class
})
@Transactional
public class GameSchemaExportTest extends SchemaExporter {
@Autowired
private LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean;
@Test
public void export() throws ClassNotFoundException {
export(MySQLDialect.class, "game", localContainerEntityManagerFactoryBean.getPersistenceUnitInfo().getManagedClassNames());
}
}
|
3e0f9281dab826a77624b54abc7c570dc00743f8 | 8,180 | java | Java | src/org/jmockit/internal/expectations/mocking/MockedClassModifier.java | jmockit/jmockit2 | 34ae9f0667bac4107df59fffcf3bfc4effa2c669 | [
"MIT"
] | 34 | 2015-10-08T03:54:01.000Z | 2022-02-23T06:27:09.000Z | src/org/jmockit/internal/expectations/mocking/MockedClassModifier.java | jmockit/jmockit2 | 34ae9f0667bac4107df59fffcf3bfc4effa2c669 | [
"MIT"
] | 1 | 2019-02-24T15:48:30.000Z | 2019-02-25T15:31:51.000Z | src/org/jmockit/internal/expectations/mocking/MockedClassModifier.java | jmockit/jmockit2 | 34ae9f0667bac4107df59fffcf3bfc4effa2c669 | [
"MIT"
] | 12 | 2016-07-07T20:17:15.000Z | 2021-01-21T08:34:47.000Z | 38.046512 | 119 | 0.695477 | 6,613 | package org.jmockit.internal.expectations.mocking;
import static java.lang.reflect.Modifier.*;
import org.jmockit.external.asm.*;
import static org.jmockit.external.asm.Opcodes.*;
import org.jmockit.internal.*;
import static org.jmockit.internal.MockingFilters.*;
import org.jmockit.internal.expectations.*;
import static org.jmockit.internal.expectations.mocking.MockedTypeModifier.*;
import org.jmockit.internal.util.*;
import static org.jmockit.internal.util.ObjectMethods.*;
import static org.jmockit.internal.util.Utilities.*;
import javax.annotation.*;
final class MockedClassModifier extends BaseClassModifier
{
private static final boolean NATIVE_UNSUPPORTED = !HOTSPOT_VM;
private static final int METHOD_ACCESS_MASK = ACC_PRIVATE + ACC_SYNTHETIC + ACC_ABSTRACT;
private static final int PUBLIC_OR_PROTECTED = ACC_PUBLIC + ACC_PROTECTED;
@Nullable private final MockedType mockedType;
private final boolean classFromNonBootstrapClassLoader;
private String className;
private boolean ignoreConstructors;
private ExecutionMode executionMode;
private boolean isProxy;
@Nullable private String defaultFilters;
MockedClassModifier(
@Nullable ClassLoader classLoader, @Nonnull ClassReader classReader, @Nullable MockedType typeMetadata
) {
super(classReader);
mockedType = typeMetadata;
classFromNonBootstrapClassLoader = classLoader != null;
setUseClassLoadingBridge(classLoader);
executionMode = ExecutionMode.Regular;
useInstanceBasedMockingIfApplicable();
}
private void useInstanceBasedMockingIfApplicable() {
if (mockedType != null && mockedType.isInjectable()) {
ignoreConstructors = true;
executionMode = ExecutionMode.PerInstance;
}
}
@Override
public void visit(
int version, int access, @Nonnull String name, @Nullable String signature, @Nullable String superName,
@Nullable String[] interfaces
) {
validateMockingOfJREClass(name);
super.visit(version, access, name, signature, superName, interfaces);
isProxy = "java/lang/reflect/Proxy".equals(superName);
if (isProxy) {
assert interfaces != null;
className = interfaces[0];
defaultFilters = null;
}
else {
className = name;
defaultFilters = filtersForClass(name);
if (defaultFilters != null && defaultFilters.isEmpty()) {
throw VisitInterruptedException.INSTANCE;
}
}
}
private void validateMockingOfJREClass(@Nonnull String internalName) {
if (internalName.startsWith("java/")) {
if (isUnmockable(internalName)) {
throw new IllegalArgumentException("Class " + internalName.replace('/', '.') + " is not mockable");
}
if (executionMode == ExecutionMode.Regular && mockedType != null && isFullMockingDisallowed(internalName)) {
String modifyingClassName = internalName.replace('/', '.');
if (modifyingClassName.equals(mockedType.getClassType().getName())) {
throw new IllegalArgumentException(
"Class " + internalName.replace('/', '.') + " cannot be @Mocked fully; " +
"instead, use @Injectable or partial mocking");
}
}
}
}
@Override
public void visitInnerClass(
@Nonnull String name, @Nullable String outerName, @Nullable String innerName, int access
) {
cw.visitInnerClass(name, outerName, innerName, access);
}
@Nullable @Override
public MethodVisitor visitMethod(
int access, @Nonnull String name, @Nonnull String desc, @Nullable String signature, @Nullable String[] exceptions
) {
if ((access & METHOD_ACCESS_MASK) != 0) {
return unmodifiedBytecode(access, name, desc, signature, exceptions);
}
boolean visitingConstructor = "<init>".equals(name);
String internalClassName = className;
if (visitingConstructor) {
if (isConstructorNotAllowedByMockingFilters(name)) {
return unmodifiedBytecode(access, name, desc, signature, exceptions);
}
startModifiedMethodVersion(access, name, desc, signature, exceptions);
generateCallToSuperConstructor();
}
else {
if (isMethodNotToBeMocked(access, name, desc)) {
return unmodifiedBytecode(access, name, desc, signature, exceptions);
}
if ("<clinit>".equals(name)) {
return stubOutClassInitializationIfApplicable(access);
}
if (stubOutFinalizeMethod(access, name, desc)) {
return null;
}
startModifiedMethodVersion(access, name, desc, signature, exceptions);
}
ExecutionMode actualExecutionMode = determineAppropriateExecutionMode(visitingConstructor);
if (useClassLoadingBridge) {
return generateCallToHandlerThroughMockingBridge(visitingConstructor);
}
generateDirectCallToHandler(mw, internalClassName, access, name, desc, signature, actualExecutionMode);
generateDecisionBetweenReturningOrContinuingToRealImplementation();
// Constructors of non-JRE classes can't be modified (unless running with "-noverify") in a way that
// "super(...)/this(...)" get called twice, so we disregard such calls when copying the original bytecode.
return copyOriginalImplementationCode(visitingConstructor);
}
private boolean isConstructorNotAllowedByMockingFilters(@Nonnull String name) {
return isProxy || ignoreConstructors || isUnmockableInvocation(defaultFilters, name);
}
private boolean isMethodNotToBeMocked(int access, @Nonnull String name, @Nonnull String desc) {
return
isNative(access) && (NATIVE_UNSUPPORTED || (access & PUBLIC_OR_PROTECTED) == 0) ||
(isProxy || executionMode == ExecutionMode.Partial) && (
isMethodFromObject(name, desc) || "annotationType".equals(name) && "()Ljava/lang/Class;".equals(desc)
);
}
@Nonnull
private MethodVisitor unmodifiedBytecode(
int access, @Nonnull String name, @Nonnull String desc, @Nullable String signature, @Nullable String[] exceptions
){
return cw.visitMethod(access, name, desc, signature, exceptions);
}
@Nullable
private MethodVisitor stubOutClassInitializationIfApplicable(int access) {
startModifiedMethodVersion(access, "<clinit>", "()V", null, null);
return mw;
}
private boolean stubOutFinalizeMethod(int access, @Nonnull String name, @Nonnull String desc) {
if ("finalize".equals(name) && "()V".equals(desc)) {
startModifiedMethodVersion(access, name, desc, null, null);
generateEmptyImplementation();
return true;
}
return false;
}
@Nonnull
private ExecutionMode determineAppropriateExecutionMode(boolean visitingConstructor) {
if (executionMode == ExecutionMode.PerInstance) {
if (visitingConstructor) {
return ignoreConstructors ? ExecutionMode.Regular : ExecutionMode.Partial;
}
if (isStatic(methodAccess)) {
return ExecutionMode.Partial;
}
}
return executionMode;
}
@Nonnull
private MethodVisitor generateCallToHandlerThroughMockingBridge(boolean visitingConstructor) {
// Copies the entire original implementation even for a constructor, in which case the complete bytecode inside
// the constructor fails the strict verification activated by "-Xfuture". However, this is necessary to allow the
// full execution of a bootstrap class constructor when the call was not meant to be mocked.
return copyOriginalImplementationCode(visitingConstructor && classFromNonBootstrapClassLoader);
}
private void generateDecisionBetweenReturningOrContinuingToRealImplementation() {
Label startOfRealImplementation = new Label();
mw.visitInsn(DUP);
mw.visitLdcInsn(VOID_TYPE);
mw.visitJumpInsn(IF_ACMPEQ, startOfRealImplementation);
generateReturnWithObjectAtTopOfTheStack(methodDesc);
mw.visitLabel(startOfRealImplementation);
mw.visitInsn(POP);
}
}
|
3e0f92df9e29df00a387ad2c17ea5f73a79eae8d | 5,553 | java | Java | src/de/halirutan/keypromoterx/KeyPromoterNotification.java | tiagozc/IntelliJ-Key-Promoter-X | 97bfc35ce304b156ad4c0e84c45e97aa5db820a6 | [
"BSD-3-Clause"
] | 2,903 | 2017-08-10T07:31:15.000Z | 2022-03-29T03:16:31.000Z | src/de/halirutan/keypromoterx/KeyPromoterNotification.java | tiagozc/IntelliJ-Key-Promoter-X | 97bfc35ce304b156ad4c0e84c45e97aa5db820a6 | [
"BSD-3-Clause"
] | 91 | 2017-08-09T07:23:41.000Z | 2022-03-31T08:26:26.000Z | src/de/halirutan/keypromoterx/KeyPromoterNotification.java | tiagozc/IntelliJ-Key-Promoter-X | 97bfc35ce304b156ad4c0e84c45e97aa5db820a6 | [
"BSD-3-Clause"
] | 81 | 2017-08-04T14:19:14.000Z | 2022-02-06T16:47:57.000Z | 48.286957 | 758 | 0.733117 | 6,614 | /*
* Copyright (c) 2017 Patrick Scheibe, Dmitry Kashin, Athiele.
*
* 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. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.halirutan.keypromoterx;
import com.intellij.notification.*;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.keymap.impl.ui.EditKeymapsDialog;
import de.halirutan.keypromoterx.statistic.KeyPromoterStatistics;
import org.jetbrains.annotations.NotNull;
/**
* A custom notification class that allows for creating 1. tips if a short cut was missed and 2. a balloon asking if
* the user wants to create a shortcut for an action that doesn't have one.
*
* @author Patrick Scheibe.
*/
public class KeyPromoterNotification {
private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup(
KeyPromoterBundle.message("kp.notification.group")
);
public static void showStartupNotification() {
final Notification notification = GROUP.createNotification(KeyPromoterBundle.message(
"kp.notification.group"),
KeyPromoterBundle.message("kp.notification.startup"),
NotificationType.INFORMATION)
.setIcon(KeyPromoterIcons.KP_ICON)
.addAction(new BrowseNotificationAction(
KeyPromoterBundle.message("kp.notification.startup.link.name"),
KeyPromoterBundle.message("kp.notification.startup.link"))
);
notification.notify(null);
}
static void showTip(KeyPromoterAction action, int count) {
String message = KeyPromoterBundle.message("kp.notification.tip", action.getDescription(), count);
final Notification notification = GROUP.createNotification(KeyPromoterBundle.message(
"kp.notification.group"),
message,
NotificationType.INFORMATION)
.setIcon(KeyPromoterIcons.KP_ICON)
.addAction(new EditKeymapAction(action, action.getShortcut()))
.addAction(new SuppressTipAction(action));
notification.notify(null);
}
static void askToCreateShortcut(KeyPromoterAction action) {
Notification notification = GROUP.createNotification(
KeyPromoterBundle.message("kp.notification.group"),
KeyPromoterBundle.message("kp.notification.ask.new.shortcut", action.getDescription()),
NotificationType.INFORMATION
)
.setIcon(KeyPromoterIcons.KP_ICON)
.addAction(new EditKeymapAction(action))
.addAction(new SuppressTipAction(action));
notification.notify(null);
}
/**
* Provides click-able links to IDEA actions. On click, the keymap editor is opened showing the exact line where
* the shortcut of an action can be edited/created.
*/
private static class EditKeymapAction extends NotificationAction {
private final KeyPromoterAction myAction;
EditKeymapAction(KeyPromoterAction action) {
super(action.getDescription());
this.myAction = action;
}
EditKeymapAction(KeyPromoterAction action, String buttonText) {
super(buttonText);
this.myAction = action;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) {
EditKeymapsDialog dialog = new EditKeymapsDialog(null, myAction.getIdeaActionID());
ApplicationManager.getApplication().invokeLater(dialog::show);
}
}
private static class SuppressTipAction extends NotificationAction {
private final KeyPromoterStatistics statistics = ApplicationManager.getApplication().getService(KeyPromoterStatistics.class);
private final KeyPromoterAction myAction;
SuppressTipAction(KeyPromoterAction action) {
super(KeyPromoterBundle.message("kp.notification.disable.message"));
myAction = action;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) {
statistics.suppressItem(myAction);
notification.expire();
}
}
}
|
3e0f92ecf6b08de757d6683e76af6a0f63995146 | 1,545 | java | Java | ham/app/src/main/java/org/kendar/servers/AnsweringDnsServer.java | kendarorg/HttpAnsweringMachine | 9659fe92844500dce8a7b910a956cb26dba87237 | [
"MIT"
] | 2 | 2022-01-17T07:45:16.000Z | 2022-03-16T22:01:35.000Z | ham/app/src/main/java/org/kendar/servers/AnsweringDnsServer.java | kendarorg/HttpAnsweringMachine | 9659fe92844500dce8a7b910a956cb26dba87237 | [
"MIT"
] | 39 | 2022-01-20T14:23:42.000Z | 2022-03-31T12:06:47.000Z | ham/app/src/main/java/org/kendar/servers/AnsweringDnsServer.java | kendarorg/HttpAnsweringMachine | 9659fe92844500dce8a7b910a956cb26dba87237 | [
"MIT"
] | 1 | 2022-03-07T22:31:59.000Z | 2022-03-07T22:31:59.000Z | 27.589286 | 97 | 0.739159 | 6,615 | package org.kendar.servers;
import org.kendar.dns.DnsQueries;
import org.kendar.dns.DnsServer;
import org.kendar.dns.configurations.DnsConfig;
import org.kendar.servers.http.PluginsInitializer;
import org.kendar.utils.LoggerBuilder;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class AnsweringDnsServer implements AnsweringServer {
private final JsonConfiguration configuration;
private final Logger logger;
private final DnsServer dnsServer;
private boolean running = false;
public AnsweringDnsServer(
LoggerBuilder loggerBuilder,
DnsServer dnsServer,
JsonConfiguration configuration,
PluginsInitializer pluginsInitializer) {
this.logger = loggerBuilder.build(AnsweringDnsServer.class);
this.dnsServer = dnsServer;
this.configuration = configuration;
pluginsInitializer.addSpecialLogger(DnsQueries.class.getName(), "DNS Logging (DEBUG,TRACE)");
}
public void isSystem() {}
@Override
public void run() {
if (running) return;
var config = configuration.getConfiguration(DnsConfig.class);
if (!config.isActive()) return;
running = true;
try {
dnsServer.run();
} catch (IOException | InterruptedException e) {
logger.error("Error running DNS server",e);
} finally {
running = false;
}
}
@Override
public boolean shouldRun() {
var localConfig = configuration.getConfiguration(DnsConfig.class);
return localConfig.isActive() && !running;
}
}
|
3e0f933ccc9b087d0c209d5756db2e107869d1e9 | 376 | java | Java | TIJ4/06permission/src/access/ChocolateChip2.java | woilanlan/java-example | a24c11b5a330525be15072f02621664a388c0bcb | [
"MIT"
] | null | null | null | TIJ4/06permission/src/access/ChocolateChip2.java | woilanlan/java-example | a24c11b5a330525be15072f02621664a388c0bcb | [
"MIT"
] | null | null | null | TIJ4/06permission/src/access/ChocolateChip2.java | woilanlan/java-example | a24c11b5a330525be15072f02621664a388c0bcb | [
"MIT"
] | null | null | null | 16.347826 | 56 | 0.606383 | 6,616 | package access;
import access.dessert.Cookie2;
/**
* ChocolateChip
*/
public class ChocolateChip2 extends Cookie2 {
public ChocolateChip2() {
System.out.println("ChocolateChip Constructor");
}
public void chomp() {
bite();
}
public static void show() {
ChocolateChip2 x = new ChocolateChip2();
x.chomp();
}
} |
3e0f961dfece8f34561b90c2a501ce956536be83 | 4,849 | java | Java | herald/src/main/java/io/heraldprox/herald/sensor/ble/BLETimer.java | pivotal-djoo/herald-for-android | 751f9311df92d19d6525812575c68baedf5a02f6 | [
"Apache-2.0"
] | 16 | 2020-09-24T22:37:48.000Z | 2021-03-27T16:50:51.000Z | herald/src/main/java/io/heraldprox/herald/sensor/ble/BLETimer.java | pivotal-djoo/herald-for-android | 751f9311df92d19d6525812575c68baedf5a02f6 | [
"Apache-2.0"
] | 100 | 2020-09-29T14:57:16.000Z | 2021-02-16T20:04:02.000Z | herald/src/main/java/io/heraldprox/herald/sensor/ble/BLETimer.java | pivotal-djoo/herald-for-android | 751f9311df92d19d6525812575c68baedf5a02f6 | [
"Apache-2.0"
] | 14 | 2020-09-24T20:34:58.000Z | 2021-03-22T05:06:23.000Z | 36.734848 | 120 | 0.646525 | 6,617 | // Copyright 2020-2021 Herald Project Contributors
// SPDX-License-Identifier: Apache-2.0
//
package io.heraldprox.herald.sensor.ble;
import android.content.Context;
import android.os.PowerManager;
import io.heraldprox.herald.sensor.data.ConcreteSensorLogger;
import io.heraldprox.herald.sensor.data.SensorLogger;
import io.heraldprox.herald.sensor.datatype.Distribution;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
/**
* Steady one second timer for controlling BLE operations. Having a reliable timer for starting
* and stopping scans is fundamental for reliable detection and tracking. Methods that have been
* tested and failed included :
* 1. Handler.postDelayed loop backed by MainLooper
* - Actual delay time can drift to 10+ minutes for a 4 second request.
* 2. Handler.postDelayed loop backed by dedicated looper backed by dedicated HandlerThread
* - Slightly better than option (1) but actual delay time can still drift to several minutes for a 4 second request.
* 3. Timer scheduled task loop
* - Timer can drift
* <p>
* Test impact of power management by ...
* <p>
* 1. Run app on device
* 2. Keep one device connected via USB only
* 3. Put app in background mode and lock device
* 4. Go to terminal
* 5. cd ~/Library/Android/sdk/platform-tools
* <p>
* Test DOZE mode
* 1. ./adb shell dumpsys battery unplug
* 2. Expect "powerSource=battery" on log
* 3. ./adb shell dumpsys deviceidle force-idle
* 4. Expect "idle=true" on log
* <p>
* Exit DOZE mode
* 1. ./adb shell dumpsys deviceidle unforce
* 2. ./adb shell dumpsys battery reset
* 3. Expect "idle=false" and "powerSource=usb/ac" on log
* <p>
* Test APP STANDBY mode
* 1. ./adb shell dumpsys battery unplug
* 2. Expect "powerSource=battery"
* 3. ./adb shell am set-inactive io.heraldprox.herald true
* <p>
* Exit APP STANDBY mode
* 1. ./adb shell am set-inactive io.heraldprox.herald false
* 2. ./adb shell am get-inactive io.heraldprox.herald
* 3. Expect "idle=false" on terminal
* 4. ./adb shell dumpsys battery reset
* 5. Expect "powerSource=usb/ac" on log
*/
public class BLETimer {
private final SensorLogger logger = new ConcreteSensorLogger("Sensor", "BLETimer");
private final Distribution distribution = new Distribution();
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
private final PowerManager.WakeLock wakeLock;
private final AtomicLong now = new AtomicLong(0);
private final Queue<BLETimerDelegate> delegates = new ConcurrentLinkedQueue<>();
private final Runnable runnable = new Runnable() {
@Override
public void run() {
for (BLETimerDelegate delegate : delegates) {
try {
delegate.bleTimer(now.get());
} catch (Throwable e) {
logger.fault("delegate execution failed", e);
}
}
}
};
@SuppressLint("WakelockTimeout")
public BLETimer(@NonNull final Context context) {
final PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Sensor:BLETimer");
wakeLock.acquire(); // Deliberate use wakelock forever and actively manage sleep time so as not to waste battery
final Thread timerThread = new Thread(new Runnable() {
private long last = 0;
@Override
public void run() {
while (true) {
now.set(System.currentTimeMillis());
final long elapsed = now.get() - last;
if (elapsed >= 1000) {
if (last != 0) {
distribution.add(elapsed);
executorService.execute(runnable);
}
last = now.get();
}
try {
Thread.sleep(500);
} catch (Throwable e) {
logger.fault("Timer interrupted", e);
}
}
}
});
timerThread.setPriority(Thread.MAX_PRIORITY);
timerThread.setName("Sensor.BLETimer");
timerThread.start();
}
@Override
protected void finalize() {
wakeLock.release();
}
/**
* Add delegate for time notification.
* @param delegate Delegate for receiving notifications
*/
public void add(@NonNull final BLETimerDelegate delegate) {
delegates.add(delegate);
}
}
|
3e0f97ef4b56a65a591eb0dbe6f917efa386a8e5 | 3,637 | java | Java | udc/udc-serv/src/main/java/com/paypal/udc/entity/dataset/DatasetStorageSystem.java | Susheendar/gimel | 62008e377ef7ff80890dadda63ee0fc4a6119367 | [
"Apache-2.0"
] | 222 | 2018-04-08T16:41:49.000Z | 2022-02-20T16:29:02.000Z | udc/udc-serv/src/main/java/com/paypal/udc/entity/dataset/DatasetStorageSystem.java | Susheendar/gimel | 62008e377ef7ff80890dadda63ee0fc4a6119367 | [
"Apache-2.0"
] | 173 | 2018-04-08T16:50:59.000Z | 2022-01-21T19:34:22.000Z | udc/udc-serv/src/main/java/com/paypal/udc/entity/dataset/DatasetStorageSystem.java | Susheendar/gimel | 62008e377ef7ff80890dadda63ee0fc4a6119367 | [
"Apache-2.0"
] | 102 | 2018-04-08T16:45:06.000Z | 2022-02-01T11:24:57.000Z | 26.165468 | 82 | 0.712675 | 6,618 | package com.paypal.udc.entity.dataset;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@Entity
@Table(name = "pc_storage_dataset_system")
public class DatasetStorageSystem implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@ApiModelProperty(notes = "The database generated dataset attribute value ID")
@Column(name = "storage_system_dataset_id")
@NotNull
private long storageSystemDatasetId;
@ApiModelProperty(notes = "Name of the storage attribute")
@Column(name = "storage_system_id")
@NotNull
private long storageSystemId;
@ApiModelProperty(notes = "Dataset ID")
@Column(name = "storage_dataset_id")
@NotNull
private long storageDataSetId;
@ApiModelProperty(notes = "Is the Storage Workspace active ?")
@Column(name = "is_active_y_n")
@JsonIgnore
private String isActiveYN;
@ApiModelProperty(notes = "Created User")
@Column(name = "cre_user")
@NotNull
@JsonIgnore
private String createdUser;
@ApiModelProperty(notes = "Created Timestamp")
@Column(name = "cre_ts")
@NotNull
@JsonIgnore
private String createdTimestamp;
@ApiModelProperty(notes = "Updated User")
@Column(name = "upd_user")
@JsonIgnore
private String updatedUser;
@ApiModelProperty(notes = "Updated Timestamp")
@Column(name = "upd_ts")
@JsonIgnore
private String updatedTimestamp;
public long getStorageSystemDatasetId() {
return this.storageSystemDatasetId;
}
public void setStorageSystemDatasetId(final long storageSystemDatasetId) {
this.storageSystemDatasetId = storageSystemDatasetId;
}
public long getStorageSystemId() {
return this.storageSystemId;
}
public void setStorageSystemId(final long storageSystemId) {
this.storageSystemId = storageSystemId;
}
public long getStorageDataSetId() {
return this.storageDataSetId;
}
public void setStorageDataSetId(final long storageDataSetId) {
this.storageDataSetId = storageDataSetId;
}
public String getIsActiveYN() {
return this.isActiveYN;
}
public void setIsActiveYN(final String isActiveYN) {
this.isActiveYN = isActiveYN;
}
@JsonIgnore
public String getCreatedUser() {
return this.createdUser;
}
@JsonProperty
public void setCreatedUser(final String createdUser) {
this.createdUser = createdUser;
}
@JsonIgnore
public String getCreatedTimestamp() {
return this.createdTimestamp;
}
@JsonProperty
public void setCreatedTimestamp(final String createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
@JsonIgnore
public String getUpdatedUser() {
return this.updatedUser;
}
@JsonProperty
public void setUpdatedUser(final String updatedUser) {
this.updatedUser = updatedUser;
}
@JsonIgnore
public String getUpdatedTimestamp() {
return this.updatedTimestamp;
}
@JsonProperty
public void setUpdatedTimestamp(final String updatedTimestamp) {
this.updatedTimestamp = updatedTimestamp;
}
}
|
3e0f985b6e05192a82167ea24fae91e16f852187 | 2,039 | java | Java | java_mysql/src/java/in/flipbrain/dto/ContentDto.java | bsodhi/flipbrain | 3c36f77c81155c848c85fc775efa77f755b89912 | [
"MIT"
] | null | null | null | java_mysql/src/java/in/flipbrain/dto/ContentDto.java | bsodhi/flipbrain | 3c36f77c81155c848c85fc775efa77f755b89912 | [
"MIT"
] | null | null | null | java_mysql/src/java/in/flipbrain/dto/ContentDto.java | bsodhi/flipbrain | 3c36f77c81155c848c85fc775efa77f755b89912 | [
"MIT"
] | null | null | null | 30.893939 | 88 | 0.61746 | 6,619 | /*
Copyright 2015 Balwinder Sodhi
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 in.flipbrain.dto;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author auser
*/
public class ContentDto extends BaseDto {
public long contentId;
public String contentType;
public String url;
public String title;
public String description;
public boolean isPrivate;
public long userId;
public String tags;
public static String YT_URL_MAIN="www.youtube.com";
public static String YT_URL_SHORT="youtu.be";
public static String YT_URL_EMBED="http://www.youtube-nocookie.com/embed/";
public static String YT_URL_THUMBNAIL="http://img.youtube.com/vi/{0}/hqdefault.jpg";
public static String getVideoIdFromUrl(String url) {
String vid=null;
try {
URL u = new URL(url);
String host = u.getHost();
String path = u.getPath();
String q = u.getQuery();
if(YT_URL_MAIN.equalsIgnoreCase(host) &&
"/watch".equalsIgnoreCase(path)) {
String[] qp = q.split("&");
for(String p : qp) {
if (p.equals("v")) {
vid=p.split("=")[1];
break;
}
}
} else if(YT_URL_SHORT.equalsIgnoreCase(host)) {
vid=path.substring(1);
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
return vid;
}
}
|
3e0f98604d3af47aca6e39e2da884535a523a7db | 7,346 | java | Java | src/main/java/fossilsarcheology/client/model/ModelNautilus.java | gabrielnido/FossilsArcheologyRevival | 083b6e59f468b9f817fb5259efc7fd1c0f44df45 | [
"CC-BY-4.0"
] | 70 | 2016-08-21T17:44:49.000Z | 2022-02-19T12:36:13.000Z | src/main/java/fossilsarcheology/client/model/ModelNautilus.java | gabrielnido/FossilsArcheologyRevival | 083b6e59f468b9f817fb5259efc7fd1c0f44df45 | [
"CC-BY-4.0"
] | 1,465 | 2016-07-16T15:24:41.000Z | 2022-03-18T16:28:15.000Z | src/main/java/fossilsarcheology/client/model/ModelNautilus.java | gabrielnido/FossilsArcheologyRevival | 083b6e59f468b9f817fb5259efc7fd1c0f44df45 | [
"CC-BY-4.0"
] | 56 | 2016-08-07T18:13:19.000Z | 2022-03-29T15:56:28.000Z | 54.014706 | 130 | 0.641438 | 6,620 | package fossilsarcheology.client.model;
import fossilsarcheology.server.entity.prehistoric.EntityNautilus;
import net.ilexiconn.llibrary.client.model.tools.AdvancedModelBase;
import net.ilexiconn.llibrary.client.model.tools.AdvancedModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
public class ModelNautilus extends AdvancedModelBase {
public final AdvancedModelRenderer shell;
public final AdvancedModelRenderer head;
public final AdvancedModelRenderer flap;
public final AdvancedModelRenderer tenticle_0;
public final AdvancedModelRenderer tenticle_1;
public final AdvancedModelRenderer tenticle_2;
public final AdvancedModelRenderer tenticle_3;
public final AdvancedModelRenderer tenticle_4;
public final AdvancedModelRenderer tenticle_5;
public ModelNautilus() {
this.textureWidth = 64;
this.textureHeight = 32;
this.head = new AdvancedModelRenderer(this, 40, 0);
this.head.setRotationPoint(0.0F, 0.7F, 0.0F);
this.head.addBox(-1.5F, -2.5F, -4.5F, 3, 5, 5, 0.0F);
this.setRotateAngle(head, 0.004537856055185257F, 0.0F, 0.0F);
this.tenticle_5 = new AdvancedModelRenderer(this, 30, 9);
this.tenticle_5.setRotationPoint(1.3F, 1.7F, -4.5F);
this.tenticle_5.addBox(0.0F, -0.5F, -4.0F, 0, 1, 4, 0.0F);
this.setRotateAngle(tenticle_5, 0.0F, -0.3490658503988659F, 0.7853981633974483F);
this.tenticle_0 = new AdvancedModelRenderer(this, 30, 9);
this.tenticle_0.setRotationPoint(-1.3F, -0.5F, -4.5F);
this.tenticle_0.addBox(0.0F, -0.5F, -4.0F, 0, 1, 4, 0.0F);
this.setRotateAngle(tenticle_0, 0.0F, 0.3490658503988659F, 0.7853981633974483F);
this.tenticle_4 = new AdvancedModelRenderer(this, 30, 9);
this.tenticle_4.setRotationPoint(1.3F, 0.6F, -4.5F);
this.tenticle_4.addBox(0.0F, -0.5F, -4.0F, 0, 1, 4, 0.0F);
this.setRotateAngle(tenticle_4, 0.0F, -0.4363323129985824F, 0.0F);
this.tenticle_2 = new AdvancedModelRenderer(this, 30, 9);
this.tenticle_2.setRotationPoint(-1.3F, 1.7F, -4.5F);
this.tenticle_2.addBox(0.0F, -0.5F, -4.0F, 0, 1, 4, 0.0F);
this.setRotateAngle(tenticle_2, 0.0F, 0.3490658503988659F, -0.7853981633974483F);
this.flap = new AdvancedModelRenderer(this, 20, 2);
this.flap.setRotationPoint(0.0F, -3.9F, 0.0F);
this.flap.addBox(-2.0F, 0.0F, -6.0F, 4, 2, 6, 0.0F);
this.setRotateAngle(flap, 0.27314402793711257F, 0.0F, 0.0F);
this.tenticle_3 = new AdvancedModelRenderer(this, 30, 9);
this.tenticle_3.setRotationPoint(1.3F, -0.5F, -4.5F);
this.tenticle_3.addBox(0.0F, -0.5F, -4.0F, 0, 1, 4, 0.0F);
this.setRotateAngle(tenticle_3, 0.0F, -0.3490658503988659F, -0.7853981633974483F);
this.tenticle_1 = new AdvancedModelRenderer(this, 30, 9);
this.tenticle_1.setRotationPoint(-1.3F, 0.6F, -4.5F);
this.tenticle_1.addBox(0.0F, -0.5F, -4.0F, 0, 1, 4, 0.0F);
this.setRotateAngle(tenticle_1, 0.0F, 0.4363323129985824F, 0.0F);
this.shell = new AdvancedModelRenderer(this, 0, 0);
this.shell.setRotationPoint(0.0F, 20.0F, -1.3F);
this.shell.addBox(-2.5F, -6.0F, 0.0F, 5, 10, 10, 0.0F);
this.setRotateAngle(shell, 0.07144541004295828F, 0.0F, -0.004841412281086836F);
this.shell.addChild(this.head);
this.head.addChild(this.tenticle_5);
this.head.addChild(this.tenticle_0);
this.head.addChild(this.tenticle_4);
this.head.addChild(this.tenticle_2);
this.shell.addChild(this.flap);
this.head.addChild(this.tenticle_3);
this.head.addChild(this.tenticle_1);
this.updateDefaultPose();
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
this.shell.render(f5);
}
@Override
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) {
this.resetToDefaultPose();
float speed = 0.2F;
shell.rotateAngleY = (float) Math.toRadians(180);
if (entity instanceof EntityLiving && !((EntityLiving) entity).isAIDisabled()) {
if (!entity.isInWater()) {
this.shell.rotateAngleZ = (float) Math.toRadians(90);
this.shell.rotationPointY = 21.5F;
this.shell.rotationPointZ = 5F;
} else {
this.bob(shell, -speed, 0.5F, true, f2, 1);
}
{
float shellProgress = ((EntityNautilus) entity).shellProgress;
sitAnimationRotation(flap, shellProgress, (float) Math.toRadians(75), 0, 0);
sitAnimationRotation(tenticle_0, shellProgress, -(float) Math.toRadians(20), 0, 0);
sitAnimationRotation(tenticle_1, shellProgress, -(float) Math.toRadians(25), 0, 0);
sitAnimationRotation(tenticle_2, shellProgress, -(float) Math.toRadians(20), -(float) Math.toRadians(20), 0);
sitAnimationRotation(tenticle_3, shellProgress, (float) Math.toRadians(20), 0, 0);
sitAnimationRotation(tenticle_4, shellProgress, (float) Math.toRadians(25), 0, 0);
sitAnimationRotation(tenticle_5, shellProgress, (float) Math.toRadians(20), (float) Math.toRadians(20), 0);
sitAnimationOffset(tenticle_0, shellProgress, -0.1F, 0, -0.25F);
sitAnimationOffset(tenticle_1, shellProgress, -0.1F, 0, -0.25F);
sitAnimationOffset(tenticle_2, shellProgress, -0.1F, 0, -0.25F);
sitAnimationOffset(tenticle_3, shellProgress, 0.1F, 0, -0.25F);
sitAnimationOffset(tenticle_4, shellProgress, 0.1F, 0, -0.25F);
sitAnimationOffset(tenticle_5, shellProgress, 0.1F, 0, -0.25F);
sitAnimationOffset(head, shellProgress, 0, 0, -0.35F);
if (shellProgress == 0) {
tenticle_0.swing(speed, 0.4F, false, 0, 0, f2, 1);
tenticle_1.swing(speed, 0.4F, false, 0, 0, f2, 1);
tenticle_2.swing(speed, 0.4F, false, 0, 0, f2, 1);
tenticle_3.swing(speed, 0.4F, true, 0, 0, f2, 1);
tenticle_4.swing(speed, 0.4F, true, 0, 0, f2, 1);
tenticle_5.swing(speed, 0.4F, true, 0, 0, f2, 1);
}
}
}
}
public void sitAnimationOffset(AdvancedModelRenderer modelRenderer, float progress, float x, float y, float z) {
modelRenderer.offsetX -= progress * x / 20.0F;
modelRenderer.offsetY -= progress * y / 20.0F;
modelRenderer.offsetZ -= progress * z / 20.0F;
}
public void sitAnimationRotation(AdvancedModelRenderer modelRenderer, float sitProgress, float rotX, float rotY, float rotZ) {
modelRenderer.rotateAngleX = sitProgress * rotX / 20.0F;
modelRenderer.rotateAngleY += sitProgress * rotY / 20.0F;
modelRenderer.rotateAngleZ += sitProgress * rotZ / 20.0F;
}
public void setRotateAngle(AdvancedModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}
|
3e0f98841b66138c4b9ea626876a46ec37d9ff55 | 1,344 | java | Java | main/boofcv-feature/src/test/java/boofcv/abst/feature/describe/TestSurfPlanar_to_DescribeRegionPoint.java | gatordevin/BoofCV | 3b84fec5f32fc2919756aaedc6c15c1e6ec1d0d9 | [
"Apache-2.0"
] | null | null | null | main/boofcv-feature/src/test/java/boofcv/abst/feature/describe/TestSurfPlanar_to_DescribeRegionPoint.java | gatordevin/BoofCV | 3b84fec5f32fc2919756aaedc6c15c1e6ec1d0d9 | [
"Apache-2.0"
] | null | null | null | main/boofcv-feature/src/test/java/boofcv/abst/feature/describe/TestSurfPlanar_to_DescribeRegionPoint.java | gatordevin/BoofCV | 3b84fec5f32fc2919756aaedc6c15c1e6ec1d0d9 | [
"Apache-2.0"
] | null | null | null | 34.461538 | 103 | 0.774554 | 6,621 | /*
* Copyright (c) 2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.abst.feature.describe;
import boofcv.factory.feature.describe.FactoryDescribeRegionPoint;
import boofcv.struct.feature.TupleDesc_F64;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.ImageType;
import boofcv.struct.image.Planar;
/**
* @author Peter Abeles
*/
class TestSurfPlanar_to_DescribeRegionPoint extends GenericDescribeRegionPointChecks<Planar<GrayF32>> {
TestSurfPlanar_to_DescribeRegionPoint() {
super(ImageType.pl(3,GrayF32.class));
}
@Override
protected DescribeRegionPoint<Planar<GrayF32>, TupleDesc_F64> createAlg() {
return (DescribeRegionPoint) FactoryDescribeRegionPoint.surfColorStable(null, imageType);
}
}
|
3e0f99e7c43b98e36909b5bb800ddc3ca7726d0e | 1,468 | java | Java | december-2020-leetcoding-challenge/src/main/java/org/redquark/leetcode/challenge/Problem31_LargestRectangleInHistogram.java | ani03sha/Leetcoding | 033cd78afb6c9b46299ea701372f12d00f0f4417 | [
"MIT"
] | 4 | 2020-10-11T11:01:20.000Z | 2022-02-03T19:26:50.000Z | december-2020-leetcoding-challenge/src/main/java/org/redquark/leetcode/challenge/Problem31_LargestRectangleInHistogram.java | ani03sha/Leetcoding | 033cd78afb6c9b46299ea701372f12d00f0f4417 | [
"MIT"
] | null | null | null | december-2020-leetcoding-challenge/src/main/java/org/redquark/leetcode/challenge/Problem31_LargestRectangleInHistogram.java | ani03sha/Leetcoding | 033cd78afb6c9b46299ea701372f12d00f0f4417 | [
"MIT"
] | 2 | 2020-10-27T10:14:54.000Z | 2020-11-08T14:23:45.000Z | 30.583333 | 106 | 0.554496 | 6,622 | package org.redquark.leetcode.challenge;
import java.util.Arrays;
import java.util.Stack;
/**
* @author Anirudh Sharma
* <p>
* Given n non-negative integers representing the histogram's bar height where the width of each bar is 1,
* find the area of largest rectangle in the histogram.
*/
public class Problem31_LargestRectangleInHistogram {
/**
* @param heights - heights of the histogram
* @return area of largest rectangle
*/
public int largestRectangleArea(int[] heights) {
// Base condition
if (heights == null || heights.length == 0) {
return 0;
}
if (heights.length == 1) {
return heights[0];
}
// Stack to store values
Stack<Integer> stack = new Stack<>();
// Copy array
int[] copy = Arrays.copyOf(heights, heights.length + 1);
// This variable will score the max area
int maxArea = 0;
// Index to iterate array
int index = 0;
// Loop through the copy array
while (index < copy.length) {
if (stack.isEmpty() || copy[index] > copy[stack.peek()]) {
stack.push(index);
index++;
} else {
int i = stack.pop();
int localArea = copy[i] * (stack.isEmpty() ? index : index - stack.peek() - 1);
maxArea = Math.max(maxArea, localArea);
}
}
return maxArea;
}
}
|
3e0f9a0f6830ecf5b6f0ea137ebc74cee97395e4 | 14,536 | java | Java | core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 3 | 2017-05-24T01:14:09.000Z | 2018-07-23T10:07:29.000Z | core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | null | null | null | core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixConsistentMap.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 8 | 2016-11-08T21:32:18.000Z | 2021-07-29T13:58:04.000Z | 41.89049 | 117 | 0.675014 | 6,623 | /*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.primitives.resources.impl;
import io.atomix.copycat.client.CopycatClient;
import io.atomix.resource.AbstractResource;
import io.atomix.resource.ResourceTypeInfo;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.onlab.util.Match;
import org.onlab.util.Tools;
import org.onosproject.store.primitives.MapUpdate;
import org.onosproject.store.primitives.TransactionId;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.Clear;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.ContainsKey;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.ContainsValue;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.EntrySet;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.Get;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.GetOrDefault;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.IsEmpty;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.KeySet;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.Listen;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.Size;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.TransactionBegin;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.TransactionCommit;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.TransactionPrepare;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.TransactionPrepareAndCommit;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.TransactionRollback;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.Unlisten;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.UpdateAndGet;
import org.onosproject.store.primitives.resources.impl.AtomixConsistentMapCommands.Values;
import org.onosproject.store.service.AsyncConsistentMap;
import org.onosproject.store.service.ConsistentMapException;
import org.onosproject.store.service.MapEvent;
import org.onosproject.store.service.MapEventListener;
import org.onosproject.store.service.TransactionLog;
import org.onosproject.store.service.Version;
import org.onosproject.store.service.Versioned;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
* Distributed resource providing the {@link AsyncConsistentMap} primitive.
*/
@ResourceTypeInfo(id = -151, factory = AtomixConsistentMapFactory.class)
public class AtomixConsistentMap extends AbstractResource<AtomixConsistentMap>
implements AsyncConsistentMap<String, byte[]> {
private final Set<Consumer<Status>> statusChangeListeners = Sets.newCopyOnWriteArraySet();
private final Map<MapEventListener<String, byte[]>, Executor> mapEventListeners = new ConcurrentHashMap<>();
public static final String CHANGE_SUBJECT = "changeEvents";
public AtomixConsistentMap(CopycatClient client, Properties properties) {
super(client, properties);
}
@Override
public String name() {
return null;
}
@Override
public CompletableFuture<AtomixConsistentMap> open() {
return super.open().thenApply(result -> {
client.onStateChange(state -> {
if (state == CopycatClient.State.CONNECTED && isListening()) {
client.submit(new Listen());
}
});
client.onEvent(CHANGE_SUBJECT, this::handleEvent);
return result;
});
}
private void handleEvent(List<MapEvent<String, byte[]>> events) {
events.forEach(event ->
mapEventListeners.forEach((listener, executor) -> executor.execute(() -> listener.event(event))));
}
@Override
public CompletableFuture<Boolean> isEmpty() {
return client.submit(new IsEmpty());
}
@Override
public CompletableFuture<Integer> size() {
return client.submit(new Size());
}
@Override
public CompletableFuture<Boolean> containsKey(String key) {
return client.submit(new ContainsKey(key));
}
@Override
public CompletableFuture<Boolean> containsValue(byte[] value) {
return client.submit(new ContainsValue(value));
}
@Override
public CompletableFuture<Versioned<byte[]>> get(String key) {
return client.submit(new Get(key));
}
@Override
public CompletableFuture<Versioned<byte[]>> getOrDefault(String key, byte[] defaultValue) {
return client.submit(new GetOrDefault(key, defaultValue));
}
@Override
public CompletableFuture<Set<String>> keySet() {
return client.submit(new KeySet());
}
@Override
public CompletableFuture<Collection<Versioned<byte[]>>> values() {
return client.submit(new Values());
}
@Override
public CompletableFuture<Set<Entry<String, Versioned<byte[]>>>> entrySet() {
return client.submit(new EntrySet());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Versioned<byte[]>> put(String key, byte[] value) {
return client.submit(new UpdateAndGet(key, value, Match.ANY, Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.oldValue());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Versioned<byte[]>> putAndGet(String key, byte[] value) {
return client.submit(new UpdateAndGet(key, value, Match.ANY, Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.newValue());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Versioned<byte[]>> putIfAbsent(String key, byte[] value) {
return client.submit(new UpdateAndGet(key, value, Match.NULL, Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.oldValue());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Versioned<byte[]>> remove(String key) {
return client.submit(new UpdateAndGet(key, null, Match.ANY, Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.oldValue());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> remove(String key, byte[] value) {
return client.submit(new UpdateAndGet(key, null, Match.ifValue(value), Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.updated());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> remove(String key, long version) {
return client.submit(new UpdateAndGet(key, null, Match.ANY, Match.ifValue(version)))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.updated());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Versioned<byte[]>> replace(String key, byte[] value) {
return client.submit(new UpdateAndGet(key, value, Match.NOT_NULL, Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.oldValue());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> replace(String key, byte[] oldValue, byte[] newValue) {
return client.submit(new UpdateAndGet(key, newValue, Match.ifValue(oldValue), Match.ANY))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.updated());
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> replace(String key, long oldVersion, byte[] newValue) {
return client.submit(new UpdateAndGet(key, newValue, Match.ANY, Match.ifValue(oldVersion)))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenApply(v -> v.updated());
}
@Override
public CompletableFuture<Void> clear() {
return client.submit(new Clear())
.whenComplete((r, e) -> throwIfLocked(r))
.thenApply(v -> null);
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Versioned<byte[]>> computeIf(String key,
Predicate<? super byte[]> condition,
BiFunction<? super String, ? super byte[], ? extends byte[]> remappingFunction) {
return get(key).thenCompose(r1 -> {
byte[] existingValue = r1 == null ? null : r1.value();
// if the condition evaluates to false, return existing value.
if (!condition.test(existingValue)) {
return CompletableFuture.completedFuture(r1);
}
AtomicReference<byte[]> computedValue = new AtomicReference<>();
// if remappingFunction throws an exception, return the exception.
try {
computedValue.set(remappingFunction.apply(key, existingValue));
} catch (Exception e) {
CompletableFuture<Versioned<byte[]>> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
if (computedValue.get() == null && r1 == null) {
return CompletableFuture.completedFuture(null);
}
Match<byte[]> valueMatch = r1 == null ? Match.NULL : Match.ANY;
Match<Long> versionMatch = r1 == null ? Match.ANY : Match.ifValue(r1.version());
return client.submit(new UpdateAndGet(key,
computedValue.get(),
valueMatch,
versionMatch))
.whenComplete((r, e) -> throwIfLocked(r.status()))
.thenCompose(r -> {
if (r.status() == MapEntryUpdateResult.Status.PRECONDITION_FAILED ||
r.status() == MapEntryUpdateResult.Status.WRITE_LOCK) {
return Tools.exceptionalFuture(new ConsistentMapException.ConcurrentModification());
}
return CompletableFuture.completedFuture(r);
})
.thenApply(v -> v.newValue());
});
}
@Override
public synchronized CompletableFuture<Void> addListener(MapEventListener<String, byte[]> listener,
Executor executor) {
if (mapEventListeners.isEmpty()) {
return client.submit(new Listen()).thenRun(() -> mapEventListeners.put(listener, executor));
} else {
mapEventListeners.put(listener, executor);
return CompletableFuture.completedFuture(null);
}
}
@Override
public synchronized CompletableFuture<Void> removeListener(MapEventListener<String, byte[]> listener) {
if (mapEventListeners.remove(listener) != null && mapEventListeners.isEmpty()) {
return client.submit(new Unlisten()).thenApply(v -> null);
}
return CompletableFuture.completedFuture(null);
}
private void throwIfLocked(MapEntryUpdateResult.Status status) {
if (status == MapEntryUpdateResult.Status.WRITE_LOCK) {
throw new ConcurrentModificationException("Cannot update map: Another transaction in progress");
}
}
@Override
public CompletableFuture<Version> begin(TransactionId transactionId) {
return client.submit(new TransactionBegin(transactionId)).thenApply(Version::new);
}
@Override
public CompletableFuture<Boolean> prepare(
TransactionLog<MapUpdate<String, byte[]>> transactionLog) {
return client.submit(new TransactionPrepare(transactionLog))
.thenApply(v -> v == PrepareResult.OK);
}
@Override
public CompletableFuture<Boolean> prepareAndCommit(
TransactionLog<MapUpdate<String, byte[]>> transactionLog) {
return client.submit(new TransactionPrepareAndCommit(transactionLog))
.thenApply(v -> v == PrepareResult.OK);
}
@Override
public CompletableFuture<Void> commit(TransactionId transactionId) {
return client.submit(new TransactionCommit(transactionId)).thenApply(v -> null);
}
@Override
public CompletableFuture<Void> rollback(TransactionId transactionId) {
return client.submit(new TransactionRollback(transactionId)).thenApply(v -> null);
}
@Override
public void addStatusChangeListener(Consumer<Status> listener) {
statusChangeListeners.add(listener);
}
@Override
public void removeStatusChangeListener(Consumer<Status> listener) {
statusChangeListeners.remove(listener);
}
@Override
public Collection<Consumer<Status>> statusChangeListeners() {
return ImmutableSet.copyOf(statusChangeListeners);
}
private boolean isListening() {
return !mapEventListeners.isEmpty();
}
}
|
3e0f9a15fa929fe3e201e9f46778015db2bc31a7 | 1,042 | java | Java | src/main/java/com/app/spring/angular/course/SpringAngularCourse/service/CustomerService.java | Joseleon1903/SpringAngularCourse | 209951954914c2257d35fb39821ba99a471d882e | [
"MIT"
] | null | null | null | src/main/java/com/app/spring/angular/course/SpringAngularCourse/service/CustomerService.java | Joseleon1903/SpringAngularCourse | 209951954914c2257d35fb39821ba99a471d882e | [
"MIT"
] | 1 | 2021-08-16T17:51:25.000Z | 2021-08-16T17:51:25.000Z | src/main/java/com/app/spring/angular/course/SpringAngularCourse/service/CustomerService.java | Joseleon1903/SpringAngularCourse | 209951954914c2257d35fb39821ba99a471d882e | [
"MIT"
] | null | null | null | 30.647059 | 90 | 0.770633 | 6,624 | package com.app.spring.angular.course.SpringAngularCourse.service;
import com.app.spring.angular.course.SpringAngularCourse.jparepository.CustomerRepository;
import com.app.spring.angular.course.SpringAngularCourse.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by jose de leon on 4/30/2021.
*/
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public List<Customer> findAllCustomers() {
return customerRepository.findAllCustomers().get();
}
public List<Customer> findCustomersByCode(String code) {
return customerRepository.findCustomersByCode(code).get();
}
public Customer findUniqueCustomersByCode(String code) {
return customerRepository.findByCustomerCode(code).get();
}
} |
3e0f9af5f3662a2eac4749046c2fb1599d3b67a1 | 6,020 | java | Java | src/main/java/UI/SingleCF.java | 757356150/medical_data_audit_system | ec1fa8d0c946da3ebd01cb87ca6e44e493634c24 | [
"Apache-2.0"
] | null | null | null | src/main/java/UI/SingleCF.java | 757356150/medical_data_audit_system | ec1fa8d0c946da3ebd01cb87ca6e44e493634c24 | [
"Apache-2.0"
] | null | null | null | src/main/java/UI/SingleCF.java | 757356150/medical_data_audit_system | ec1fa8d0c946da3ebd01cb87ca6e44e493634c24 | [
"Apache-2.0"
] | null | null | null | 28.130841 | 89 | 0.521927 | 6,625 | package UI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SingleCF {
static JFrame jf = new JFrame("居民医疗保险数据分析系统");
static void firtPage() {
// 1.设置窗体大小和标题
jf.setPreferredSize(new Dimension(700, 700));
// 2.设置关闭窗口就是关闭程序
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 最精准的布局模式空布局
jf.setLayout(null);
// 设置定位
JLabel jl = new JLabel("手动添加处方", JLabel.CENTER);
jl.setPreferredSize(new Dimension(680, 30));
jf.add(jl);
jl.setBounds(0, 0, 690, 30);
jl.setFont(new Font("宋体", Font.BOLD, 24));
jl.setForeground(Color.decode("#375a7f"));
// 菜单栏
// 新建一个菜单条
JMenuBar jb = new JMenuBar();
jf.add(jb);
jb.setBounds(0, 40, 690, 30);
jb.setBackground(Color.decode("#65991a"));
// 新建一个菜单选项
JMenu jmenu = new JMenu("首页");
jmenu.setPreferredSize(new Dimension(100, 30));
jmenu.setForeground(Color.white);
jb.add(jmenu);
JMenuItem jm0 = new JMenuItem("回到主页");
jmenu.add(jm0);
// 新建一个菜单项
JMenu jmenu0 = new JMenu("处方集处理");
jmenu0.setPreferredSize(new Dimension(100, 30));
jmenu0.setForeground(Color.white);
jb.add(jmenu0);
// 新建一个菜单项
JMenuItem jm1 = new JMenuItem("导入处方集文件");
JMenuItem jm2 = new JMenuItem("手动添加");
jmenu0.add(jm1);
jmenu0.add(jm2);
// 新建一个菜单选项
JMenu jmenu1 = new JMenu("医疗数据审核");
jmenu1.setForeground(Color.white);
jmenu1.setPreferredSize(new Dimension(100, 30));
jb.add(jmenu1);
// 新建一个菜单项
JMenuItem jm3 = new JMenuItem("单条数据审核");
JMenuItem jm4 = new JMenuItem("批量数据审核");
jmenu1.add(jm3);
jmenu1.add(jm4);
// 以下是显示位移的地方
// 放置图片
Container c= jf.getContentPane();
JLabel cn = new JLabel("中文名:");
c.add(cn);
cn.setBounds(0, -200, 700, 600);
JLabel en = new JLabel("英文名:");
c.add(en);
en.setBounds(0, -150, 700, 600);
JLabel sym = new JLabel("适应症:");
c.add(sym);
sym.setBounds(0, -100, 700, 600);
JLabel attention = new JLabel("注意事项:");
c.add(attention);
attention.setBounds(0, -50, 700, 600);
JLabel fbd = new JLabel("禁忌症:");
c.add(fbd);
fbd.setBounds(0, 0, 700, 600);
JLabel side = new JLabel("不良反应:");
c.add(side);
side.setBounds(0, 50, 700, 600);
JLabel use = new JLabel("用法和用量:");
c.add(use);
use.setBounds(0, 100, 700, 600);
JLabel formation = new JLabel("规格和制剂:");
c.add(formation);
formation.setBounds(0, 150, 700, 600);
JTextField txt1=new JTextField(40);
c.add(txt1);
txt1.setBounds(100,92,200,20);
JTextField txt2=new JTextField(40);
c.add(txt2);
txt2.setBounds(100,142,200,20);
JTextField txt3=new JTextField(100);
c.add(txt3);
txt3.setBounds(100,192,500,20);
JTextField txt4=new JTextField(100);
c.add(txt4);
txt4.setBounds(100,242,500,20);
JTextField txt5=new JTextField(100);
c.add(txt5);
txt5.setBounds(100,292,500,20);
JTextField txt6=new JTextField(100);
c.add(txt6);
txt6.setBounds(100,342,500,20);
JTextField txt7=new JTextField(100);
c.add(txt7);
txt7.setBounds(100,392,500,20);
JTextField txt8=new JTextField(100);
c.add(txt8);
txt8.setBounds(100,442,500,20);
JButton exe=new JButton("导入");
c.add(exe);
exe.setBounds(500,550,100,20);
JLabel done=new JLabel();
c.add(done);
done.setBounds(300,550,100,20);
exe.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
DAO.Process.symProcess(txt1.getText(),txt2.getText(),txt3.getText());
DAO.Process.fbdProcess(txt1.getText(),txt2.getText(),txt5.getText());
} catch (Exception ex) {
ex.printStackTrace();
}
done.setText("完成");
}
});
//开始监听事件
jm0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//销毁当前页面
closeThis();
//打开一个新的页面
new IndexPage().firtPage();
}
});
jm1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//销毁当前页面
closeThis();
//打开一个新的页面
new ChuFangProcess().firtPage();
}
});
jm2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//销毁当前页面
closeThis();
//打开一个新的页面
new SingleCF().firtPage();
}
});
jm3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//销毁当前页面
closeThis();
//打开一个新的页面
new SingleAudit().firtPage();
}
});
jm4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//销毁当前页面
closeThis();
//打开一个新的页面
new BatchAudit().firtPage();
}
});
// 3.设置窗体可见
jf.pack();
jf.setVisible(true);
}
public static void closeThis(){
jf.dispose();
}
public static void main(String[] args) {
firtPage();
}
}
|
3e0f9bf4c9868e8a9f55c6c5e71d97a567553f79 | 1,632 | java | Java | java7/org/omg/DynamicAny/DynEnumOperations.java | rain9155/javaSource | 4fe5d49b4a78e2c0195b43989168f7497435d486 | [
"Apache-2.0"
] | null | null | null | java7/org/omg/DynamicAny/DynEnumOperations.java | rain9155/javaSource | 4fe5d49b4a78e2c0195b43989168f7497435d486 | [
"Apache-2.0"
] | null | null | null | java7/org/omg/DynamicAny/DynEnumOperations.java | rain9155/javaSource | 4fe5d49b4a78e2c0195b43989168f7497435d486 | [
"Apache-2.0"
] | 2 | 2020-07-12T00:31:07.000Z | 2021-05-26T07:38:37.000Z | 34.723404 | 118 | 0.679534 | 6,626 | package org.omg.DynamicAny;
/**
* org/omg/DynamicAny/DynEnumOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl
* Friday, March 1, 2013 3:32:44 AM PST
*/
/**
* DynEnum objects support the manipulation of IDL enumerated values.
* The current position of a DynEnum is always -1.
*/
public interface DynEnumOperations extends org.omg.DynamicAny.DynAnyOperations
{
/**
* Returns the value of the DynEnum as an IDL identifier.
*/
String get_as_string ();
/**
* Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.
*
* @exception InvalidValue If value contains a string that is not a valid IDL identifier
* for the corresponding enumerated type
*/
void set_as_string (String value) throws org.omg.DynamicAny.DynAnyPackage.InvalidValue;
/**
* Returns the value of the DynEnum as the enumerated value's ordinal value.
* Enumerators have ordinal values 0 to n-1, as they appear from left to right
* in the corresponding IDL definition.
*/
int get_as_ulong ();
/**
* Sets the value of the DynEnum as the enumerated value's ordinal value.
*
* @exception InvalidValue If value contains a value that is outside the range of ordinal values
* for the corresponding enumerated type
*/
void set_as_ulong (int value) throws org.omg.DynamicAny.DynAnyPackage.InvalidValue;
} // interface DynEnumOperations
|
3e0f9ccfea3e785a8bdd5a88fb1a925d93a28740 | 1,973 | java | Java | modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorLifecycleConfiguration.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/internal/visor/node/VisorLifecycleConfiguration.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/internal/visor/node/VisorLifecycleConfiguration.java | gridgain/incubator-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 15 | 2016-03-18T09:25:39.000Z | 2021-10-01T05:49:39.000Z | 31.822581 | 80 | 0.718196 | 6,627 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.visor.node;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.jetbrains.annotations.*;
import java.io.*;
import static org.apache.ignite.internal.visor.util.VisorTaskUtils.*;
/**
* Data transfer object for node lifecycle configuration properties.
*/
public class VisorLifecycleConfiguration implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Lifecycle beans. */
private String beans;
/**
* @param c Grid configuration.
* @return Data transfer object for node lifecycle configuration properties.
*/
public static VisorLifecycleConfiguration from(IgniteConfiguration c) {
VisorLifecycleConfiguration cfg = new VisorLifecycleConfiguration();
cfg.beans = compactArray(c.getLifecycleBeans());
return cfg;
}
/**
* @return Lifecycle beans.
*/
@Nullable public String beans() {
return beans;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(VisorLifecycleConfiguration.class, this);
}
}
|
3e0f9cfa41b0ccbf9e3aeeca43dbbb07e43db379 | 5,590 | java | Java | src/main/java/dhbwka/wwi/vertsys/javaee/myTravelator/common/ejb/UserBean.java | yoenkol/myTravelator | 31c404b4b88dd2f4f3544934a99ec598ea6400aa | [
"CC-BY-4.0"
] | null | null | null | src/main/java/dhbwka/wwi/vertsys/javaee/myTravelator/common/ejb/UserBean.java | yoenkol/myTravelator | 31c404b4b88dd2f4f3544934a99ec598ea6400aa | [
"CC-BY-4.0"
] | null | null | null | src/main/java/dhbwka/wwi/vertsys/javaee/myTravelator/common/ejb/UserBean.java | yoenkol/myTravelator | 31c404b4b88dd2f4f3544934a99ec598ea6400aa | [
"CC-BY-4.0"
] | 1 | 2019-04-28T02:06:29.000Z | 2019-04-28T02:06:29.000Z | 30.048387 | 158 | 0.651637 | 6,628 | /*
* Copyright © 2018 Dennis Schulmeister-Zimolong
*
* E-Mail: ychag@example.com
* Webseite: https://www.wpvs.de/
*
* Dieser Quellcode ist lizenziert unter einer
* Creative Commons Namensnennung 4.0 International Lizenz.
*/
package dhbwka.wwi.vertsys.javaee.myTravelator.common.ejb;
import dhbwka.wwi.vertsys.javaee.myTravelator.common.jpa.User;
import java.util.List;
import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
* Spezielle EJB zum Anlegen eines Benutzers und Aktualisierung des Passworts.
*/
@Stateless
public class UserBean {
@PersistenceContext
EntityManager em;
@Resource
EJBContext ctx;
/**
* Gibt das Datenbankobjekt des aktuell eingeloggten Benutzers zurück,
*
* @return Eingeloggter Benutzer oder null
*/
public User getCurrentUser() {
return this.em.find(User.class, this.ctx.getCallerPrincipal().getName());
}
/**
* Gibt alle Datenbankobjekt User zurück,
*
* @return Liste der registrierten User
*/
public List<User> findAll() {
return this.em.createQuery("SELECT u FROM User u").getResultList();
}
/**
* Findet einen User nach seiner ID,
*
* @return User der gesuchten ID
*/
public User findUser(String id) {
return em.find(User.class, id);
}
/**
*
* @param username
* @param password
* @throws UserBean.UserAlreadyExistsException
*/
public void signup(String username, String password, String first_name, String last_name) throws UserAlreadyExistsException {
if (em.find(User.class, username) != null) {
throw new UserAlreadyExistsException("Der Benutzername $B ist bereits vergeben.".replace("$B", username));
}
User user = new User(username, password, last_name, first_name);
user.addToGroup("app-user");
em.persist(user);
}
/**
* Passwort ändern (ohne zu speichern)
*
* @param user
* @param oldPassword
* @param newPassword
* @throws UserBean.InvalidCredentialsException
*/
@RolesAllowed("app-user")
public void changePassword(User user, String oldPassword, String newPassword) throws InvalidCredentialsException {
if (user == null || !user.checkPassword(oldPassword)) {
throw new InvalidCredentialsException("Das Alte Passwort stimmt nicht überein.");
}
user.setPassword(newPassword);
em.merge(user);
}
public User findByUsername(String userName) {
CriteriaBuilder cb = this.em.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> from = query.from(User.class);
query.select(from);
query.where(cb.and(
cb.equal(from.get("username"), userName)));
List<User> result = em.createQuery(query).getResultList(); // getResultList() verhindert Nullpointer
User user = result != null && result.size() == 1 ? result.get(0) : null;
if (user != null) {
user.addToGroup("app-user"); // Defaultgruppe
}
return user;
}
public void updateCredentials(User user, String first_name, String last_name) throws UserAlreadyExistsException {
//List <User> users = em.createQuery("SELECT u.username FROM User u WHERE u.username = :username").setParameter("username", username).getResultList();
//if (users != null && users.size()>0) {
if (first_name == null && first_name.isEmpty()) {
throw new UserAlreadyExistsException("Der Vorname darf nicht leer sein.");
}
if (last_name == null && last_name.isEmpty()) {
throw new UserAlreadyExistsException("Der Nachname darf nicht leer sein.");
}
user.setFirst_name(first_name);
user.setLast_name(last_name);
em.merge(user);
}
public void updateFirstName(User user, String vorname) {
user.setFirst_name(vorname);
em.merge(user);
}
public void updateLastName(User user, String nachname) {
user.setLast_name(nachname);
em.merge(user);
}
/**
* Benutzer löschen
*
* @param user Zu löschender Benutzer
*/
@RolesAllowed("app-user")
public void delete(User user) {
this.em.remove(user);
}
/**
* Benutzer aktualisieren
*
* @param user Zu aktualisierender Benutzer
* @return Gespeicherter Benutzer
*/
@RolesAllowed("app-user")
public User update(User user) {
return em.merge(user);
}
public List<User> searchUser(String query) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Fehler: Der Benutzername ist bereits vergeben
*/
public class UserAlreadyExistsException extends Exception {
public UserAlreadyExistsException(String message) {
super(message);
}
}
/**
* Fehler: Das übergebene Passwort stimmt nicht mit dem des Benutzers
* überein
*/
public class InvalidCredentialsException extends Exception {
public InvalidCredentialsException(String message) {
super(message);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.