hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
acdffa129bbb5969feb0957e86df79b6ff912422 | 5,569 | /*
* Copyright 2018 Nafundi
*
* 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.odk.collect.android.formentry.audit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.odk.collect.android.location.client.LocationClient.Priority.PRIORITY_BALANCED_POWER_ACCURACY;
import static org.odk.collect.android.location.client.LocationClient.Priority.PRIORITY_HIGH_ACCURACY;
import static org.odk.collect.android.location.client.LocationClient.Priority.PRIORITY_LOW_POWER;
import static org.odk.collect.android.location.client.LocationClient.Priority.PRIORITY_NO_POWER;
public class AuditConfigTest {
@Test
public void testParameters() {
AuditConfig auditConfig = new AuditConfig("high-accuracy", "10", "60", true, false);
assertTrue(auditConfig.isTrackingChangesEnabled());
assertTrue(auditConfig.isLocationEnabled());
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
assertEquals(10000, auditConfig.getLocationMinInterval().intValue());
assertEquals(60000, auditConfig.getLocationMaxAge().intValue());
auditConfig = new AuditConfig("high-accuracy", "0", "60", false, false);
assertFalse(auditConfig.isTrackingChangesEnabled());
assertTrue(auditConfig.isLocationEnabled());
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
assertEquals(1000, auditConfig.getLocationMinInterval().intValue());
assertEquals(60000, auditConfig.getLocationMaxAge().intValue());
}
@Test
public void logLocationCoordinatesOnlyIfAllParametersAreSet() {
AuditConfig auditConfig = new AuditConfig("high-accuracy", "10", "60", false, false);
assertTrue(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig(null, "10", "60", false, false);
assertFalse(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig(null, null, "60", false, false);
assertFalse(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig(null, null, null, false, false);
assertFalse(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig("balanced", null, null, false, false);
assertFalse(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig("balanced", "10", null, false, false);
assertFalse(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig("balanced", null, "60", false, false);
assertFalse(auditConfig.isLocationEnabled());
auditConfig = new AuditConfig(null, null, "60", false, false);
assertFalse(auditConfig.isLocationEnabled());
}
@Test
public void testPriorities() {
AuditConfig auditConfig = new AuditConfig("high_accuracy", null, null, false, false);
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("high-accuracy", null, null, false, false);
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("HIGH_ACCURACY", null, null, false, false);
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("balanced", null, null, false, false);
assertEquals(PRIORITY_BALANCED_POWER_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("BALANCED", null, null, false, false);
assertEquals(PRIORITY_BALANCED_POWER_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("low_power", null, null, false, false);
assertEquals(PRIORITY_LOW_POWER, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("low-power", null, null, false, false);
assertEquals(PRIORITY_LOW_POWER, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("low_POWER", null, null, false, false);
assertEquals(PRIORITY_LOW_POWER, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("no_power", null, null, false, false);
assertEquals(PRIORITY_NO_POWER, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("no-power", null, null, false, false);
assertEquals(PRIORITY_NO_POWER, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("NO_power", null, null, false, false);
assertEquals(PRIORITY_NO_POWER, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("qwerty", null, null, false, false);
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig("", null, null, false, false);
assertEquals(PRIORITY_HIGH_ACCURACY, auditConfig.getLocationPriority());
auditConfig = new AuditConfig(null, null, null, false, false);
assertNull(auditConfig.getLocationPriority());
}
}
| 54.067961 | 111 | 0.730113 |
3e3684f328a20698b03364a7069a65ec8afb9f9d | 11,344 | package com.example.WorkoutBuddy.workoutbuddy.Fragments.MainFragments;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.WorkoutBuddy.workoutbuddy.DataBase.Data.SubWorkout;
import com.example.WorkoutBuddy.workoutbuddy.DataBase.DatabaseManagment.DataBaseContract;
import com.example.WorkoutBuddy.workoutbuddy.DataBase.Data.WorkoutExercise;
import com.example.WorkoutBuddy.workoutbuddy.DataBase.TableManagers.WorkoutStatsTable;
import com.example.WorkoutBuddy.workoutbuddy.Fragments.FragmentPopupWindows.WorkoutStatsPopupWindows.DeleteWorkoutStatsPopup;
import com.example.WorkoutBuddy.workoutbuddy.Fragments.Managers.FragmentStackManager;
import com.example.WorkoutBuddy.workoutbuddy.Fragments.SubFragments.FullWorkoutStatsFragment;
import com.example.WorkoutBuddy.workoutbuddy.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
// use floating action button to reset list
import static android.content.Context.SEARCH_SERVICE;
//fix search bugs
public class WorkoutStatsFragment extends Fragment {
private Menu menu;
private View root;
private RecyclerView recyclerView;
private FragmentStackManager fragmentStackManager;
private RecyclerAdapter recyclerAdapter;
private List<SubWorkout> subWorkoutList;
public WorkoutStatsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_workout_stats, container, false);
new MyAsyncTask().execute(subWorkoutList);
setSearchViewOnClick();
FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
if(fab != null) {
fab.setVisibility(View.INVISIBLE);
}
return root;
}
@Override
public void onDetach() {
super.onDetach();
resetFloatingActionButton();
}
private void resetFloatingActionButton() {
FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
if(fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do nothing
}
});
}
}
public void setMenu(Menu menu) {
this.menu = menu;
}
public void setFragmentStackManager(FragmentStackManager fragmentStackManager) {
this.fragmentStackManager = fragmentStackManager;
}
private void setRecycleView(View root, RecyclerAdapter adapter) {
RecyclerView.LayoutManager manager = new GridLayoutManager(getContext(),2);
recyclerView = (RecyclerView) root.findViewById(R.id.workoutStatsRecycleView);
recyclerView.setItemViewCacheSize(12);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(adapter);
if (subWorkoutList.size()==0) {
TextView textView = (TextView) root.findViewById(R.id.noWorkoutStats);
textView.setVisibility(View.VISIBLE);
}
}
private void setSearchViewOnClick() {
SearchView searchView =
(SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getActivity().getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
WorkoutStatsTable table = new WorkoutStatsTable(getContext());
loadSearchedItems(table.searchTable(query));
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
private void showFullWorkoutStatsFragment(List<WorkoutExercise> workoutData) {
FullWorkoutStatsFragment fw = new FullWorkoutStatsFragment();
fw.setWorkoutData(workoutData);
fragmentStackManager.addFragmentToStack(fw,R.id.fullWorkoutStats_fragment);
}
public List<SubWorkout> loadSearchedItems(Map<String,List<String>> queriedData) {
List<SubWorkout> list = new ArrayList<>();
if(queriedData!=null) {
List<String> mainWorkoutNames = queriedData.get(DataBaseContract.WorkoutData.COLUMN_MAINWORKOUT);
List<String> subWorkoutNames = queriedData.get(DataBaseContract.WorkoutData.COLUMN_SUBWORKOUT);
List<String> dates = queriedData.get(DataBaseContract.WorkoutData.COLUMN_DATE);
for (int x = 0; x < mainWorkoutNames.size(); x++) {
String mainWorkoutName = mainWorkoutNames.get(x);
String subWorkoutName = subWorkoutNames.get(x);
String date = dates.get(x);
for (int i = 0; i < subWorkoutList.size(); i++) {
SubWorkout subWorkout = subWorkoutList.get(i);
String mainName = subWorkout.getMainWorkoutName();
String subName = subWorkout.getSubWorkoutName();
String dateSubWorkoutList = subWorkout.getDate();
if(mainWorkoutName.equals(mainName) && subWorkoutName.equals(subName)
&& date.equals(dateSubWorkoutList)) {
list.add(subWorkout);
}
}
}
}
recyclerView.setAdapter(new RecyclerAdapter(list));
return list;
}
private void showDeleteWorkoutStatsPopup(int position) {
DeleteWorkoutStatsPopup popup = new DeleteWorkoutStatsPopup(root,getContext());
popup.setPosition(position);
popup.setRecyclerView(recyclerView);
popup.setSubWorkoutList(subWorkoutList);
popup.showPopupWindow();
}
private class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.CustomViewHolder> {
private List<SubWorkout> subWorkoutList;
public RecyclerAdapter(List<SubWorkout> subWorkoutList) {
this.subWorkoutList = subWorkoutList;
}
@Override
public int getItemCount() {
return (null != subWorkoutList ? subWorkoutList.size() : 0);
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup,int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.workout_card_view,null);
return new CustomViewHolder(view);
}
@Override
public void onBindViewHolder(CustomViewHolder customViewHolder,int i) {
SubWorkout subWorkout = subWorkoutList.get(i);
customViewHolder.dateView.setText(customViewHolder.dateView.getText()+" "+
subWorkout.getDate());
customViewHolder.mainWorkoutView.setText(customViewHolder.mainWorkoutView.getText() + " " +
subWorkout.getMainWorkoutName());
customViewHolder.subWorkoutView.setText(customViewHolder.subWorkoutView.getText()+" "+
subWorkout.getSubWorkoutName());
customViewHolder.setsView.setText(customViewHolder.setsView.getText()+" "+
subWorkout.getTotalSets());
customViewHolder.repsView.setText(customViewHolder.repsView.getText()+" "+
subWorkout.getTotalReps());
customViewHolder.weightView.setText(customViewHolder.weightView.getText()+" "+
subWorkout.getTotalWeight());
customViewHolder.openFullWorkoutStats(customViewHolder.cardView,subWorkout.getWorkoutData());
}
class CustomViewHolder extends RecyclerView.ViewHolder {
protected CardView cardView;
protected TextView dateView;
protected TextView mainWorkoutView;
protected TextView subWorkoutView;
protected TextView setsView;
protected TextView repsView;
protected TextView weightView;
public CustomViewHolder(View rowView) {
super(rowView);
cardView = (CardView) rowView.findViewById(R.id.workoutStatsCardView);
dateView = (TextView) rowView.findViewById(R.id.liftingStatsDate_textView);
mainWorkoutView = (TextView) rowView.findViewById(R.id.mainWorkout_textView);
subWorkoutView = (TextView) rowView.findViewById(R.id.subWorkout_textView);
setsView = (TextView) rowView.findViewById(R.id.sets_textView);
repsView = (TextView) rowView.findViewById(R.id.reps_textView);
weightView = (TextView) rowView.findViewById(R.id.weight_textView);
deleteWorkoutStats(cardView);
}
public void openFullWorkoutStats(CardView cardView, List<WorkoutExercise> workoutData) {
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFullWorkoutStatsFragment(workoutData);}
});
}
public void deleteWorkoutStats(CardView cardView) {
cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showDeleteWorkoutStatsPopup(getLayoutPosition());
return true;
}
});
}
}
}
private class MyAsyncTask extends AsyncTask<List<SubWorkout>,Void,List<SubWorkout>> {
private WorkoutStatsTable table;
private ProgressDialog progressDialog;
@Override
protected void onPreExecute(){
table = new WorkoutStatsTable(getContext());
progressDialog = new ProgressDialog(getContext(),ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
@Override
protected List<SubWorkout> doInBackground(List<SubWorkout>[] params) {
params[0] = table.getCompletedWorkouts();
subWorkoutList = params[0];
return params[0];
}
@Override
protected void onPostExecute(List<SubWorkout> subWorkoutList) {
progressDialog.dismiss();
recyclerAdapter = new RecyclerAdapter(subWorkoutList);
setRecycleView(root,recyclerAdapter);
}
}
}
| 41.553114 | 125 | 0.662465 |
8801b32b7e7cbe6a331058f80a70efbd53bb9522 | 3,544 | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.cpachecker.util.predicates.regions;
import org.sosy_lab.common.ShutdownNotifier;
/**
* RegionCreator is an interface that contains all methods for creating
* {@link Region} instances.
* It is a super-interface of {@link RegionManager} with a subset of methods
* intended to be used for code that needs only limited access.
*/
public interface RegionCreator {
/**
* Return a new {@link RegionBuilder} instance.
*/
RegionBuilder builder(ShutdownNotifier pShutdownNotifier);
/** Returns a representation of logical truth. */
Region makeTrue();
/** Returns a representation of logical falseness. */
Region makeFalse();
/**
* Creates a region representing a negation of the argument
*
* @param f an AbstractFormula
* @return (!f1)
*/
Region makeNot(Region f);
/**
* Creates a region representing an AND of the two argument
*
* @param f1 an AbstractFormula
* @param f2 an AbstractFormula
* @return (f1 & f2)
*/
Region makeAnd(Region f1, Region f2);
/**
* Creates a region representing an OR of the two argument
*
* @param f1 an AbstractFormula
* @param f2 an AbstractFormula
* @return (f1 | f2)
*/
Region makeOr(Region f1, Region f2);
/**
* Creates a region representing an equality (bi-implication) of the two argument
*
* @param f1 an AbstractFormula
* @param f2 an AbstractFormula
* @return (f1 <=> f2)
*/
Region makeEqual(Region f1, Region f2);
/**
* Creates a region representing an disequality (XOR) of the two argument
* @param f1 an AbstractFormula
* @param f2 an AbstractFormula
* @return (f1 ^ f2)
*/
Region makeUnequal(Region f1, Region f2);
/**
* Creates a region representing an if then else construct of the three arguments
*
* @param f1 an AbstractFormula
* @param f2 an AbstractFormula
* @param f3 an AbstractFormula
* @return (if f1 then f2 else f3)
*/
Region makeIte(Region f1, Region f2, Region f3);
/**
* Creates a region representing an existential quantification of the second
* argument. If there are more arguments, each of them is quantified.
* @param f1 an AbstractFormula
* @param f2 one or more AbstractFormulas
* @return (exists f2... : f1)
*/
Region makeExists(Region f1, Region... f2);
/**
* A stateful region builder for regions that are disjunctions
* of conjunctive literals.
* Using this can be more efficient than calling {@link RegionCreator#makeOr(Region, Region)}
* and {@link RegionCreator#makeAnd(Region, Region)} repeatedly.
*/
interface RegionBuilder extends AutoCloseable {
/**
* Start a new conjunctive clause.
*/
void startNewConjunction();
/**
* Add a region to the current conjunctive clause.
*/
void addPositiveRegion(Region r);
/**
* Add the negation of a region to the current conjunctive clause.
*/
void addNegativeRegion(Region r);
/**
* End the current conjunctive clause and add it to the global disjunction.
*/
void finishConjunction();
/**
* Retrieve the disjunction of all the conjunctive clauses created
* with this builder so far.
*/
Region getResult() throws InterruptedException;
@Override
void close();
}
}
| 26.848485 | 95 | 0.677765 |
12fca7009751c4cf18420faca7c59ee09aa2b4e3 | 3,706 | package com.jantvrdik.intellij.latte.lexer;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.LookAheadLexer;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.jantvrdik.intellij.latte.psi.LatteTypes;
import com.jantvrdik.intellij.latte.utils.LatteTagsUtil;
import com.jantvrdik.intellij.latte.utils.LatteTypesUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Lexer used for syntax highlighting
*
* It reuses the simple lexer, changing types of some tokens
*/
public class LatteLookAheadLexer extends LookAheadLexer {
private static final TokenSet WHITESPACES = TokenSet.create(TokenType.WHITE_SPACE, LatteTypes.T_WHITESPACE);
private static final TokenSet TAG_TAGS = TokenSet.create(LatteTypes.T_HTML_TAG_ATTR_EQUAL_SIGN, LatteTypes.T_HTML_TAG_ATTR_DQ);
private static final String IDENTIFIER_LINKS = "links";
private static final String IDENTIFIER_TYPES = "types";
private final Map<String, Boolean> lastValid = new HashMap<>();
private final Map<String, Boolean> replaceAs = new HashMap<>();
final private Lexer lexer;
public LatteLookAheadLexer(Lexer baseLexer) {
super(baseLexer, 1);
lexer = baseLexer;
}
@Override
protected void addToken(int endOffset, IElementType type) {
boolean wasLinkDestination = false;
if ((type == LatteTypes.T_PHP_IDENTIFIER || type == LatteTypes.T_PHP_KEYWORD || (type == LatteTypes.T_MACRO_ARGS && isCharacterAtCurrentPosition(lexer, '#', ':'))) && needReplaceAsMacro(IDENTIFIER_LINKS)) {
type = LatteTypes.T_LINK_DESTINATION;
wasLinkDestination = true;
}
boolean wasTypeDefinition = false;
boolean isMacroSeparator = type == LatteTypes.T_PHP_MACRO_SEPARATOR;
boolean isMacroFilters = type == LatteTypes.T_MACRO_FILTERS;
if ((LatteTypesUtil.phpTypeTokens.contains(type) || isMacroSeparator || isMacroFilters) && needReplaceAsMacro(IDENTIFIER_TYPES)) {
if (isMacroSeparator) {
type = LatteTypes.T_PHP_OR_INCLUSIVE;
} else if (isMacroFilters) {
type = LatteTypes.T_PHP_IDENTIFIER;
}
wasTypeDefinition = true;
}
super.addToken(endOffset, type);
if (!TAG_TAGS.contains(type)) {
checkMacroType(IDENTIFIER_LINKS, type, LatteTagsUtil.LINK_TAGS_LIST, wasLinkDestination);
checkMacroType(IDENTIFIER_TYPES, type, LatteTagsUtil.TYPE_TAGS_LIST, wasTypeDefinition);
}
}
private boolean needReplaceAsMacro(@NotNull String identifier) {
return replaceAs.getOrDefault(identifier, false);
}
private void checkMacroType(@NotNull String identifier, IElementType type, @NotNull List<String> types, boolean currentValid) {
boolean current = (type == LatteTypes.T_MACRO_NAME || type == LatteTypes.T_HTML_TAG_NATTR_NAME) && isMacroTypeMacro(lexer, types);
replaceAs.put(identifier, (currentValid && !WHITESPACES.contains(type))
|| (!currentValid && lastValid.containsKey(identifier) && lastValid.getOrDefault(identifier, false) && WHITESPACES.contains(type))
|| current);
lastValid.put(identifier, current);
}
public static boolean isCharacterAtCurrentPosition(Lexer baseLexer, char ...characters) {
char current = baseLexer.getBufferSequence().charAt(baseLexer.getCurrentPosition().getOffset());
for (char character : characters) {
if (current == character) {
return true;
}
}
return false;
}
private static boolean isMacroTypeMacro(Lexer baseLexer, @NotNull List<String> types) {
CharSequence tagName = baseLexer.getBufferSequence().subSequence(baseLexer.getTokenStart(), baseLexer.getTokenEnd());
if (tagName.length() == 0) {
return false;
}
return types.contains(tagName.toString());
}
}
| 38.604167 | 208 | 0.768214 |
231a9225b84076b5f76ae688a4e17cb81b07fca6 | 486 | package com.emse.spring.faircorp.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class DummyUserService implements UserService{
@Autowired
GreetingService gs;
List<String> names= Arrays.asList("fatouma","khadouj");
@Override
public void greetAll() {
for(String name :names){
gs.greet(name);
}
}
}
| 22.090909 | 62 | 0.707819 |
a189969f8355920c6cfac213017df2bd6319939c | 1,581 | // @formatter:off
/*******************************************************************************
*
* This file is part of JMad.
*
* Copyright (c) 2008-2011, CERN. 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.
*
******************************************************************************/
// @formatter:on
package cern.accsoft.steering.jmad.domain.machine;
import java.util.List;
import cern.accsoft.steering.jmad.domain.beam.Beam;
public interface Sequence {
/**
* @return the name
*/
public abstract String getName();
/**
* @return the available ranges of the sequence.
*/
public abstract List<Range> getRanges();
/**
* @return the default range for this sequence
*/
public abstract Range getDefaultRange();
/**
* @return the beam
*/
public abstract Beam getBeam();
/**
* @return the defining SequenceDefinition
*/
public abstract SequenceDefinition getSequenceDefinition();
}
| 27.736842 | 82 | 0.588235 |
99709004369e5124d21a24116dee9b12ec2281af | 547 | package com.didispace.scca.core.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
/**
* Created by 程序猿DD/翟永超 on 2018/4/24.
* <p>
* Blog: http://blog.didispace.com/
* Github: https://github.com/dyc87112/
*/
@EnableConfigServer
@SpringBootApplication
public class TestCoreApplication {
public static void main(String[] args) {
SpringApplication.run(TestCoreApplication.class);
}
}
| 24.863636 | 68 | 0.765996 |
3fa2605fc2e11a25b4486256c0c47d657782148b | 3,069 | /*
* This file is part of COMPASS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
package de.dfki.asr.compass.business.queries;
import de.dfki.asr.compass.model.Project;
import de.dfki.asr.compass.model.Scenario;
import de.dfki.asr.compass.business.services.CRUDService;
import de.dfki.asr.compass.model.Project_;
import de.dfki.asr.compass.model.Scenario_;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
public class ProjectQueries {
@Inject
private CRUDService crudService;
@Inject
private CriteriaBuilder criteriaBuilder;
public List<Project> getAllSortedAscendingByName() {
CriteriaQuery<Project> q = criteriaBuilder.createQuery(Project.class);
Root<Project> p = q.from(Project.class);
q.orderBy(criteriaBuilder.asc(p.get(Project_.name)));
return crudService.createQuery(q).getResultList();
}
public List<Project> getProjectsByNameAndId(final String projectName, final long id) {
CriteriaQuery<Project> q = criteriaBuilder.createQuery(Project.class);
Root<Project> p = q.from(Project.class);
q.where(criteriaBuilder.and(
criteriaBuilder.equal(p.get(Project_.name), projectName),
criteriaBuilder.notEqual(p.get(Project_.id), id)
));
return crudService.createQuery(q).getResultList();
}
public List<Project> getProjectsWithName(final String projectName) {
CriteriaQuery<Project> q = criteriaBuilder.createQuery(Project.class);
Root<Project> p = q.from(Project.class);
q.where(criteriaBuilder.equal(p.get(Project_.name), projectName));
return crudService.createQuery(q).getResultList();
}
@SuppressWarnings("CPD-START")
public List<Scenario> getScenariosByName(final long projectId, final String scenarioName) {
CriteriaQuery<Scenario> q = criteriaBuilder.createQuery(Scenario.class);
Root<Scenario> s = q.from(Scenario.class);
q.where(
criteriaBuilder.and(
criteriaBuilder.equal(s.get(Scenario_.name), scenarioName),
criteriaBuilder.equal(
s.get(Scenario_.project).get(Project_.id),
projectId
)
)
);
return crudService.createQuery(q).getResultList();
}
@SuppressWarnings("CPD-END")
public List<Scenario> getScenariosByNameAndDifferentId(final long projectId, final String scenarioName, final long scenarioId) {
CriteriaQuery<Scenario> q = criteriaBuilder.createQuery(Scenario.class);
Root<Scenario> s = q.from(Scenario.class);
q.where(
criteriaBuilder.and(
criteriaBuilder.equal(s.get(Scenario_.name), scenarioName),
criteriaBuilder.equal(
s.get(Scenario_.project).get(Project_.id),
projectId
),
criteriaBuilder.notEqual(
s.get(Scenario_.id),
scenarioId
)
)
);
return crudService.createQuery(q).getResultList();
}
}
| 34.1 | 129 | 0.758553 |
8139f679bac97c8cb68002fbdd308ea6aa20a15f | 3,518 |
package com.dnb.services.customproduct;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ObjectAttachmentForResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ObjectAttachmentForResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ContentReferenceIdentifier" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="240"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ContentObject" type="{http://www.w3.org/2001/XMLSchema}anySimpleType"/>
* <element name="ObjectFormatTypeText" type="{http://services.dnb.com/CustomProductServiceV2.0}DNBDecodedStringType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ObjectAttachmentForResponse", namespace = "http://services.dnb.com/CustomProductServiceV2.0", propOrder = {
"contentReferenceIdentifier",
"contentObject",
"objectFormatTypeText"
})
public class ObjectAttachmentForResponse {
@XmlElement(name = "ContentReferenceIdentifier")
protected String contentReferenceIdentifier;
@XmlElement(name = "ContentObject", required = true)
protected Object contentObject;
@XmlElement(name = "ObjectFormatTypeText", required = true)
protected DNBDecodedStringType objectFormatTypeText;
/**
* Gets the value of the contentReferenceIdentifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContentReferenceIdentifier() {
return contentReferenceIdentifier;
}
/**
* Sets the value of the contentReferenceIdentifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContentReferenceIdentifier(String value) {
this.contentReferenceIdentifier = value;
}
/**
* Gets the value of the contentObject property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getContentObject() {
return contentObject;
}
/**
* Sets the value of the contentObject property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setContentObject(Object value) {
this.contentObject = value;
}
/**
* Gets the value of the objectFormatTypeText property.
*
* @return
* possible object is
* {@link DNBDecodedStringType }
*
*/
public DNBDecodedStringType getObjectFormatTypeText() {
return objectFormatTypeText;
}
/**
* Sets the value of the objectFormatTypeText property.
*
* @param value
* allowed object is
* {@link DNBDecodedStringType }
*
*/
public void setObjectFormatTypeText(DNBDecodedStringType value) {
this.objectFormatTypeText = value;
}
}
| 28.144 | 130 | 0.630472 |
0793bdfd165f6a74e2b7dcf3f91c76914652e88e | 85 | package be.idevelop.cqrs;
@Event(TestId.class)
public record TestCreatedEvent() {
}
| 14.166667 | 34 | 0.764706 |
390ed159b823d9417997360e2007d40cddb247ad | 2,771 | package com.greatorator.tolkienmobs.entity.ai.goal;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.ai.goal.Goal;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.EggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ShootableItem;
import net.minecraft.item.SnowballItem;
public class TTMSwitchCombat extends Goal
{
private MobEntity hostMob;
private LivingEntity target;
private double minDistance;
private double maxDistance;
public TTMSwitchCombat(MobEntity mobEntity, double minDistance, double maxDistance) {
this.hostMob = mobEntity;
this.minDistance = minDistance;
this.maxDistance = maxDistance;
}
private boolean hasRangedItemInMainhand()
{
return this.hostMob.getMainHandItem().getItem() instanceof ShootableItem
|| this.hostMob.getMainHandItem().getItem() instanceof SnowballItem
|| this.hostMob.getMainHandItem().getItem() instanceof EggItem;
}
private boolean hasRangedItemInOffhand()
{
return this.hostMob.getOffhandItem().getItem() instanceof ShootableItem
|| this.hostMob.getOffhandItem().getItem() instanceof SnowballItem
|| this.hostMob.getMainHandItem().getItem() instanceof EggItem;
}
private void swapWeapons(){
ItemStack mainhand = this.hostMob.getMainHandItem();
ItemStack offhand = this.hostMob.getOffhandItem();
this.hostMob.setItemSlot(EquipmentSlotType.OFFHAND, mainhand);
this.hostMob.setItemSlot(EquipmentSlotType.MAINHAND, offhand);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
@Override
public boolean canUse()
{
this.target = this.hostMob.getTarget();
if (target == null)
{
return false;
}
else if (!target.isAlive())
{
return false;
}
else
{
// check if we are close to the target and have a ranged item in mainhand and do not have one in offhand,
// or if we are far from the target, and we do not have a ranged item in our mainhand but do have one in our offhand
return this.hostMob.canSee(this.target) && shouldSwitch();
}
}
/**
* Resets the task
*/
@Override
public void stop()
{
target = null;
}
/**
* Updates the task
*/
@Override
public void tick()
{
if (shouldSwitch()) {
swapWeapons();
}
}
private boolean shouldSwitch() {
return this.hostMob.distanceTo(this.target) < minDistance != hasRangedItemInOffhand();
}
}
| 29.168421 | 128 | 0.64742 |
e448ecf2c79d0b98b8341e37546f8d41d702a4fc | 876 | /**
*
* @author Dokuru
*/
package com.template.spring.dao.impl;
import com.template.spring.dao.MakeAppointmentsDAOService;
import com.template.spring.domain.Schedule;
import java.sql.ResultSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class MakeAppointmentsDAOServiceImpl implements MakeAppointmentsDAOService {
@Autowired
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Schedule> getOpenSlots(Integer courseID, Integer facultyID) {
return null;
}
}
| 23.052632 | 83 | 0.740868 |
df32ed19fcd0f3a23cb02c4b20e0c32520eefe1f | 2,469 | package zqh.web.admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import zqh.dto.AjaxResult;
import zqh.model.Administrator;
import zqh.service.AdminService;
import javax.servlet.http.HttpSession;
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {
@Autowired
private AdminService adminService;
@PostMapping("/addition")
public AjaxResult addition(@RequestBody Administrator administrator){
adminService.save(administrator);
return AjaxResult.success("新增管理员用户信息成功");
}
@PutMapping("/update")
public AjaxResult update(@RequestBody Administrator administrator, HttpSession session) {
Administrator admin = (Administrator) session.getAttribute("admin");
if (admin == null || !admin.getAccount().equals(administrator.getAccount())) {
return AjaxResult.fail(203, "只允许修改用户自己的信息");
}
adminService.update(administrator);
return AjaxResult.success("修改管理员用户信息成功");
}
@PutMapping("/password/update")
public AjaxResult updatePassword(@RequestBody Administrator administrator, HttpSession session) {
Administrator admin = (Administrator) session.getAttribute("admin");
if (admin != null) {
if (!admin.getPassword().equals(administrator.getAccount())) {
return AjaxResult.fail(204,"密码错误");
} else {
administrator.setAccount(admin.getAccount());
adminService.updatePassword(administrator);
return AjaxResult.success("修改管理员用户信息成功");
}
} else {
return AjaxResult.fail(2,"");
}
}
@PostMapping("/login")
public AjaxResult login(@RequestBody Administrator administrator, HttpSession session){
Administrator admin = adminService.login(administrator);
session.setAttribute("admin", admin);
return AjaxResult.success("登陆成功");
}
@GetMapping("/detail")
public AjaxResult detail(HttpSession session){
Administrator admin = (Administrator) session.getAttribute("admin");
admin.setPassword("");
return AjaxResult.success(admin);
}
@GetMapping("/logout")
public AjaxResult logout(HttpSession session){
session.removeAttribute("admin");
return AjaxResult.success("退出登录成功");
}
}
| 33.821918 | 101 | 0.678817 |
d2e70f35b8e308cc5ac6947453444225816f3713 | 280 | package com.dummy.myerp.consumer.dao.contrat;
/**
* Interface du Proxy d'accès à la couche DAO
*/
public interface DaoProxy {
/**
* Renvoie un {@link ComptabiliteDao}
*
* @return {@link ComptabiliteDao}
*/
ComptabiliteDao getComptabiliteDao();
}
| 16.470588 | 45 | 0.646429 |
75fb0df916cd96690b8e80af7afb4312dd580daa | 2,441 | package com.androidhuman.rxfirebase3.firestore;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.Source;
import com.androidhuman.rxfirebase3.core.OnCompleteDisposable;
import com.androidhuman.rxfirebase3.firestore.model.Value;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleObserver;
final class QueryObserver extends Single<Value<QuerySnapshot>> {
private final Query query;
@Nullable
private final Source source;
QueryObserver(@NonNull Query query) {
this(query, null);
}
QueryObserver(@NonNull Query query, @Nullable Source source) {
this.query = query;
this.source = source;
}
@Override
protected void subscribeActual(
@NonNull final SingleObserver<? super Value<QuerySnapshot>> observer) {
Listener listener = new Listener(observer);
observer.onSubscribe(listener);
if (null != source) {
query.get(source)
.addOnCompleteListener(listener);
} else {
query.get()
.addOnCompleteListener(listener);
}
}
static final class Listener extends OnCompleteDisposable<QuerySnapshot> {
private final SingleObserver<? super Value<QuerySnapshot>> observer;
Listener(@NonNull SingleObserver<? super Value<QuerySnapshot>> observer) {
this.observer = observer;
}
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (!isDisposed()) {
if (!task.isSuccessful()) {
Exception ex = task.getException();
if (null != ex) {
observer.onError(ex);
} else {
observer.onError(new UnknownError());
}
} else {
QuerySnapshot snapshot = task.getResult();
if (snapshot != null && !snapshot.isEmpty()) {
observer.onSuccess(Value.of(snapshot));
} else {
observer.onSuccess(Value.<QuerySnapshot>empty());
}
}
}
}
}
}
| 31.294872 | 83 | 0.594838 |
c412151cca8fd853e9733d0bc7914c00fca0549b | 3,325 | package org.ncic.bioinfo.sparkseq.algorithms.walker.mutect;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.BinomialDistribution;
import org.apache.commons.math.distribution.BinomialDistributionImpl;
/**
* Author: wbc
*/
public class TumorPowerCalculator extends AbstractPowerCalculator{
private double constantContamination;
private boolean enableSmoothing;
public TumorPowerCalculator(double constantEps, double constantLodThreshold, double constantContamination) {
this(constantEps, constantLodThreshold, constantContamination, true);
}
public TumorPowerCalculator(double constantEps, double constantLodThreshold, double constantContamination, boolean enableSmoothing) {
this.constantEps = constantEps;
this.constantLodThreshold = constantLodThreshold;
this.constantContamination = constantContamination;
this.enableSmoothing = enableSmoothing;
}
public double cachingPowerCalculation(int n, double delta) throws MathException {
PowerCacheKey key = new PowerCacheKey(n, delta);
Double power = cache.get(key);
if (power == null) {
power = calculatePower(n, constantEps, constantLodThreshold, delta, constantContamination, enableSmoothing);
cache.put(key, power);
}
return power;
}
protected static double calculateTumorLod(int depth, int alts, double eps, double contam) {
double f = (double) alts / (double) depth;
return (calculateLogLikelihood(depth, alts, eps, f) - calculateLogLikelihood(depth, alts, eps, Math.min(f,contam)));
}
protected static double calculatePower(int depth, double eps, double lodThreshold, double delta, double contam, boolean enableSmoothing) throws MathException {
if (depth==0) return 0;
// calculate the probability of each configuration
double p_alt_given_e_delta = delta*(1d-eps) + (1d-delta)*eps;
BinomialDistribution binom = new BinomialDistributionImpl(depth, p_alt_given_e_delta);
double[] p = new double[depth+1];
for(int i=0; i<p.length; i++) {
p[i] = binom.probability(i);
}
// calculate the LOD scores
double[] lod = new double[depth+1];
for(int i=0; i<lod.length; i++) {
lod[i] = calculateTumorLod(depth, i, eps, contam);
}
int k = -1;
for(int i=0; i<lod.length; i++) {
if (lod[i] >= lodThreshold) {
k = i;
break;
}
}
// if no depth meets the lod score, the power is zero
if (k == -1) {
return 0;
}
double power = 0;
// here we correct for the fact that the exact lod threshold is likely somewhere between
// the k and k-1 bin, so we prorate the power from that bin
// the k and k-1 bin, so we prorate the power from that bin
// if k==0, it must be that lodThreshold == lod[k] so we don't have to make this correction
if ( enableSmoothing && k > 0 ) {
double x = 1d - (lodThreshold - lod[k-1]) / (lod[k] - lod[k-1]);
power = x*p[k-1];
}
for(int i=k; i<p.length; i++) {
power += p[i];
}
return(power);
}
}
| 36.141304 | 163 | 0.63609 |
d4cc34611496759634ad297687178cf9d1f70dcd | 2,503 | /*
* Copyright 2013 David Curtis
*
* 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.logicmill.util.concurrent;
import org.logicmill.util.concurrent.ConcurrentLargeHashMapProbe.SegmentProbe;
/** Thrown by {@link ConcurrentLargeHashMapAuditor#verifyMapIntegrity(boolean, int)}
* to indicate that an illegal value was observed in the
* {@code ConcurrentLargeHashMap.Segment.offsets} array. Legal offset values include
* only {@code NULL_OFFSET} (-1) and integers between 0 (inclusive) and
* {@code HOP_RANGE} (32, exclusive).
* All other values are illegal.
* @author David Curtis
*
*/
public class IllegalOffsetValueException extends SegmentIntegrityException {
private static final long serialVersionUID = -8824296711479722977L;
private final int bucketIndex;
private final int offset;
private final int offsetValue;
/** Creates and IllegalOffsetValueException with the specified details.
* @param segmentProbe proxy for segment in which exception occurred; uses
* reflection to access private segment internals
* @param bucketIndex index of the bucket in which the illegal offset was
* observed
* @param offset offset (from the bucket index) of the illegal offset
* value
* @param offsetValue the illegal offset value
*/
public IllegalOffsetValueException(SegmentProbe segmentProbe,
int bucketIndex, int offset, int offsetValue) {
super(String.format("illegal offset value in buckets[%d + %d]: %d",
bucketIndex, offset, offsetValue), segmentProbe);
this.bucketIndex = bucketIndex;
this.offset = offset;
this.offsetValue = offsetValue;
}
/**
* @return index of the bucket containing the illegal offset value
*/
public int getBucketIndex() { return bucketIndex; }
/**
* @return the offset (from the bucket index) at which the illegal
* value was observed
*/
public int getOffset() { return offset; }
/**
* @return the observed illegal offset value
*/
public int getOffsetValue() { return offsetValue; }
}
| 37.924242 | 84 | 0.7503 |
9f85ad6dd24dc4b9a6b779fd7fb8f79ad79c85e8 | 1,835 | package com.chutneytesting.task.function;
import com.google.common.base.Ascii;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
class XmlUtils {
static Document toDocument(String documentAsString) throws InvalidXmlDocumentException {
SAXBuilder sxb = new SAXBuilder();
try {
return sxb.build(new ByteArrayInputStream(documentAsString.getBytes()));
} catch (JDOMException | IOException e) {
throw new InvalidXmlDocumentException(documentAsString);
}
}
static XPathExpression<Object> compileXPath(String xpath, Map<String, String> nsPrefixes) throws InvalidXPathException {
try {
List<Namespace> ns = new ArrayList<>();
nsPrefixes.forEach((prefix, url) -> ns.add(Namespace.getNamespace(prefix, url)));
return XPathFactory.instance().compile(xpath, Filters.fpassthrough(), null, ns);
} catch (IllegalArgumentException e) {
throw new InvalidXPathException(xpath);
}
}
@SuppressWarnings("serial")
public static class InvalidXmlDocumentException extends Exception {
InvalidXmlDocumentException(String documentAsString) {
super("Unable to parse XML document: " + Ascii.truncate(documentAsString, 100, "..."));
}
}
@SuppressWarnings("serial")
public static class InvalidXPathException extends Exception {
InvalidXPathException(String xpath) {
super("Unable to compile XPath: " + xpath);
}
}
}
| 35.980392 | 124 | 0.700272 |
27993e729c693d517a641e2086dfe9b1ac33353e | 1,958 | /*
* 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.aliyuncs.rds.transform.v20140815;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.rds.model.v20140815.PreCheckDBInstanceOperationResponse;
import com.aliyuncs.rds.model.v20140815.PreCheckDBInstanceOperationResponse.FailuresItem;
import com.aliyuncs.transform.UnmarshallerContext;
public class PreCheckDBInstanceOperationResponseUnmarshaller {
public static PreCheckDBInstanceOperationResponse unmarshall(PreCheckDBInstanceOperationResponse preCheckDBInstanceOperationResponse, UnmarshallerContext _ctx) {
preCheckDBInstanceOperationResponse.setRequestId(_ctx.stringValue("PreCheckDBInstanceOperationResponse.RequestId"));
preCheckDBInstanceOperationResponse.setPreCheckResult(_ctx.booleanValue("PreCheckDBInstanceOperationResponse.PreCheckResult"));
List<FailuresItem> failures = new ArrayList<FailuresItem>();
for (int i = 0; i < _ctx.lengthValue("PreCheckDBInstanceOperationResponse.Failures.Length"); i++) {
FailuresItem failuresItem = new FailuresItem();
failuresItem.setMessage(_ctx.stringValue("PreCheckDBInstanceOperationResponse.Failures["+ i +"].Message"));
failuresItem.setCode(_ctx.stringValue("PreCheckDBInstanceOperationResponse.Failures["+ i +"].Code"));
failures.add(failuresItem);
}
preCheckDBInstanceOperationResponse.setFailures(failures);
return preCheckDBInstanceOperationResponse;
}
} | 44.5 | 162 | 0.802349 |
a7762b231119ee05b2f79e036f948a041bb5dded | 222 | package com.example.render;
import react4j.annotations.PreUpdate;
import react4j.annotations.View;
@View( type = View.Type.NO_RENDER )
abstract class NoRenderWithPreUpdateView
{
@PreUpdate
void preUpdate()
{
}
}
| 15.857143 | 40 | 0.761261 |
8c2fcc289e596cfd8f9511557bd1d68fd50b1ca8 | 2,680 | package com.commercetools.sunrise.myaccount.authentication.recoverpassword.reset;
import com.commercetools.sunrise.framework.hooks.HookRunner;
import com.commercetools.sunrise.framework.hooks.ctprequests.CustomerPasswordResetCommandHook;
import io.sphere.sdk.client.SphereClient;
import io.sphere.sdk.customers.Customer;
import io.sphere.sdk.customers.commands.CustomerPasswordResetCommand;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultResetPasswordControllerAction}.
*/
public class DefaultResetPasswordControllerActionTest {
@Mock
private SphereClient sphereClient;
@Mock
private HookRunner hookRunner;
@Mock
private Customer customer;
@Captor
private ArgumentCaptor<CustomerPasswordResetCommand> customerPasswordResetCommandCaptor;
@InjectMocks
private DefaultResetPasswordControllerAction defaultResetPasswordControllerAction;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void execute() throws ExecutionException, InterruptedException {
final String password = "password";
final DefaultResetPasswordFormData resetPasswordFormData = new DefaultResetPasswordFormData();
resetPasswordFormData.setConfirmPassword(password);
resetPasswordFormData.setNewPassword(password);
final String resetTokenValue = "reset-token-value";
when:
{
when(hookRunner.runUnaryOperatorHook(eq(CustomerPasswordResetCommandHook.class), any(), customerPasswordResetCommandCaptor.capture()))
.thenAnswer(invocation -> invocation.getArgument(2));
when(sphereClient.execute(any()))
.thenReturn(CompletableFuture.completedFuture(customer));
}
final Customer updatedCustomer = defaultResetPasswordControllerAction.apply(resetTokenValue, resetPasswordFormData)
.toCompletableFuture().get();
then: {
assertThat(updatedCustomer).isNotNull();
final CustomerPasswordResetCommand customerPasswordResetCommand = customerPasswordResetCommandCaptor.getValue();
assertThat(customerPasswordResetCommand.getTokenValue()).isEqualTo(resetTokenValue);
assertThat(customerPasswordResetCommand.getNewPassword()).isEqualTo(password);
}
}
}
| 37.746479 | 146 | 0.75709 |
0177dc1245de5ba2de2c9cc122b1be031bba8706 | 5,498 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|tika
operator|.
name|config
package|;
end_package
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayOutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|File
import|;
end_import
begin_import
import|import
name|java
operator|.
name|math
operator|.
name|BigInteger
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URI
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URL
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashSet
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|*
import|;
end_import
begin_class
specifier|public
class|class
name|ParamTest
block|{
annotation|@
name|Test
specifier|public
name|void
name|testSaveAndLoad
parameter_list|()
throws|throws
name|Exception
block|{
name|Object
name|objects
index|[]
init|=
block|{
name|Integer
operator|.
name|MAX_VALUE
block|,
literal|2.5f
block|,
literal|4000.57576
block|,
literal|true
block|,
literal|false
block|,
name|Long
operator|.
name|MAX_VALUE
block|,
literal|"Hello this is a boring string"
block|,
operator|new
name|URL
argument_list|(
literal|"http://apache.org"
argument_list|)
block|,
operator|new
name|URI
argument_list|(
literal|"tika://org.apache.tika.ner.parser?impl=xyz"
argument_list|)
block|,
operator|new
name|BigInteger
argument_list|(
name|Long
operator|.
name|MAX_VALUE
operator|+
literal|""
argument_list|)
operator|.
name|add
argument_list|(
operator|new
name|BigInteger
argument_list|(
name|Long
operator|.
name|MAX_VALUE
operator|+
literal|""
argument_list|)
argument_list|)
block|,
operator|new
name|File
argument_list|(
literal|"."
argument_list|)
block|, }
decl_stmt|;
for|for
control|(
name|Object
name|object
range|:
name|objects
control|)
block|{
name|String
name|name
init|=
literal|"name"
operator|+
name|System
operator|.
name|currentTimeMillis
argument_list|()
decl_stmt|;
name|Param
argument_list|<
name|?
argument_list|>
name|param
init|=
operator|new
name|Param
argument_list|<>
argument_list|(
name|name
argument_list|,
name|object
argument_list|)
decl_stmt|;
name|ByteArrayOutputStream
name|stream
init|=
operator|new
name|ByteArrayOutputStream
argument_list|()
decl_stmt|;
name|param
operator|.
name|save
argument_list|(
name|stream
argument_list|)
expr_stmt|;
name|ByteArrayInputStream
name|inStream
init|=
operator|new
name|ByteArrayInputStream
argument_list|(
name|stream
operator|.
name|toByteArray
argument_list|()
argument_list|)
decl_stmt|;
name|stream
operator|.
name|close
argument_list|()
expr_stmt|;
name|inStream
operator|.
name|close
argument_list|()
expr_stmt|;
name|Param
argument_list|<
name|?
argument_list|>
name|loaded
init|=
name|Param
operator|.
name|load
argument_list|(
name|inStream
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|param
operator|.
name|getName
argument_list|()
argument_list|,
name|loaded
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|param
operator|.
name|getTypeString
argument_list|()
argument_list|,
name|loaded
operator|.
name|getTypeString
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|param
operator|.
name|getType
argument_list|()
argument_list|,
name|loaded
operator|.
name|getType
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|param
operator|.
name|getValue
argument_list|()
argument_list|,
name|loaded
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|loaded
operator|.
name|getValue
argument_list|()
argument_list|,
name|object
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|loaded
operator|.
name|getName
argument_list|()
argument_list|,
name|name
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|loaded
operator|.
name|getType
argument_list|()
argument_list|,
name|object
operator|.
name|getClass
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 14.739946 | 809 | 0.791379 |
cbd1b31b5b97243ece7cdf816d8ee9d87215088c | 5,577 | /**
* The MIT License (MIT)
*
* Copyright (c) 2014 jc0mm0n
*
* 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.waynezhang.mcommon.support;
import java.lang.ref.WeakReference;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import com.waynezhang.mcommon.network.NetworkChecker;
import com.waynezhang.mcommon.network.ResultCode;
import com.waynezhang.mcommon.util.L;
import com.waynezhang.mcommon.xwidget.LoadingLayout;
public abstract class McAbsCallback {
private boolean alwaysCallback = false;
private WeakReference<FragmentActivity> mActivityRef;
private WeakReference<LoadingLayout> mLoadingLayoutRef;
private WeakReference<Fragment> mFragmentRef;
public McAbsCallback(){
alwaysCallback = true;
}
public McAbsCallback(FragmentActivity activity) {
init(activity, null);
}
public McAbsCallback(Fragment fragment) {
init(fragment, null);
}
public McAbsCallback(FragmentActivity activity, LoadingLayout loadingLayout) {
init(activity, loadingLayout);
}
public McAbsCallback(Fragment fragment, LoadingLayout loadingLayout) {
init(fragment, loadingLayout);
}
private void init(Fragment fragment, LoadingLayout loadingLayout) {
if (fragment == null)
throw new RuntimeException("fragment should not be null when init ReqCallback");
mFragmentRef = new WeakReference<Fragment>(fragment);
init(fragment.getActivity(), loadingLayout);
}
private void init(FragmentActivity activity, LoadingLayout loadingLayout) {
if (activity == null)
L.w("JcAbsCallback", "activity should not be null when init ReqCallback");
mActivityRef = new WeakReference<FragmentActivity>(activity);
mLoadingLayoutRef = new WeakReference<LoadingLayout>(
loadingLayout);
startLoading();
}
/**
* 如果相应的Activity都不存在时也要进行回调
*/
protected boolean isAlwaysCallback() {
return alwaysCallback;
}
protected boolean canCallback() {
if(mFragmentRef != null){
//如果由Fragment发起回调,当回调中调用getActivity时有些情况会出现Activity为null
//此处对这些情况进行过滤
if(exists(mFragmentRef) && mFragmentRef.get().getActivity() != null){
return !Safeguard.ignorable(mFragmentRef.get());
}
}else if(mActivityRef != null && !Safeguard.ignorable(mActivityRef.get())){
return !Safeguard.ignorable(mActivityRef.get());
}
return false;
}
protected boolean needShowLoading(){
return true;
}
private <T> boolean exists(WeakReference<T> ref) {
if (ref == null) {
return false;
}
T obj = ref.get();
return obj!= null;
}
protected void startLoading() {
if(!needShowLoading())
return;
if (exists(mLoadingLayoutRef)) {
LoadingLayout loadingLayout = mLoadingLayoutRef.get();
loadingLayout.showLoadingView();
}
}
protected void endLoading() {
if(!needShowLoading())
return;
if (exists(mLoadingLayoutRef)) {
LoadingLayout loadingLayout = mLoadingLayoutRef.get();
loadingLayout.hideLoadingView();
}
}
@SuppressWarnings("incomplete-switch")
protected void showLoadingWithException(ResultCode code) {
if (exists(mLoadingLayoutRef)) {
LoadingLayout loadingLayout = mLoadingLayoutRef.get();
switch (code){
case NoNetwork:
loadingLayout.showView(LoadingLayout.ViewType.NoNetwork);
break;
case NetworkException:
if(NetworkChecker.isOffline(loadingLayout.getContext())){
loadingLayout.showView(LoadingLayout.ViewType.NoNetwork);
} else {
loadingLayout.showView(LoadingLayout.ViewType.NetworkException);
}
break;
case RequestTimeout:
loadingLayout.showView(LoadingLayout.ViewType.Timeout);
break;
case ServerException:
loadingLayout.showView(LoadingLayout.ViewType.ServerException);
break;
case DefaultException:
loadingLayout.showView(LoadingLayout.ViewType.DefaultException);
break;
}
}
}
}
| 34.639752 | 92 | 0.649453 |
1cee8fffbcb6e5f8891097346df4d0fea576e937 | 7,680 | package me.bayang.reader.controllers;
import java.text.MessageFormat;
import java.util.List;
import java.util.ResourceBundle;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXSnackbar;
import com.jfoenix.controls.JFXSnackbar.SnackbarEvent;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXToggleButton;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import me.bayang.reader.FXMain;
import me.bayang.reader.share.wallabag.WallabagClient;
import me.bayang.reader.share.wallabag.WallabagCredentials;
import me.bayang.reader.storage.IStorageService;
import me.bayang.reader.utils.Theme;
import me.bayang.reader.view.PocketOauthView;
import me.bayang.reader.view.RssView;
@FXMLController
public class SettingsController {
private static final Logger LOGGER = LoggerFactory.getLogger(SettingsController.class);
private static ResourceBundle bundle = ResourceBundle.getBundle("i18n.translations");
@Autowired
private IStorageService configStorage;
@FXML
private VBox settingsContainer;
@FXML
private JFXToggleButton layoutToggle;
@FXML
private JFXToggleButton pocketActivate;
@FXML
private JFXToggleButton wallabagActivate;
@FXML
private JFXButton pocketConfigure;
@FXML
private JFXButton backButton;
@FXML
private Label pocketStatus;
@FXML
private JFXComboBox<String> themeComboBox;
@FXML
private JFXButton wallabagConnect;
@FXML
private JFXTextField wallabagUrlField;
@FXML
private JFXTextField wallabagUserField;
@FXML
private JFXPasswordField wallabagPasswordField;
@FXML
private JFXTextField wallabagClientIdField;
@FXML
private JFXTextField wallabagClientSecretField;
@Autowired
private PocketOauthView pocketOauthView;
private PocketOauthController pocketOauthController;
private Stage pocketOauthStage;
private static JFXSnackbar snackbar;
@Autowired
public List<AbstractFxmlView> views;
@Autowired
private WallabagClient wallabagClient;
@FXML
public void initialize() {
for (Theme t : Theme.values()) {
themeComboBox.getItems().add(t.getDisplayName());
}
themeComboBox.getSelectionModel().select(configStorage.getAppTheme().getDisplayName());
pocketActivate.selectedProperty().bindBidirectional(configStorage.pocketEnabledProperty());
layoutToggle.selectedProperty().bindBidirectional(configStorage.prefersGridLayoutProperty());
pocketStatus.textProperty().bind(Bindings.when(configStorage.pocketUserProperty().isEmpty())
.then("")
.otherwise(MessageFormat.format(bundle.getString("settingsShareProviderStatus"), configStorage.pocketUserProperty().getValue())));
wallabagActivate.selectedProperty().bindBidirectional(configStorage.wallabagEnabledProperty());
initWallabagFieldsBindings();
snackbar = new JFXSnackbar(settingsContainer);
}
public void initWallabagFieldsBindings() {
wallabagClientIdField.disableProperty().bind(Bindings.not(wallabagActivate.selectedProperty()));
wallabagClientSecretField.disableProperty().bind(Bindings.not(wallabagActivate.selectedProperty()));
wallabagUrlField.disableProperty().bind(Bindings.not(wallabagActivate.selectedProperty()));
wallabagPasswordField.disableProperty().bind(Bindings.not(wallabagActivate.selectedProperty()));
wallabagUserField.disableProperty().bind(Bindings.not(wallabagActivate.selectedProperty()));
}
@FXML
public void showMainScreen() {
FXMain.showView(RssView.class);
}
@FXML
public void showPocketOauthStage() {
if (pocketOauthStage == null) {
Stage dialogStage = new Stage();
dialogStage.setTitle(bundle.getString("pocketLogin"));
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(FXMain.getStage());
dialogStage.getIcons().add(new Image("icon.png"));
dialogStage.setResizable(true);
Scene scene = new Scene(pocketOauthView.getView());
dialogStage.setScene(scene);
this.pocketOauthStage = dialogStage;
pocketOauthController = (PocketOauthController) pocketOauthView.getPresenter();
pocketOauthController.setStage(dialogStage);
// Show the dialog and wait until the user closes it
pocketOauthController.processLogin();
dialogStage.showAndWait();
}
else {
pocketOauthController.processLogin();
pocketOauthStage.showAndWait();
}
}
@FXML
public void changeTheme() {
LOGGER.debug("theme : {}", themeComboBox.getValue());
Theme theme = Theme.forDisplayName(themeComboBox.getValue());
if (theme != null) {
configStorage.setAppTheme(theme);
setTheme(theme);
}
}
public void setTheme(Theme theme) {
LOGGER.debug("changing theme to {}", theme.getPath());
FXMain.getScene().getStylesheets().clear();
FXMain.setUserAgentStylesheet(null);
FXMain.setUserAgentStylesheet(FXMain.STYLESHEET_MODENA);
FXMain.getScene().getStylesheets().add(getClass().getResource(theme.getPath()).toExternalForm());
for (AbstractFxmlView v : views) {
v.getView().getStylesheets().clear();
v.getView();
}
}
@FXML
public void wallabagConnect() {
if (validateWallabagFields()) {
WallabagCredentials credentials =
new WallabagCredentials(wallabagUrlField.getText(), wallabagUserField.getText(),
wallabagPasswordField.getText(), wallabagClientIdField.getText(),
wallabagClientSecretField.getText(), null, null);
if (wallabagClient.testCredentials(credentials)) {
snackbarNotify(FXMain.bundle.getString("reachedServer"), 2000);
}
else {
snackbarNotify(FXMain.bundle.getString("failedVerification"), 2500);
}
}
else {
snackbarNotify(FXMain.bundle.getString("allFieldsMandatory"), 2000);
}
}
private boolean validateWallabagFields() {
if (!StringUtils.isBlank(wallabagClientIdField.getText())
&& ! StringUtils.isBlank(wallabagClientSecretField.getText())
&& ! StringUtils.isBlank(wallabagPasswordField.getText())
&& ! StringUtils.isBlank(wallabagUserField.getText())
&& ! StringUtils.isBlank(wallabagUrlField.getText())) {
return true;
}
return false;
}
public static void snackbarNotify(String msg, long duration) {
if (msg != null) {
snackbar.enqueue(new SnackbarEvent(msg, null, duration, false, null));
}
}
}
| 35.391705 | 162 | 0.679427 |
6447c44818340f98f2cea8b6e9ef6581187b503b | 844 | package edu.virginia.vcgr.smb.server.set;
import edu.virginia.vcgr.smb.server.FileTime;
import edu.virginia.vcgr.smb.server.SMBBuffer;
import edu.virginia.vcgr.smb.server.SMBFile;
public class SMBSetFileBasicInfo
{
public static void encode(SMBFile fd, SMBBuffer dataIn)
{
FileTime createTime = FileTime.decode(dataIn);
FileTime accessTime = FileTime.decode(dataIn);
FileTime writeTime = FileTime.decode(dataIn);
/* FileTime changeTime = */FileTime.decode(dataIn);
int fileAttr = dataIn.getInt();
dataIn.getInt();
if (!createTime.isZero() && !createTime.isMax())
fd.setCreateTime(createTime.toMillis());
if (!accessTime.isZero() && !accessTime.isMax())
fd.setAccessTime(accessTime.toMillis());
if (!writeTime.isZero() && !writeTime.isMax())
fd.setWriteTime(writeTime.toMillis());
fd.setExtAttr(fileAttr);
}
}
| 31.259259 | 56 | 0.739336 |
c944ba94468cb6c3419fed8f35fa6781ec8ada47 | 2,966 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gobblin.data.management.copy;
import gobblin.configuration.SourceState;
import gobblin.configuration.State;
import gobblin.configuration.WorkUnitState;
import gobblin.data.management.copy.extractor.CloseableFsFileAwareInputStreamExtractor;
import gobblin.source.extractor.Extractor;
import gobblin.source.extractor.extract.sftp.SftpLightWeightFileSystem;
import gobblin.util.HadoopUtils;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.fs.FileSystem;
import com.google.common.io.Closer;
/**
* Used instead of {@link CopySource} for {@link FileSystem}s that need be closed after use E.g
* {@link SftpLightWeightFileSystem}.
* <p>
* Note that all {@link FileSystem} implementations should not be closed as Hadoop's
* {@link FileSystem#get(org.apache.hadoop.conf.Configuration)} API returns a cached copy of {@link FileSystem} by
* default. The same {@link FileSystem} instance may be used by other classes in the same JVM. Closing a cached
* {@link FileSystem} may cause {@link IOException} at other parts of the code using the same instance.
* </p>
* <p>
* For {@link SftpLightWeightFileSystem} a new instance is returned on every
* {@link FileSystem#get(org.apache.hadoop.conf.Configuration)} call. Closing is necessary as the file system maintains
* a session with the remote server.
*
* @see HadoopUtils#newConfiguration()
* @See SftpLightWeightFileSystem
* </p>
*/
@Slf4j
public class CloseableFsCopySource extends CopySource {
private final Closer closer = Closer.create();
@Override
protected FileSystem getSourceFileSystem(State state)
throws IOException {
return this.closer.register(super.getSourceFileSystem(state));
}
@Override
public void shutdown(SourceState state) {
try {
this.closer.close();
} catch (IOException e) {
log.warn("Failed to close all closeables", e);
}
}
@Override
protected Extractor<String, FileAwareInputStream> extractorForCopyableFile(FileSystem fs, CopyableFile cf,
WorkUnitState state)
throws IOException {
return new CloseableFsFileAwareInputStreamExtractor(fs, cf, state);
}
}
| 36.617284 | 119 | 0.759272 |
c7bd148771e6d10a86d2f8d8669cb5a9e6a847ae | 496 | package ch.lukasmartinelli.redditclone.bl.reddit;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
public class RedditRepository implements Serializable {
private ArrayList<Reddit> reddits = new ArrayList<>();
public RedditRepository() {
}
public ArrayList<Reddit> getReddits() {
return reddits;
}
public void setReddits(ArrayList<Reddit> r) {
reddits = r;
}
public Reddit getRedditById(int id) {
return new Reddit();
}
}
| 19.84 | 55 | 0.743952 |
85f936a9978439491817454139df72c171fb8d0c | 550 | package io.github.mrdear.excel.convert;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author rxliuli
*/
class LocalYmdDateConverterTest {
private final IConverter<LocalDate> converter = new LocalDateConverter();
private final LocalDate now = LocalDate.now();
@Test
void to() {
assertThat(converter.to(now))
.isEqualTo(now.toString());
}
@Test
void from() {
assertThat(converter.from(now.toString()))
.isEqualTo(now);
}
} | 20.37037 | 75 | 0.7 |
33fb45a7573d6eaf85137a103a6ce7890b20a699 | 12,012 | /**
* ##library.name##
*
* <p>##library.sentence##
*
* <p>##library.url##
*
* <p>Copyright ##copyright## ##author##
*
* <p>This library is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* <p>This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* <p>You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* @author ##author##
* @modified ##date##
* @version ##library.prettyVersion## (##library.version##)
*/
package mqtt;
import java.lang.reflect.*;
import java.lang.Exception;
import java.lang.Override;
import java.lang.String;
import java.lang.Throwable;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.concurrent.CopyOnWriteArrayList;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.*;
import processing.core.*;
/** An MQTTClient that can publish and subscribe. */
public class MQTTClient implements MqttCallbackExtended {
private MqttAsyncClient client;
private PApplet parent;
private CopyOnWriteArrayList<Message> messages;
private CopyOnWriteArrayList<Event> events;
private Will will;
private MQTTListener listener;
private Method messageReceivedMethod;
private Method clientConnectedMethod;
private Method connectionLostMethod;
private final static long TIMEOUT = 2000;
/**
* The constructor, usually called in the setup() method in your sketch to initialize and start
* the library.
*
* @param parent A reference to the running sketch.
*/
public MQTTClient(PApplet parent) {
// save parent
this.parent = parent;
// init messages and events list
messages = new CopyOnWriteArrayList<>();
events = new CopyOnWriteArrayList<>();
// register callbacks
parent.registerMethod("dispose", this);
parent.registerMethod("draw", this);
// find callbacks
messageReceivedMethod = findMessageReceivedCallback();
clientConnectedMethod = findClientConnectedCallback();
connectionLostMethod = findConnectionLostCallback();
}
/**
* The constructor, usually called in the setup() method in your sketch to initialize and start
* the library.
*
* @param parent A reference to the running sketch.
* @param listener A class that receives events.
*/
public MQTTClient(PApplet parent, MQTTListener listener) {
// save parent
this.parent = parent;
this.listener = listener;
// init messages and events list
messages = new CopyOnWriteArrayList<>();
events = new CopyOnWriteArrayList<>();
// register callbacks
parent.registerMethod("dispose", this);
parent.registerMethod("draw", this);
}
/**
* Set a last will message with topic, payload, QoS and the retained flag.
*
* @param topic The topic.
* @param payload The payload.
* @param qos The qos level.
* @param retained The retainged flag.
*/
public void setWill(String topic, String payload, int qos, boolean retained) {
setWill(topic, payload.getBytes(Charset.forName("UTF-8")), qos, retained);
}
/**
* Set a last will message with topic and payload.
*
* @param topic The topic.
* @param payload The payload.
*/
public void setWill(String topic, String payload) {
setWill(topic, payload, 0, false);
}
/**
* Set a last will message with topic, payload, QoS and the retained flag.
*
* @param topic The topic.
* @param payload The payload.
* @param qos The qos.
* @param retained The retained flag.
*/
public void setWill(String topic, byte[] payload, int qos, boolean retained) {
will = new Will(topic, payload, qos, retained);
}
/**
* Connect to a broker using only a broker URI.
*
* @param brokerURI The broker URI.
*/
public void connect(String brokerURI) {
connect(brokerURI, MqttClient.generateClientId());
}
/**
* Connect to a broker using an broker URI and client ID.
*
* @param brokerURI The broker URI.
* @param clientID The client ID.
*/
public void connect(String brokerURI, String clientID) {
connect(brokerURI, clientID, true);
}
/**
* Connect to a broker using an broker URI, client Id and cleanSession flag.
*
* @param brokerURI The broker URI.
* @param clientId The client ID.
* @param cleanSession The clean session flag.
*/
public void connect(String brokerURI, String clientId, boolean cleanSession) {
// parse uri
URI uri;
try {
uri = new URI(brokerURI);
} catch (URISyntaxException e) {
throw new RuntimeException("[MQTT] Failed to parse URI: " + e.getMessage(), e);
}
try {
// prepare connection options
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(cleanSession);
options.setAutomaticReconnect(true);
// check will messafe
if (will != null) {
options.setWill(will.topic, will.payload, will.qos, will.retained);
}
// check for auth info
if (uri.getUserInfo() != null) {
String[] auth = uri.getUserInfo().split(":");
// check username
if (auth.length > 0) {
options.setUserName(auth[0]);
// check passsword
if (auth.length > 1) {
options.setPassword(auth[1].toCharArray());
}
}
}
// parse scheme
String scheme = uri.getScheme();
if (scheme.equals("mqtt")) {
scheme = "tcp";
} else if (scheme.equals("mqtts")) {
scheme = "ssl";
}
// finalize location
String loc = scheme + "://" + uri.getHost();
if (uri.getPort() != -1) {
loc = loc + ":" + uri.getPort();
}
// create client
client = new MqttAsyncClient(loc, clientId, new MemoryPersistence());
client.setCallback(this);
// connect to broker
client.connect(options).waitForCompletion(TIMEOUT);
} catch (MqttException e) {
throw new RuntimeException("[MQTT] Failed to connect:: " + e.getMessage(), e);
}
}
/**
* Publish a message with a topic.
*
* @param topic The topic.
*/
public void publish(String topic) {
byte[] bytes = {};
publish(topic, bytes);
}
/**
* Publish a message with a topic and payload.
*
* @param topic The topic.
* @param payload The payload.
*/
public void publish(String topic, String payload) {
publish(topic, payload, 0, false);
}
/**
* Publish a message with a topic, payload qos and retain flag.
*
* @param topic The topic.
* @param payload The payload.
* @param qos The qos level.
* @param retained The retained flag.
*/
public void publish(String topic, String payload, int qos, boolean retained) {
publish(topic, payload.getBytes(Charset.forName("UTF-8")), qos, retained);
}
/**
* Publish a message with a topic and payload.
*
* @param topic The topic.
* @param payload The payload.
*/
public void publish(String topic, byte[] payload) {
publish(topic, payload, 0, false);
}
/**
* Publish a message with a topic, payload qos and retain flag.
*
* @param topic The topic.
* @param payload The payload.
* @param qos The qos level.
* @param retained The retained flag.
*/
public void publish(String topic, byte[] payload, int qos, boolean retained) {
try {
client.publish(topic, payload, qos, retained).waitForCompletion(TIMEOUT);
} catch (MqttException e) {
throw new RuntimeException("[MQTT] Failed to publish: " + e.getMessage(), e);
}
}
/**
* Subscribe a topic.
*
* @param topic The topic.
*/
public void subscribe(String topic) {
this.subscribe(topic, 0);
}
/**
* Subscribe a topic with QoS.
*
* @param topic The topic.
* @param qos The qos level.
*/
public void subscribe(String topic, int qos) {
try {
client.subscribe(topic, qos).waitForCompletion(TIMEOUT);
} catch (MqttException e) {
throw new RuntimeException("[MQTT] Failed to subscribe: " + e.getMessage(), e);
}
}
/**
* Unsubscribe a topic.
*
* @param topic The topic.
*/
public void unsubscribe(String topic) {
try {
client.unsubscribe(topic).waitForCompletion(TIMEOUT);
} catch (MqttException e) {
throw new RuntimeException("[MQTT] Failed to unsubscribe: " + e.getMessage(), e);
}
}
/**
* Disconnect from the broker.
*/
public void disconnect() {
try {
client.disconnect().waitForCompletion(TIMEOUT);
} catch (MqttException e) {
throw new RuntimeException("[MQTT] Failed to disconnect: " + e.getMessage(), e);
}
}
public void dispose() {
try {
disconnect();
} catch(Exception ignored) { }
}
public void draw() {
// process all queue events
for (Event event : events) {
// invoke client connected callback
if (event.clientConnected) {
if(listener != null) {
try {
listener.clientConnected();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (clientConnectedMethod != null) {
try {
clientConnectedMethod.invoke(parent);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// invoke connection lost callback
if (event.connectionLost) {
if(listener != null) {
try {
listener.connectionLost();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (connectionLostMethod != null) {
try {
connectionLostMethod.invoke(parent);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
// process all messages and invoke message received callback
for (Message message : messages) {
if(listener != null) {
try {
listener.messageReceived(message.topic, message.message.getPayload());
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (messageReceivedMethod != null) {
try {
messageReceivedMethod.invoke(parent, message.topic, message.message.getPayload());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// clear all queued events and messages
events.clear();
messages.clear();
}
@Override
public void connectComplete(boolean b, String s) {
events.add(new Event(true, false));
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) {
messages.add(new Message(topic, mqttMessage));
}
@Override
public void connectionLost(Throwable throwable) {
events.add(new Event(false, true));
}
private Method findMessageReceivedCallback() {
try {
return parent.getClass().getMethod("messageReceived", String.class, byte[].class);
} catch (Exception e) {
throw new RuntimeException("MQTT] Callback not found!", e);
}
}
private Method findClientConnectedCallback() {
try {
return parent.getClass().getMethod("clientConnected");
} catch (Exception e) {
return null;
}
}
private Method findConnectionLostCallback() {
try {
return parent.getClass().getMethod("connectionLost");
} catch (Exception e) {
return null;
}
}
}
| 27.677419 | 100 | 0.637945 |
ba1ac24d172cfdd56c4ccf7e4fb2d10843bf6d37 | 144 | package com.quorum.tessera.test.rest;
public interface RawHeaderName {
String SENDER = "c11n-from";
String RECIPIENTS = "c11n-to";
}
| 16 | 37 | 0.701389 |
ca268ef62fcef5336a626d19c0ad4082278d9872 | 2,158 | package org.december.beanui.element.annotation;
import java.lang.annotation.*;
@Documented
@Target({ElementType.FIELD, ElementType.TYPE})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Tooltip {
class Placement {
public static final String TOP = "top";
public static final String TOP_START = "top_start";
public static final String TOP_END = "top_end";
public static final String BOTTOM = "bottom";
public static final String BOTTOM_START = "bottom_start";
public static final String BOTTOM_END = "bottom_end";
public static final String LEFT = "left";
public static final String LEFT_START = "left_start";
public static final String LEFT_END = "left_end";
public static final String RIGHT = "right";
public static final String RIGHT_START = "right_start";
public static final String RIGHT_END = "right_end";
}
String effect() default ""; //默认提供的主题 String dark/light dark
String content() default ""; //显示的内容,也可以通过 slot#content 传入 DOM String — —
String placement() default ""; //Tooltip 的出现位置 String top/top_start/top_end/bottom/bottom_start/bottom_end/left/left_start/left_end/right/right_start/right_end bottom
String value() default "";//(v_model) 状态是否可见 Boolean — false
String disabled() default ""; //Tooltip 是否可用 Boolean — false
String offset() default "";// 出现位置的偏移量 Number — 0
String transition() default ""; //定义渐变动画 String — el_fade_in_linear
String visible_arrow() default "";// 是否显示 Tooltip 箭头,更多参数可见Vue_popper Boolean — true
String popper_options() default "";// popper.js 的参数 Object 参考 popper.js 文档 { boundariesElement: 'body', gpuAcceleration: false }
String open_delay() default "";// 延迟出现,单位毫秒 Number — 0
String manual() default "";// 手动控制模式,设置为 true 后,mouseenter 和 mouseleave 事件将不会生效 Boolean — false
String popper_class() default "";// 为 Tooltip 的 popper 添加类名 String — —
String enterable() default "";// 鼠标是否可进入到 tooltip 中 Boolean — true
String hide_after() default "";// Tooltip 出现后自动隐藏延时,单位毫秒,为 0 则不会自动隐藏 number — 0
String tag() default "el-tooltip";
}
| 52.634146 | 170 | 0.703892 |
350004af13efaf9aa2886ef9f8a73b9a80489adf | 746 | package chapter4.partitioner;
import java.util.StringTokenizer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;
import chapter4.LogWritable;
/**
* HTTP server log processing sample for the Chapter 4 of Hadoop MapReduce
* Cookbook.
*
* @author Thilina Gunarathne
*/
public class IPBasedPartitioner extends Partitioner<Text, LogWritable>{
@Override
public int getPartition(Text ipAddress, LogWritable value, int numPartitions) {
StringTokenizer tokenizer = new StringTokenizer(ipAddress.toString(), ".");
if (tokenizer.hasMoreTokens()){
String token = tokenizer.nextToken();
return ((token.hashCode() & Integer.MAX_VALUE) % numPartitions);
}
return 0;
}
}
| 27.62963 | 81 | 0.726542 |
900d85e88c56164360a269f1661ce3b433a013fd | 265 | package com.gtecnologia.store.services.exceptions;
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException (Object id) {
super("Resource not found. id " + id);
}
}
| 24.090909 | 65 | 0.781132 |
28b7a27cd38d75b4bf182e3f005ee6d3111bca0f | 4,326 | package sort;
/*
Se basa en la técnica divide y vencerás, que consiste en ir subdividiendo el array en arrays más pequeños, y ordenar éstos. Para hacer esta división, se toma un valor del array como pivote, y se mueven todos los
elementos menores que este pivote a su izquierda, y los mayores a su derecha. A continuación se aplica el mismo método a cada una de las dos partes en las que queda dividido el array.
Después de elegir el pivote se realizan dos búsquedas:
Una de izquierda a derecha, buscando un elemento mayor que el pivote
Otra de derecha a izquierda, buscando un elemento menor que el pivote.
Cuando se han encontrado los dos elementos anteriores, se intercambian, y se sigue realizando la búsqueda hasta que las dos búsquedas se encuentran.
Suponiendo que tomamos como pivote el primer elemento, el método Java Quicksort que implementa este algoritmo de ordenación para ordenar un array de enteros se presenta a continuación. Los parámetros izq y
der son el primer y último elemento del array a tratar en cada momento.
El método ordena un array A d eenteros desde la posición izq hasta la posición der. En la primera llamada recibirá los valores izq = 0, der = ELEMENTOS-1.
Los elementos iguales que el pivote (duplicados) van a una u otra partición, pero siempre a la misma.
En el peor caso, cuando el pivote es el elemento menor del array el tiempo de ejecución del método Quicksort es O(n2).
En general el tiempo medio de ejecución del Quicksort es O(n log n).
El proceso de selección consiste en, dado un vector de N elementos, encontrar el k-ésimo menor elemento.
Se puede resolver el problema de selección en tiempo lineal, en promedio.
El peor caso en la selección rápida se presenta cuando la llamada recursiva se realiza con un solo elemento menos.
La mediana de un grupo de N elementos es el [N/2]-ésimo menor elemento.
*/
public class QuickSort {
private static void insertionSort(Comparable[] a, int low, int high) {
for (int p = low + 1; p <= high; p++) {
Comparable tmp = a[p];
int j;
for (j = p; j > low && tmp.lessThan(a[j - 1]); j--)
a[j] = a[j - 1];
a[j] = tmp;
}
}
/**
* Quicksort algorithm.
*
* @param a an array of Comparable items.
*/
public static void quicksort(Comparable[] a) {
quicksort(a, 0, a.length - 1);
}
private static final int CUTOFF = 10;
/**
* Method to swap to elements in an array.
*
* @param a an array of objects.
* @param index1 the index of the first object.
* @param index2 the index of the second object.
*/
public static void swapReferences(Object[] a, int index1, int index2) {
Object tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
/**
* Internal quicksort method that makes recursive calls.
* Uses median-of-three partitioning and a cutoff of 10.
* @param a an array of Comparable items.
* @param low the left-most index of the subarray.
* @param high the right-most index of the subarray. */
private static void quicksort( Comparable [ ] a, int low, int high ) {
if( low + CUTOFF > high )
insertionSort( a, low, high );
else {
// Sort low, middle, high
int middle = ( low + high ) / 2;
if( a[ middle ].lessThan( a[ low ] ) )
swapReferences( a, low, middle );
if( a[ high ].lessThan( a[ low ] ) )
swapReferences( a, low, high );
if( a[ high ].lessThan( a[ middle ] ) )
swapReferences( a, middle, high );
// Place pivot at position high - 1
swapReferences( a, middle, high - 1 );
Comparable pivot = a[ high - 1 ];
// Begin partitioning
int i, j;
for( i = low, j = high - 1; ; ) {
while( a[ ++i ].lessThan( pivot ) );
while( pivot.lessThan( a[ --j ] ) );
if( i < j )
swapReferences( a, i, j );
else
break;
}
// Restore pivot
swapReferences( a, i, high - 1 );
quicksort( a, low, i - 1 ); // Sort small elements
quicksort( a, i + 1, high ); // Sort large elements
}
}
}
| 43.26 | 211 | 0.622977 |
742e93c8d37bca5de704bcfdbe6d4a982519185e | 829 | package com.trigyn.jws.dbutils.entities;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.stereotype.Repository;
import com.trigyn.jws.dbutils.vo.DataSourceVO;
@Repository
public interface AdditionalDatasourceRepository extends JpaRepositoryImplementation<AdditionalDatasource, String> {
@Query("SELECT new com.trigyn.jws.dbutils.vo.DataSourceVO(ad.additionalDatasourceId AS additionalDataSourceId, dl.driverClassName AS driverClassName, ad.datasourceConfiguration AS dataSourceConfiguration)"
+ " FROM AdditionalDatasource AS ad INNER JOIN ad.datasourceLookup AS dl WHERE ad.additionalDatasourceId = :additionalDatasourceId")
DataSourceVO getDataSourceConfiguration(String additionalDatasourceId);
}
| 46.055556 | 206 | 0.854041 |
4722e882a8267bee94c711d7f4237e494ab6d453 | 176 | package com.u2.day15.abstractfactory;
public class HpKeyboard extends Keyboard {
@Override
public void print() {
System.out.println("我是惠普键盘");
}
}
| 19.555556 | 43 | 0.642045 |
e60b7b0864f2a25d2f84e6a9c7ec1ff8f363e1fa | 1,179 | package com.imakerstudio.JH;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import com.imakerstudio.pandaui.EditText.FilterEditText;
public class MainActivity extends AppCompatActivity {
private FilterEditText mEdit;
private Button testButton;
private String[] alertArray = {
"Can not be empty",
"Must be float"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
mEdit = findViewById(R.id.test);
testButton = findViewById(R.id.btn);
mEdit.setInputFloat(1.33, 30.33, 2);
mEdit.setAlertTip("Must be 5 ~ 30");
mEdit.setAlertArray(alertArray);
Log.i("Test", mEdit.getAlertArray(0));
testButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mEdit.setAlert(!mEdit.getAlert());
}
});
}
} | 26.795455 | 61 | 0.649703 |
706b7aa55bbe871a0dfd1cac4b7ebd40a906b786 | 2,040 | /*
* Copyright (c) 2020, Zaphod Consulting BV, Christine Karman
* This project is free software: you can redistribute it and/or modify it under the terms of
* the Apache License, Version 2.0. You can find a copy of the license at
* http://www.apache.org/licenses/LICENSE-2.0.
*/
package nl.christine.app.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import nl.christine.app.R;
import nl.christine.app.fragment.BaseViewHolder;
import java.util.ArrayList;
import java.util.List;
public class MainAdapter extends RecyclerView.Adapter<BaseViewHolder> {
List<String> messages = new ArrayList<>();
public void addMessage(String message) {
messages.add(message);
}
@NonNull
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.messages_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
holder.onBind(position);
}
@Override
public int getItemCount() {
return messages.size();
}
public void clear() {
messages.clear();
notifyDataSetChanged();
}
private class ViewHolder extends BaseViewHolder {
TextView messageView;
public ViewHolder(View view) {
super(view);
messageView = view.findViewById(R.id.message);
}
@Override
public void onBind(int position) {
super.onBind(position);
messageView.setText(messages.get(position));
}
@Override
protected void clear() {
messageView.setText("");
}
}
}
| 26.493506 | 93 | 0.673039 |
6d71295f0f6707dfcbca7710c3cb6f2f1fe31816 | 2,986 | package jp.co.cyberagent.valor.ql.parse;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import jp.co.cyberagent.valor.sdk.StandardContextFactory;
import jp.co.cyberagent.valor.sdk.ValorConnectionFactory;
import jp.co.cyberagent.valor.sdk.plan.function.EqualOperator;
import jp.co.cyberagent.valor.spi.ValorConnection;
import jp.co.cyberagent.valor.spi.exception.ValorException;
import jp.co.cyberagent.valor.spi.plan.model.AttributeNameExpression;
import jp.co.cyberagent.valor.spi.plan.model.ConstantExpression;
import jp.co.cyberagent.valor.spi.plan.model.DeleteStatement;
import jp.co.cyberagent.valor.spi.plan.model.LogicalPlanNode;
import jp.co.cyberagent.valor.spi.plan.model.PredicativeExpression;
import jp.co.cyberagent.valor.spi.plan.model.RelationSource;
import jp.co.cyberagent.valor.spi.relation.ImmutableRelation;
import jp.co.cyberagent.valor.spi.relation.Relation;
import jp.co.cyberagent.valor.spi.relation.type.IntegerAttributeType;
import jp.co.cyberagent.valor.spi.relation.type.StringAttributeType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class TestParseDeleteStatement {
static final Relation relation = ImmutableRelation.builder().relationId("relId")
.addAttribute("k", true, StringAttributeType.INSTANCE)
.addAttribute("v", false, IntegerAttributeType.INSTANCE)
.build();
static ValorConnection conn;
@BeforeAll
public static void init() throws ValorException {
conn = ValorConnectionFactory.create(StandardContextFactory.create());
conn.createRelation(relation, true);
}
@AfterAll
public static void tearDown() throws IOException {
conn.close();
}
static Fixture[] getFixtures() {
return new Fixture[] {
new Fixture("DELETE FROM relId WHERE k = 100", relation,
new EqualOperator(
new AttributeNameExpression("k", StringAttributeType.INSTANCE),
new ConstantExpression(100)))
};
}
@ParameterizedTest
@MethodSource("getFixtures")
public void test(Fixture fixture) {
Parser parser = new Parser(conn);
LogicalPlanNode plan = parser.parseStatement(fixture.statement);
assertThat(fixture.statement, plan, equalTo(fixture.buildStatement()));
}
static class Fixture {
public final String statement;
public final Relation relation;
public final PredicativeExpression condition;
public Fixture(String stmt, Relation relation, PredicativeExpression condition) {
this.statement = stmt;
this.relation = relation;
this.condition = condition;
}
public DeleteStatement buildStatement() {
DeleteStatement stmt = new DeleteStatement();
stmt.setRelation(new RelationSource(relation));
stmt.setCondition(condition);
return stmt;
}
}
}
| 35.975904 | 85 | 0.761554 |
becbd8fd82507afd986c9fc67adce0fc789f8944 | 4,494 | /* 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.camunda.bpm.engine.test.api.history;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.historycleanup.HistoryCleanupHelper;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.util.ProcessEngineBootstrapRule;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/**
* @author Svetlana Dorokhova
*/
@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_ACTIVITY)
public class HistoryCleanupOnEngineStartTest {
protected static final String ONE_TASK_PROCESS = "oneTaskProcess";
protected ProcessEngineBootstrapRule bootstrapRule = new ProcessEngineBootstrapRule() {
@Override
public ProcessEngineConfiguration configureEngine(ProcessEngineConfigurationImpl configuration) {
configuration.setHistoryCleanupBatchWindowStartTime("23:00");
configuration.setHistoryCleanupBatchWindowEndTime("01:00");
return configuration;
}
};
protected ProvidedProcessEngineRule engineRule = new ProvidedProcessEngineRule(bootstrapRule);
public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);
private HistoryService historyService;
@Rule
public RuleChain ruleChain = RuleChain.outerRule(bootstrapRule).around(engineRule).around(testRule);
@Before
public void init() {
historyService = engineRule.getProcessEngine().getHistoryService();
}
@After
public void clearDatabase(){
ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl)engineRule.getProcessEngine().getProcessEngineConfiguration();
processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {
public Void execute(CommandContext commandContext) {
List<Job> jobs = engineRule.getProcessEngine().getManagementService().createJobQuery().list();
if (jobs.size() > 0) {
assertEquals(1, jobs.size());
String jobId = jobs.get(0).getId();
commandContext.getJobManager().deleteJob((JobEntity) jobs.get(0));
commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(jobId);
}
return null;
}
});
}
@Test
public void testHistoryCleanupJob() throws ParseException {
final List<Job> historyCleanupJobs = historyService.findHistoryCleanupJobs();
assertFalse(historyCleanupJobs.isEmpty());
Date historyCleanupBatchWindowStartTime = ((ProcessEngineConfigurationImpl) engineRule.getProcessEngine().getProcessEngineConfiguration())
.getHistoryCleanupBatchWindowStartTimeAsDate();
Date historyCleanupBatchWindowEndTime = ((ProcessEngineConfigurationImpl) engineRule.getProcessEngine().getProcessEngineConfiguration())
.getHistoryCleanupBatchWindowEndTimeAsDate();
for (Job historyCleanupJob : historyCleanupJobs) {
assertEquals(HistoryCleanupHelper.getCurrentOrNextBatchWindowStartTime(ClockUtil.getCurrentTime(), historyCleanupBatchWindowStartTime,
HistoryCleanupHelper.addDays(historyCleanupBatchWindowEndTime, 1)), historyCleanupJob.getDuedate());
}
}
}
| 42.396226 | 158 | 0.78883 |
0314239f6e3961b5c72dfd57a6459162a5446889 | 3,955 | /*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. 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.wso2.esb.integration.common.clients.registry;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.registry.search.stub.SearchAdminServiceRegistryExceptionException;
import org.wso2.carbon.registry.search.stub.SearchAdminServiceStub;
import org.wso2.carbon.registry.search.stub.beans.xsd.AdvancedSearchResultsBean;
import org.wso2.carbon.registry.search.stub.beans.xsd.CustomSearchParameterBean;
import org.wso2.carbon.registry.search.stub.beans.xsd.MediaTypeValueList;
import org.wso2.carbon.registry.search.stub.beans.xsd.SearchResultsBean;
import org.wso2.esb.integration.common.clients.client.utils.AuthenticateStub;
import java.rmi.RemoteException;
public class SearchAdminServiceClient {
private static final Log log = LogFactory.getLog(SearchAdminServiceClient.class);
private final String serviceName = "SearchAdminService";
private SearchAdminServiceStub searchAdminServiceStub;
public SearchAdminServiceClient(String backEndUrl, String sessionCookie) throws AxisFault {
String endPoint = backEndUrl + serviceName;
searchAdminServiceStub = new SearchAdminServiceStub(endPoint);
AuthenticateStub.authenticateStub(sessionCookie, searchAdminServiceStub);
}
public SearchAdminServiceClient(String backEndUrl, String username, String password)
throws AxisFault {
String endPoint = backEndUrl + serviceName;
searchAdminServiceStub = new SearchAdminServiceStub(endPoint);
AuthenticateStub.authenticateStub(username, password, searchAdminServiceStub);
}
public void deleteFilter(String filterName)
throws SearchAdminServiceRegistryExceptionException, RemoteException {
searchAdminServiceStub.deleteFilter(filterName);
}
public CustomSearchParameterBean getAdvancedSearchFilter(String filterName)
throws SearchAdminServiceRegistryExceptionException, RemoteException {
return searchAdminServiceStub.getAdvancedSearchFilter(filterName);
}
public MediaTypeValueList getMediaTypeSearch(String mediaType)
throws SearchAdminServiceRegistryExceptionException, RemoteException {
return searchAdminServiceStub.getMediaTypeSearch(mediaType);
}
public AdvancedSearchResultsBean getAdvancedSearchResults(
CustomSearchParameterBean searchParams)
throws SearchAdminServiceRegistryExceptionException, RemoteException {
return searchAdminServiceStub.getAdvancedSearchResults(searchParams);
}
public String[] getSavedFilters()
throws SearchAdminServiceRegistryExceptionException, RemoteException {
return searchAdminServiceStub.getSavedFilters();
}
public SearchResultsBean getSearchResults(String searchType, String criteria)
throws SearchAdminServiceRegistryExceptionException, RemoteException {
return searchAdminServiceStub.getSearchResults(searchType, criteria);
}
public void saveAdvancedSearchFilter(CustomSearchParameterBean queryBean, String filterName)
throws SearchAdminServiceRegistryExceptionException, RemoteException {
searchAdminServiceStub.saveAdvancedSearchFilter(queryBean, filterName);
}
}
| 43.461538 | 96 | 0.787611 |
c51196af3bf75851efcee6591cac87b15d27870a | 11,675 | /*
* 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.kylin.query.relnode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.hydromatic.linq4j.expressions.Blocks;
import net.hydromatic.linq4j.expressions.Expressions;
import net.hydromatic.optiq.rules.java.EnumerableRelImplementor;
import net.hydromatic.optiq.rules.java.JavaRules.EnumerableJoinRel;
import net.hydromatic.optiq.rules.java.PhysType;
import net.hydromatic.optiq.rules.java.PhysTypeImpl;
import org.apache.kylin.query.schema.OLAPTable;
import org.eigenbase.rel.InvalidRelException;
import org.eigenbase.rel.JoinInfo;
import org.eigenbase.rel.JoinRelType;
import org.eigenbase.rel.RelNode;
import org.eigenbase.relopt.RelOptCluster;
import org.eigenbase.relopt.RelOptCost;
import org.eigenbase.relopt.RelOptPlanner;
import org.eigenbase.relopt.RelOptTable;
import org.eigenbase.relopt.RelTrait;
import org.eigenbase.relopt.RelTraitSet;
import org.eigenbase.reltype.RelDataType;
import org.eigenbase.reltype.RelDataTypeFactory.FieldInfoBuilder;
import org.eigenbase.reltype.RelDataTypeField;
import org.eigenbase.reltype.RelDataTypeFieldImpl;
import org.eigenbase.rex.RexCall;
import org.eigenbase.rex.RexInputRef;
import org.eigenbase.rex.RexNode;
import org.eigenbase.sql.SqlKind;
import org.eigenbase.util.ImmutableIntList;
import com.google.common.base.Preconditions;
import org.apache.kylin.metadata.model.JoinDesc;
import org.apache.kylin.metadata.model.TblColRef;
/**
* @author xjiang
*/
public class OLAPJoinRel extends EnumerableJoinRel implements OLAPRel {
private final static String[] COLUMN_ARRAY_MARKER = new String[0];
private OLAPContext context;
private ColumnRowType columnRowType;
private boolean isTopJoin;
private boolean hasSubQuery;
public OLAPJoinRel(RelOptCluster cluster, RelTraitSet traits, RelNode left, RelNode right, //
RexNode condition, ImmutableIntList leftKeys, ImmutableIntList rightKeys, //
JoinRelType joinType, Set<String> variablesStopped) throws InvalidRelException {
super(cluster, traits, left, right, condition, leftKeys, rightKeys, joinType, variablesStopped);
Preconditions.checkArgument(getConvention() == OLAPRel.CONVENTION);
this.rowType = getRowType();
this.isTopJoin = false;
}
@Override
public EnumerableJoinRel copy(RelTraitSet traitSet, RexNode conditionExpr, RelNode left, RelNode right, //
JoinRelType joinType, boolean semiJoinDone) {
final JoinInfo joinInfo = JoinInfo.of(left, right, condition);
assert joinInfo.isEqui();
try {
return new OLAPJoinRel(getCluster(), traitSet, left, right, condition, joinInfo.leftKeys, joinInfo.rightKeys, joinType, variablesStopped);
} catch (InvalidRelException e) {
// Semantic error not possible. Must be a bug. Convert to
// internal error.
throw new AssertionError(e);
}
}
@Override
public RelOptCost computeSelfCost(RelOptPlanner planner) {
return super.computeSelfCost(planner).multiplyBy(.05);
}
@Override
public double getRows() {
return super.getRows() * 0.1;
}
@Override
public void implementOLAP(OLAPImplementor implementor) {
// create context for root join
if (!(implementor.getParentNode() instanceof OLAPJoinRel)) {
implementor.allocateContext();
}
this.context = implementor.getContext();
this.isTopJoin = !this.context.hasJoin;
this.context.hasJoin = true;
// as we keep the first table as fact table, we need to visit from left
// to right
implementor.visitChild(this.left, this);
if (this.context != implementor.getContext() || ((OLAPRel) this.left).hasSubQuery()) {
this.hasSubQuery = true;
implementor.freeContext();
}
implementor.visitChild(this.right, this);
if (this.context != implementor.getContext() || ((OLAPRel) this.right).hasSubQuery()) {
this.hasSubQuery = true;
implementor.freeContext();
}
this.columnRowType = buildColumnRowType();
if (isTopJoin) {
this.context.afterJoin = true;
}
if (!this.hasSubQuery) {
this.context.allColumns.clear();
this.context.olapRowType = getRowType();
buildAliasMap();
// build JoinDesc
RexCall condition = (RexCall) this.getCondition();
JoinDesc join = buildJoin(condition);
JoinRelType joinRelType = this.getJoinType();
String joinType = joinRelType == JoinRelType.INNER ? "INNER" : joinRelType == JoinRelType.LEFT ? "LEFT" : null;
join.setType(joinType);
this.context.joins.add(join);
}
}
private ColumnRowType buildColumnRowType() {
List<TblColRef> columns = new ArrayList<TblColRef>();
OLAPRel olapLeft = (OLAPRel) this.left;
ColumnRowType leftColumnRowType = olapLeft.getColumnRowType();
columns.addAll(leftColumnRowType.getAllColumns());
OLAPRel olapRight = (OLAPRel) this.right;
ColumnRowType rightColumnRowType = olapRight.getColumnRowType();
columns.addAll(rightColumnRowType.getAllColumns());
if (columns.size() != this.rowType.getFieldCount()) {
throw new IllegalStateException("RowType=" + this.rowType.getFieldCount() + ", ColumnRowType=" + columns.size());
}
return new ColumnRowType(columns);
}
private JoinDesc buildJoin(RexCall condition) {
Map<TblColRef, TblColRef> joinColumns = new HashMap<TblColRef, TblColRef>();
translateJoinColumn(condition, joinColumns);
List<String> pks = new ArrayList<String>();
List<TblColRef> pkCols = new ArrayList<TblColRef>();
List<String> fks = new ArrayList<String>();
List<TblColRef> fkCols = new ArrayList<TblColRef>();
String factTable = context.firstTableScan.getTableName();
for (Map.Entry<TblColRef, TblColRef> columnPair : joinColumns.entrySet()) {
TblColRef fromCol = columnPair.getKey();
TblColRef toCol = columnPair.getValue();
if (factTable.equalsIgnoreCase(fromCol.getTable())) {
fks.add(fromCol.getName());
fkCols.add(fromCol);
pks.add(toCol.getName());
pkCols.add(toCol);
} else {
fks.add(toCol.getName());
fkCols.add(toCol);
pks.add(fromCol.getName());
pkCols.add(fromCol);
}
}
JoinDesc join = new JoinDesc();
join.setForeignKey(fks.toArray(COLUMN_ARRAY_MARKER));
join.setForeignKeyColumns(fkCols.toArray(new TblColRef[fkCols.size()]));
join.setPrimaryKey(pks.toArray(COLUMN_ARRAY_MARKER));
join.setPrimaryKeyColumns(pkCols.toArray(new TblColRef[pkCols.size()]));
return join;
}
private void translateJoinColumn(RexCall condition, Map<TblColRef, TblColRef> joinColumns) {
SqlKind kind = condition.getOperator().getKind();
if (kind == SqlKind.AND) {
for (RexNode operand : condition.getOperands()) {
RexCall subCond = (RexCall) operand;
translateJoinColumn(subCond, joinColumns);
}
} else if (kind == SqlKind.EQUALS) {
List<RexNode> operands = condition.getOperands();
RexInputRef op0 = (RexInputRef) operands.get(0);
TblColRef col0 = columnRowType.getColumnByIndex(op0.getIndex());
RexInputRef op1 = (RexInputRef) operands.get(1);
TblColRef col1 = columnRowType.getColumnByIndex(op1.getIndex());
joinColumns.put(col0, col1);
}
}
private void buildAliasMap() {
int size = this.rowType.getFieldList().size();
for (int i = 0; i < size; i++) {
RelDataTypeField field = this.rowType.getFieldList().get(i);
TblColRef column = this.columnRowType.getColumnByIndex(i);
context.storageContext.addAlias(column, field.getName());
}
}
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
Result result = null;
if (this.hasSubQuery) {
result = super.implement(implementor, pref);
} else {
PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), pref.preferArray());
RelOptTable factTable = context.firstTableScan.getTable();
result = implementor.result(physType, Blocks.toBlock(Expressions.call(factTable.getExpression(OLAPTable.class), "executeIndexQuery", implementor.getRootExpression(), Expressions.constant(context.id))));
}
return result;
}
@Override
public ColumnRowType getColumnRowType() {
return columnRowType;
}
@Override
public void implementRewrite(RewriteImplementor implementor) {
implementor.visitChild(this, this.left);
implementor.visitChild(this, this.right);
this.rowType = this.deriveRowType();
if (this.isTopJoin && RewriteImplementor.needRewrite(this.context)) {
// find missed rewrite fields
int paramIndex = this.rowType.getFieldList().size();
List<RelDataTypeField> newFieldList = new LinkedList<RelDataTypeField>();
for (Map.Entry<String, RelDataType> rewriteField : this.context.rewriteFields.entrySet()) {
String fieldName = rewriteField.getKey();
if (this.rowType.getField(fieldName, true) == null) {
RelDataType fieldType = rewriteField.getValue();
RelDataTypeField newField = new RelDataTypeFieldImpl(fieldName, paramIndex++, fieldType);
newFieldList.add(newField);
}
}
// rebuild row type
FieldInfoBuilder fieldInfo = getCluster().getTypeFactory().builder();
fieldInfo.addAll(this.rowType.getFieldList());
fieldInfo.addAll(newFieldList);
this.rowType = getCluster().getTypeFactory().createStructType(fieldInfo);
this.context.olapRowType = this.rowType;
// rebuild columns
this.columnRowType = this.buildColumnRowType();
}
}
@Override
public OLAPContext getContext() {
return context;
}
@Override
public boolean hasSubQuery() {
return this.hasSubQuery;
}
@Override
public RelTraitSet replaceTraitSet(RelTrait trait) {
RelTraitSet oldTraitSet = this.traitSet;
this.traitSet = this.traitSet.replace(trait);
return oldTraitSet;
}
}
| 39.177852 | 214 | 0.666467 |
1d5d3ccd7080a8e13d3a337b21679ee08dd8f85d | 168 | package NO_0374_Guess_Number_Higher_or_Lower;
/**
* @author Angus
* @date 2019/1/12
*/
public class GuessGame {
int guess(int num) {
return -1;
}
}
| 14 | 45 | 0.630952 |
622c687695ddff3fc625291a758b521cc0a991ff | 927 | package com.fauconnet.devisu;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class ImagesPOTtester {
public static void main(String[] args) {
try {
MongoProxy proxy = new MongoProxy("localhost", 27017, "POT");
File dir = new File("C:\\Local\\POTdata\\media");
String []images=dir.list();
List<String> imagesList=Arrays.asList(images);
List<DBObject>list=proxy.getDocuments("radarDetails", new BasicDBObject(), -1);
for(DBObject obj : list){
String img=(String) obj.get("inf_img");
int p=imagesList.indexOf(img);
String message="";
if(p>-1)
message=img+" ok in "+obj.get("techno");
else
message=img+"!!!! ko in "+obj.get("techno");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 22.609756 | 83 | 0.629989 |
d58579b185eb57441214ebb63dfdb2d48de78d1b | 624 | package fr.sii.ogham.template.freemarker.adapter;
import fr.sii.ogham.template.freemarker.TemplateLoaderOptions;
import freemarker.cache.TemplateLoader;
/**
* Abstract class to handle options configuration for the adapted
* {@link TemplateLoader}.
*
* @author Cyril Dejonghe
*
*/
public abstract class AbstractFreeMarkerTemplateLoaderOptionsAdapter implements TemplateLoaderAdapter {
private TemplateLoaderOptions options;
public TemplateLoaderOptions getOptions() {
return options;
}
@Override
public void setOptions(TemplateLoaderOptions options) {
this.options = options;
}
}
| 24.96 | 104 | 0.766026 |
fd7ed04b8b6bbf9c79c5586b7f695305d9f33770 | 1,580 | package br.com.erudio.services;
import br.com.erudio.exception.ResourceNotFoundException;
import br.com.erudio.model.Person;
import br.com.erudio.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PersonService {
@Autowired
PersonRepository repository;
public Person findById(Long id){
return repository
.findById(id)
.orElseThrow(
()->new ResourceNotFoundException("No records found for the given ID")
);
}
public Person create(Person p){
return repository.save(p);
}
public Person update(Person p){
Person entity = repository
.findById(p.getId())
.orElseThrow(
()->new ResourceNotFoundException("No records found for the given ID")
);
entity.setFirstName(p.getFirstName());
entity.setLastName(p.getLastName());
entity.setAddress(p.getAddress());
entity.setGender(p.getGender());
repository.save(entity);
return entity;
}
public void delete(Long id){
Person entity = repository
.findById(id)
.orElseThrow(
()->new ResourceNotFoundException("No records found for the given ID")
);
repository.delete(entity);
}
public List<Person> findAll(){
return repository.findAll();
}
}
| 24.6875 | 94 | 0.601899 |
c6ba1efddb599eb9dfc9bea659d79acda2d1c32d | 4,580 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.api.collector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.flink.runtime.io.network.api.RecordWriter;
import org.apache.flink.runtime.plugable.SerializationDelegate;
import org.apache.flink.streaming.api.streamrecord.StreamRecord;
import org.apache.flink.util.Collector;
import org.apache.flink.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Collector for tuples in Apache Flink stream processing. The collected values
* will be wrapped with ID in a {@link StreamRecord} and then emitted to the
* outputs.
*
* @param <OUT>
* Type of the Tuples/Objects collected.
*/
public class StreamCollector<OUT> implements Collector<OUT> {
private static final Logger LOG = LoggerFactory.getLogger(StreamCollector.class);
protected StreamRecord<OUT> streamRecord;
protected int channelID;
private List<RecordWriter<SerializationDelegate<StreamRecord<OUT>>>> outputs;
protected Map<String, List<RecordWriter<SerializationDelegate<StreamRecord<OUT>>>>> outputMap;
protected SerializationDelegate<StreamRecord<OUT>> serializationDelegate;
/**
* Creates a new StreamCollector
*
* @param channelID
* Channel ID of the Task
* @param serializationDelegate
* Serialization delegate used for serialization
*/
public StreamCollector(int channelID,
SerializationDelegate<StreamRecord<OUT>> serializationDelegate) {
this.serializationDelegate = serializationDelegate;
if (serializationDelegate != null) {
this.streamRecord = serializationDelegate.getInstance();
} else {
this.streamRecord = new StreamRecord<OUT>();
}
this.channelID = channelID;
this.outputs = new ArrayList<RecordWriter<SerializationDelegate<StreamRecord<OUT>>>>();
this.outputMap = new HashMap<String, List<RecordWriter<SerializationDelegate<StreamRecord<OUT>>>>>();
}
/**
* Adds an output with the given user defined name
*
* @param output
* The RecordWriter object representing the output.
* @param outputNames
* User defined names of the output.
*/
public void addOutput(RecordWriter<SerializationDelegate<StreamRecord<OUT>>> output,
List<String> outputNames) {
outputs.add(output);
for (String outputName : outputNames) {
if (outputName != null) {
if (!outputMap.containsKey(outputName)) {
outputMap
.put(outputName,
new ArrayList<RecordWriter<SerializationDelegate<StreamRecord<OUT>>>>());
outputMap.get(outputName).add(output);
} else {
if (!outputMap.get(outputName).contains(output)) {
outputMap.get(outputName).add(output);
}
}
}
}
}
/**
* Collects and emits a tuple/object to the outputs by reusing a
* StreamRecord object.
*
* @param outputObject
* Object to be collected and emitted.
*/
@Override
public void collect(OUT outputObject) {
streamRecord.setObject(outputObject);
emit(streamRecord);
}
/**
* Emits a StreamRecord to all the outputs.
*
* @param streamRecord
* StreamRecord to emit.
*/
private void emit(StreamRecord<OUT> streamRecord) {
streamRecord.newId(channelID);
serializationDelegate.setInstance(streamRecord);
for (RecordWriter<SerializationDelegate<StreamRecord<OUT>>> output : outputs) {
try {
output.emit(serializationDelegate);
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(String.format("Emit failed due to: %s",
StringUtils.stringifyException(e)));
}
}
}
}
@Override
public void close() {
}
}
| 33.188406 | 104 | 0.703712 |
39b2111de3031c54d779b21bd0f6cdc8c41028d1 | 1,885 |
package cryptohash;
import static java.lang.Math.pow;
import java.util.ArrayList;
import java.util.Collections;
public class modulo{ ///tests modulos with info data
private ArrayList results=new ArrayList();
private ArrayList testRoots=new ArrayList();
private ArrayList firstRoots=new ArrayList();
private int primitiveRoot;
private boolean isPrimeRoot=false;
private int[] testData;
private int[] modulos;
private int i,b;
public modulo(int[] testData,int[] modulos){
this.testData=testData;
this.modulos=modulos;
}
public void testModulos(){
for(i=0;i<testData.length;i++){
for(b=0;b<modulos.length;b++){
results.add(testData[i]%modulos[b]);
System.out.println(testData[i]+"%"+modulos[b]+"="+results.get(i));
}
}
}
public void getExample(){
for(i=0;i<testData.length;i++)System.out.println(testData[i]);
}
public void getModulos(){
for(i=0;i<modulos.length;i++)System.out.println(modulos[i]);
}
public int calcPrimRoot(int modulus) { ///NEEDS MASSIVE OPTIMIZATION
for(b=2;!isPrimeRoot;b++){
isPrimeRoot=true;
for (i=1;i<modulus;i++) {
if(b==2)firstRoots.add((pow(b,i)%modulus));
testRoots.add(pow(b,i)%modulus);
}
Collections.sort(testRoots);
for(i=0;i<testRoots.size()-1;i++){
if((double)testRoots.get(i)+1!=(double)testRoots.get(i+1)){
isPrimeRoot=false;
break;
}
}
System.out.println(testRoots);
if(!isPrimeRoot)testRoots.clear();
else{primitiveRoot=b;}
}
return primitiveRoot;
}
}
| 32.5 | 83 | 0.545358 |
0c81f91dc1f6505fa1293398ea19c92c568b9a2e | 275 | package com.wang.wx.model.response;
import lombok.Data;
/**
* @Desc check access token response
* @Author cui·weiman
* @Since 2021/10/7 20:44
*/
@Data
public class CheckAccessTokenResponse {
private Integer errcode;
private String errmsg;
}
| 15.277778 | 40 | 0.665455 |
089cc2d7873f01f33f61234f41e9aff5b0c1ff6a | 3,260 | /******************************************************************************
* Compilation: javac PictureDump.java
* Execution: java PictureDump width height < file
* Dependencies: BinaryStdIn.java Picture.java
* Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt
*
* Reads in a binary file and writes out the bits as w-by-h picture,
* with the 1 bits in black and the 0 bits in white.
*
* % more abra.txt
* ABRACADABRA!
*
* % java PictureDump 16 6 < abra.txt
*
******************************************************************************/
package algs4;
import java.awt.*;
/**
* The {@code PictureDump} class provides a client for displaying the contents
* of a binary file as a black-and-white picture.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/55compress">Section 5.5</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* <p>
* See also {@link BinaryDump} and {@link HexDump}.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class PictureDump {
// Do not instantiate.
private PictureDump() { }
/**
* Reads in a sequence of bytes from standard input and draws
* them to standard drawing output as a width-by-height picture,
* using black for 1 and white for 0 (and red for any leftover
* pixels).
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
Picture picture = new Picture(width, height);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
if (!BinaryStdIn.isEmpty()) {
boolean bit = BinaryStdIn.readBoolean();
if (bit) picture.set(col, row, Color.BLACK);
else picture.set(col, row, Color.WHITE);
}
else {
picture.set(col, row, Color.RED);
}
}
}
picture.show();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
| 35.824176 | 80 | 0.570552 |
8badd10320c9280c25b6d45b63b9f08a9659d26f | 2,627 | /*
* The MIT License (MIT)
* Copyright © 2019 <sky>
*
* 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.skycloud.base.authorization.config.custom;
import com.google.common.collect.Maps;
import com.skycloud.base.authentication.api.model.bo.CustomUserDetail;
import com.skycloud.base.authentication.api.model.token.CustomAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import java.util.Map;
/**
* 自定义token携带内容
* 原有token增强
*
* @author
*/
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> additionalInfo = Maps.newHashMap();
Authentication userAuthentication = authentication.getUserAuthentication();
if (userAuthentication != null && userAuthentication instanceof CustomAuthenticationToken) {
CustomAuthenticationToken token = (CustomAuthenticationToken) userAuthentication;
CustomUserDetail customUserDetail = (CustomUserDetail) token.getDetails();
additionalInfo.put("user_id", customUserDetail.getUserId());
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
} | 46.910714 | 106 | 0.776171 |
569c38bb61c62f4ed5528417c14e0aef6ca27325 | 4,412 | /*
* Copyright 2018 esfak47(esfak47@qq.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 com.esfak47.common.utils.io.resource;
import com.esfak47.common.utils.io.FilenameUtils;
import com.esfak47.common.utils.reflection.ClassLoaderUtils;
import com.esfak47.common.utils.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Classpath的资源描述
*
* @author tony on 2016/4/11.
*/
public class ClassPathResourceDescriptor extends AbstractResourceDescriptor {
private final String path;
private ClassLoader classLoader;
private Class<?> clazz;
public ClassPathResourceDescriptor(String path) {
this(path, (ClassLoader) null);
}
public ClassPathResourceDescriptor(String path, ClassLoader classLoader) {
if (StringUtils.isEmpty(path)) {
throw new IllegalArgumentException("Path must not be null.");
}
this.path = path;
this.classLoader = (classLoader == null) ? ClassLoaderUtils.getDefaultClassLoader() : classLoader;
}
public ClassPathResourceDescriptor(String path, Class<?> clazz) {
if (StringUtils.isEmpty(path)) {
throw new IllegalArgumentException("Path must not be null.");
}
this.path = path;
this.clazz = clazz;
}
public ClassPathResourceDescriptor(String path, ClassLoader classLoader, Class<?> clazz) {
if (StringUtils.isEmpty(path)) {
throw new IllegalArgumentException("Path must not be null.");
}
this.path = path;
this.classLoader = classLoader;
this.clazz = clazz;
}
public final String getPath() {
return path;
}
/**
* 判断资源是否存在
*/
@Override
public boolean exists() {
URL url;
if (this.clazz != null) {
url = this.clazz.getResource(this.path);
} else {
url = this.classLoader.getResource(this.path);
}
return url != null;
}
/**
* 获取输入流,该输入流支持多次读取
*/
@Override
public InputStream getInputStream() {
InputStream in;
if (this.clazz != null) {
in = this.clazz.getResourceAsStream(this.path);
} else {
in = this.classLoader.getResourceAsStream(this.path);
}
return in;
}
/**
* 返回{@code URL}资源
*
* @throws IOException IO异常
*/
@Override
public URL getURL() throws IOException {
URL url;
if (this.clazz != null) {
url = this.clazz.getResource(this.path);
} else {
url = this.classLoader.getResource(this.path);
}
return url;
}
/**
* 返回文件名,如果资源不存在,则返回{@code null}
*/
@Override
public String getFilename() {
return FilenameUtils.getFilename(this.path);
}
/**
* 返回文件对象,如果对象不存在则返回{@code null}
*
* @return 文件对象
*/
@Override
public File getFile() throws IOException {
URL url = this.getURL();
return new File(url.getFile());
}
/**
* Return a description for this resource, to be used for error output when working with the resource.
* <p>Implementations are also encouraged to return this value from their {@code toString} method.
*
* @see Object#toString()
*/
@Override
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
String pathToUse = path;
if (this.clazz != null && !pathToUse.startsWith(File.pathSeparator)) {
builder.append(File.pathSeparator);
}
if (pathToUse.startsWith(File.pathSeparator)) {
pathToUse = pathToUse.substring(1);
}
builder.append(pathToUse);
builder.append(']');
return builder.toString();
}
}
| 28.101911 | 106 | 0.618994 |
438ad400c266abd9749353b11afcacbf3d8cf6cf | 614 | package com.guo.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @Param:
* @return:
* @Author: gouli
* @Date: 2020/6/11
* @Description: 启动类
*/
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8002
{
public static void main(String[] args) {
SpringApplication.run(PaymentMain8002.class, args);
}
}
| 23.615385 | 73 | 0.754072 |
9612dd2b9500c26f2e1e97c28d40f2e676817dc7 | 4,058 | package nefra.jfx.game;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import nefra.db.GUIFunctions;
import nefra.game.Division;
import nefra.jfx.CommonGUI;
public class ViewDivisionGUI {
private final GUIFunctions guif = new GUIFunctions();
private final TableView<Division> table = new TableView<>();
/**
* Creates the GUI for the create referee, and sets it up with its own features.
* It uses the CommonGUI for the menus and also to allow the backToMainMenu button function.
*
* @return the root BorderPane
*/
public BorderPane initGUI() {
ObservableList<Division> div = FXCollections.observableArrayList(Division.divisionList);
//Top
MenuBar menu = CommonGUI.getInstance().loadMenu();
//Centre
GridPane centre = new GridPane();
final Label viewDivisionLabel = new Label("VIEW DIVISIONS");
Button removeButton = new Button("Remove");
/*
* Set the action for the enter button based on what information was entered into the fields.
*/
removeButton.setOnAction(e -> {
if(guif.removeWarning("division") == 1)
guif.removeDivision(e, table.getSelectionModel().getSelectedItem());
});
removeButton.setStyle("-fx-font-weight: bold;" +
"-fx-font-size: 16px;");
GridPane.setHalignment(viewDivisionLabel, HPos.CENTER);
GridPane.setValignment(viewDivisionLabel, VPos.CENTER);
viewDivisionLabel.setStyle("-fx-font-weight: bold;" +
"-fx-font-size: 36px;");
GridPane.setConstraints(viewDivisionLabel, 5, 1, 4, 2);
GridPane.setConstraints(table, 5, 3, 5, 6);
GridPane.setConstraints(removeButton, 8, 9);
setupTable();
table.setItems(div);
CommonGUI.getInstance().makeRowsAndCols(centre);
centre.getChildren().addAll(table, viewDivisionLabel,removeButton);
//Container
BorderPane viewDivisions = new BorderPane(centre, menu, null, CommonGUI.getInstance().bottomBox(), null);
viewDivisions.setPrefSize(640,480);
CommonGUI.panes.add(viewDivisions);
return viewDivisions;
}
private void setupTable() {
table.setEditable(false);
final TableColumn<Division, String> nameCol = new TableColumn<>("Name");
nameCol.setMinWidth(150);
nameCol.setCellValueFactory(new PropertyValueFactory<>("divisionName"));
final TableColumn<Division, Number> mainCol = new TableColumn<>("Main Referee Fee");
mainCol.setMinWidth(50);
mainCol.setCellValueFactory(new PropertyValueFactory<>("mainRefereeFee"));
mainCol.setCellFactory(tc -> setTableCell());
final TableColumn<Division, Number> arCol = new TableColumn<>("Assistant Referee Fee");
arCol.setMinWidth(50);
arCol.setCellValueFactory(new PropertyValueFactory<>("arFee"));
arCol.setCellFactory(tc -> setTableCell());
table.setPlaceholder(new Label("There are no divisions to display"));
table.getColumns().clear();
table.getColumns().add(nameCol);
table.getColumns().add(mainCol);
table.getColumns().add(arCol);
}
private TableCell<Division, Number> setTableCell() {
return new TableCell<Division, Number>() {
@Override
protected void updateItem(Number value, boolean empty) {
super.updateItem(value, empty) ;
if (empty) {
setText(null);
} else {
setText(String.format("$%.2f", value.doubleValue()));
}
}
};
}
}
| 36.232143 | 114 | 0.629621 |
1866711349f0e0999827c5bbfefb9115d420fde5 | 830 | package com.project.dao.proxysale;
import com.project.core.orm.hibernate.HibernateDao;
import com.project.entity.proxysale.CancelOrderLog;
import com.project.utils.CollectionsUtil;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by admin on 2016/4/28.
*/
@Component
public class CancelOrderLogDao extends HibernateDao<CancelOrderLog, Integer> {
/**
* 根据订单渠道ID查询操作记录
* @param channelNo
* @return
*/
public CancelOrderLog findCancelLogWithChannelNo(String channelNo){
String sql=" SELECT col.* from cancel_order_log col WHERE channel_order_no=? ORDER BY operate_time DESC";
List<CancelOrderLog> logs=findWithSql(sql,channelNo);
if(CollectionsUtil.isNotEmpty(logs)){
return logs.get(0);
}
return null;
}
}
| 28.62069 | 113 | 0.716867 |
f4a258d5f6a19cec876a2467dc58fc78373b35c5 | 681 | package network.aika.neuron.steps;
import network.aika.neuron.activation.Element;
import network.aika.neuron.activation.direction.Direction;
import network.aika.neuron.visitor.tasks.VisitorTask;
import java.util.List;
import java.util.Set;
public abstract class VisitorStep<E extends Element, T extends VisitorTask> extends Step<E> {
protected final T task;
protected final List<Direction> directions;
public VisitorStep(E element, T task, List<Direction> dirs) {
super(element);
this.task = task;
this.directions = dirs;
}
@Override
public String getStepName() {
return super.getStepName() + ":" + directions;
}
}
| 26.192308 | 93 | 0.712188 |
5868857c6a76c0f63cf8cdc90f63307a5614e9e4 | 2,626 | package com.service.auth.serviceauth.config;
import com.service.auth.serviceauth.customImpl.MyRedisTokenStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456");
// 配置两个客户端,一个用于password认证一个用于client认证
clients.inMemory().withClient("client_1")
// .resourceIds(Utils.RESOURCEIDS.ORDER)
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("select")
.authorities("oauth2")
.secret(finalSecret)
.and().withClient("client_2")
// .resourceIds(Utils.RESOURCEIDS.ORDER)
.authorizedGrantTypes("password", "refresh_token")
.scopes("server")
.authorities("oauth2")
.secret(finalSecret);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(new MyRedisTokenStore(redisConnectionFactory))
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// 允许表单认证
security.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
| 44.508475 | 116 | 0.795506 |
11cf94cc0f89d0a24396e65a593cfa5815812f15 | 134 | package server;
public interface IServer {
public void startServer();
//starts the server along with all its functionalities
}
| 14.888889 | 55 | 0.753731 |
a463125833e84b8dfea413a0fae24801302e3d46 | 1,242 | package com.ffx.novelreader.impl.dao;
import com.ffx.novelreader.entity.po.Menu;
import com.ffx.novelreader.inter.dao.MenuDao;
import org.litepal.crud.DataSupport;
import java.util.List;
/**
* Created by TwoFlyLiu on 2019/8/7.
*/
public class MenuDaoImpl implements MenuDao {
@Override
public boolean save(Menu menu) {
return menu.save();
}
@Override
public boolean delete(Menu menu) {
int rowsAffected = menu.delete();
return rowsAffected > 0;
}
@Override
public boolean update(Menu menu) {
return menu.save();
}
@Override
public List<Menu> findByNovelId(int novelId) {
return DataSupport.where("novelid=?", String.valueOf(novelId)).find(Menu.class);
}
@Override
public boolean saveAll(List<Menu> menuList) {
boolean result = true;
try {
DataSupport.saveAll(menuList);
} catch(Exception e) {
e.printStackTrace();
result = false;
}
return result;
}
@Override
public boolean deleteByNovelId(int novelId) {
int rowsAfected = DataSupport.deleteAll(Menu.class, "novelid=?", String.valueOf(novelId));
return rowsAfected > 0;
}
}
| 22.178571 | 98 | 0.626409 |
7c95578761c6980bea22ffba0a3a2b9c3684f70c | 495 | /*
* 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 de.abring.helfer.maproute.exception;
import de.abring.helfer.maproute.MapAddress;
/**
*
* @author Bring
*/
public class AddressNotValidException extends Exception {
public AddressNotValidException(String text) {
super("Address at: " + text + " is not Valid!");
}
} | 27.5 | 80 | 0.692929 |
b8c6843cf41f86a6bad8a3190ff740b50c60e127 | 399 | package com.huowu.java;
public class ArrayTest {
public static void main(String[] args) {
int[][] arr2 = new int[3][];
System.out.println(arr2[2]);
int[][] arr1 = new int[3][4];
System.out.println(arr1[0]);
int[][] arr = new int[][]{{1,2,3},{4,6}};
System.out.println(arr[1][1]);
System.out.println(arr[0][2]);
}
}
| 23.470588 | 50 | 0.498747 |
ac809ae8c60f190560b338436a46eff216fc1fa2 | 2,540 | package com.mygdx.elmaze.controller;
import com.mygdx.elmaze.ELMaze;
import com.mygdx.elmaze.networking.MessageToServer;
import com.mygdx.elmaze.networking.NetworkManager;
import com.mygdx.elmaze.view.MenuFactory;
import com.mygdx.elmaze.view.MenuView;
/**
* Game Controller Singleton class
*/
public class GameController {
private static GameController instance;
/** Game Controller Status */
public enum STATUS { NOT_RUNNING , RUNNING , DISCONNECT , SV_FULL };
private ELMaze game;
private STATUS status = STATUS.NOT_RUNNING;
/**
* @return Singleton's class instance
*/
public static GameController getInstance() {
if (instance == null) {
instance = new GameController();
}
return instance;
}
private GameController() {}
/**
* Sets the controller game class object reference
*
* @param game Game class object reference
*/
public void setGameReference(ELMaze game) {
this.game = game;
}
/**
* @return Returns the Controller current status
*/
public STATUS getStatus() {
return status;
}
/**
* Triggers a game start event, thus setting the Controller status to RUNNING
*/
public void startGame() {
status = STATUS.RUNNING;
}
/**
* Triggers a game stop event, thus setting the Controller status to NOT_RUNNING
*/
public void stopGame() {
status = STATUS.NOT_RUNNING;
}
/**
* Triggers a server full event, thus setting the Controller status to SV_FULL
*/
public void triggerServerFull() {
status = STATUS.SV_FULL;
}
/**
* Triggers the client disconnect from server event, thus setting the Controller status to DISCONNECT
*/
public void triggerServerDC() {
status = STATUS.DISCONNECT;
}
/**
* Moves the ball on the server, based on the mobile device accelerometer's values
*
* @param accelerometerX Accelerometer X axis value
* @param accelerometerY Accelerometer Y axis value
*/
public void moveBall(float accelerometerX, float accelerometerY) {
boolean broadcastSuccess = NetworkManager.getInstance().broadcastMessage( new MessageToServer(
accelerometerX,
accelerometerY
));
if(!broadcastSuccess) {
NetworkManager.getInstance().closeConnection();
game.activateMenu(MenuFactory.makeMenu(game, MenuView.TYPE.SERVER_DC));
}
}
}
| 25.918367 | 105 | 0.644882 |
355ba72a521a656a33b166ab2a7e38050bba6b57 | 960 | package net.algorithm.answer;
/**
* @Author TieJianKuDan
* @Date 2021/12/27 10:44
* @Description 825. 适龄的朋友
* @Since version-1.0
*/
public class NumFriendRequests {
public static void main(String[] args) {
int[] ages = {20, 30, 100, 110, 120};
NumFriendRequests self = new NumFriendRequests();
System.out.println(self.numFriendRequests(ages));
}
public int numFriendRequests(int[] ages) {
int res = 0;
int[] counts = new int[121];
int[] preSum = new int[121];
for (int age : ages) {
counts[age]++;
}
preSum[0] = counts[0];
for (int i = 1; i < preSum.length; i++) {
preSum[i] = counts[i] + preSum[i - 1];
}
for (int i = 0; i < ages.length; i++) {
if (ages[i] >= 15) {
res += preSum[ages[i]] - preSum[(int) Math.floor(0.5 * ages[i] + 7)] - 1;
}
}
return res;
}
}
| 27.428571 | 89 | 0.507292 |
ab23ec1795551fd52a760acf98d5f3a1f54a28d4 | 3,838 | /**
* TaggableEntityProviderMock.java - entity-broker - 2007 Aug 8, 2007 5:39:49 PM - AZ
*/
package org.sakaiproject.entitybroker.mocks;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.sakaiproject.entitybroker.entityprovider.capabilities.TagProvideable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Taggable;
import org.sakaiproject.entitybroker.entityprovider.extension.EntityData;
import org.sakaiproject.entitybroker.entityprovider.search.Search;
/**
* Mock which emulates the taggable abilities, note that by default there are no tags on entities
*
* @author Aaron Zeckoski (aaron@caret.cam.ac.uk)
*/
public class TaggableEntityProviderMock extends EntityProviderMock implements Taggable, TagProvideable {
public Map<String, Set<String>> entityTags = new HashMap<String, Set<String>>();
/**
* TEST constructor: allows for easy testing
*
* @param prefix
*/
public TaggableEntityProviderMock(String prefix) {
super(prefix);
}
/**
* TEST constructor: allows for easy testing by setting up tags for a specific reference
*
* @param prefix
* @param reference
* an entity reference
* @param tags
* an array of tags for this reference
*/
public TaggableEntityProviderMock(String prefix, String reference, String[] tags) {
super(prefix);
setTagsForEntity(reference, tags);
}
public void addTagsToEntity(String reference, String[] tags) {
if (entityTags.containsKey(reference)) {
for (String tag : tags) {
// just add it to the set
entityTags.get(reference).add(tag);
}
} else {
setTagsForEntity(reference, tags);
}
}
public List<String> getTagsForEntity(String reference) {
if (! entityTags.containsKey(reference)) {
return new ArrayList<String>();
}
ArrayList<String> tags = new ArrayList<String>( entityTags.get(reference) );
Collections.sort(tags);
return tags;
}
public void removeTagsFromEntity(String reference, String[] tags) {
if (entityTags.containsKey(reference)) {
for (String tag : tags) {
entityTags.get(reference).remove(tag);
}
}
}
public void setTagsForEntity(String reference, String[] tags) {
if (tags.length == 0) {
entityTags.remove(reference);
} else {
Set<String> s = new HashSet<String>();
for (int i = 0; i < tags.length; i++) {
s.add(tags[i]);
}
entityTags.put(reference, s);
}
}
public List<EntityData> findEntitesByTags(String[] tags, boolean matchAll, Search search) {
Set<String> refs = new HashSet<String>();
if (matchAll) {
HashSet<String> allTags = new HashSet<String>();
for (int i = 0; i < tags.length; i++) {
allTags.add(tags[i]);
}
for (Entry<String, Set<String>> entry : entityTags.entrySet()) {
if (entry.getValue().containsAll(allTags)) {
refs.add(entry.getKey());
}
}
} else {
for (String key : entityTags.keySet()) {
Set<String> s = entityTags.get(key);
for (int i = 0; i < tags.length; i++) {
if (s.contains(tags[i])) {
refs.add(key);
}
}
}
}
ArrayList<EntityData> results = new ArrayList<EntityData>();
for (String ref : refs) {
results.add( new EntityData(ref, (String)null) );
}
Collections.sort(results, new EntityData.ReferenceComparator());
return results;
}
}
| 30.951613 | 104 | 0.620896 |
30e2d114323d4c7ea122dbd08827a4c96685f376 | 7,262 | package com.testes.activity;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Instances;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.echonest.api.v4.EchoNestAPI;
import com.echonest.api.v4.EchoNestException;
import com.echonest.api.v4.Track;
import com.testes.android.R;
public class ImageActivity extends ActionBarActivity{
String buttonText= "";
static final String TAG = "ImageActivity";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_weight);
// RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mViewHolder.startDate.getLayoutParams();
// RelativeLayout.LayoutParams paramsImage = (RelativeLayout.LayoutParams) imgView.
// double conversion = minute*2.7;
// int topmargin = (int)conversion;
// params.setMargins(0,topmargin,0,0);
// params.topMargin = topmargin;
// paramsImage.topMargin = topmargin+15;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
String date = df.format(Calendar.getInstance().getTime());
// if(hour == myList.get(position).getPosition())
// {
// mViewHolder.startDate.setLayoutParams(params);
// mViewHolder.startDate.setTextColor(Color.BLUE);
// mViewHolder.startDate =detail(convertView, R.id.datetitle, date);
// if(imgView != null)
// imgView.setLayoutParams(paramsImage);
// imgView.setVisibility(1);
// imgView.bringToFront();
// }
// else{
// params.topMargin=0;
// mViewHolder.startDate.setLayoutParams(params);
// mViewHolder.startDate.setTextColor(Color.BLACK);
// imgView.setVisibility(View.INVISIBLE);
// }
ArrayList<String> instanceIdList = new ArrayList<String>();
ArrayList<Long> startDateList = new ArrayList<Long>();
ContentResolver resolver = getContentResolver();
String[] EVENT_PROJECTION = new String[]
{
Instances.TITLE,
Instances.BEGIN,
Instances.END,
Instances.EVENT_ID,
Instances.RRULE,
Instances.RDATE
};
Cursor cursor = Instances.query(resolver, EVENT_PROJECTION, System.currentTimeMillis(), System.currentTimeMillis()+3*24*60*60*1000);
// Use the cursor to step through the returned records
while (cursor.moveToNext())
{
String eventTitle = cursor.getString(cursor.getColumnIndex(Instances.TITLE));
long eventStartDt = cursor.getLong(cursor.getColumnIndex(Instances.BEGIN));
long eventEndDt = cursor.getLong(cursor.getColumnIndex(Instances.END));
long instanceID = cursor.getLong(cursor.getColumnIndex(Instances.EVENT_ID));
String rrule = cursor.getString(cursor.getColumnIndex(Instances.RRULE));
String rdate = cursor.getString(cursor.getColumnIndex(Instances.RDATE));
Log.i("calendarActivitu", rrule + " date:"+ rdate);
instanceIdList.add(String.valueOf(instanceID));
startDateList.add(eventStartDt);
//instanceEnd.add(eventEndDt);
}
ArrayList<String> selectedNames = new ArrayList<String>();
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("joao_amarosilva@hotmail.com");
emailList.add("patriccia@hotmial.com");
emailList.add("marco@hotmial.com");
selectedNames.add("Joao");
selectedNames.add("Patricia");
selectedNames.add("Marco");
int countOuter = 0;
int countInner = 0;
int numberOfAttendees = selectedNames.size()-1; //selectedNames: the chosen attendees
// If only one attendee is chosen, add it to the event id
if(selectedNames.size() == 1)
{
ContentValues attendees = new ContentValues();
attendees.put(Attendees.ATTENDEE_EMAIL, emailList.get(0));
attendees.put(Attendees.EVENT_ID, 52);
Uri uriAttendees = resolver.insert(Attendees.CONTENT_URI, attendees);
uriAttendees.buildUpon();
}
//multiple attendees to assign
else
{
if(!instanceIdList.isEmpty())
{
while(instanceIdList.size() > countOuter)
{
ContentValues attendees = new ContentValues();
// Add one attendee from list to one instance of an event
while(countInner < 1)
{
attendees.put(Attendees.EVENT_ID, instanceIdList.get(countOuter));
attendees.put(Attendees.ATTENDEE_EMAIL,emailList.get(numberOfAttendees));
attendees.put(Attendees.ATTENDEE_NAME, selectedNames.get(countOuter));
attendees.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_OPTIONAL);
countInner++;
numberOfAttendees--;
// If all attendees in list has been assigned and
// there are still more instances, start assigning to
// the attendees in the list again
if(numberOfAttendees == -1)
{
numberOfAttendees = selectedNames.size()-1;
}
}
countInner = 0;
countOuter++;
Uri uriAttendees = resolver.insert(Attendees.CONTENT_URI, attendees);
uriAttendees.buildUpon();
}
}
}
new EchoTask().execute();
Bitmap backBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image_load_success1);
Options options = new Options();
options.inSampleSize = 2;
// Bitmap failBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image_load_failed,options);
}
public class EchoTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
String[] args={"/storage/sdcard0/Music/halo.mp3"};
File file = new File(args[0]);
if(!file.canRead())
{
Log.i(TAG,"Insert a valid path!");
}
EchoNestAPI echoNest = new EchoNestAPI("XLNN9CZXKLXYFC66X");
Log.i(TAG,"hello echonest!");
Track track = null;
try {
track = echoNest.uploadTrack(file);
} catch (EchoNestException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i(TAG, "uploaded!");
if(track!=null){
try {
track.waitForAnalysis((60*1000)/2);
} catch (EchoNestException e) {
e.printStackTrace();
}
Log.i(TAG, "ID: "+track.getID());
try {
Log.i(TAG, "Artist: "+track.getArtistName());
} catch (EchoNestException e) {
e.printStackTrace();
}
try {
Log.i(TAG, "Title: "+track.getTitle());
} catch (EchoNestException e) {
e.printStackTrace();
}
}
return null;
}
}
}
| 31.437229 | 134 | 0.701735 |
5ea0cdee30e979d8c5e2fc09702b0f0adf581519 | 446 | package com.pl.arraysCopyOf;
import java.util.Arrays;
/**
* @author LIPIAO
* @Description Arrays.copyOf 给数组扩容
* @date 2019/8/7 12:00
*/
public class DemoArraysCopyOf {
public static void main(String[] args) {
int[] ints = new int[10];
for (int i = 0; i < ints.length; i++) {
ints[i] = i + 1;
}
int[] newInts = Arrays.copyOf(ints, 15);
System.out.println(newInts.length);
}
}
| 17.84 | 48 | 0.569507 |
3a725cab4afb91963d8e8f91a6edb8f3d05beea1 | 3,129 | package com.example.walkinclinic;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.TextView;
import android.widget.RatingBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class ClinicRating extends AppCompatActivity {
DatabaseSQLiteHelper db;
Button submitRate,dontRate;
TextView clinicname;
EditText comment;
RatingBar rating;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clinic_rating);
submitRate = (Button) findViewById(R.id.btn_RateClinic);
clinicname = (TextView) findViewById(R.id.clinicNameRate);
comment = (EditText) findViewById(R.id.text_Comment);
rating = (RatingBar) findViewById(R.id.ratingBar);
db = new DatabaseSQLiteHelper(this);
dontRate = (Button) findViewById(R.id.btn_DontRateClinic);
final String clinicID = getIntent().getStringExtra("clinicIDString");
//We require the Clinic's Name
toastMessage("THIS IS THE CLINIC ID = " + clinicID);
final String clinicsName = db.getClinicName(clinicID);
final String getData = getIntent().getStringExtra("currUser");
if (clinicsName != "error") {
clinicname.setText(clinicsName);
}
//An error has occured, move them back to the patient home
else {
toastMessage("Error has occured, Please return to patient home");
}
submitRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Gather all the required data
String commentToStore = comment.getText().toString();
String ratingToStore = Float.toString(rating.getRating());
//We don't allow 0 stars
if ((ratingToStore == "0" || clinicsName == "error")) {
toastMessage("Please Select Amount of Stars"); }
else{
if(db.insertNewRating(clinicID, ratingToStore, commentToStore)){
toastMessage("Rating Successfuly Sent");
MoveToPatientHome(getData);
}
else{
toastMessage("Server Error"); } }
}
});
dontRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MoveToPatientHome(getData); }
});
}
private void MoveToPatientHome(String getData) {
Intent newScreen = new Intent(this, PatientHome.class);
//For an error not to occur, we need to send back the username data with the key "USER_Name"
newScreen.putExtra("USER_Name", getData);
startActivity(newScreen);
}
public void toastMessage(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
}
| 32.59375 | 100 | 0.627037 |
f30e528c49e12b6fdb504daa991945110c9dc407 | 871 | package leetcode.Problem_242_Valid_Anagram;
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
var arr = new int[26];
for (int i = 0; i < s.length(); i++) {
/*
A char is actually just stored as a number (its code point value). We have syntax to represent
characters like char c = 'A';, but it's equivalent to char c = 65; and 'A' == 65 is true.
When we subtract 'a' from 'a' we get 0, because it's the same as 98 - 98.
The same story with 'b'. When we subtract 'a' from 'b' we do 99(b char code) - 98(a char code)
*/
arr[s.charAt(i) - 'a']++;
arr[t.charAt(i) - 'a']--;
}
for (int i: arr) {
if (i != 0) return false;
}
return true;
}
} | 31.107143 | 106 | 0.515499 |
4849179280dabd1cd87c9ec4af9943aa91747d80 | 929 | package com.tutorialspoint.eclipselink.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private int id;
private double salery;
private String jobDescr;
public Job() {
}
public int getId() {
return id;
}
public void setId(int param) {
this.id = param;
}
public double getSalery() {
return salery;
}
public void setSalery(double param) {
this.salery = param;
}
public String getJobDescr() {
return jobDescr;
}
public void setJobDescr(String param) {
this.jobDescr = param;
}
@Override
public String toString() {
return "Job [id=" + id + ", salery=" + salery + ", jobDescr=" + jobDescr +"]";
}
} | 17.865385 | 83 | 0.714747 |
d21b54e9c943377d58cb709da361febd3e9ea7c0 | 14,710 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package editeurpanovisu;
import static editeurpanovisu.EditeurPanovisu.getPanoramiquesProjet;
import static editeurpanovisu.EditeurPanovisu.getPoGeolocalisation;
import static editeurpanovisu.EditeurPanovisu.getTabInterface;
import static editeurpanovisu.EditeurPanovisu.getiPanoActuel;
import java.io.File;
import javafx.concurrent.Worker.State;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import netscape.javascript.JSObject;
/**
*
* @author LANG Laurent
*/
public class NavigateurOpenLayers {
private CoordonneesGeographiques marqueur;
private NavigateurCarte navigateurCarte;
private boolean bDebut = false;
private String[] strCartesOpenLayers;
private final ToggleGroup tgCartesOpenLayers = new ToggleGroup();
private AnchorPane apChoixCartographie = new AnchorPane();
private String strCartoActive="";
private String bingApiKey = "";
//private String bingApiKey = "";
/**
* @return the marqueur
*/
public CoordonneesGeographiques getMarqueur() {
return marqueur;
}
/**
* @param marqueur the marqueur to set
*/
public void setMarqueur(CoordonneesGeographiques marqueur) {
this.marqueur = marqueur;
}
/**
*
* @param coordonnees
* @param iFacteurZoom
*/
public void allerCoordonnees(CoordonneesGeographiques coordonnees, int iFacteurZoom) {
navigateurCarte.getWebEngine().executeScript("allerCoordonnees(" + coordonnees.getLongitude() + "," + coordonnees.getLatitude() + "," + iFacteurZoom + ")");
}
/**
*
* @return
*/
public CoordonneesGeographiques recupereCoordonnees() {
CoordonneesGeographiques coordonnees = new CoordonneesGeographiques();
String strCoord = navigateurCarte.getWebEngine().executeScript("getCoordonnees()").toString();
coordonnees.setLongitude(Double.parseDouble(strCoord.split(";")[0]));
coordonnees.setLatitude(Double.parseDouble(strCoord.split(";")[1]));
return coordonnees;
}
/**
*
* @param iNumeroMarqueur
*/
public void retireMarqueur(int iNumeroMarqueur) {
navigateurCarte.getWebEngine().executeScript("enleveMarqueur(" + iNumeroMarqueur + ")");
}
/**
*
* @param iNumeroMarqueur
* @param coordMarqueur
* @param strHTML
*/
public void ajouteMarqueur(int iNumeroMarqueur, CoordonneesGeographiques coordMarqueur, String strHTML) {
navigateurCarte.getWebEngine().executeScript("ajouteMarqueur(" + iNumeroMarqueur + "," + coordMarqueur.getLongitude() + "," + coordMarqueur.getLatitude() + ",\"" + strHTML + "\")");
}
/**
*
* @param strAdresse
* @param iFacteurZoom
*/
public void allerAdresse(String strAdresse, int iFacteurZoom) {
navigateurCarte.getWebEngine().executeScript("chercheAdresse('" + strAdresse + "'," + iFacteurZoom + ")");
}
/**
*
* @param iFacteurZoom
*/
public void choixZoom(int iFacteurZoom) {
navigateurCarte.getWebEngine().executeScript("choixZoom(" + iFacteurZoom + ")");
}
/**
*
* @param bingApiKey
*/
public void valideBingApiKey(String bingApiKey) {
if (bingApiKey.equals("")) {
bingApiKey = EditeurPanovisu.getStrBingAPIKey();
};
if (!bingApiKey.equals("")) {
navigateurCarte.getWebEngine().executeScript("setBingApiKey(\"" + bingApiKey + "\");");
}
afficheCartesOpenlayer();
}
/**
*
* @return
*/
public String recupereCartographiesOpenLayers() {
return navigateurCarte.getWebEngine().executeScript("getNomsLayers()").toString();
}
public void changeCarte(String strCarto) {
navigateurCarte.getWebEngine().executeScript("changeLayer('" + strCarto + "')");
}
public void afficheCartesOpenlayer() {
getApChoixCartographie().getChildren().clear();
String nomsCartes = recupereCartographiesOpenLayers();
strCartesOpenLayers = nomsCartes.split("\\|");
for (int i = 0; i < strCartesOpenLayers.length; i++) {
boolean bCarteChoisie = false;
if (strCartesOpenLayers[i].substring(0, 1).equals("*")) {
strCartesOpenLayers[i] = strCartesOpenLayers[i].substring(1, strCartesOpenLayers[i].length());
bCarteChoisie = true;
}
RadioButton rbCarto = new RadioButton(strCartesOpenLayers[i]);
rbCarto.setLayoutX(10);
rbCarto.setLayoutY(i * 30);
rbCarto.setUserData(strCartesOpenLayers[i]);
rbCarto.setSelected(bCarteChoisie);
rbCarto.setToggleGroup(tgCartesOpenLayers);
getApChoixCartographie().getChildren().add(rbCarto);
}
}
/**
*
* @param tfLongitude
* @param tfLatitude
* @param bChoixMarqueur
* @return
*/
public AnchorPane afficheNavigateurOpenLayer(TextField tfLongitude, TextField tfLatitude, boolean bChoixMarqueur) {
AnchorPane apOpenLayers = new AnchorPane();
apOpenLayers.setStyle("-fx-background-color : -fx-base;-fx-border-width : 1px;-fx-border-style : solid;-fx-border-color : #777;"
+ "-fx-border-color: #777;"
+ "-fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.5) , 8, 0.0 , 0 , 8 );"
+ "-fx-border-width: 1px;"
);
Label lblAttente = new Label("Chargement en cours. Veuillez patienter");
lblAttente.setAlignment(Pos.CENTER);
lblAttente.setStyle("-fx-background-color : #777;");
lblAttente.setTextFill(Color.WHITE);
lblAttente.setLayoutX(10);
lblAttente.setLayoutY(70);
apOpenLayers.getChildren().add(lblAttente);
navigateurCarte = new NavigateurCarte();
navigateurCarte.setLayoutX(10);
navigateurCarte.setLayoutY(70);
navigateurCarte.setVisible(false);
getApChoixCartographie().setMaxWidth(180);
apOpenLayers.getChildren().add(navigateurCarte);
File fileRep = new File("");
String strRepertAppli = fileRep.getAbsolutePath();
TextField tfRechercheAdresse = new TextField();
Button btnRechercheAdresse = new Button("Recherche", new ImageView(new Image("file:" + strRepertAppli + File.separator + "images/loupe.png", -1, 16, true, true)));
Button btnRecupereCoordonnees = new Button("valide position");
Button btnCentreCarte = new Button("recentre carte");
Button btnFerme = new Button("X");
btnFerme.setOnAction((e) -> {
apOpenLayers.setVisible(false);
});
if (bChoixMarqueur) {
tfRechercheAdresse.setPromptText("Votre recherche d'adresse");
tfRechercheAdresse.setPrefWidth(200);
tfRechercheAdresse.setLayoutX(10);
tfRechercheAdresse.setLayoutY(40);
btnRechercheAdresse.setLayoutX(220);
btnRechercheAdresse.setLayoutY(40);
btnRecupereCoordonnees.setLayoutX(10);
btnRecupereCoordonnees.setLayoutY(10);
btnRecupereCoordonnees.setPrefWidth(120);
btnCentreCarte.setLayoutX(140);
btnCentreCarte.setLayoutY(10);
btnCentreCarte.setPrefWidth(120);
apOpenLayers.getChildren().addAll(btnRecupereCoordonnees, btnCentreCarte, btnFerme,
tfRechercheAdresse, btnRechercheAdresse, getApChoixCartographie());
}
lblAttente.setPrefSize(apOpenLayers.getPrefWidth() - 220, apOpenLayers.getPrefHeight() - 120);
if (bChoixMarqueur) {
navigateurCarte.getWebView().setPrefWidth(apOpenLayers.getPrefWidth() - 220);
navigateurCarte.getWebView().setPrefHeight(apOpenLayers.getPrefHeight() - 120);
getApChoixCartographie().setLayoutX(apOpenLayers.getPrefWidth() - 180);
getApChoixCartographie().setLayoutY(70);
} else {
navigateurCarte.getWebView().setPrefWidth(apOpenLayers.getPrefWidth());
navigateurCarte.getWebView().setPrefHeight(apOpenLayers.getPrefHeight());
navigateurCarte.setLayoutX(0);
navigateurCarte.setLayoutY(0);
}
navigateurCarte.getWebEngine().getLoadWorker().stateProperty().addListener((paramObservableValue, from, to) -> {
if (to == State.SUCCEEDED) {
navigateurCarte.setVisible(true);
valideBingApiKey(getBingApiKey());
JSObject window = (JSObject) navigateurCarte.getWebEngine().executeScript("window");
window.setMember("javafx", new JavaApplication());
allerAdresse("Metz rue Serpenoise", 14);
bDebut = true;
getTabInterface().setDisable(false);
}
});
if (bChoixMarqueur) {
btnCentreCarte.setOnAction((e) -> {
if (bDebut) {
if (getMarqueur() != null) {
allerCoordonnees(getMarqueur(), 17);
}
}
});
btnRecupereCoordonnees.setOnAction((e) -> {
if (bDebut) {
setMarqueur(this.recupereCoordonnees());
if (tfLongitude != null) {
tfLongitude.setText(CoordonneesGeographiques.toDMS(getMarqueur().getLongitude()));
}
if (tfLatitude != null) {
tfLatitude.setText(CoordonneesGeographiques.toDMS(getMarqueur().getLatitude()));
}
getPoGeolocalisation().setbValide(true);
String strHTML = "<span style='font-family : Verdana,Arial,sans-serif;font-weight:bold;font-size : 12px;'>"
+ getPanoramiquesProjet()[getiPanoActuel()].getStrTitrePanoramique()
+ "</span><br/>"
+ "<span style='font-family : Verdana,Arial,sans-serif;bold;font-size : 10px;'>"
+ getPanoramiquesProjet()[getiPanoActuel()].getStrNomFichier()
+ "</span>";
strHTML = strHTML.replace("\\", "/");
retireMarqueur(0);
getPanoramiquesProjet()[getiPanoActuel()].setMarqueurGeolocatisation(getMarqueur());
ajouteMarqueur(0, getMarqueur(), strHTML);
}
});
}
tfRechercheAdresse.setOnKeyPressed((e) -> {
if (e.getCode() == KeyCode.ENTER) {
if (bDebut) {
allerAdresse(tfRechercheAdresse.getText(), 17);
}
}
});
btnRechercheAdresse.setOnAction((e) -> {
if (bDebut) {
allerAdresse(tfRechercheAdresse.getText(), 17);
}
});
tgCartesOpenLayers.selectedToggleProperty().addListener((ov, old_toggle, new_toggle) -> {
if (tgCartesOpenLayers.getSelectedToggle() != null) {
setStrCartoActive(tgCartesOpenLayers.getSelectedToggle().getUserData().toString());
changeCarte(getStrCartoActive());
}
});
apOpenLayers.widthProperty().addListener((ov, av, nv) -> {
if (bChoixMarqueur) {
lblAttente.setPrefWidth(apOpenLayers.getPrefWidth() - 220);
navigateurCarte.getWebView().setPrefWidth((double) nv - 200);
getApChoixCartographie().setLayoutX((double) nv - 180);
btnFerme.setLayoutX((double) nv - 35);
} else {
navigateurCarte.getWebView().setPrefWidth((double) nv);
}
});
apOpenLayers.heightProperty().addListener((ov, av, nv) -> {
if (bChoixMarqueur) {
lblAttente.setPrefHeight(apOpenLayers.getPrefHeight() - 120);
navigateurCarte.getWebView().setPrefHeight((double) nv - 80);
btnFerme.setLayoutY(10);
} else {
navigateurCarte.getWebView().setPrefHeight((double) nv);
}
});
return apOpenLayers;
}
/**
* @return the strCartoActive
*/
public String getStrCartoActive() {
return strCartoActive;
}
/**
* @param strCartoActive the strCartoActive to set
*/
public void setStrCartoActive(String strCartoActive) {
this.strCartoActive = strCartoActive;
}
/**
* @return the apChoixCartographie
*/
public AnchorPane getApChoixCartographie() {
return apChoixCartographie;
}
/**
* @param apChoixCartographie the apChoixCartographie to set
*/
public void setApChoixCartographie(AnchorPane apChoixCartographie) {
this.apChoixCartographie = apChoixCartographie;
}
/**
* @return the bingApiKey
*/
public String getBingApiKey() {
return bingApiKey;
}
/**
* @param bingApiKey the bingApiKey to set
*/
public void setBingApiKey(String bingApiKey) {
this.bingApiKey = bingApiKey;
}
/**
*
*/
public class JavaApplication {
/**
*
* @param msg
*/
public void adresseInconnue(String msg) {
//System.out.println("Adresse Inconnue\n" + msg);
}
/**
*
* @param lon
* @param lat
*/
public void adresseTrouvee(double lon, double lat) {
//System.out.println(
// "Adresse trouvée aux coordonnées : " + CoordonneesGeographiques.toDMS(lat) + " " + CoordonneesGeographiques.toDMS(lon)
// );
}
/**
*
* @param strChaine
*/
public void afficheChaine(String strChaine) {
System.out.println(strChaine);
}
}
}
| 37.717949 | 190 | 0.590143 |
536f8fd06982d13e98a981b67ec7b59aa78198ca | 1,725 | /*
* Copyright 2016 Author:Bestoa bestoapache@gmail.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 shadowsocks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import shadowsocks.crypto.CryptoFactory;
import shadowsocks.util.GlobalConfig;
public class Main{
public static Logger log = LogManager.getLogger(Main.class.getName());
public static final String VERSION = "0.8.3";
public static void main(String argv[])
{
log.info("Shadowsocks " + VERSION);
if (!GlobalConfig.getConfigFromArgv(argv)) {
return;
}
try {
GlobalConfig.getConfigFromFile();
}catch(ClassCastException e) {
log.fatal("Get config from json file error.", e);
return;
}
//make sure this method could work.
if (CryptoFactory.create(GlobalConfig.get().getMethod(), GlobalConfig.get().getPassword()) == null) {
log.fatal("Unsupport crypto method: " + GlobalConfig.get().getMethod());
return;
}
GlobalConfig.get().printConfig();
new ShadowsocksVertx(GlobalConfig.get().isServerMode()).start();
}
}
| 33.173077 | 109 | 0.667826 |
e5968579aae834b6385ef26b5012573a5aebd535 | 2,409 | /*
* Copyright (c) 2020 Bixbit - Krzysztof Benedyczak. All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.engine.api.policyAgreement;
import java.util.Date;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import pl.edu.icm.unity.Constants;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.types.policyAgreement.PolicyAgreementAcceptanceStatus;
public class PolicyAgreementState
{
public final long policyDocumentId;
public final int policyDocumentRevision;
public final PolicyAgreementAcceptanceStatus acceptanceStatus;
public final Date decisionTs;
@JsonCreator
public PolicyAgreementState(@JsonProperty("policyDocumentId") Long policyDocumentId,
@JsonProperty("policyDocumentRevision") Integer policyDocumentRevision,
@JsonProperty("acceptanceStatus") PolicyAgreementAcceptanceStatus acceptanceStatus,
@JsonProperty("decisionTs") Date decisionTs)
{
this.policyDocumentId = policyDocumentId;
this.policyDocumentRevision = policyDocumentRevision;
this.acceptanceStatus = acceptanceStatus;
this.decisionTs = decisionTs;
}
public String toJson() throws EngineException
{
try
{
return Constants.MAPPER.writeValueAsString(this);
} catch (JsonProcessingException e)
{
throw new EngineException("Can not save policy agreement state value");
}
}
public static PolicyAgreementState fromJson(String jsonConfig) throws EngineException
{
try
{
return Constants.MAPPER.readValue(jsonConfig, PolicyAgreementState.class);
} catch (Exception e)
{
throw new EngineException("Can not parse policy agreement state value");
}
}
@Override
public boolean equals(final Object other)
{
if (!(other instanceof PolicyAgreementState))
return false;
PolicyAgreementState castOther = (PolicyAgreementState) other;
return Objects.equals(policyDocumentId, castOther.policyDocumentId)
&& Objects.equals(policyDocumentRevision, castOther.policyDocumentRevision)
&& Objects.equals(acceptanceStatus, castOther.acceptanceStatus)
&& Objects.equals(decisionTs, castOther.decisionTs);
}
@Override
public int hashCode()
{
return Objects.hash(policyDocumentId, policyDocumentRevision, acceptanceStatus, decisionTs);
}
}
| 30.493671 | 94 | 0.794521 |
70cbccb626a3d1d05be37f1dd4ecc558244035cb | 677 | /*
* Copyright (c) 2016-2021 Association of Universities for Research in Astronomy, Inc. (AURA)
* For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause
*/
package edu.gemini.epics.acm;
/**
* Defines the interface that must be implemented by clients to monitor the
* execution of a command.
*
* @author jluhrs
*
*/
public interface CaCommandListener {
/**
* Called when the command completes successfully.
*/
void onSuccess();
/**
* Called when the command completes with an error.
*/
void onFailure(Exception cause);
/**
* Called when the command is paused.
*/
void onPause();
}
| 21.83871 | 93 | 0.66322 |
43950585c078a2a67c292afa1fd2241b72f7996f | 932 | package com.taoerxue.mapper;
import com.taoerxue.pojo.EducationType;
import com.taoerxue.pojo.EducationTypeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface EducationTypeMapper {
int countByExample(EducationTypeExample example);
int deleteByExample(EducationTypeExample example);
int deleteByPrimaryKey(Integer id);
int insert(EducationType record);
int insertSelective(EducationType record);
List<EducationType> selectByExample(EducationTypeExample example);
EducationType selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") EducationType record, @Param("example") EducationTypeExample example);
int updateByExample(@Param("record") EducationType record, @Param("example") EducationTypeExample example);
int updateByPrimaryKeySelective(EducationType record);
int updateByPrimaryKey(EducationType record);
} | 31.066667 | 120 | 0.79721 |
9010bdad9ecf9294c20ca453b7b48c9853b53ce0 | 776 | import foursquare.Arguments;
import foursquare.FSReply;
import foursquare.FSResponse;
import foursquare.FSVenue;
import foursquare.Foursquare;
public class testFoursquareCall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments aFArgs = new Arguments();
// aFArgs.addLL("40.7", "-74");
aFArgs.addPrice("1,2,3,4");
aFArgs.addIntent("browse");
aFArgs.addNorthEast("40.695","-74.005");
aFArgs.addSouthWest("40.705","-73.995");
FSReply aRes = Foursquare.getData(aFArgs);
if (aRes!=null) {
System.out.println("#venues:"+aRes.response.venues.length);
for (FSVenue aVenue:aRes.response.venues){
System.out.println("#venue name:"+aVenue.name);
}
}
}
}
| 19.4 | 62 | 0.66366 |
868197e20601b8211c41b75f37a5680cfa052cc0 | 604 | package definitions;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import pages.QuoteForm;
import java.util.*;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class LoginPage {
@Given("User lands on {requested page}")
public void iNavigateToPage(String page) {
switch (page) {
case "quote":
new QuoteForm().open();
break;
default:
throw new RuntimeException("Unknown page: " + page);
}
}
}
| 24.16 | 68 | 0.634106 |
1c7c4df9e835c917501ff079f4b9f8a7726e4e80 | 19,307 | package hudson.plugins.performance.constraints;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import hudson.plugins.performance.constraints.blocks.TestCaseBlock;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestBuilder;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.plugins.performance.PerformancePublisher;
import hudson.plugins.performance.constraints.AbstractConstraint.Escalation;
import hudson.plugins.performance.constraints.AbstractConstraint.Metric;
import hudson.plugins.performance.constraints.AbstractConstraint.Operator;
public class ConstraintTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@After
public void shutdown() throws Exception {
j.after();
}
/**
* Testing: Escalation.INFORMATION
* Build must stay successful if the value is exceeded.
* <p>
* Specified value: 1
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void informationModeDoesntAffectBuildStatus() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// Value set to 1L to violate constraint. Due to Escalation.INFORMATION the build status must be SUCCESS.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_GREATER, "testResult.xml", Escalation.INFORMATION, false, testCaseBlock, 1L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher("", 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
performancePublisher.setFailBuildIfNoResultFile(false);
FreeStyleProject p = j.createFreeStyleProject("informationModeDoesntAffectBuildStatus");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.SUCCESS, result.getResult());
}
/**
* Testing: Escalation.WARNING
* Build must be unstable if the value is exceeded.
* <p>
* Specified value: 1
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void warningModeMakesBuildUnstable() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// Value set to 1L to violate constraint. Due to Escalation.WARNING the build status must be UNSTABLE.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_GREATER, "testResult.xml", Escalation.WARNING, false, testCaseBlock, 1L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher("testResult.xml", 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
FreeStyleProject p = j.createFreeStyleProject("warningModeMakesBuildUnstable");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.UNSTABLE, result.getResult());
}
/**
* Testing: Escalation.ERROR
* Build must fail if the value is exceeded.
* <p>
* Specified value: 1
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void errorModeMakesBuildFail() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// Value set to 1L to violate constraint. Due to Escalation.ERROR the build status must be FAILURE.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_GREATER, "constraint-test.xml", Escalation.ERROR, false, testCaseBlock, 1L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher(getClass().getResource("/constraint-test.xml").getFile(), 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
FreeStyleProject p = j.createFreeStyleProject("errorModeMakesBuildFail");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.FAILURE, result.getResult());
}
/**
* Testing: Operator.NOT_GREATER
* Calculated value is equal to specified => Build.SUCCESS
* <p>
* Specified value: 56
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void equalValuesWithNotGreaterOperator() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// The specified value and calculated value are equal.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_GREATER, "testResult.xml", Escalation.ERROR, false, testCaseBlock, 56L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher("", 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
performancePublisher.setFailBuildIfNoResultFile(false);
FreeStyleProject p = j.createFreeStyleProject("equalValuesWithNotGreaterOperator");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.SUCCESS, result.getResult());
}
/**
* Testing: Operator.NOT_GREATER
* Calculated value is greater than specified => Build.FAILURE
* <p>
* Specified value: 55
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void calculatedValueGreaterWithNotGreaterOperator() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// The specified should not be exceeded.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_GREATER, "constraint-test.xml", Escalation.ERROR, false, testCaseBlock, 55L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher(getClass().getResource("/constraint-test.xml").getFile(), 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
FreeStyleProject p = j.createFreeStyleProject("calculatedValueGreaterWithNotGreaterOperator");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.FAILURE, result.getResult());
}
/**
* Testing: Operator.NOT_EQUAL
* Calculated value is equal to specified => Build.FAILURE
* <p>
* Specified value: 56
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void equalValuesWithNotEqualOperator() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// The specified value and calculated value are equal.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_EQUAL, "constraint-test.xml", Escalation.ERROR, false, testCaseBlock, 56L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher(getClass().getResource("/constraint-test.xml").getFile(), 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
FreeStyleProject p = j.createFreeStyleProject("equalValuesWithNotEqualOperator");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.FAILURE, result.getResult());
}
/**
* Testing: Operator.NOT_EQUAL
* Calculated value is not equal than specified => Build.SUCCESS
* <p>
* Specified value: 55
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void notEqualValueWithNotEqualOperator() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// The specified should not be exceeded.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_EQUAL, "testResult.xml", Escalation.ERROR, false, testCaseBlock, 55L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher("", 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
performancePublisher.setFailBuildIfNoResultFile(false);
FreeStyleProject p = j.createFreeStyleProject("notEqualValueWithNotEqualOperator");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.SUCCESS, result.getResult());
}
/**
* Testing: Operator.NOT_LESS
* Calculated value is equal to specified => Build.SUCCES
* <p>
* Specified value: 56
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void equalValuesWithNotLessOperator() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// The specified value and calculated value are equal.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_LESS, "testResult.xml", Escalation.ERROR, false, testCaseBlock, 56L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher("", 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
performancePublisher.setFailBuildIfNoResultFile(false);
FreeStyleProject p = j.createFreeStyleProject("equalValuesWithNotLessOperator");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.SUCCESS, result.getResult());
}
/**
* Testing: Operator.NOT_LESS
* Calculated value is less than specified => Build.FAILURE
* <p>
* Specified value: 57
* Calculated average value: 56
*
* @throws Exception if test encounters errors.
*/
@Test
public void calculatedValueLessWithNotLessOperator() throws Exception {
TestCaseBlock testCaseBlock = new TestCaseBlock("listShows");
// The specified should not be exceeded.
AbsoluteConstraint absoluteConstraint = new AbsoluteConstraint(Metric.AVERAGE, Operator.NOT_LESS, "constraint-test.xml", Escalation.ERROR, false, testCaseBlock, 57L);
List<AbstractConstraint> abstractBuildsList = new ArrayList<AbstractConstraint>();
abstractBuildsList.add(absoluteConstraint);
PerformancePublisher performancePublisher = new PerformancePublisher(getClass().getResource("/constraint-test.xml").getFile(), 10, 20, "", 0, 0, 0, 0, 0, false, "", false, true, false, true, null);
performancePublisher.setModeEvaluation(true);
performancePublisher.setConstraints(abstractBuildsList);
performancePublisher.setIgnoreFailedBuilds(false);
performancePublisher.setIgnoreUnstableBuilds(false);
performancePublisher.setPersistConstraintLog(false);
FreeStyleProject p = j.createFreeStyleProject("calculatedValueLessWithNotLessOperator");
p.getPublishersList().add(performancePublisher);
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
build.getWorkspace().child("testResult.xml").copyFrom(getClass().getResource("/constraint-test.xml"));
return true;
}
});
FreeStyleBuild result = p.scheduleBuild2(0).get();
Assert.assertEquals(Result.FAILURE, result.getResult());
}
} | 46.188995 | 205 | 0.685347 |
807fe790fcd9c5ed4126803b60d28b609f678f40 | 13,377 |
package jean.ensembl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import jam.lang.JamException;
import jam.util.MapUtil;
import jean.hugo.HugoSymbol;
import jean.fasta.FastaPeptideReader;
import jean.fasta.FastaPeptideRecord;
/**
* Manages the human proteome data from Ensembl.
*/
public final class EnsemblProteinDb {
// Protein and transcript keys map uniquely to peptide structures...
private final Map<EnsemblProteinID, EnsemblProteinRecord> proteinRecordMap;
private final Map<EnsemblTranscriptID, EnsemblProteinRecord> transcriptRecordMap;
// ...while gene identifiers may map to multiple peptide structures.
private final Multimap<HugoSymbol, EnsemblProteinRecord> hugoRecordMap;
private final Multimap<EnsemblGeneID, EnsemblProteinRecord> geneRecordMap;
// The GRCh38 reference Ensembl database defines a mapping from gene to HUGO symbol...
private final Map<EnsemblGeneID, HugoSymbol> geneHugoMap;
private static EnsemblProteinDb reference = null;
private EnsemblProteinDb() {
this.proteinRecordMap = new HashMap<EnsemblProteinID, EnsemblProteinRecord>();
this.transcriptRecordMap = new HashMap<EnsemblTranscriptID, EnsemblProteinRecord>();
this.hugoRecordMap = HashMultimap.create();
this.geneRecordMap = HashMultimap.create();
this.geneHugoMap = new HashMap<EnsemblGeneID, HugoSymbol>();
}
/**
* Creates a database of Ensembl records from FASTA files.
*
* <p>The first file is the <em>primary</em> file:
* files are <em>secondary</em> files: they may contain duplicate
* protein or transcript identifiers, but those records will be
* ignored.
*
* @param primaryFile the primary FASTA file: all protein and
* transcript identifiers in this file must be unique.
*
* @param secondaryFiles optional secondary FASTA files: they may
* contain duplicate protein or transcript identifiers, which will
* be ignored.
*
* @return the database of Ensembl records.
*
* @throws RuntimeException if any I/O errors occur.
*/
public static EnsemblProteinDb load(String primaryFile, String... secondaryFiles) {
EnsemblProteinDb database = new EnsemblProteinDb();
database.loadPrimary(primaryFile);
for (String secondaryFile : secondaryFiles)
database.loadSecondary(secondaryFile);
return database;
}
private void loadPrimary(String fastaFile) {
try (FastaPeptideReader reader = FastaPeptideReader.open(fastaFile)) {
loadPrimary(reader);
}
}
private void loadSecondary(String fastaFile) {
try (FastaPeptideReader reader = FastaPeptideReader.open(fastaFile)) {
loadSecondary(reader);
}
}
private void loadPrimary(Iterable<FastaPeptideRecord> records) {
for (FastaPeptideRecord record : records)
addPrimary(record);
}
private void loadSecondary(Iterable<FastaPeptideRecord> records) {
for (FastaPeptideRecord record : records)
addSecondary(record);
}
private void addPrimary(FastaPeptideRecord fastaRecord) {
EnsemblProteinRecord ensemblRecord = EnsemblProteinRecord.parse(fastaRecord);
mapProtein(ensemblRecord);
mapTranscript(ensemblRecord);
mapGene(ensemblRecord);
mapHugo(ensemblRecord);
}
private void mapProtein(EnsemblProteinRecord record) {
EnsemblProteinID proteinID = record.getEnsemblProteinID();
if (proteinRecordMap.put(proteinID, record) != null)
throw JamException.runtime("Duplicate protein ID: [%s]", proteinID);
}
private void mapTranscript(EnsemblProteinRecord record) {
EnsemblTranscriptID transcriptID = record.getEnsemblTranscriptID();
if (transcriptRecordMap.put(transcriptID, record) != null)
throw JamException.runtime("Duplicate transcript ID: [%s]", transcriptID);
}
private void mapGene(EnsemblProteinRecord record) {
//
// There will be multiple records for a single gene...
//
geneRecordMap.put(record.getEnsemblGeneID(), record);
}
private void mapHugo(EnsemblProteinRecord record) {
HugoSymbol hugo = record.getHugoSymbol();
EnsemblGeneID gene = record.getEnsemblGeneID();
if (hugo != null) {
hugoRecordMap.put(hugo, record);
MapUtil.putUnique(geneHugoMap, gene, hugo);
}
}
private void addSecondary(FastaPeptideRecord fastaRecord) {
EnsemblProteinRecord ensemblRecord = EnsemblProteinRecord.parse(fastaRecord);
if (isUniqueProtein(ensemblRecord) && isUniqueTranscript(ensemblRecord))
addPrimary(fastaRecord);
}
private boolean isUniqueProtein(EnsemblProteinRecord ensemblRecord) {
return !proteinRecordMap.containsKey(ensemblRecord.getEnsemblProteinID());
}
private boolean isUniqueTranscript(EnsemblProteinRecord ensemblRecord) {
return !transcriptRecordMap.containsKey(ensemblRecord.getEnsemblTranscriptID());
}
/**
* Returns the reference human proteome.
*
* @return the reference human proteome.
*/
public static synchronized EnsemblProteinDb reference() {
if (reference == null)
reference = loadReference();
return reference;
}
private static EnsemblProteinDb loadReference() {
String primaryFile = EnsemblLocator.resolvePrimaryProteomeFileName();
String secondaryFile = EnsemblLocator.resolveSecondaryProteomeFileName();
if (secondaryFile != null)
return load(primaryFile, secondaryFile);
else
return load(primaryFile);
}
/**
* Identifies genes in this map.
*
* @param gene a gene of interest.
*
* @return {@code true} iff this map contains the specified gene.
*/
public boolean contains(EnsemblGeneID gene) {
return geneRecordMap.containsKey(gene);
}
/**
* Identifies proteins in this map.
*
* @param protein a protein of interest.
*
* @return {@code true} iff this map contains the specified protein.
*/
public boolean contains(EnsemblProteinID protein) {
return proteinRecordMap.containsKey(protein);
}
/**
* Identifies transcripts in this map.
*
* @param transcript a transcript of interest.
*
* @return {@code true} iff this map contains the specified transcript.
*/
public boolean contains(EnsemblTranscriptID transcript) {
return transcriptRecordMap.containsKey(transcript);
}
/**
* Identifies HUGO symbols in this map.
*
* @param hugo a HUGO symbol of interest.
*
* @return {@code true} iff this map contains the specified HUGO
* symbol.
*/
public boolean contains(HugoSymbol hugo) {
return hugoRecordMap.containsKey(hugo);
}
/**
* Counts the number of peptides mapped to a given gene.
*
* @param gene a gene of interest.
*
* @return the number of peptides mapped to the given gene.
*/
public int count(EnsemblGeneID gene) {
return geneRecordMap.get(gene).size();
}
/**
* Counts the number of peptides mapped to a given HUGO symbol.
*
* @param hugo a HUGO symbol of interest.
*
* @return the number of peptides mapped to the given HUGO symbol.
*/
public int count(HugoSymbol hugo) {
return hugoRecordMap.get(hugo).size();
}
/**
* Returns a read-only view of the records mapped to a given
* gene.
*
* @param gene the gene of interest.
*
* @return a read-only collection containing the records mapped
* to the specified gene (an empty collection if the gene is not
* mapped).
*/
public Collection<EnsemblProteinRecord> get(EnsemblGeneID gene) {
return Collections.unmodifiableCollection(geneRecordMap.get(gene));
}
/**
* Returns a read-only view of the records mapped to a collection
* of genes.
*
* @param genes the genes of interest.
*
* @return a read-only collection containing the records mapped to
* the specified genes (an empty collection if none of the genes
* are mapped).
*/
public Collection<EnsemblProteinRecord> get(Collection<EnsemblGeneID> genes) {
List<EnsemblProteinRecord> records = new ArrayList<EnsemblProteinRecord>();
for (EnsemblGeneID gene : genes)
records.addAll(get(gene));
return records;
}
/**
* Returns the record mapped to a given protein.
*
* @param protein the protein of interest.
*
* @return the record mapped to the specified protein (or
* {@code null} if there is no mapping).
*/
public EnsemblProteinRecord get(EnsemblProteinID protein) {
return proteinRecordMap.get(protein);
}
/**
* Returns the record mapped to a given transcript.
*
* @param transcript the transcript of interest.
*
* @return the record mapped to the specified transcript (or
* {@code null} if there is no mapping).
*/
public EnsemblProteinRecord get(EnsemblTranscriptID transcript) {
return transcriptRecordMap.get(transcript);
}
/**
* Returns a read-only view of the records mapped to a given
* HUGO symbol.
*
* @param hugo the HUGO symbol of interest.
*
* @return a read-only collection containing the records mapped
* to the specified HUGO symbol (an empty collection if the HUGO
* symbol is not mapped).
*/
public Collection<EnsemblProteinRecord> get(HugoSymbol hugo) {
return Collections.unmodifiableCollection(hugoRecordMap.get(hugo));
}
/**
* Returns the HUGO symbol mapped to a given gene.
*
* @param gene the gene of interest.
*
* @return the HUGO symbol mapped to the specified gene, or
* {@code null} if there is no mapping.
*/
public HugoSymbol getHugo(EnsemblGeneID gene) {
return geneHugoMap.get(gene);
}
/**
* Returns the HUGO symbol mapped to a given transcript.
*
* @param transcript the transcript of interest.
*
* @return the HUGO symbol mapped to the specified transcript, or
* {@code null} if there is no mapping.
*/
public HugoSymbol getHugo(EnsemblTranscriptID transcript) {
EnsemblProteinRecord record = get(transcript);
if (record != null)
return getHugo(record.getEnsemblGeneID());
else
return null;
}
/**
* Returns a read-only view of the genes in this map.
*
* @return a read-only set containing the genes in this map.
*/
public Set<EnsemblGeneID> geneSet() {
return Collections.unmodifiableSet(geneRecordMap.keySet());
}
/**
* Returns a read-only view of the HUGO symbols in this map.
*
* @return a read-only set containing the HUGO symbols in this
* map.
*/
public Set<HugoSymbol> hugoSet() {
return Collections.unmodifiableSet(hugoRecordMap.keySet());
}
/**
* Returns a read-only view of the proteins in this map.
*
* @return a read-only set containing the proteins in this map.
*/
public Set<EnsemblProteinID> proteinSet() {
return Collections.unmodifiableSet(proteinRecordMap.keySet());
}
/**
* Returns the record mapped to a given protein.
*
* @param protein the protein of interest.
*
* @return the record mapped to the specified protein.
*
* @throws RuntimeException unless the correponding protein
* exists.
*/
public EnsemblProteinRecord require(EnsemblProteinID protein) {
EnsemblProteinRecord record = get(protein);
if (record != null)
return record;
else
throw JamException.runtime("Unmapped protein: [%s].", protein.getKey());
}
/**
* Returns the record mapped to a given transcript.
*
* @param transcript the transcript of interest.
*
* @return the record mapped to the specified transcript.
*
* @throws RuntimeException unless the correponding protein
* exists.
*/
public EnsemblProteinRecord require(EnsemblTranscriptID transcript) {
EnsemblProteinRecord record = get(transcript);
if (record != null)
return record;
else
throw JamException.runtime("Unmapped transcript: [%s].", transcript.getKey());
}
/**
* Returns a read-only view of the transcripts in this map.
*
* @return a read-only set containing the transcripts in this map.
*/
public Set<EnsemblTranscriptID> transcriptSet() {
return Collections.unmodifiableSet(transcriptRecordMap.keySet());
}
/**
* Returns the number of records in this database.
*
* @return the number of records in this database.
*/
public int size() {
return proteinRecordMap.size();
}
}
| 31.254673 | 92 | 0.659939 |
86cee09315106a12d0bcd4528e5ce70ebeb13c34 | 2,117 | /*
Derby - Class org.apache.derby.impl.sql.compile.RowNumberFunctionNode
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.derby.impl.sql.compile;
import java.sql.Types;
import java.util.List;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.types.TypeId;
/**
* Class that represents a call to the ROW_NUMBER() window function.
*/
public final class RowNumberFunctionNode extends WindowFunctionNode
{
/**
*
* @param op operand (null for now)
* @param w The window definition or reference
*/
public RowNumberFunctionNode(ValueNode op, WindowNode w, ContextManager cm)
throws StandardException {
super(op, "ROW_NUMBER", w, cm);
setType( TypeId.getBuiltInTypeId( Types.BIGINT ),
TypeId.LONGINT_PRECISION,
TypeId.LONGINT_SCALE,
false,
TypeId.LONGINT_MAXWIDTH);
}
/**
* ValueNode override.
* @see ValueNode#bindExpression
*/
@Override
ValueNode bindExpression(
FromList fromList, SubqueryList subqueryList, List<AggregateNode> aggregates)
throws StandardException
{
super.bindExpression(fromList, subqueryList, aggregates);
return this;
}
}
| 34.145161 | 97 | 0.701937 |
999ac5ed6d5b130f70fcb87c9de5db35e35470c6 | 2,863 | package math;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
*
* @author exponential-e
* 백준 9359번: 서로소
*
* @see https://www.acmicpc.net/problem/9359
*
*/
public class Boj9359 {
private static List<Long> primes;
private static boolean[] prime;
private static Map<Long, Integer> mapper;
private static final String CASE = "Case #";
private static final String COLON = ": ";
private static final String NEW_LINE = "\n";
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
eratosThenesSieve();
StringBuilder sb = new StringBuilder();
for(int t = 1; t <= T; t++) {
StringTokenizer st = new StringTokenizer(br.readLine());
long A = Long.parseLong(st.nextToken());
long B = Long.parseLong(st.nextToken());
long N = Long.parseLong(st.nextToken());
sb.append(CASE).append(t).append(COLON).append(inExclude(A, B, N)).append(NEW_LINE);
}
System.out.println(sb.toString());
}
/**
*
* Eratos Thenes sieve
*
*/
private static void eratosThenesSieve() {
prime = new boolean[100_001];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
primes = new ArrayList<>();
for(int i = 2; i < prime.length; i++){
if(!prime[i]) continue;
primes.add((long) i);
for(int j = i + i; j < prime.length; j += i){
prime[j] = false;
}
}
}
private static long inExclude(long a, long b, long n) {
List<Long> division = new ArrayList<>();
mapper = new HashMap<>();
while(n > 1){
boolean flag = true;
for(long p : primes){
if(n % p != 0) continue;
n /= p;
flag = false;
mapper.put(p, 1);
break;
}
if(flag) break;
}
if(n != 1) mapper.put(n, 1);
for(Long key: mapper.keySet()){
division.add(key);
}
long ans = 0;
int size = division.size();
long bit = 1L << size;
for(int i = 1; i < bit; i++){
long count = 0, sum = 1;
for(int j = 0; j < size; j++){
if((i & (1 << j)) == 0) continue;
count++;
sum *= division.get(j);
}
long before = (a - 1) / sum + 1;
long after = b / sum;
if(before > after) continue;
long interval = after - before + 1;
ans += ((count & 1) > 0 ? 1L: -1L) * interval;
}
return b - a + 1 - ans;
}
}
| 24.681034 | 96 | 0.492141 |
c03f45ba3335deab0f8050c277160fabed4b54b0 | 1,134 | package dataAccessLayer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import businessLogicLayer.Log;
import constants.DalEnum;
import constants.Severity;
import serviceLayer.CtrlLog;
public class DataBaseAccess {
public static Connection getConnection( ) {
CtrlLog ctrlLog = CtrlLog.getInstance( );
Connection cnx = null;
try{
Class.forName("YOUR SQL DRIVER CLASS NAME");
Log driverOk = new Log(Severity.Information, new Date( ), "Driver O.K.");
ctrlLog.writeLog(driverOk, DalEnum.TextFile);
String url = "jdbc:DATABASE://DATABASE_ADDRESS";
String user = "USERNAME";
String passwd = "PASSWORD";
cnx = DriverManager.getConnection(url, user, passwd);
}catch(SQLException e){
Log log = new Log(e, Severity.Critical, new Date( ), "Could not connect to database!");
ctrlLog.writeLog(log, DalEnum.TextFile);
}catch(Exception e){
Log log = new Log(e, Severity.Critical, new Date( ),
"An exception occured while trying to connect to the database!");
ctrlLog.writeLog(log, DalEnum.TextFile);
}
return cnx;
}
}
| 25.2 | 90 | 0.722222 |
3bd1ad7b9200171b43adb960ee71e0df31028714 | 4,915 | //Copyright (c) 2015, David Missmann
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification,
//are permitted provided that the following conditions are met:
//
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
//disclaimer.
//
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
//disclaimer in the documentation and/or other materials provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dm.analyze.http;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import dm.analyze.constants.Constant;
import dm.analyze.warningns.Warning;
import dm.data.Call;
import dm.db.DBHelper;
import dm.util.Strings;
public class CFURLConnection {
private static final Logger log = Logger.getLogger(CFURLConnection.class);
private static Set<CFURLConnection> connections;
private String ref;
private CFURLRequest request;
private String username;
private String password;
private Set<Warning> warnings;
public static synchronized Set<CFURLConnection> getConnections() {
if (connections == null) {
connections = new HashSet<CFURLConnection>();
try {
DBHelper connection = DBHelper.getReadableConnections();
List<Call> createCalls = connection.findCall(null, null,
"CFURLConnectionCreate", null, null, null, null);
for (Call call : createCalls) {
connections.add(new CFURLConnection(call.getReturnValue(),
getRequestWithRef(call.getParameter().get(1)
.getValue())));
}
List<Call> createWithPropertiesCalls = connection.findCall(
null, null, "CFURLConnectionCreateWithProperties",
null, null, null, null);
for (Call call : createWithPropertiesCalls) {
connections.add(new CFURLConnection(call.getReturnValue(),
getRequestWithRef(call.getParameter().get(1)
.getValue())));
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return connections;
}
private static CFURLRequest getRequestWithRef(String ref) {
Set<CFURLRequest> requests = CFURLRequest.getRequests();
for (CFURLRequest request : requests) {
if (request.getRef().equals(ref)) {
return request;
}
}
return null;
}
public CFURLConnection(String ref, CFURLRequest request) {
this.ref = ref;
this.request = request;
// Check if creds were set
try {
DBHelper connection = DBHelper.getReadableConnections();
List<Call> useCredsCalls = connection.findCall(null, null,
"CFURLConnectionUseCredential", null, null, this.ref, null);
if (useCredsCalls.size() == 1) {
List<Call> createCredentialCalls = connection.findCall(null,
null, "CFURLCredentialCreate", null, null,
useCredsCalls.get(0).getParameter().get(1).getValue(),
null);
if (createCredentialCalls.size() == 1) {
this.username = createCredentialCalls.get(0).getParameter()
.get(1).getDescription();
this.password = createCredentialCalls.get(0).getParameter()
.get(2).getDescription();
} else {
log.warn("There should be exactly one CreateCredentials call");
}
} else if (useCredsCalls.size() > 0) {
// TODO: Maybe we should handle this case...
throw new UnsupportedOperationException();
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public synchronized void check() {
if (this.warnings != null) {
return;
}
this.warnings = new HashSet<Warning>();
if (this.username != null
&& Constant.find(Strings.stringToHex(this.username)) != null) {
this.warnings.add(new Warning("Username is constants"));
}
if (this.password != null
&& Constant.find(Strings.stringToHex(this.password)) != null) {
this.warnings.add(new Warning("Password is constants"));
}
}
public synchronized Set<Warning> getWarnings() {
if (this.warnings == null) {
this.check();
}
return this.warnings;
}
public CFURLRequest getRequest() {
return request;
}
}
| 32.766667 | 120 | 0.721668 |
dd2c693fbe43b5f63c333626cdee8a5b85f88ea4 | 1,277 | package com.selenium.HRMDemo;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
public class VerifyJob extends Main{
private String[] jobDetails = new String[3];// Since Java doesn't support returning multiple values, I'm using an array to overcome that issue.
VerifyPageNavigation navigation = new VerifyPageNavigation();
public void setJob(String title, String description, String note) {//Original method without DDT
this.jobDetails[0] = title;
this.jobDetails[1] = description;
this.jobDetails[2] = note;
/* for(String a:jobDetails) { //For each loop, just for debugging
System.out.println(a);
} */
}
@Test
public String getJob() {//Planning to convert this class to a TestNG class
String objective = "Verify the user can add a new \"Job Title\" :";
String status = "Pass";
driver.findElement(By.id("btnAdd")).click();
driver.findElement(By.id("jobTitle_jobTitle")).sendKeys("ttttt"); //Will map with the setter later
driver.findElement(By.id("jobTitle_jobDescription")).sendKeys("ddddddd");
driver.findElement(By.id("jobTitle_note")).sendKeys("nnnn");
driver.findElement(By.id("btnSave")).click();
//Job specification will be added later.
navigation.Wait();
return objective.concat(status);
}
} | 33.605263 | 144 | 0.724354 |
82c97745d772f199909516139e3843dc32ee65e4 | 867 | package com.wissen.e_commerce.pojo;
public class SellerBo {
private Long id;
private String sellerName;
private String email;
private String phoneNumber;
private String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
| 15.482143 | 50 | 0.6609 |
28fc95001360e138ec52803d2036eeaf342887bd | 1,839 | package com.htnova.system.workflow.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.htnova.common.util.DateUtil;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.Model;
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class ActModelDTO {
/** id */
private String id;
/** 名称 */
private String name;
/** 唯一标识,基于key升级版本号 */
private String key;
/** 分类 */
private String category;
/** 版本 */
private Integer version;
/** 附加字段(json) */
private ActModelMeta metaInfo;
/** 部署id */
private String deploymentId;
/** 创建时间 */
private LocalDateTime createTime;
/** 更新时间 */
private LocalDateTime lastUpdateTime;
/** 租户id */
private String tenantId;
/** xml 模型数据 */
private String editorSourceValue;
/** 附带数据 */
private ActModelExtraValue editorSourceExtraValue;
// 只展示最新版本
private boolean lastVersion;
public ActModelDTO(Model model) {
this.id = model.getId();
this.name = model.getName();
this.key = model.getKey();
this.category = model.getCategory();
this.version = model.getVersion();
this.deploymentId = model.getDeploymentId();
this.createTime = DateUtil.converter(model.getCreateTime());
this.lastUpdateTime = DateUtil.converter(model.getLastUpdateTime());
this.tenantId = model.getTenantId();
try {
ActModelMeta actModelMeta = new ObjectMapper().readValue(model.getMetaInfo(), ActModelMeta.class);
this.metaInfo = actModelMeta;
} catch (Exception e) {
log.error("反序列化失败:", e);
}
}
}
| 23.883117 | 110 | 0.656335 |
4c6638f3d1e8a63678a54c4efadea8f97fb983c6 | 11,910 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.broad.igv.data.expression;
import org.broad.igv.logging.*;
import org.broad.igv.Globals;
import org.broad.igv.exceptions.LoadResourceFromServerException;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.HttpUtils;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/**
* @author: Marc-Danie Nazaire
* private static String affyMappingURL =
* SERVER_URL + "/igv/resources/probes/affy_probe_gene_mapping.txt.gz";
* private static String agilentMappingURL =
* SERVER_URL + "/igv/resources/probes/agilent_probe_gene_mapping.txt.gz";
* private static String illuminaMappingURL =
* SERVER_URL + "/igv/resources/probes/illumina_probe_gene_mapping.txt.gz";
*/
public class ProbeToLocusMap {
enum Platform {Affymetrix, Agilient, Illumina, Methylation, Mirna, unknown}
public static final String SERVER_URL = "https://data.broadinstitute.org";
private static Logger log = LogManager.getLogger(ProbeToLocusMap.class);
private static String affyGenesMappingURL =
SERVER_URL + "/igvdata/probes/affy/affy_probe_gene_mapping.txt.gz";
private static String affyHumanMappingURL =
SERVER_URL + "/igvdata/probes/affy/affy_human_mappings.txt.gz";
private static String affyMouseMappingURL =
SERVER_URL + "/igvdata/probes/affy/affy_mouse_mappings.txt.gz";
private static String affyOtherMappingURL =
SERVER_URL + "/igvdata/probes/affy/affy_other_mappings.txt.gz";
private static String agilentGenesMappingURL =
SERVER_URL + "/igvdata/probes/agilent/agilent_probe_gene_mapping.txt.gz";
private static String agilentHumanMappingURL =
SERVER_URL + "/igvdata/probes/agilent/agilent_human_mappings.txt.gz";
private static String agilentMouseMappingURL =
SERVER_URL + "/igvdata/probes/agilent/agilent_mouse_mappings.txt.gz";
private static String agilentOtherMappingURL =
SERVER_URL + "/igvdata/probes/agilent/agilent_other_mappings.txt.gz";
private static String illuminaMappingURL =
SERVER_URL + "/igvdata/probes/illumina/illumina_allMappings.txt.gz";
private static String illuminaGenesMappingURL =
SERVER_URL + "/igvdata/probes/illumina/illumina_probe_gene_mapping.txt.gz";
private static String methylationGeneMappingURL =
SERVER_URL + "/igvdata/probes/meth/methylation_pobeToGene.tab.gz";
private static String methylationLociMappingURL =
SERVER_URL + "/igvdata/probes/meth/methylation_probeToLoci.mappings.txt.gz";
private static ProbeToLocusMap instance;
private Map<String, Map<String, String[]>> probeMaps = new HashMap();
private MappingUrlCache mappingUrlCache = new MappingUrlCache();
public static synchronized ProbeToLocusMap getInstance() {
if (instance == null) {
instance = new ProbeToLocusMap();
}
return instance;
}
public void clearProbeMappings() {
if (probeMaps != null) {
probeMaps.clear();
}
if (mappingUrlCache != null) {
mappingUrlCache.clear();
}
}
public void loadMapping(String urlString, Map<String, String[]> map) {
BufferedReader bufReader = null;
InputStream is = null;
try {
if (HttpUtils.isRemoteURL(urlString)) {
URL url = HttpUtils.createURL(urlString);
is = HttpUtils.getInstance().openConnectionStream(url);
} else {
is = new FileInputStream(urlString);
}
if (urlString.endsWith("gz")) {
is = new GZIPInputStream(is);
}
bufReader = new BufferedReader(new InputStreamReader(is));
loadMapping(bufReader, map);
} catch (Exception e) {
log.error("Error loading probe mapping", e);
throw new LoadResourceFromServerException(e.getMessage(), urlString, e.getClass().getSimpleName());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("Error closing probe mapping stream", e);
}
}
}
}
public void loadMapping(BufferedReader bufReader, Map<String, String[]> map) throws IOException {
String line;
while ((line = bufReader.readLine()) != null) {
String[] result = Globals.tabPattern.split(line, -1);
int nTokens = result.length;
if (nTokens != 2) {
continue;
}
// check if more than one gene symbol found
String[] genes = result[1].split("///");
map.put(result[0].trim(), genes);
}
}
/**
* Return the URL to the mapping file for the give genomeId and platform.
*
* @param genomeId
* @param platform
* @return
*/
public String getMappingURL(String genomeId, Platform platform) {
if (platform == Platform.unknown) {
return null;
}
String mappingUrl = mappingUrlCache.getMappingUrl(genomeId, platform);
if (mappingUrl == null) {
boolean mapToGenes = PreferencesManager.getPreferences().getAsBoolean(Constants.PROBE_MAPPING_KEY);
if (!mapToGenes) {
boolean hasLociMapping = checkForLociMapping(platform, genomeId);
if (!hasLociMapping) {
MessageUtils.showMessage(
"<html>" + platform.toString() + " probe locations are not available for the selected genome " +
" (" + genomeId + "). <br>Expression data will be mapped to gene locations.");
mapToGenes = true;
}
}
if (platform == Platform.Affymetrix) {
if (mapToGenes) {
mappingUrl = affyGenesMappingURL;
} else if (genomeId.startsWith("hg")) {
mappingUrl = affyHumanMappingURL;
} else if (genomeId.startsWith("mm")) {
mappingUrl = affyMouseMappingURL;
} else {
mappingUrl = affyOtherMappingURL;
}
} else if (platform == Platform.Agilient) {
if (mapToGenes) {
mappingUrl = agilentGenesMappingURL;
} else if (genomeId.startsWith("hg")) {
mappingUrl = agilentHumanMappingURL;
} else if (genomeId.startsWith("mm")) {
mappingUrl = agilentMouseMappingURL;
} else {
mappingUrl = agilentOtherMappingURL;
}
} else if (platform == Platform.Illumina) {
if (mapToGenes) {
mappingUrl = illuminaGenesMappingURL;
} else {
mappingUrl = illuminaMappingURL;
}
} else if (platform == Platform.Methylation) {
if (mapToGenes) {
mappingUrl = methylationGeneMappingURL;
} else {
mappingUrl = methylationLociMappingURL;
}
} else {
return null;
}
mappingUrlCache.put(genomeId, platform, mappingUrl);
}
return mappingUrl;
}
public static Platform getPlatform(String probeId) {
if (probeId.endsWith("_at") || probeId.endsWith("_st")) {
return Platform.Affymetrix;
} else if (probeId.startsWith("A_")) {
return Platform.Agilient;
} else if (probeId.startsWith("ILMN_") || probeId.startsWith("GI_") || probeId.startsWith(
"NM_") || probeId.startsWith("XM_")) {
return Platform.Illumina;
} else if (probeId.startsWith("cg")) {
return Platform.Methylation;
}
return Platform.unknown;
}
//mm9 (Affymetrix), mm5 (Agilent) or mm8 (Illumina)
private static boolean checkForLociMapping(Platform platform, String genomeId) {
boolean hasLociMapping = true;
if (genomeId.startsWith("hg") && !genomeId.equals("hg18")) {
hasLociMapping = false;
} else if (genomeId.startsWith("mm")) {
switch (platform) {
case Affymetrix:
if (!genomeId.equals("mm9")) {
hasLociMapping = false;
}
break;
case Agilient:
if (!genomeId.equals("mm5")) {
hasLociMapping = false;
}
break;
case Illumina:
if (!genomeId.equals("mm8")) {
hasLociMapping = false;
}
break;
}
}
return hasLociMapping;
}
public String[] getLociForProbe(String probeId, String genomeId) {
Platform platform = getPlatform(probeId);
if (platform == Platform.unknown) {
return null;
}
String mappingURL = getMappingURL(genomeId, platform);
if (mappingURL == null) {
return null;
}
Map<String, String[]> pMap = probeMaps.get(mappingURL);
if (pMap == null) {
pMap = new HashMap(500000);
loadMapping(mappingURL, pMap);
probeMaps.put(mappingURL, pMap);
}
if (log.isDebugEnabled() && pMap == null) {
log.debug(("Null probeMap for:" + mappingURL));
}
return pMap == null ? null : (String[]) pMap.get(probeId);
}
// TODO -- this could be generalized to a Generic 2 key cache
static class MappingUrlCache {
Map<Platform, Map<String, String>> cache = new Hashtable();
public void clear() {
cache.clear();
}
public String getMappingUrl(String genomeId, Platform platform) {
if (cache.containsKey(platform)) {
Map<String, String> urlMap = cache.get(platform);
return urlMap.get(genomeId);
} else {
return null;
}
}
public void put(String genomeId, Platform platform, String mappingUrl) {
if (!cache.containsKey(platform)) {
cache.put(platform, new Hashtable());
}
cache.get(platform).put(genomeId, mappingUrl);
}
}
}
| 36.533742 | 124 | 0.592191 |
3289251bc7e97a8286038e1024ce8dcf94175c1e | 3,380 | package me.tomassetti.turin.parser.ast;
import me.tomassetti.turin.resolvers.ResolverRegistry;
import me.tomassetti.turin.parser.Parser;
import me.tomassetti.turin.resolvers.InFileSymbolResolver;
import me.tomassetti.turin.resolvers.jdk.JdkTypeResolver;
import me.tomassetti.turin.resolvers.SymbolResolver;
import me.tomassetti.turin.parser.ast.expressions.ValueReference;
import me.tomassetti.turin.typesystem.ArrayTypeUsage;
import me.tomassetti.turin.typesystem.UnsignedPrimitiveTypeUsage;
import me.tomassetti.turin.typesystem.ReferenceTypeUsage;
import me.tomassetti.turin.typesystem.TypeUsage;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.Assert.*;
public class ValueReferenceTest {
@Test
public void solveReferenceToLocalVariable() throws IOException {
String code = "namespace examples\n" +
"program Example(String[] args) {\n" +
" val uint a = 0\n" +
" a\n" +
"}\n";
InputStream stream = new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
TurinFile turinFile = new Parser().parse(stream);
List<ValueReference> valueReferences = turinFile.findAll(ValueReference.class);
assertEquals(1, valueReferences.size());
SymbolResolver resolver = new InFileSymbolResolver(JdkTypeResolver.getInstance());
ResolverRegistry.INSTANCE.record(turinFile, resolver);
TypeUsage type = valueReferences.get(0).calcType();
assertTrue(type.sameType(UnsignedPrimitiveTypeUsage.UINT));
}
@Test
public void solveReferenceToProgramParam() throws IOException {
String code = "namespace examples\n" +
"program Example(String[] args) {\n" +
" args\n" +
"}\n";
InputStream stream = new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
TurinFile turinFile = new Parser().parse(stream);
List<ValueReference> valueReferences = turinFile.findAll(ValueReference.class);
assertEquals(1, valueReferences.size());
SymbolResolver resolver = new InFileSymbolResolver(JdkTypeResolver.getInstance());
ResolverRegistry.INSTANCE.record(turinFile, resolver);
TypeUsage type = valueReferences.get(0).calcType();
assertTrue(new ArrayTypeUsage(ReferenceTypeUsage.STRING(resolver)).sameType(type));
}
@Test
public void solveReferenceToMethodParam() throws IOException {
String code = "namespace examples\n" +
"type Example {\n" +
" void foo(int a) = a\n" +
"}\n";
InputStream stream = new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
TurinFile turinFile = new Parser().parse(stream);
List<ValueReference> valueReferences = turinFile.findAll(ValueReference.class);
assertEquals(1, valueReferences.size());
SymbolResolver resolver = new InFileSymbolResolver(JdkTypeResolver.getInstance());
ResolverRegistry.INSTANCE.record(turinFile, resolver);
TypeUsage type = valueReferences.get(0).calcType();
assertTrue(type.isPrimitive());
assertTrue(type.asPrimitiveTypeUsage().isInt());
}
}
| 44.473684 | 93 | 0.702663 |
cbd256d0b52e361469f10cdc21f84f4b6fe851ba | 2,856 | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.springsource.greenhouse.events.sessions;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.social.greenhouse.api.Event;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.springsource.greenhouse.AbstractGreenhouseListActivity;
import com.springsource.greenhouse.R;
/**
* @author Roy Clarkson
*/
public class EventSessionsScheduleActivity extends AbstractGreenhouseListActivity {
@SuppressWarnings("unused")
private static final String TAG = EventSessionsScheduleActivity.class.getSimpleName();
private Event event;
private List<Date> conferenceDates;
//***************************************
// Activity methods
//***************************************
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
event = getApplicationContext().getSelectedEvent();
getApplicationContext().setSelectedDay(null);
refreshScheduleDays();
}
//***************************************
// ListActivity methods
//***************************************
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Date day = conferenceDates.get(position);
getApplicationContext().setSelectedDay(day);
startActivity(new Intent(v.getContext(), EventSessionsByDayActivity.class));
}
//***************************************
// Private methods
//***************************************
private void refreshScheduleDays() {
if (event == null) {
return;
}
conferenceDates = new ArrayList<Date>();
List<String> conferenceDays = new ArrayList<String>();
Date day = (Date) event.getStartTime().clone();
while (day.before(event.getEndTime())) {
conferenceDates.add((Date) day.clone());
conferenceDays.add(new SimpleDateFormat("EEEE, MMM d").format(day));
day.setDate(day.getDate() + 1);
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.menu_list_item, conferenceDays));
}
}
| 30.063158 | 90 | 0.684174 |
d5782485883adedf1be018415d6a4a003641cf78 | 1,916 | /*
* Copyright 2021 ACC Cyfronet AGH
*
* 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 pl.cyfronet.s4e.util;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.val;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
public class ZipArtifact {
public static Optional<String> getName(JsonNode artifactsNode) {
if (artifactsNode == null || !artifactsNode.isObject()) {
return Optional.empty();
}
return getName(getArtifactsMap(artifactsNode));
}
public static Optional<String> getName(Map<String, String> artifacts) {
if (artifacts == null || artifacts.isEmpty()) {
return Optional.empty();
}
return artifacts
.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.filter(entry -> entry.getValue().endsWith(".zip"))
.map(Map.Entry::getKey)
.sorted()
.findFirst();
}
private static Map<String, String> getArtifactsMap(JsonNode artifactsNode) {
val map = new LinkedHashMap<String, String>();
artifactsNode.fields().forEachRemaining(entry -> {
val value = entry.getValue();
if (value.isTextual()) {
map.put(entry.getKey(), value.asText());
}
});
return map;
}
}
| 31.409836 | 80 | 0.631002 |
6e187fa35a456697367d0882703843a9ac5d3fd8 | 773 | package services;
import java.util.ArrayList;
/**
* Created by dinever on 4/5/16.
*/
public class FeedbackStore {
private static FeedbackStore instance = null;
private ArrayList<Feedback> feedbackList;
public FeedbackStore() {
this.feedbackList = new ArrayList<Feedback>();
}
public ArrayList<Feedback> getFeedbackList() {
return feedbackList;
}
public void setFeedbackList(ArrayList<Feedback> feedbackList) {
this.feedbackList = feedbackList;
}
public void appendFeedback(Feedback feedback) {
feedbackList.add(feedback);
}
public static FeedbackStore getInstance() {
if (instance == null) {
instance = new FeedbackStore();
}
return instance;
}
}
| 21.472222 | 67 | 0.649418 |
aa0f5dfde0722ecbdbbda6689751513d91609710 | 193 | package com.jdt.fedlearn.core.entity.distributedKeyGeneMsg;
public class EmptyKeyGeneMsg extends KeyGeneMsg{
public EmptyKeyGeneMsg(int reqTypeCode) {
super(reqTypeCode);
}
}
| 21.444444 | 59 | 0.756477 |
e78c1533e419acdee180133dd92a36f3167842a5 | 3,340 | package me.modmuss50.technicaldimensions.tiles;
import me.modmuss50.technicaldimensions.blocks.BlockPortalController;
import me.modmuss50.technicaldimensions.init.ModBlocks;
import me.modmuss50.technicaldimensions.misc.TeleportationUtils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
/**
* Created by Mark on 05/08/2016.
*/
public class TilePortalController extends TileEntity implements ITickable {
public String imageID;
public double x, y, z;
public float yaw, pitch;
public int dim;
public boolean rotated = false;
public void tpEntity(Entity entity) {
if (imageID != null && !imageID.isEmpty())
TeleportationUtils.teleportEntity(entity, x, y, z, yaw, pitch, dim);
}
@Override
public AxisAlignedBB getRenderBoundingBox() {
return super.getRenderBoundingBox();
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
if (compound.hasKey("imageID")) {
imageID = compound.getString("imageID");
}
x = compound.getDouble("Lx");
y = compound.getDouble("Ly");
z = compound.getDouble("Lz");
yaw = compound.getFloat("yaw");
pitch = compound.getFloat("pitch");
dim = compound.getInteger("dimID");
rotated = compound.getBoolean("rotated");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
if (imageID != null && !imageID.isEmpty()) {
compound.setString("imageID", imageID);
}
compound.setDouble("Lx", x);
compound.setDouble("Ly", y);
compound.setDouble("Lz", z);
compound.setFloat("yaw", yaw);
compound.setFloat("pitch", pitch);
compound.setInteger("dimID", dim);
compound.setBoolean("rotated", rotated);
return compound;
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) {
return false;
}
@Nonnull
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
return new SPacketUpdateTileEntity(getPos(), getBlockMetadata(), writeToNBT(new NBTTagCompound()));
}
@Override
public NBTTagCompound getUpdateTag() {
NBTTagCompound compound = super.writeToNBT(new NBTTagCompound());
writeToNBT(compound);
return compound;
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) {
readFromNBT(packet.getNbtCompound());
}
@Override
public void update() {
if (worldObj.getTotalWorldTime() % 20 == 0) {
if (worldObj.getBlockState(getPos()).getBlock() == ModBlocks.portalController) {
rotated = worldObj.getBlockState(getPos()).getValue(BlockPortalController.ROTATED);
}
}
}
}
| 29.821429 | 107 | 0.675449 |
adc88ccfbad1865b8404df820e36599a0685cf72 | 158 | package de.uni_hildesheim.sse.serializer;
/**
* A syntactic sequencer...
*/
public class IvmlSyntacticSequencer extends AbstractIvmlSyntacticSequencer {
}
| 19.75 | 76 | 0.791139 |
87bb00f2898c02f82a92e54df694fa9cb535c433 | 396 | package common;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* Created by rohitsamala on 02/06/2017.
*/
public class Driver {
public static WebDriver driver;
public static void initialiseDriver(){
System.setProperty("webdriver.gecko.driver","src/test/java/common/geckodriver");
driver = new FirefoxDriver();
}
}
| 18.857143 | 88 | 0.709596 |
2ce78310f6053ad9cec6d0d0d9be0d7499371236 | 4,781 | /*
* Copyright 2010, Moshe Waisberg
*
* 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.sf.jncu.cdil.mnp;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.BlockingQueue;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
/**
* Listener to handle all serial port events.
*
* @author moshew
*/
public class MNPSerialPortEventListener implements SerialPortEventListener {
protected final SerialPort port;
private final BlockingQueue<Byte> q;
private final OutputStream out;
/**
* Creates a new port event listener.
*
* @param port the port.
* @param queue the buffer for populating data.
*/
public MNPSerialPortEventListener(SerialPort port, BlockingQueue<Byte> queue) {
super();
this.port = port;
this.out = null;
this.q = queue;
}
/**
* Creates a new port event listener.
*
* @param port the port.
* @param out the buffer for populating data.
*/
public MNPSerialPortEventListener(SerialPort port, OutputStream out) {
super();
this.port = port;
this.out = out;
this.q = null;
}
@Override
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BREAK:
breakInterrupt(event);
break;
case SerialPortEvent.CTS:
clearToSend(event);
break;
case SerialPortEvent.RXCHAR:
dataAvailable(event);
break;
case SerialPortEvent.DSR:
dataSetReady(event);
break;
case SerialPortEvent.ERR:
error(event);
break;
case SerialPortEvent.TXEMPTY:
outputBufferEmpty(event);
break;
case SerialPortEvent.RING:
ringIndicator(event);
break;
}
}
/**
* Handle ring indicator events.
*
* @param event the event.
*/
protected void ringIndicator(SerialPortEvent event) {
}
/**
* Handle output buffer empty events.
*
* @param event the event.
*/
protected void outputBufferEmpty(SerialPortEvent event) {
}
/**
* Handle error events.
*
* @param event the event.
*/
protected void error(SerialPortEvent event) {
}
/**
* Handle data set ready events.
*
* @param event the event.
*/
protected void dataSetReady(SerialPortEvent event) {
}
/**
* Handle data available events.<br>
* This method is <tt>synchronized</tt> to try and keep the events
* sequential and correctly ordered.
*
* @param event the event.
*/
protected synchronized void dataAvailable(SerialPortEvent event) {
String portName = event.getPortName();
if (!portName.equals(port.getPortName()))
return;
int count = event.getEventValue();
if (count == 0)
return;
byte[] buf;
try {
buf = port.readBytes(count);
if (q != null) {
for (byte b : buf)
q.put(b);
} else {
out.write(buf);
out.flush();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (SerialPortException se) {
se.printStackTrace();
}
}
/**
* Handle clear to send events.
*
* @param event the event.
*/
protected void clearToSend(SerialPortEvent event) {
}
/**
* Handle break interrupt events.
*
* @param event the event.
*/
protected void breakInterrupt(SerialPortEvent event) {
}
/**
* Listener has been removed and needs to free resources.
*/
public void close() {
if (out != null) {
try {
out.close();
} catch (Exception e) {
// ignore
}
}
}
}
| 25.566845 | 83 | 0.569337 |
bbabd1cc87860a68fb299b54fc6fdb7875057dc5 | 1,145 | package analisesaude;
import javax.swing.JOptionPane;
public class AnaliseSaude {
public static void main(String[] args) {
String nome = JOptionPane.showInputDialog("nome");
String comer = JOptionPane.showInputDialog("o que vc mais costuma comer?\n C -carnes\n V - verduras\n L- legumes\n F- frutas\n T - fast food\n NDA - nem queira saber");
comer = comer.toUpperCase();
switch(comer){
case "C":
JOptionPane.showMessageDialog(null, "Dieta rica em proteína");
break;
case "V":
case "L":
JOptionPane.showMessageDialog(null, "Dieta rica em vitaminas");
break;
case "F":
JOptionPane.showMessageDialog(null, "Dieta rica em fibras");
break;
case "T":
JOptionPane.showMessageDialog(null, "Dieta rica em doenças");
break;
case "NDA":
JOptionPane.showMessageDialog(null, "Só Jesus na causa!");
break;
}
}
}
| 31.805556 | 176 | 0.522271 |
b9f4e8a05bee0f02f3c2fe4850b41065a91acbdb | 621 | package com.cracker.algorithm.base.struct.stack;
import com.cracker.algorithm.base.core.BaseStruct;
public abstract class Stack<I> extends BaseStruct<I> {
/**
* Add an item to the stack.
* @param item item
*/
public abstract void push(I item);
/**
* Deletes the most recently added element.
* @return Deletes the most recently added element
*/
public abstract I pop();
/**
* Returns the first element of the stack without removing it.
* @return Returns the first element of the stack without removing it
*/
public abstract I peek();
}
| 24.84 | 73 | 0.645733 |
fe8e1dd4f6a35801e248169b6d5dc42473944030 | 1,356 | package blacksmith.sullivanway.display;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import blacksmith.sullivanway.R;
public class FcmDialogActivtiy extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_fcm_dialog_activtiy);
getWindow().getAttributes().width = (int)(getResources().getDisplayMetrics().widthPixels * 0.8);
getWindow().getAttributes().height = (int)(getResources().getDisplayMetrics().heightPixels * 0.4);
String msg = getIntent().getStringExtra("message");
// TextView
TextView fcmMsgTextView = (TextView)findViewById(R.id.textView);
fcmMsgTextView.setMovementMethod(new ScrollingMovementMethod());
fcmMsgTextView.setText(msg);//도착 지하철정보 설정
// Button
TextView button = (TextView) findViewById(R.id.confirmButton);
button.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
| 33.073171 | 106 | 0.698378 |
6c21b015106e03aa12f5abd5bfc769fe870d8e5a | 2,563 | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.compiler.xml.processes;
import org.drools.core.xml.ExtensibleXmlParser;
import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.node.FaultNode;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class FaultNodeHandler extends AbstractNodeHandler {
protected Node createNode() {
return new FaultNode();
}
public void handleNode( final Node node, final Element element, final String uri,
final String localName, final ExtensibleXmlParser parser)
throws SAXException {
super.handleNode(node, element, uri, localName, parser);
FaultNode faultNode = (FaultNode) node;
String faultName = element.getAttribute("faultName");
if (faultName != null && faultName.length() != 0 ) {
faultNode.setFaultName(faultName);
}
String faultVariable = element.getAttribute("faultVariable");
if (faultVariable != null && !"".equals(faultVariable) ) {
faultNode.setFaultVariable(faultVariable);
}
}
public Class generateNodeFor() {
return FaultNode.class;
}
public void writeNode( Node node, StringBuilder xmlDump, boolean includeMeta) {
FaultNode faultNode = (FaultNode) node;
writeNode("fault", faultNode, xmlDump, includeMeta);
String faultName = faultNode.getFaultName();
if (faultName != null && faultName.length() != 0) {
xmlDump.append("faultName=\"" + faultName + "\" ");
}
String faultVariable = faultNode.getFaultVariable();
if (faultVariable != null && faultVariable.length() != 0) {
xmlDump.append("faultVariable=\"" + faultVariable + "\" ");
}
if (includeMeta && containsMetaData(faultNode)) {
xmlDump.append(">" + EOL);
writeMetaData(faultNode, xmlDump);
endNode("fault", xmlDump);
} else {
endNode(xmlDump);
}
}
}
| 36.614286 | 85 | 0.664846 |
14c58f09c09e54cf44a70cdfeeb14b511aecca3f | 3,626 | /*
* Copyright (c) 2020. Vladimir Ulitin, Partners Healthcare and members of Forome Association
*
* Developed by Vladimir Ulitin and Michael Bouzinier
*
* 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.forome.astorage.core.source;
import org.forome.database.exception.DatabaseException;
import org.forome.astorage.core.Metadata;
import org.forome.astorage.core.batch.BatchRecord;
import org.forome.astorage.core.exception.ExceptionBuilder;
import org.forome.astorage.core.packer.PackInterval;
import org.forome.astorage.core.record.Record;
import org.forome.astorage.core.rocksdb.RocksDBDatabase;
import org.forome.core.struct.Assembly;
import org.forome.core.struct.Interval;
import org.forome.core.struct.Position;
import org.rocksdb.ColumnFamilyHandle;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import java.nio.file.Path;
public class SourceDatabase implements Source {
public static final short VERSION_FORMAT = 1;
public static final String COLUMN_FAMILY_INFO = "info";
public static final String COLUMN_FAMILY_RECORD = "record";
public final Assembly assembly;
private final Metadata metadata;
private final RocksDBDatabase rocksDBDatabase;
public SourceDatabase(Assembly assembly, Path pathDatabase) throws DatabaseException {
this.assembly = assembly;
this.rocksDBDatabase = new RocksDBDatabase(pathDatabase);
ColumnFamilyHandle columnFamilyInfo = rocksDBDatabase.getColumnFamily(COLUMN_FAMILY_INFO);
if (columnFamilyInfo == null) {
throw ExceptionBuilder.buildDatabaseException("ColumnFamily not found");
}
this.metadata = new Metadata(rocksDBDatabase.rocksDB, columnFamilyInfo);
if (metadata.getFormatVersion() != VERSION_FORMAT) {
throw new RuntimeException("Format version RocksDB does not correct: " + metadata.getFormatVersion());
}
if (metadata.getAssembly() != assembly) {
throw new RuntimeException("Not equals assembly: " + metadata.getAssembly());
}
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public Record getRecord(Position position) {
BatchRecord batchRecord = getBatchRecord(
rocksDBDatabase.rocksDB,
rocksDBDatabase.getColumnFamily(COLUMN_FAMILY_RECORD),
position
);
if (batchRecord != null) {
return batchRecord.getRecord(position);
} else {
return null;
}
}
public static Interval getIntervalBatchRecord(Position position) {
int k = position.value / BatchRecord.DEFAULT_SIZE;
return Interval.of(
position.chromosome,
k * BatchRecord.DEFAULT_SIZE,
k * BatchRecord.DEFAULT_SIZE + BatchRecord.DEFAULT_SIZE - 1
);
}
public static BatchRecord getBatchRecord(RocksDB rocksDB, ColumnFamilyHandle columnFamilyHandle, Position position) {
Interval interval = getIntervalBatchRecord(position);
try {
byte[] bytes = rocksDB.get(
columnFamilyHandle,
new PackInterval(BatchRecord.DEFAULT_SIZE).toByteArray(interval)
);
if (bytes == null) return null;
return new BatchRecord(interval, bytes);
} catch (RocksDBException ex) {
throw ExceptionBuilder.buildDatabaseException(ex);
}
}
}
| 32.666667 | 118 | 0.768616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.