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
|
---|---|---|---|---|---|
9b1f118575fcf0883c01afd4e65c149776b3ec9e
| 32,695 |
package com.mindoo.domino.jna.test;
import java.util.Arrays;
import java.util.Calendar;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import com.mindoo.domino.jna.NotesCollection;
import com.mindoo.domino.jna.NotesCollection.Direction;
import com.mindoo.domino.jna.NotesCollection.EntriesAsListCallback;
import com.mindoo.domino.jna.NotesCollection.ViewLookupCallback;
import com.mindoo.domino.jna.NotesDatabase;
import com.mindoo.domino.jna.NotesIDTable;
import com.mindoo.domino.jna.NotesViewEntryData;
import com.mindoo.domino.jna.constants.Find;
import com.mindoo.domino.jna.constants.Navigate;
import com.mindoo.domino.jna.constants.OpenCollection;
import com.mindoo.domino.jna.constants.ReadMask;
import com.mindoo.domino.jna.constants.UpdateCollectionFilters;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.Session;
/**
* Test cases that read data from views
*
* @author Karsten Lehmann
*/
public class TestViewTraversal extends BaseJNATestClass {
@Test
public void testViewTraversal_readNoteIdAndPosition() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("People");
for (int i=0; i<3; i++) {
long t0=System.currentTimeMillis();
List<NotesViewEntryData> entries = colFromDbData.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY),
Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID, ReadMask.INDEXPOSITION), new NotesCollection.EntriesAsListCallback(Integer.MAX_VALUE));
long t1=System.currentTimeMillis();
System.out.println("It took "+(t1-t0)+"ms to read "+entries.size()+" note ids and index positions");
}
return null;
}
});
};
@Test
public void testViewTraversal_columnTitleLookup() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("People");
colFromDbData.update();
List<NotesViewEntryData> entries = colFromDbData.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), 10, EnumSet.of(ReadMask.NOTEID, ReadMask.SUMMARY), new EntriesAsListCallback(10));
Assert.assertTrue("Row data could be read", entries.size() > 0);
NotesViewEntryData firstEntry = entries.get(0);
//try to read a value by column title; the programmatic name for this column is different ($17)
String name = firstEntry.getAsString("name", null);
Assert.assertTrue("Name value can be read", name!=null);
return null;
}
});
}
@Test
public void testViewTraversal_numericInequalityLookup() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("PeopleFlatMultiColumnSort");
colFromDbData.update();
colFromDbData.resortView("col_internetaddresslength", Direction.Ascending);
double minVal = 10;
List<NotesViewEntryData> entriesGreaterOrEqualMinVal = colFromDbData.getAllEntriesByKey(EnumSet.of(Find.GREATER_THAN, Find.EQUAL),
EnumSet.of(ReadMask.SUMMARY, ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE), Double.valueOf(minVal));
Assert.assertFalse("There should be entries with lengths column values matching the search key", entriesGreaterOrEqualMinVal.isEmpty());
Set<Integer> noteIdsInRange = new HashSet<Integer>();
for (NotesViewEntryData currEntry : entriesGreaterOrEqualMinVal) {
noteIdsInRange.add(currEntry.getNoteId());
Number currLength = (Number) currEntry.get("col_internetaddresslength");
Assert.assertTrue("Length "+currLength.doubleValue()+" of entry with note id "+currEntry.getNoteId()+" should be greater than "+minVal, currLength.doubleValue()>=minVal);
}
NotesIDTable selectedList = colFromDbData.getSelectedList();
selectedList.clear();
selectedList.addNotes(noteIdsInRange);
selectedList.setInverted(true);
//for remote databases, re-send modified SelectedList
colFromDbData.updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED));
//now do an inverted lookup to find every entry not in range
List<NotesViewEntryData> entriesNotGreaterOrEqualMinVal = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_SELECTED), Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID, ReadMask.SUMMARY), new EntriesAsListCallback(Integer.MAX_VALUE));
Assert.assertFalse("There should be entries with lengths column values not matching the search key", entriesNotGreaterOrEqualMinVal.isEmpty());
for (NotesViewEntryData currEntry : entriesNotGreaterOrEqualMinVal) {
Assert.assertFalse("Inverted flag in selected list works", noteIdsInRange.contains(currEntry.getNoteId()));
Number currLength = (Number) currEntry.get("col_internetaddresslength");
Assert.assertFalse("Length "+currLength.doubleValue()+" of entry with note id "+currEntry.getNoteId()+" should not be greater than "+minVal, currLength.doubleValue()>=minVal);
}
return null;
}
});
}
@Test
public void testViewTraversal_stringInequalityLookup() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("PeopleFlatMultiColumnSort");
colFromDbData.update();
colFromDbData.resortView("lastname", Direction.Ascending);
String minVal = "D";
List<NotesViewEntryData> entriesGreaterOrEqualMinVal = colFromDbData.getAllEntriesByKey(EnumSet.of(Find.GREATER_THAN, Find.EQUAL),
EnumSet.of(ReadMask.SUMMARY, ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE),
minVal);
Assert.assertFalse("There should be entries with lastname column values matching the search key", entriesGreaterOrEqualMinVal.isEmpty());
Set<Integer> noteIdsInRange = new HashSet<Integer>();
for (NotesViewEntryData currEntry : entriesGreaterOrEqualMinVal) {
noteIdsInRange.add(currEntry.getNoteId());
String currLastname = (String) currEntry.get("lastname");
if (currLastname!=null) {
Assert.assertTrue("Lastname "+currLastname+" of entry with note id "+currEntry.getNoteId()+" should be greater or equal "+minVal, currLastname.compareToIgnoreCase(minVal) >=0);
}
}
NotesIDTable selectedList = colFromDbData.getSelectedList();
selectedList.clear();
selectedList.addNotes(noteIdsInRange);
selectedList.setInverted(true);
//for remote databases, re-send modified SelectedList
colFromDbData.updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED));
//now do an inverted lookup to find every entry not in range
List<NotesViewEntryData> entriesNotGreaterOrEqualMinVal = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_SELECTED), Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID, ReadMask.SUMMARY), new EntriesAsListCallback(Integer.MAX_VALUE));
Assert.assertFalse("There should be entries with lastname column values not matching the search key", entriesNotGreaterOrEqualMinVal.isEmpty());
for (NotesViewEntryData currEntry : entriesNotGreaterOrEqualMinVal) {
Assert.assertFalse("Inverted flag in selected list works", noteIdsInRange.contains(currEntry.getNoteId()));
String currLastname = (String) currEntry.get("lastname");
Assert.assertTrue("Lastname "+currLastname+" of entry with note id "+currEntry.getNoteId()+" should not be greater or equal "+minVal, currLastname.compareToIgnoreCase(minVal)<0);
}
return null;
}
});
}
@Test
public void testViewTraversal_readAllEntryDataInDataDb() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase db = getFakeNamesDb();
NotesCollection col = db.openCollectionByName("People");
long t0=System.currentTimeMillis();
List<NotesViewEntryData> entries = col.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_PEER),
Integer.MAX_VALUE,
EnumSet.of(
ReadMask.NOTEID,
ReadMask.SUMMARY,
ReadMask.INDEXPOSITION,
// ReadMask.SUMMARYVALUES,
ReadMask.NOTECLASS,
ReadMask.NOTEUNID
), new EntriesAsListCallback(Integer.MAX_VALUE));
long t1=System.currentTimeMillis();
System.out.println("Reading data of "+entries.size()+" top level entries took "+(t1-t0)+"ms");
for (NotesViewEntryData currEntry : entries) {
Assert.assertTrue("Note id is not null", currEntry.getNoteId()!=0);
Assert.assertNotNull("Position is not null", currEntry.getPositionStr());
Assert.assertNotNull("Column values are not null", currEntry.get("$17"));
Assert.assertTrue("Note class is set", currEntry.getNoteClass()!=0);
Assert.assertNotNull("UNID is not null", currEntry.getUNID());
}
return null;
}
});
}
/**
* Opens the fakenames.nsf and fakenames-views.nsf databases locally, which are expected to have the
* same template, and open the views "People". When opening the view from fakenames-views.nsf, we
* point it to the fakenames.nsf database so that its data come from there. The test makes sure
* both views have the same data.
*/
@Test
public void testViewTraversal_readAllEntriesViaViewDb() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesDatabase dbView = getFakeNamesViewsDb();
EnumSet<ReadMask> returnValues = EnumSet.of(
ReadMask.NOTEID,
ReadMask.SUMMARY,
ReadMask.INDEXPOSITION,
ReadMask.SUMMARYVALUES,
ReadMask.NOTECLASS,
ReadMask.NOTEUNID);
//flush remotely fetched index of view by opening it localy in dbView
NotesCollection colFromDbViewWithLocalData = dbView.openCollectionByName("People", EnumSet.of(OpenCollection.REBUILD_INDEX));
List<NotesViewEntryData> entriesFromDbViewLocally = colFromDbViewWithLocalData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_PEER),
Integer.MAX_VALUE,
returnValues, new EntriesAsListCallback(Integer.MAX_VALUE));
Assert.assertTrue("View opened locally in dbViews is empty", entriesFromDbViewLocally.size()==0);
colFromDbViewWithLocalData.recycle();
//now open it with reference to external db (works like a private view)
NotesCollection colFromDbView = dbView.openCollectionByNameWithExternalData(dbData, "People", EnumSet.of(OpenCollection.REBUILD_INDEX));
//and open the same view in the external database
NotesCollection colFromDbData = dbData.openCollectionByName("People");
colFromDbData.update();
long t0=System.currentTimeMillis();
List<NotesViewEntryData> entriesFromDbView = colFromDbView.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_PEER),
Integer.MAX_VALUE,
returnValues, new EntriesAsListCallback(Integer.MAX_VALUE));
long t1=System.currentTimeMillis();
System.out.println("Reading summary data and note ids of "+entriesFromDbView.size()+" top level entries took "+(t1-t0)+"ms");
List<NotesViewEntryData> entriesFromDbData = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_PEER),
Integer.MAX_VALUE,
returnValues, new EntriesAsListCallback(Integer.MAX_VALUE));
Assert.assertTrue("View opened with remote database is not empty", entriesFromDbView.size()!=0);
Assert.assertTrue("View opened in data db is not empty", entriesFromDbData.size()!=0);
Assert.assertEquals("Same number of view entries in view db and data db collection",
entriesFromDbData.size(), entriesFromDbView.size());
for (int i=0; i<entriesFromDbView.size(); i++) {
NotesViewEntryData currEntryDbView = entriesFromDbView.get(i);
NotesViewEntryData currEntryDbData = entriesFromDbData.get(i);
Assert.assertEquals("Note ids #"+i+" match",
currEntryDbView.getNoteId(),
currEntryDbData.getNoteId());
Assert.assertEquals("Position #"+i+" matches", currEntryDbView.getPositionStr(), currEntryDbData.getPositionStr());
Assert.assertEquals("Column data #"+i+" matches",
currEntryDbView.getColumnDataAsMap(),
currEntryDbData.getColumnDataAsMap());
Assert.assertEquals("Note class #"+i+" matches", currEntryDbView.getNoteClass(), currEntryDbData.getNoteClass());
Assert.assertEquals("UNID #"+i+" matches", currEntryDbView.getUNID(), currEntryDbData.getUNID());
}
return null;
}
});
}
/**
* Picks random note ids from the People collection and then populates the selectedList of the
* collection with those note ids. Next, we traverse only selected entries in the collection
* and make sure all picked ids get visited.
*/
@Test
public void testViewTraversal_readSelectedEntries() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
//open People view
NotesCollection colFromDbData = dbData.openCollectionByName("People");
colFromDbData.update();
//read all note ids from the collection
LinkedHashSet<Integer> allIds = colFromDbData.getAllIds(Navigate.NEXT_NONCATEGORY);
System.out.println("All ids in People view: "+allIds.size());
Integer[] allIdsArr = allIds.toArray(new Integer[allIds.size()]);
//pick random note ids
Set<Integer> pickedNoteIds = new HashSet<Integer>();
while (pickedNoteIds.size() < 1000) {
int randomIndex = (int) (Math.random() * allIdsArr.length);
int randomNoteId = allIdsArr[randomIndex];
pickedNoteIds.add(randomNoteId);
}
//populate selected list
colFromDbData.select(pickedNoteIds, true);
//run multiple times to compare durations
for (int i=0; i<3; i++) {
long t0=System.currentTimeMillis();
int countSelectedEntries = colFromDbData.getEntryCount(Navigate.NEXT_SELECTED);
long t1=System.currentTimeMillis();
System.out.println("#1 Number of readable selected entries read in "+(t1-t0)+"ms: "+countSelectedEntries);
}
for (int i=0; i<3; i++) {
NotesIDTable idTable = new NotesIDTable();
long t0=System.currentTimeMillis();
colFromDbData.getAllIds(Navigate.NEXT_SELECTED, true, idTable);
int countSelectedEntries = idTable.getCount();
long t1=System.currentTimeMillis();
idTable.recycle();
System.out.println("#2 Number of readable selected entries read in "+(t1-t0)+"ms: "+countSelectedEntries);
}
//next, traverse selected entries only
List<NotesViewEntryData> selectedEntries = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_SELECTED), Integer.MAX_VALUE,
EnumSet.of(ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE));
//check if we really read entries from our selection
for (NotesViewEntryData currEntry : selectedEntries) {
Assert.assertTrue("Entry read from view is contained in selected list", pickedNoteIds.contains(currEntry.getNoteId()));
}
//now remove all read ids from pickedNoteIds and make sure that we did not miss anything
for (NotesViewEntryData currEntry : selectedEntries) {
pickedNoteIds.remove(currEntry.getNoteId());
}
Assert.assertTrue("All ids from the selected list can be found in the view", pickedNoteIds.isEmpty());
return null;
}
});
}
/**
* Picks random note ids from the People collection, populates the selectedList of the
* collection with those note ids and inverts the selectedList.
* Next, we traverse only unselected entries in the collection
* and make sure all picked ids are skipped.
*/
@Test
public void testViewTraversal_readUnselectedEntries() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("People");
colFromDbData.update();
//read all note ids from the collection
List<NotesViewEntryData> allEntries = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT), Integer.MAX_VALUE,
EnumSet.of(ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE));
//pick random note ids
Set<Integer> pickedNoteIds = new HashSet<Integer>();
while (pickedNoteIds.size() < 1000) {
int randomIndex = (int) (Math.random() * allEntries.size());
NotesViewEntryData randomEntry = allEntries.get(randomIndex);
int randomNoteId = randomEntry.getNoteId();
pickedNoteIds.add(randomNoteId);
}
//populate selected list (only works locally)
NotesIDTable selectedList = colFromDbData.getSelectedList();
selectedList.clear();
for (Integer currNoteId : pickedNoteIds) {
selectedList.addNote(currNoteId.intValue());
}
selectedList.setInverted(true);
//for remote databases, re-send modified SelectedList
colFromDbData.updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED));
//next, traverse selected entries
List<NotesViewEntryData> selectedEntries = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_SELECTED), Integer.MAX_VALUE,
EnumSet.of(ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE));
for (NotesViewEntryData currEntry : selectedEntries) {
Assert.assertTrue("Entry read from view is contained in selected list", !pickedNoteIds.contains(currEntry.getNoteId()));
}
return null;
}
});
}
@Test
public void testViewTraversal_readAllDescendantEntriesWithMaxLevel() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("CompaniesHierarchical");
colFromDbData.update();
NotesIDTable filterTable = colFromDbData.getSelectedList();
filterTable.clear();
filterTable.addNote(0xE332);
colFromDbData.updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED));
for (int i=0; i<5; i++) {
NotesIDTable retTable = new NotesIDTable();
NotesIDTable retTable2 = new NotesIDTable();
long t0=System.currentTimeMillis();
colFromDbData.getAllIds(Navigate.NEXT, false, retTable);
long t1=System.currentTimeMillis();
System.out.println("Total: "+retTable.getCount()+" docs in "+(t1-t0)+"ms");
colFromDbData.getAllIds(Navigate.NEXT, true, retTable2);
long t2=System.currentTimeMillis();
System.out.println("Total: "+retTable2.getCount()+" docs in "+(t2-t1)+"ms");
retTable.recycle();
retTable2.recycle();
}
int maxLevelFound;
//read all descendants of position 1 from the collection
List<NotesViewEntryData> allDescendantsEntries = colFromDbData.getAllEntries("1", 1,
EnumSet.of(Navigate.ALL_DESCENDANTS),
Integer.MAX_VALUE,
EnumSet.of(ReadMask.INDEXPOSITION, ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE));
//make sure we have higher levels than 1 in the result
maxLevelFound = 0;
for (NotesViewEntryData currEntry : allDescendantsEntries) {
Assert.assertEquals("Entry is descendant of 1", 1, currEntry.getPosition()[0]);
int currLevel = currEntry.getLevel();
if (currLevel > maxLevelFound) {
maxLevelFound = currLevel;
}
}
Assert.assertTrue("Entries with level 2 or higher in the result", maxLevelFound>=2);
//read all descendants of position 1 with minlevel=0 and maxlevel=1 from the collection
List<NotesViewEntryData> allDescendantsEntriesMaxLevel1 = colFromDbData.getAllEntries("1|0-1", 1,
EnumSet.of(Navigate.ALL_DESCENDANTS, Navigate.MINLEVEL, Navigate.MAXLEVEL),
Integer.MAX_VALUE,
EnumSet.of(ReadMask.INDEXPOSITION, ReadMask.NOTEID), new EntriesAsListCallback(Integer.MAX_VALUE));
maxLevelFound = 0;
for (NotesViewEntryData currEntry : allDescendantsEntriesMaxLevel1) {
int currLevel = currEntry.getLevel();
if (currLevel > maxLevelFound) {
maxLevelFound = currLevel;
}
}
Assert.assertTrue("Entries with max level 1 in the result", maxLevelFound<=1);
return null;
}
});
}
@Test
public void testViewTraversal_umlauts() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
Database dbLegacyAPI = session.getDatabase(dbData.getServer(), dbData.getRelativeFilePath());
NotesCollection colFromDbData = dbData.openCollectionByName("PeopleFlatMultiColumnSort");
colFromDbData.update();
colFromDbData.resortView("Lastname", Direction.Ascending);
List<NotesViewEntryData> umlautEntryAsList = colFromDbData.getAllEntriesByKey(EnumSet.of(Find.PARTIAL),
EnumSet.of(ReadMask.SUMMARY, ReadMask.NOTEID), new EntriesAsListCallback(1), "Umlaut");
Assert.assertFalse("There is a person document with lastname starting with 'Umlaut'", umlautEntryAsList.isEmpty());
NotesViewEntryData umlautEntry = umlautEntryAsList.get(0);
String lastNameFromView = (String) umlautEntry.get("lastname");
Document docPerson = dbLegacyAPI.getDocumentByID(umlautEntry.getNoteIdAsHex());
String lastNameFromDoc = docPerson.getItemValueString("Lastname");
docPerson.recycle();
Assert.assertEquals("LMBCS decoding to Java String works for Umlauts", lastNameFromDoc, lastNameFromView);
return null;
}
});
}
@Test
public void testViewTraversal_readDatatypes() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("PeopleFlatMultiColumnSort");
colFromDbData.update();
List<NotesViewEntryData> entries = colFromDbData.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_NONCATEGORY),
1000,
EnumSet.of(ReadMask.NOTEID, ReadMask.NOTEUNID, ReadMask.SUMMARY), new EntriesAsListCallback(Integer.MAX_VALUE));
for (NotesViewEntryData currEntry : entries) {
String lastNameStr = currEntry.getAsString("lastname", "");
if (lastNameStr.toLowerCase().startsWith("hidden")) {
//lastname - string
Object lastName = currEntry.get("lastname");
if (lastName!=null)
Assert.assertTrue("String column contains correct datatype", lastName instanceof String);
//col_namevariants - stringlist
Object nameVariants = currEntry.get("col_namevariants");
if (nameVariants!=null)
Assert.assertTrue("Numberlist column contains correct datatype", (nameVariants instanceof List && isListOfType((List<?>)nameVariants, String.class)));
//col_namevariantlengths - numberlist
Object nameVariantLengths = currEntry.get("col_namevariantlengths");
if (nameVariantLengths!=null)
Assert.assertTrue("Numberlist column contains correct datatype", (nameVariantLengths instanceof List && isListOfType((List<?>)nameVariantLengths, Double.class)));
//col_createdmodified - datelist
Object createdModified = currEntry.get("col_createdmodified");
if (createdModified!=null) {
Assert.assertTrue("Datelist column contains correct datatype", (createdModified instanceof List && isListOfType((List<?>)createdModified, Calendar.class)));
}
//HTTPPasswordChangeDate - datetime
Object httpPwdChangeDate = currEntry.get("HTTPPasswordChangeDate");
if (httpPwdChangeDate!=null)
Assert.assertTrue("Datetime column contains correct datatype", httpPwdChangeDate instanceof Calendar);
//col_internetaddresslength - number
Object internetAddressLength = currEntry.get("col_internetaddresslength");
if (internetAddressLength!=null)
Assert.assertTrue("Number column contains correct datatype", internetAddressLength instanceof Double);
//col_createdmodifiedrange - daterange
Object createModifiedRange = currEntry.get("col_createdmodifiedrange");
if (createModifiedRange!=null) {
Assert.assertTrue("Daterange column of note unid "+currEntry.getUNID()+" contains correct datatype", createModifiedRange!=null && (createModifiedRange instanceof List && isListOfType((List<?>)createModifiedRange, Calendar[].class)));
}
}
}
return null;
}
});
}
/**
* The test compares reading view data with limited and unlimited preload buffer; boths
* are expected to return the same result, which shows that continuing reading view
* data after the first preload buffer has been processed restarts reading at the right
* position
*/
@Test
public void testViewTraversal_allEntriesLimitedPreloadBuffer() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
System.out.println("Starting limited preload buffer test");
NotesDatabase dbData = getFakeNamesDb();
final int nrOfNotesToRead = 20; // no more than we have in the view
//only read 10 entries per readEntries call
int preloadBufferEntries = 10;
//grab some note ids from the People view
NotesCollection col = dbData.openCollectionByName("People");
int[] someNoteIdsReadWithLimitedPreloadBuffer = col.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), preloadBufferEntries, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<int[]>() {
int m_idx = 0;
@Override
public int[] startingLookup() {
return new int[nrOfNotesToRead];
}
@Override
public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(int[] result,
NotesViewEntryData entryData) {
if (m_idx < result.length) {
result[m_idx] = entryData.getNoteId();
m_idx++;
return Action.Continue;
}
else {
return Action.Stop;
}
}
@Override
public int[] lookupDone(int[] result) {
return result;
}
});
int cntNonNullIds = 0;
for (int currId : someNoteIdsReadWithLimitedPreloadBuffer) {
if (currId!=0) {
cntNonNullIds++;
}
}
Assert.assertEquals("All ids have been read", someNoteIdsReadWithLimitedPreloadBuffer.length, cntNonNullIds);
//now read with unlimited buffer, which effectively reads 64K of data, but only
//takes the first "nrOfNotesToRead" entries of them
int[] someNoteIdsReadWithUnlimitedPreloadBuffer = col.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<int[]>() {
int m_idx = 0;
@Override
public int[] startingLookup() {
return new int[nrOfNotesToRead];
}
@Override
public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(int[] result,
NotesViewEntryData entryData) {
if (m_idx < result.length) {
result[m_idx] = entryData.getNoteId();
m_idx++;
return Action.Continue;
}
else {
return Action.Stop;
}
}
@Override
public int[] lookupDone(int[] result) {
return result;
}
});
Assert.assertTrue("Reading with limited and unlimited preload buffer produces the same result", Arrays.equals(someNoteIdsReadWithLimitedPreloadBuffer, someNoteIdsReadWithUnlimitedPreloadBuffer));
System.out.println("Done with limited preload buffer test");
return null;
}
});
}
@Test
public void testViewTraversal_idScan() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
//compare the result of two scan functions, one using NIFGetIDTableExtended and
//the other one using NIFReadEntries
NotesDatabase dbData = getFakeNamesDb();
NotesCollection colFromDbData = dbData.openCollectionByName("CompaniesHierarchical");
colFromDbData.update();
long t0=System.currentTimeMillis();
NotesIDTable idTableUnsorted = new NotesIDTable();
colFromDbData.getAllIds(Navigate.NEXT_NONCATEGORY, false, idTableUnsorted);
long t1=System.currentTimeMillis();
System.out.println("Read "+idTableUnsorted.getCount()+" entries unsorted in "+(t1-t0)+"ms");
t0=System.currentTimeMillis();
LinkedHashSet<Integer> idsSorted = colFromDbData.getAllEntries("0", 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<LinkedHashSet<Integer>>() {
@Override
public LinkedHashSet<Integer> startingLookup() {
return new LinkedHashSet<Integer>();
}
@Override
public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(
LinkedHashSet<Integer> ctx, NotesViewEntryData entryData) {
ctx.add(entryData.getNoteId());
return Action.Continue;
}
@Override
public LinkedHashSet<Integer> lookupDone(LinkedHashSet<Integer> result) {
return result;
}
});
t1=System.currentTimeMillis();
System.out.println("Read "+idsSorted.size()+" entries sorted in "+(t1-t0)+"ms");
//compare both lists
Assert.assertEquals("Both id lists have the same size", idTableUnsorted.getCount(), idsSorted.size());
for (Integer currNoteId : idsSorted) {
Assert.assertTrue("ID table contains note id "+currNoteId, idTableUnsorted.contains(currNoteId));
}
for (Integer currNoteId : idsSorted) {
idTableUnsorted.removeNote(currNoteId);
}
Assert.assertTrue("ID table is empty after removing all entries from sorted list", idTableUnsorted.isEmpty());
//test isNoteInView function
for (Integer currNoteId : idsSorted) {
Assert.assertTrue("Note with note ID "+currNoteId+" is in view", colFromDbData.isNoteInView(currNoteId));
}
return null;
}
});
}
private boolean isListOfType(List<?> list, Class<?> classType) {
if (list.size()==0) {
return true;
}
for (int i=0; i<list.size(); i++) {
Object currObj = list.get(i);
if (!classType.isInstance(currObj)) {
return false;
}
}
return true;
}
@Test
public void testSelectedEntryCountWithPaging() {
runWithSession(new IDominoCallable<Object>() {
@Override
public Object call(Session session) throws Exception {
NotesDatabase dbData = getFakeNamesDb();
NotesCollection peopleView = dbData.openCollectionByName("People");
NotesIDTable idsInView = new NotesIDTable();
peopleView.getAllIds(Navigate.NEXT, false, idsInView);
int[] idsInViewAsArr = idsInView.toArray();
int firstId = idsInViewAsArr[0];
int secondId = idsInViewAsArr[1];
int lastId = idsInViewAsArr[idsInViewAsArr.length-1];
peopleView.select(Arrays.asList(firstId, secondId, lastId), true);
int NUM_PER_PAGE = 50;
List<NotesViewEntryData> viewEntries = peopleView.getAllEntries("0", 1,
EnumSet.of(Navigate.NEXT_SELECTED), NUM_PER_PAGE,
EnumSet.of(ReadMask.NOTEID, ReadMask.SUMMARYVALUES),
new EntriesAsListCallback(NUM_PER_PAGE));
Assert.assertEquals("No duplicate or missing rows returned", 3, viewEntries.size());
Set<Integer> returnedIds = new HashSet<Integer>();
for(int i=0; i<viewEntries.size(); i++) {
NotesViewEntryData currEntry = viewEntries.get(i);
returnedIds.add(currEntry.getNoteId());
System.out.println("#"+i+"\t"+currEntry.getNoteId()+"\t"+currEntry.getColumnDataAsMap());
}
Assert.assertTrue("Looked returned first filter id", returnedIds.contains(firstId));
Assert.assertTrue("Looked returned second filter id", returnedIds.contains(secondId));
Assert.assertTrue("Looked returned last filter id", returnedIds.contains(lastId));
return null;
}
});
}
}
| 38.600945 | 240 | 0.718275 |
1c230f551ce5425d46212d24f6f00ec6a095b3d3
| 2,953 |
package com.smartlogic.ses.examples;
import com.smartlogic.ses.client.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LoadTightLoopExample {
private static final int NUM_THREADS = 30;
private static final int MAX_LOOPS = 10;
public static void main(String[] args) {
try (SESClient client = ConfigUtil.getSESClient()) {
Thread[] threads = new Thread[NUM_THREADS];
{
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(() -> {
for ( int j = 0; j <= MAX_LOOPS; j++)
performWork(client);
});
threads[i].start();
}
}
for (int i = 0; i < NUM_THREADS; i++) {
threads[i].join();
}
System.out.println("Test completed");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void performWork(SESClient client) {
client.setMaxConnections(NUM_THREADS + 2);
Set<Term> allTerms = new HashSet<>();
try {
VersionInfo vInfo = client.getVersion();
System.out.println("Version: " + vInfo.getVersion());
for (Model m : client.listModels()) {
System.out.println("Model: " + m.getName());
}
Map<String, TermHint> hints = client.getTermHints("bus");
System.out.println("Hints: (bus)");
for (TermHint hint : hints.values())
System.out.println(hint.toString());
System.out.println("Mapped concept for 'Business':");
Map<String, Term> concepts = client.getMappedConcepts("Business");
for (Term t : concepts.values()) {
System.out.println(" Mapped concept : " + t.getName().getValue());
System.out.println(" Mapped concept id: " + t.getId().getValue());
}
Map<String, Term> rootTerms = client.browse(null);
for (Term t : rootTerms.values()) {
allTerms.add(t);
System.out.println("Top concept: " + t.getName().getValue());
Map<String, Term> childTerms = client.browse(t.getId().getValue());
if (childTerms != null) {
System.out.println(childTerms.size() + " child terms returned");
}
}
int loopCounter = 0;
for (Term t : allTerms) {
if (loopCounter++ > 10)
break;
Term tempTerm = client.getTermDetails(t.getId().getValue(), SESClient.DetailLevel.FULL);
System.out.println("Term details: " + t.getId().getValue());
System.out.println(tempTerm.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 33.942529 | 104 | 0.508297 |
6ac29aa3c7286644df67636ebdf91a06f96042da
| 1,739 |
/**
*@author Moises Guerrero Lopez
*@version 1.0
*@since November 30,2017
*/
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
public class ServidorHiloconPool
implements Runnable
{
Socket enchufe;
public ServidorHiloconPool(Socket s)
{enchufe = s;}
/**
*@override
*/
public void run()
{
try{
BufferedReader entrada = new BufferedReader(
new InputStreamReader(
enchufe.getInputStream()));
String datos = entrada.readLine();
int j;
int i = Integer.valueOf(datos).intValue();
for(j=1; j<=20; j++){
System.out.println("El hilo "+Thread.currentThread().getName()+" escribiendo el dato "+i);
Thread.currentThread().sleep(1000);}
enchufe.close();
System.out.println("El hilo "+Thread.currentThread().getName()+"cierra su conexion...");
} catch(Exception e) {System.out.println("Error...");}
}//run
public static void main (String[] args)
{
int i;
int puerto = 2001;
try{
ServerSocket chuff = new ServerSocket (puerto, 3000);
ThreadPoolExecutor exec = (ThreadPoolExecutor) Executors.newCachedThreadPool();
while (true){
System.out.println("Esperando solicitud de conexion...");
Socket cable = chuff.accept();
System.out.println("Recibida solicitud de conexion...");
exec.execute(new ServidorHiloconPool(cable));
}
//while
} catch (Exception e)
{System.out.println("Error en sockets...");}
}//main
}//Servidor_Hilos
| 28.983333 | 99 | 0.557217 |
0c741c7a6c166518a2cd82408ad4bf115fb28279
| 1,777 |
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@GwtIncompatible
final class JdkPattern extends CommonPattern implements Serializable {
private static final long serialVersionUID = 0;
private final Pattern pattern;
private static final class JdkMatcher extends CommonMatcher {
final Matcher matcher;
JdkMatcher(Matcher matcher) {
this.matcher = (Matcher) Preconditions.checkNotNull(matcher);
}
boolean matches() {
return this.matcher.matches();
}
boolean find() {
return this.matcher.find();
}
boolean find(int index) {
return this.matcher.find(index);
}
String replaceAll(String replacement) {
return this.matcher.replaceAll(replacement);
}
int end() {
return this.matcher.end();
}
int start() {
return this.matcher.start();
}
}
JdkPattern(Pattern pattern) {
this.pattern = (Pattern) Preconditions.checkNotNull(pattern);
}
CommonMatcher matcher(CharSequence t) {
return new JdkMatcher(this.pattern.matcher(t));
}
String pattern() {
return this.pattern.pattern();
}
int flags() {
return this.pattern.flags();
}
public String toString() {
return this.pattern.toString();
}
public int hashCode() {
return this.pattern.hashCode();
}
public boolean equals(Object o) {
if (o instanceof JdkPattern) {
return this.pattern.equals(((JdkPattern) o).pattern);
}
return false;
}
}
| 23.381579 | 73 | 0.607203 |
0c8f7cfe1e15353c429a866f3806ac222937bd82
| 508 |
package com.acmerobotics.library.hardware;
import com.qualcomm.robotcore.hardware.I2cDeviceSynchImplOnSimple;
import com.qualcomm.robotcore.hardware.I2cDeviceSynchSimple;
public class BetterI2cDeviceSynchImplOnSimple extends I2cDeviceSynchImplOnSimple {
public BetterI2cDeviceSynchImplOnSimple(I2cDeviceSynchSimple simple, boolean isSimpleOwned) {
super(simple, isSimpleOwned);
}
@Override
public void setReadWindow(ReadWindow window) {
// intentionally do nothing
}
}
| 31.75 | 97 | 0.795276 |
a443f47f63ecb384780dce43e130cf503a049123
| 202 |
package chapter_3.exercise_6;
public class StringCount {
public static int countLowerCaseLetters(String input) {
return (int) input.chars().filter(Character::isLowerCase).count();
}
}
| 22.444444 | 74 | 0.717822 |
0927a8f288a71f9ade4b623e0e858dc478daa11e
| 2,225 |
package ru.xander.replicator.schema;
import ru.xander.replicator.exception.ReplicatorException;
import ru.xander.replicator.exception.SchemaException;
import ru.xander.replicator.listener.Listener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author Alexander Shakhov
*/
public class SchemaConnection implements AutoCloseable {
private final String jdbcDriver;
private final String jdbcUrl;
private final String username;
private final String password;
private final Listener listener;
private Connection connection;
public SchemaConnection(SchemaConfig config, Listener listener) {
this.jdbcDriver = config.getJdbcDriver();
this.jdbcUrl = config.getJdbcUrl();
this.username = config.getUsername();
this.password = config.getPassword();
this.listener = listener;
}
public Connection getJdbcConnection() {
if (connection == null) {
try {
notify("Connect to " + jdbcUrl + "...");
Class.forName(jdbcDriver);
connection = DriverManager.getConnection(jdbcUrl, username, password);
} catch (SQLException | ClassNotFoundException e) {
error(e);
String errorMessage = String.format(
"Error occurred while connecting to schema %s: %s",
jdbcUrl, e.getMessage());
throw new SchemaException(errorMessage);
}
}
return connection;
}
@Override
public void close() {
try {
if (this.connection != null) {
notify("Close connection.");
this.connection.close();
}
} catch (SQLException e) {
error(e);
String errorMessage = "Failed to close connection: " + e.getMessage();
throw new ReplicatorException(errorMessage, e);
}
}
private void notify(String message) {
if (listener != null) {
listener.notify(message);
}
}
private void error(Exception e) {
if (listener != null) {
listener.error(e);
}
}
}
| 30.067568 | 86 | 0.597753 |
ba84eb5b121f90b4d9e541c19ca13dba7f4fe938
| 13,814 |
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/8.0.33
* Generated at: 2016-04-18 03:03:01 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.JSPs;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class signup_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent,
org.apache.jasper.runtime.JspSourceImports {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private static final java.util.Set<java.lang.String> _jspx_imports_packages;
private static final java.util.Set<java.lang.String> _jspx_imports_classes;
static {
_jspx_imports_packages = new java.util.HashSet<>();
_jspx_imports_packages.add("javax.servlet");
_jspx_imports_packages.add("javax.servlet.jsp");
_jspx_imports_packages.add("javax.servlet.http");
_jspx_imports_classes = null;
}
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public java.util.Set<java.lang.String> getPackageImports() {
return _jspx_imports_packages;
}
public java.util.Set<java.lang.String> getClassImports() {
return _jspx_imports_classes;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("<html lang=\"en\">\n");
out.write("\n");
out.write("<head>\n");
out.write("\n");
out.write(" <meta charset=\"utf-8\">\n");
out.write(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n");
out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
out.write(" \n");
out.write(" <title>User Signin page</title>\n");
out.write("\n");
out.write(" <!-- Bootstrap Core CSS -->\n");
out.write(" <link href=\"../css/bootstrap.min.css\" rel=\"stylesheet\">\n");
out.write("\n");
out.write(" <!-- Custom CSS: You can use this stylesheet to override any Bootstrap styles and/or apply your own styles -->\n");
out.write(" <link href=\"../css/login.css\" rel=\"stylesheet\">\n");
out.write("\n");
out.write(" <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>\n");
out.write(" \n");
out.write("</head>\n");
out.write("\n");
out.write("<body>\n");
out.write("\n");
out.write(" <!-- Navigation -->\n");
out.write(" <nav id=\"siteNav\" class=\"navbar navbar-default navbar-fixed-top\" role=\"navigation\">\n");
out.write(" <div class=\"container\">\n");
out.write(" <!-- Logo and responsive toggle -->\n");
out.write(" <div class=\"navbar-header\">\n");
out.write(" <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#navbar\">\n");
out.write(" <span class=\"sr-only\">Toggle navigation</span>\n");
out.write(" <span class=\"icon-bar\"></span>\n");
out.write(" <span class=\"icon-bar\"></span>\n");
out.write(" <span class=\"icon-bar\"></span>\n");
out.write(" </button>\n");
out.write(" <a class=\"navbar-brand\" href=\"#\">\n");
out.write(" <span class=\"glyphicon glyphicon-fire\"></span> \n");
out.write(" STORE\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" <!-- Navbar links -->\n");
out.write(" <div class=\"collapse navbar-collapse\" id=\"navbar\">\n");
out.write(" <ul class=\"nav navbar-nav navbar-center\">\n");
out.write(" <li class=\"active\">\n");
out.write(" <a href=\"../index.html\"><font color=\"black\"><b>Home</b></font></a>\n");
out.write(" </li>\n");
out.write(" \n");
out.write(" </ul>\n");
out.write(" \n");
out.write(" </div><!-- /.navbar-collapse -->\n");
out.write(" </div><!-- /.container -->\n");
out.write(" </nav>\n");
out.write("\n");
out.write(" <!-- Header -->\n");
out.write(" <header>\n");
out.write(" <div class=\"header-content\">\n");
out.write(" <div class=\"header-content-inner\">\n");
out.write(" <form>\n");
out.write(" <h1><font color= #cc6600>New User</font></h1>\n");
out.write("\t\t<p><font color=#cc6600><b>Username:</b></font>\n");
out.write("\t\t<input type=\"text\" name=\"username\"> </p>\n");
out.write("\t\t<br>\n");
out.write("\t\t<p><font color=#cc6600><b>Role</b></font>\n");
out.write("\t\t<select name=\"role\">\n");
out.write("\t\t\t<option value=\"owner\">owner</option>\n");
out.write("\t\t\t<option value=\"customer\">customer</option>\n");
out.write("\t\t</select> </p>\n");
out.write("\t\t<br> \n");
out.write("\t\t<p><font color=#cc6600><b>Age</b></font>\n");
out.write("\t\t<input type=\"text\" name=\"age\"> </p>\n");
out.write("\t\t<br>\n");
out.write("\t\t<p><font color=#cc6600><b>State</b></font>\n");
out.write("\t\t<select name=\"state\">\n");
out.write("\t\t\t<option value=\"AL\">Alabama</option>\n");
out.write("\t\t\t<option value=\"AK\">Alaska</option>\n");
out.write("\t\t\t<option value=\"AZ\">Arizona</option>\n");
out.write("\t\t\t<option value=\"AR\">Arkansas</option>\n");
out.write("\t\t\t<option value=\"CA\">California</option>\n");
out.write("\t\t\t<option value=\"CO\">Colorado</option>\n");
out.write("\t\t\t<option value=\"CT\">Connecticut</option>\n");
out.write("\t\t\t<option value=\"DE\">Delaware</option>\n");
out.write("\t\t\t<option value=\"DC\">District Of Columbia</option>\n");
out.write("\t\t\t<option value=\"FL\">Florida</option>\n");
out.write("\t\t\t<option value=\"GA\">Georgia</option>\n");
out.write("\t\t\t<option value=\"HI\">Hawaii</option>\n");
out.write("\t\t\t<option value=\"ID\">Idaho</option>\n");
out.write("\t\t\t<option value=\"IL\">Illinois</option>\n");
out.write("\t\t\t<option value=\"IN\">Indiana</option>\n");
out.write("\t\t\t<option value=\"IA\">Iowa</option>\n");
out.write("\t\t\t<option value=\"KS\">Kansas</option>\n");
out.write("\t\t\t<option value=\"KY\">Kentucky</option>\n");
out.write("\t\t\t<option value=\"LA\">Louisiana</option>\n");
out.write("\t\t\t<option value=\"ME\">Maine</option>\n");
out.write("\t\t\t<option value=\"MD\">Maryland</option>\n");
out.write("\t\t\t<option value=\"MA\">Massachusetts</option>\n");
out.write("\t\t\t<option value=\"MI\">Michigan</option>\n");
out.write("\t\t\t<option value=\"MN\">Minnesota</option>\n");
out.write("\t\t\t<option value=\"MS\">Mississippi</option>\n");
out.write("\t\t\t<option value=\"MO\">Missouri</option>\n");
out.write("\t\t\t<option value=\"MT\">Montana</option>\n");
out.write("\t\t\t<option value=\"NE\">Nebraska</option>\n");
out.write("\t\t\t<option value=\"NV\">Nevada</option>\n");
out.write("\t\t\t<option value=\"NH\">New Hampshire</option>\n");
out.write("\t\t\t<option value=\"NJ\">New Jersey</option>\n");
out.write("\t\t\t<option value=\"NM\">New Mexico</option>\n");
out.write("\t\t\t<option value=\"NY\">New York</option>\n");
out.write("\t\t\t<option value=\"NC\">North Carolina</option>\n");
out.write("\t\t\t<option value=\"ND\">North Dakota</option>\n");
out.write("\t\t\t<option value=\"OH\">Ohio</option>\n");
out.write("\t\t\t<option value=\"OK\">Oklahoma</option>\n");
out.write("\t\t\t<option value=\"OR\">Oregon</option>\n");
out.write("\t\t\t<option value=\"PA\">Pennsylvania</option>\n");
out.write("\t\t\t<option value=\"RI\">Rhode Island</option>\n");
out.write("\t\t\t<option value=\"SC\">South Carolina</option>\n");
out.write("\t\t\t<option value=\"SD\">South Dakota</option>\n");
out.write("\t\t\t<option value=\"TN\">Tennessee</option>\n");
out.write("\t\t\t<option value=\"TX\">Texas</option>\n");
out.write("\t\t\t<option value=\"UT\">Utah</option>\n");
out.write("\t\t\t<option value=\"VT\">Vermont</option>\n");
out.write("\t\t\t<option value=\"VA\">Virginia</option>\n");
out.write("\t\t\t<option value=\"WA\">Washington</option>\n");
out.write("\t\t\t<option value=\"WV\">West Virginia</option>\n");
out.write("\t\t\t<option value=\"WI\">Wisconsin</option>\n");
out.write("\t\t\t<option value=\"WY\">Wyoming</option>\n");
out.write("\t\t</select> </p>\n");
out.write("\t\t<br>\n");
out.write("\t\t<a href=\"MainPage.jsp\" class=\"btn btn-primary btn-lg\">Sign Up</a>\n");
out.write("\t</form>\n");
out.write(" </div>\n");
out.write(" </div> \n");
out.write(" </header>\n");
out.write("\n");
out.write(" \n");
out.write(" <footer class=\"page-footer\">\n");
out.write(" \n");
out.write("\n");
out.write(" <div class=\"small-print\">\n");
out.write(" <div class=\"container\">\n");
out.write(" <p>Copyright ©Whatever 2016</p>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" </footer>\n");
out.write("\n");
out.write(" <!-- jQuery -->\n");
out.write(" <script src=\"js/jquery-1.11.3.min.js\"></script>\n");
out.write("\n");
out.write(" <!-- Bootstrap Core JavaScript -->\n");
out.write(" <script src=\"js/bootstrap.min.js\"></script>\n");
out.write("\n");
out.write(" <!-- Plugin JavaScript -->\n");
out.write(" <script src=\"js/jquery.easing.min.js\"></script>\n");
out.write(" \n");
out.write(" <!-- Custom Javascript -->\n");
out.write(" <script src=\"js/custom.js\"></script>\n");
out.write("\n");
out.write("</body>\n");
out.write("\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 48.132404 | 191 | 0.576082 |
d4d0a5348799256372e50cafd844c99409ed4d45
| 9,883 |
package tools;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class ReportGenerator
{
private int totalDesktopTests = 0;
private int totalTabletTests = 0;
private int totalMobileTests = 0;
public void generateReport()
{
String htmlTemplate = null;
try {
htmlTemplate = new String(Files.readAllBytes(Paths.get(TestConfig.PATH_TO_REPORT_TEMPLATE)), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
Map<String, String> map = this.generateMenu();
Map<String, String> errors = this.generateErrorsMenu();
htmlTemplate = htmlTemplate.replace("@@DESKTOP_MENU@@", errors.get("desktop") + map.get("desktop"));
htmlTemplate = htmlTemplate.replace("@@TABLET_MENU@@", errors.get("tablet") + map.get("tablet"));
htmlTemplate = htmlTemplate.replace("@@MOBILE_MENU@@", errors.get("mobile") + map.get("mobile"));
htmlTemplate = htmlTemplate.replace("@@ERRORS_LOG@@", generateErrorsLog());
htmlTemplate = htmlTemplate.replace("@@RESULTS@@", this.generateResults());
htmlTemplate = htmlTemplate.replace("@@TOTAL_DESKTOP@@", Integer.toString(totalDesktopTests));
htmlTemplate = htmlTemplate.replace("@@TOTAL_TABLET@@", Integer.toString(totalTabletTests));
htmlTemplate = htmlTemplate.replace("@@TOTAL_MOBILE@@", Integer.toString(totalMobileTests));
PrintWriter writer = null;
try {
writer = new PrintWriter(TestConfig.PATH_TO_OUTPUT_REPORT_FILE, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
writer.println(htmlTemplate);
writer.close();
}
private Map<String, String> generateErrorsMenu()
{
String desktopHtml = "";
String tabletHtml = "";
String mobileHtml = "";
// create menu item for errors log
String pageId;
File directory = new File(TestConfig.PATH_TO_ACTUAL_SCREENSHOTS);
File[] filesList = directory.listFiles();
Arrays.sort(filesList);
int id = 0;
for (File file : filesList)
{
if (file.isFile())
{
id++;
pageId = "page" + id;
String isError = "";
File errorFile = new File(TestConfig.PATH_TO_DIFF_SCREENSHOTS + file.getName());
// skip if there isn't diff file
if(errorFile.exists() == false) {
continue;
}
isError = "<b class='w3-red'>ERROR: </b>";
String pageName = file.getName().replace(".png", "");
pageName = pageName.substring(0, 1).toUpperCase() + pageName.substring(1);
if(file.getName().contains("1920"))
{
totalDesktopTests++;
desktopHtml += String.format("<button style='word-wrap: break-word; width:100%%;' class='w3-bar-item w3-button w3-left-align tablink' onclick=\"openLink(this, '%s')\">", pageId);
desktopHtml += String.format("%s%s", isError, pageName);
desktopHtml += "</button>";
}
if(file.getName().contains("769") || file.getName().contains("768"))
{
totalTabletTests++;
tabletHtml += String.format("<button style='word-wrap: break-word; width:100%%;' class='w3-bar-item w3-button w3-left-align tablink' onclick=\"openLink(this, '%s')\">", pageId);
tabletHtml += String.format("%s%s", isError, pageName);
tabletHtml += "</button>";
}
if(file.getName().contains("360"))
{
totalMobileTests++;
mobileHtml += String.format("<button style='word-wrap: break-word; width:100%%;' class='w3-bar-item w3-button w3-left-align tablink' onclick=\"openLink(this, '%s')\">", pageId);
mobileHtml += String.format("%s%s", isError, pageName);
mobileHtml += "</button>";
}
}
}
Map<String, String> map = new HashMap<String, String>();
map.put("desktop", desktopHtml);
map.put("tablet", tabletHtml);
map.put("mobile", mobileHtml);
return map;
}
private Map<String, String> generateMenu()
{
String desktopHtml = "";
String tabletHtml = "";
String mobileHtml = "";
// create menu item for errors log
String pageId;
File directory = new File(TestConfig.PATH_TO_ACTUAL_SCREENSHOTS);
File[] filesList = directory.listFiles();
Arrays.sort(filesList);
int id = 0;
for (File file : filesList)
{
if (file.isFile())
{
id++;
pageId = "page" + id;
String isError = "";
File errorFile = new File(TestConfig.PATH_TO_DIFF_SCREENSHOTS + file.getName());
if(errorFile.exists()) {
continue;
}
String pageName = file.getName().replace(".png", "");
pageName = pageName.substring(0, 1).toUpperCase() + pageName.substring(1);
if(file.getName().contains("1920"))
{
totalDesktopTests++;
desktopHtml += String.format("<button style='word-wrap: break-word; width:100%%;' class='w3-bar-item w3-button w3-left-align tablink' onclick=\"openLink(this, '%s')\">", pageId);
desktopHtml += String.format("%s%s", isError, pageName);
desktopHtml += "</button>";
}
if(file.getName().contains("769") || file.getName().contains("768"))
{
totalTabletTests++;
tabletHtml += String.format("<button style='word-wrap: break-word; width:100%%;' class='w3-bar-item w3-button w3-left-align tablink' onclick=\"openLink(this, '%s')\">", pageId);
tabletHtml += String.format("%s%s", isError, pageName);
tabletHtml += "</button>";
}
if(file.getName().contains("360"))
{
totalMobileTests++;
mobileHtml += String.format("<button style='word-wrap: break-word; width:100%%;' class='w3-bar-item w3-button w3-left-align tablink' onclick=\"openLink(this, '%s')\">", pageId);
mobileHtml += String.format("%s%s", isError, pageName);
mobileHtml += "</button>";
}
}
}
Map<String, String> map = new HashMap<String, String>();
map.put("desktop", desktopHtml);
map.put("tablet", tabletHtml);
map.put("mobile", mobileHtml);
return map;
}
private String generateResults()
{
String contentHtml = "";
String pageId;
File directory = new File(TestConfig.PATH_TO_ACTUAL_SCREENSHOTS);
File[] filesList = directory.listFiles();
Arrays.sort(filesList);
int id = 0;
for (File file : filesList)
{
if (file.isFile())
{
id++;
pageId = "page" + id;
String gifFilename = file.getName().replace("png", "gif");
contentHtml += String.format("<div id='%s' class='w3-row w3-animate-right result' style='width: 80%%; margin-left: 20%%; display: none;'>", pageId);
contentHtml += String.format("<h1 class='w3-center w3-cyan'>%s</h1>", file.getName());
contentHtml += "<div class='w3-col' style='width:25%; padding:0 5px;'>";
contentHtml += "<h2 class='w3-center'>EXPECTED</h2>";
contentHtml += String.format("<img src='../%s%s'>", TestConfig.PATH_TO_EXPECTED_SCREENSHOTS, file.getName());
contentHtml += "</div>";
contentHtml += "<div class='w3-col' style='width:25%; padding:0 5px;'>";
contentHtml += "<h2 class='w3-center'>ACTUAL</h2>";
contentHtml += String.format("<img src='../%s%s'>", TestConfig.PATH_TO_ACTUAL_SCREENSHOTS, file.getName());
contentHtml += "</div>";
contentHtml += "<div class='w3-col' style='width:25%; padding:0 5px;'>";
contentHtml += "<h2 class='w3-center'>DIFFERENCE</h2>";
File diffFile = new File(TestConfig.PATH_TO_DIFF_SCREENSHOTS + file.getName());
if(diffFile.exists()) {
contentHtml += String.format("<img src='../%s%s'>", TestConfig.PATH_TO_DIFF_SCREENSHOTS, file.getName());
}
contentHtml += "</div>";
contentHtml += "<div class='w3-col' style='width:25%; padding:0 5px;'>";
contentHtml += "<h2 class='w3-center'>GIF</h2>";
File gifFile = new File(TestConfig.PATH_TO_GIF_SCREENSHOTS + gifFilename);
if(gifFile.exists()) {
contentHtml += String.format("<img src='../%s%s'>", TestConfig.PATH_TO_GIF_SCREENSHOTS, gifFilename);
}
contentHtml += "</div>";
contentHtml += "</div>";
}
}
return contentHtml;
}
private String generateErrorsLog()
{
String errorsLog = "";
try {
errorsLog = new String(Files.readAllBytes(Paths.get(TestConfig.PATH_TO_ERRORS_LOG)));
} catch (IOException e) {
e.printStackTrace();
}
String contentHtml = "";
contentHtml += errorsLog;
return contentHtml;
}
}
| 37.577947 | 199 | 0.534453 |
4c7c6284bcd7b54616a64abf44371cb4b2095bc4
| 5,774 |
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
class Book
{
private String author, title;
protected int pages;
public String getAuthor() { return author; }
public Book()
{
this.author = "John Steinbeck";
this.title = "Of Mice and Men";
this.pages = 107;
}
public Book(String author, String title, int pages)
{
if (author.length() < 2 || title.length() < 4)
{
throw new IllegalArgumentException();
}
this.author = author;
this.title = title;
this.pages = pages;
}
public int getPages()
{
return pages;
}
public String getShortName()
{
return author.substring(0, 2) + ": " + title.substring(0, 4) + "; " + pages;
}
//@Override
public String toString()
{
return author + ": " + title + ", pages: " + pages;
}
public String createReference(String article, int from, int to)
{
return getShortName() + " [" + from + "-" + to + "] referenced in article: " + article;
}
}
enum CoverType
{
Softcover,
Hardcover;
}
class PrintedBook extends Book
{
protected CoverType cover;
public PrintedBook()
{
this.pages += 6;
this.cover = CoverType.Hardcover;
}
public PrintedBook(String author, String title, int pages, CoverType cover)
{
super(author, title, pages + 6);
this.cover = cover;
}
public int getPrice()
{
if (cover == CoverType.Softcover)
{
return pages * 2;
}
else
{
return pages * 3;
}
}
//@Override
public String toString()
{
if (cover == CoverType.Softcover)
{
return super.toString() + " (softcover)";
}
else
{
return super.toString() + " (hardcover)";
}
}
@Override
public String createReference(String article, int from, int to)
{
return super.toString() + " [" + from + "-" + to + "] referenced in article: " + article;
}
}
class EBook extends Book
{
protected int PDFSize;
public EBook(String author, String title, int pages, int PDFSize)
{
super(author, title, pages);
this.PDFSize = PDFSize;
}
public int getPrice()
{
return pages + PDFSize;
}
@Override
public String createReference(String article, int from, int to)
{
return super.toString() + " (PDF size: " + PDFSize + ") [" + from + "-" + to + "] referenced in article: " + article;
}
//@Override // compile error
public String createReference(String article, String date)
{
return super.toString() + " (PDF size: " + PDFSize + ") referenced in article: " + article + ", accessing PDF date: " + date;
}
}
class Article
{
private String title, body, conclusion;
private PrintWriter pw;
private ArrayList<Book> refs;
public Article(String title, String body, String conclusion)
{
this.title = title;
this.body = body;
this.conclusion = conclusion;
this.refs = new ArrayList<Book>();
}
public void addBookToReferences(Book book)
{
refs.add(book);
}
private void printReference(Book book, int from, int to)
{
String ref = book.createReference(this.title, from, to);
// Book, PrintedBook and EBook have a proper createReference() method, that takes care of proper reference creation.
// Note here the caller doesn't even interested in if book is a Book, PrintedBook or EBook, just the fact that every Book have a createReference() method.
// Easy to add new kind of Book-s, we just have to take care to define a proper createReference() method.
// The imperative solution (without method overriding and LSP) would be to check here what the exact type of book,
// which would result in many if-conditions in the source code, which is not the dream of a programmer.
pw.print(ref);
pw.print(System.lineSeparator());
}
public void print(String destfilename)
{
try
{
pw = new PrintWriter(new File(destfilename));
pw.print(title);
pw.print(System.lineSeparator());
pw.print(body);
pw.print(System.lineSeparator());
pw.print(conclusion);
pw.print(System.lineSeparator());
for (Book book : refs)
{
printReference(book, 1, book.getPages()); // LSP
}
}
catch (IOException exc)
{
System.out.println(exc.getStackTrace());
}
finally
{
pw.close();
}
}
}
class Main
{
public static void main(String[] args)
{
Book book1 = new Book();
PrintedBook pbook1 = new PrintedBook();
EBook ebook1 = new EBook("author2", "Digitalised: Title", 100, 12);
System.out.println(book1);
System.out.println(pbook1);
System.out.println(ebook1);
System.out.println();
System.out.println(book1.createReference("articlename", 10, 20));
System.out.println(pbook1.createReference("articlename", 10, 20));
System.out.println(ebook1.createReference("articlename", 10, 20));
Article myArticle = new Article("My fictional article", "foo_body", "foo_conclusion");
myArticle.addBookToReferences(book1); // LSP
myArticle.addBookToReferences(pbook1); // LSP
myArticle.addBookToReferences(ebook1); // LSP
myArticle.print("out.txt");
}
}
| 25.213974 | 162 | 0.579321 |
b755f9de4ce3c8900c271c04106ae916fe279dd5
| 8,941 |
package us.ihmc.commonWalkingControlModules.trajectories;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import us.ihmc.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest;
import us.ihmc.euclid.referenceFrame.FramePoint3D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.tools.ReferenceFrameTools;
import us.ihmc.yoVariables.registry.YoVariableRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.simulationconstructionset.Robot;
import us.ihmc.simulationconstructionset.SimulationConstructionSet;
import us.ihmc.tools.MemoryTools;
import us.ihmc.commons.thread.ThreadTools;
public class CoMHeightTimeDerivativesSmootherTest
{
private final ReferenceFrame worldFrame = ReferenceFrame.getWorldFrame();
@Before
public void showMemoryUsageBeforeTest()
{
MemoryTools.printCurrentMemoryUsageAndReturnUsedMemoryInMB(getClass().getSimpleName() + " before test.");
}
@After
public void showMemoryUsageAfterTest()
{
ReferenceFrameTools.clearWorldFrameTree();
MemoryTools.printCurrentMemoryUsageAndReturnUsedMemoryInMB(getClass().getSimpleName() + " after test.");
}
@ContinuousIntegrationTest(estimatedDuration = 0.4)
@Test(timeout = 30000)
public void testConstantHeight()
{
double dt = 0.001;
YoVariableRegistry registry = new YoVariableRegistry("Test");
CoMHeightTimeDerivativesSmoother smoother = new CoMHeightTimeDerivativesSmoother(dt, registry);
CoMHeightTimeDerivativesData comHeightDataOut = new CoMHeightTimeDerivativesData();
CoMHeightTimeDerivativesData comHeightDataIn = new CoMHeightTimeDerivativesData();
double comHeight = 1.2;
double comHeightVelocity = 0.0;
double comHeightAcceleration = 0.0;
comHeightDataIn.setComHeight(ReferenceFrame.getWorldFrame(), comHeight);
comHeightDataIn.setComHeightVelocity(comHeightVelocity);
comHeightDataIn.setComHeightAcceleration(comHeightAcceleration);
smoother.initialize(comHeightDataIn);
smoother.smooth(comHeightDataOut, comHeightDataIn);
FramePoint3D comHeightPoint = new FramePoint3D(ReferenceFrame.getWorldFrame());
comHeightDataOut.getComHeight(comHeightPoint);
double comHeightOut = comHeightPoint.getZ();
double comHeightVelocityOut = comHeightDataOut.getComHeightVelocity();
double comHeightAccelerationOut = comHeightDataOut.getComHeightAcceleration();
assertEquals(comHeight, comHeightOut, 1e-7);
assertEquals(comHeightVelocity, comHeightVelocityOut, 1e-7);
assertEquals(comHeightAcceleration, comHeightAccelerationOut, 1e-7);
}
@ContinuousIntegrationTest(estimatedDuration = 0.3)
@Test(timeout = 30000)
public void testDiscreetJump()
{
boolean visualize = false;
double dt = 0.002;
YoVariableRegistry registry = new YoVariableRegistry("Test");
YoDouble testTime = new YoDouble("testTime", registry);
SimulationConstructionSet scs = null;
if (visualize)
{
scs = new SimulationConstructionSet(new Robot("Null"));
scs.addYoVariableRegistry(registry);
scs.startOnAThread();
}
CoMHeightTimeDerivativesSmoother smoother = new CoMHeightTimeDerivativesSmoother(dt, registry);
CoMHeightTimeDerivativesData comHeightDataOut = new CoMHeightTimeDerivativesData();
CoMHeightTimeDerivativesData comHeightDataIn = new CoMHeightTimeDerivativesData();
double comHeightIn = 1.0;
double comHeightVelocityIn = 0.0;
double comHeightAccelerationIn = 0.0;
comHeightDataIn.setComHeight(worldFrame, comHeightIn);
comHeightDataIn.setComHeightVelocity(comHeightVelocityIn);
comHeightDataIn.setComHeightAcceleration(comHeightAccelerationIn);
smoother.initialize(comHeightDataIn);
smoother.smooth(comHeightDataOut, comHeightDataIn);
FramePoint3D comHeightPoint = new FramePoint3D(ReferenceFrame.getWorldFrame());
comHeightDataOut.getComHeight(comHeightPoint);
double comHeightOut = comHeightPoint.getZ();
double comHeightVelocityOut = comHeightDataOut.getComHeightVelocity();
double comHeightAccelerationOut = comHeightDataOut.getComHeightAcceleration();
assertEquals(comHeightIn, comHeightOut, 1e-7);
assertEquals(comHeightVelocityIn, comHeightVelocityOut, 1e-7);
assertEquals(comHeightAccelerationIn, comHeightAccelerationOut, 1e-7);
comHeightIn = 1.2;
comHeightDataIn.setComHeight(worldFrame, comHeightIn);
double previousCoMHeightOut = comHeightOut;
double previousCoMHeightVelocityOut = comHeightVelocityOut;
double estimatedZDot, estimatedZDDot;
if (visualize)
{
scs.updateAndTick();
}
for (int i = 0; i < (1.5 / dt); i++)
{
testTime.add(dt);
smoother.smooth(comHeightDataOut, comHeightDataIn);
comHeightDataOut.getComHeight(comHeightPoint);
double newComHeightOut = comHeightPoint.getZ();
estimatedZDot = (newComHeightOut - previousCoMHeightOut) / dt;
estimatedZDDot = (estimatedZDot - previousCoMHeightVelocityOut) / dt;
assertEquals(estimatedZDot, comHeightDataOut.getComHeightVelocity(), 1e-7);
assertEquals(estimatedZDDot, comHeightDataOut.getComHeightAcceleration(), 1e-7);
// comHeightDataIn.set(comHeightDataOut);
previousCoMHeightOut = newComHeightOut;
previousCoMHeightVelocityOut = comHeightDataOut.getComHeightVelocity();
if (visualize)
{
scs.tickAndUpdate();
}
}
comHeightDataOut.getComHeight(comHeightPoint);
double finalComHeightOut = comHeightPoint.getZ();
assertEquals(comHeightIn, finalComHeightOut, 1e-4);
assertEquals(comHeightVelocityIn, comHeightDataOut.getComHeightVelocity(), 1e-3);
assertEquals(comHeightAccelerationIn, comHeightDataOut.getComHeightAcceleration(), 1e-2);
if (visualize)
{
scs.cropBuffer();
ThreadTools.sleepForever();
}
}
@ContinuousIntegrationTest(estimatedDuration = 0.3)
@Test(timeout = 30000)
public void testSinusoidalInput()
{
boolean visualize = false;
double dt = 0.002;
YoVariableRegistry registry = new YoVariableRegistry("Test");
YoDouble testTime = new YoDouble("testTime", registry);
YoDouble amplitude = new YoDouble("amplitude", registry);
YoDouble frequency = new YoDouble("frequency", registry);
amplitude.set(0.2);
frequency.set(1.0);
SimulationConstructionSet scs = null;
if (visualize)
{
scs = new SimulationConstructionSet(new Robot("Null"));
scs.addYoVariableRegistry(registry);
scs.startOnAThread();
}
CoMHeightTimeDerivativesSmoother smoother = new CoMHeightTimeDerivativesSmoother(dt, registry);
CoMHeightTimeDerivativesData comHeightDataOut = new CoMHeightTimeDerivativesData();
CoMHeightTimeDerivativesData comHeightDataIn = new CoMHeightTimeDerivativesData();
double comHeightIn = 0.0; //amplitude.getDoubleValue(); //1.0;
double comHeightVelocityIn = 2.0 * Math.PI * frequency.getDoubleValue() * amplitude.getDoubleValue();
double comHeightAccelerationIn = 0.0;
comHeightDataIn.setComHeight(worldFrame, comHeightIn);
comHeightDataIn.setComHeightVelocity(comHeightVelocityIn);
comHeightDataIn.setComHeightAcceleration(comHeightAccelerationIn);
smoother.initialize(comHeightDataIn);
smoother.smooth(comHeightDataOut, comHeightDataIn);
if (visualize)
{
scs.updateAndTick();
}
boolean done = false;
while (!done)
{
testTime.add(dt);
double twoPIFreq = 2.0 * Math.PI * frequency.getDoubleValue();
comHeightIn = amplitude.getDoubleValue() * Math.sin(twoPIFreq * testTime.getDoubleValue());
comHeightVelocityIn = twoPIFreq * amplitude.getDoubleValue() * Math.cos(twoPIFreq * testTime.getDoubleValue());
comHeightAccelerationIn = -twoPIFreq * twoPIFreq * amplitude.getDoubleValue() * Math.sin(twoPIFreq * testTime.getDoubleValue());
comHeightDataIn.setComHeight(worldFrame, comHeightIn);
comHeightDataIn.setComHeightVelocity(comHeightVelocityIn);
comHeightDataIn.setComHeightAcceleration(comHeightAccelerationIn);
smoother.smooth(comHeightDataOut, comHeightDataIn);
if (visualize)
{
// ThreadTools.sleep((long) (dt * 1000));
scs.tickAndUpdate();
}
// else
{
if (testTime.getDoubleValue() > 3.0)
done = true;
}
}
if (visualize)
{
scs.cropBuffer();
ThreadTools.sleepForever();
}
}
}
| 36.643443 | 137 | 0.717705 |
378015cb6e0e12fbf2f1dce9efeaea64b7593518
| 449 |
package com.xxxx.service.impl;
import com.xxxx.pojo.SysMsg;
import com.xxxx.mapper.SysMsgMapper;
import com.xxxx.service.ISysMsgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author OriginalCoder
* @since 2021-02-03
*/
@Service
public class SysMsgServiceImpl extends ServiceImpl<SysMsgMapper, SysMsg> implements ISysMsgService {
}
| 21.380952 | 100 | 0.772829 |
85213de7951b21b7ac988d547ad2916148e8434d
| 14,671 |
/*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.physics.mixed;
import hmi.animation.SkeletonPose;
import hmi.animation.VJoint;
import hmi.math.Mat4f;
import hmi.math.Quat4f;
import hmi.math.Vec3f;
import hmi.physics.PhysicalHumanoid;
import hmi.physics.PhysicalSegment;
import hmi.physics.inversedynamics.IDBranch;
import hmi.physics.inversedynamics.IDSegment;
import hmi.util.PhysicsSync;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A system that contains a group of physically steered joints and 0 or more
* groups of kinematically steered groups, connected to the physical group with
* a @see{Connector}. Each frame, the torques and forces calculated from the
* movement of the kinematically steered part are applied to the physically
* steered group of joints
*
* @author welberge
*/
public class MixedSystem
{
private static final Logger logger = LoggerFactory.getLogger(MixedSystem.class.getName());
private ArrayList<Branch> branches = new ArrayList<Branch>();
private float spatialV0[] = new float[6];
private float spatialA0[] = new float[6];
private float f[];
private float gravity[] = new float[6];
private float mass;
private float com[] = new float[3];
// private float c[]=new float[3];
private float tempM1[] = new float[16];
private float tempM2[] = new float[16];
private float qTemp[] = new float[4];
private float vTemp[] = new float[4];
private float vTemp2[] = new float[4];
private float connectorTransform[] = new float[16];
private PhysicalHumanoid pHuman;
private SkeletonPose startPose;
/**
* Constructor
*
* @param g
* Vec3f of gravity acceleration
* @param p
* physical humanoid used for this system
*/
public MixedSystem(float[] g, PhysicalHumanoid p)
{
Vec3f.set(gravity, 3, g, 0);
pHuman = p;
}
/**
* Should be called once the Physical human is fully created, automatically
* called in MixedSystemAssembler
*/
public void setup()
{
PhysicalSegment[] phSegs = pHuman.getSegments();
String configs[] = new String[phSegs.length];
for (int i = 0; i < phSegs.length; i++)
{
configs[i] = phSegs[i].getSid();
}
startPose = new SkeletonPose("start", configs, "TRVW");
startPose.setTargets(pHuman.getSegments());
startPose.setFromTarget();
}
/**
* Sets the startup pose of the physical human, that is the pose to return
* to on reset
*/
public void setResetPose(VJoint v)
{
pHuman.setPoseFromVJoint(v);
startPose.setFromTarget();
}
/**
* Set the state of the idbranches to match the state of a PhysicalHumanoid
*
* @param p
*/
private void setIDFromPHuman(PhysicalHumanoid p)
{
for (Branch b : branches)
{
boolean changed = false;
for (IDSegment ids : b.idBranch.getSegments())
{
PhysicalSegment ps = p.getSegment(ids.name);
if (ps != null)
{
changed = true;
synchronized (PhysicsSync.getSync())
{
ps.getRotation(qTemp);
ps.getTranslation(vTemp);
}
}
}
if (changed)
{
// TODO: actually calculate connector velocities?
b.connector.reset();
}
}
}
private float aVel[] = new float[3];
private float aVelPrev[] = new float[3];
private float velPrev[] = new float[3];
private void setPHumanFromID(ArrayList<Branch> bs, float[] q, float w[])
{
int iq = 0;
int iw = 0;
for (Branch b : bs)
{
synchronized (PhysicsSync.getSync())
{
b.connector.getWorldTransform(connectorTransform);
}
b.connector.getAvelocity(aVelPrev);
b.connector.getVelocity(velPrev);
Mat4f.set(tempM1, connectorTransform);
for (IDSegment seg : b.idBranch.getSegments())
{
Mat4f.setIdentity(tempM2);
Mat4f.setRotation(tempM2, 0, q, iq);
Mat4f.setTranslation(tempM2, seg.translation);
Mat4f.mul(tempM1, tempM2);
Quat4f.setFromMat4f(qTemp, tempM1);
// test
/*
* Vec3f.set(vTemp2,seg.CoM); Vec3f.scale(-1,vTemp2);
* Mat4f.transformPoint(tempM1, vTemp, vTemp2);
*/
Mat4f.transformPoint(tempM1, vTemp, seg.com);
Quat4f.transformVec3f(q, iq, w, iw, aVel, 0);
Vec3f.add(aVel, aVelPrev);
PhysicalSegment ps = pHuman.getSegment(seg.name);
if (ps != null)
{
ps.setTranslation(vTemp);
logger.debug("Setting pos {} {} ",seg.name,Vec3f.toString(vTemp));
logger.debug("Setting rot {} {} local rot {}", new Object[]{seg.name,Quat4f.toString(qTemp),Quat4f.toString(q, iq)});
ps.setRotation(qTemp);
ps.setAngularVelocity(aVel);
Vec3f.scale(-1, vTemp2, ps.startJointOffset);
Vec3f.cross(vTemp, 0, w, iw, vTemp2, 0);
Vec3f.add(vTemp, velPrev);
ps.setVelocity(vTemp);
// TEST
/*
* ps.setVelocity(0,0,0); ps.setAngularVelocity(0,0,0);
*/
}
Vec3f.set(aVelPrev, aVel);
Vec3f.cross(vTemp, 0, w, iw, seg.translation, 0);
Vec3f.add(velPrev, vTemp);
iw += 3;
iq += 4;
}
}
}
private void setIDFromID(ArrayList<Branch> srcBranches)
{
for (Branch b : branches)
{
for (Branch bSrc : srcBranches)
{
if (bSrc.idBranch.getRoot().name
.equals(b.idBranch.getRoot().name))
{
b.connector.setVel(bSrc.connector);
}
}
}
}
/**
* Sets the system to s. That is: - Set the state of the pHuman to match
* that of s.pHuman - Set the state of the ID branches, to match that of
* s.branches - Set the velocity and position of segments in the pHuman to
* match that of the velocity in s.branches in matching segments - Set the
* connector velocity to match the velocity in s.pHuman (currently just set
* to 0)
*/
public void set(MixedSystem s, float q[], float w[])
{
// set matching physical segments
pHuman.set(s.pHuman);
// previous humanoid had no segments, set CoM to current CoM
if (s.pHuman.getRootSegment() == null && s.pHuman.getSegments().length == 0)
{
pHuman.updateCOM(0);
}
// set matching ID branches
setIDFromID(s.branches);
// ID from s to pHuman
setIDFromPHuman(s.pHuman);
// pHuman in s to ID
setPHumanFromID(s.branches, q, w);
}
/**
* Resets the velocity and acceleration of the connectors
*
* @param vj
* next joint, will contain start pose
*/
public void reset(VJoint vj)
{
synchronized (PhysicsSync.getSync())
{
logger.debug("Mixed system reset");
startPose.setToTarget();
for (PhysicalSegment ps : pHuman.getSegments())
{
ps.box.setForce(0, 0, 0);
ps.box.setTorque(0, 0, 0);
}
// pHuman.setCOMOffset(Vec3f.getZero(), 0);
setMassOffset(vj);
pHuman.updateCOM(0);
for (Branch b : branches)
{
b.connector.reset();
}
}
}
/**
* Adds a kinematic branch
*
* @param ch
* the chain to add
* @param con
* the connector
*/
public void addBranch(IDBranch idb, Connector con)
{
Branch b = new Branch();
b.connector = con;
b.idBranch = idb;
branches.add(b);
}
/**
* Set the feedback ratio for all connectors
*
* @param k
* the new feedback ratio
*/
public void setFeedbackRatio(float k)
{
for (Branch b : branches)
{
b.connector.setFeedbackRatio(k);
}
}
public int getRots(VJoint vj, IDSegment seg, int i, float[] q)
{
for (IDSegment s : seg.getChildren())
{
vj.getPart(s.name).getRotation(q, i);
i = getRots(vj, s, i + 4, q);
}
return i;
}
public void setMassOffset(VJoint vj)
{
int i = 0;
float q[] = new float[vj.getParts().size() * 4];
for (Branch b : branches)
{
for (IDSegment seg : b.idBranch.getRoot().getChildren())
{
vj.getPart(seg.name).getRotation(q, i);
i = getRots(vj, seg, i + 4, q);
}
}
setMassOffset(q);
}
/**
* set mass offset to the physical humanoid based on joint rotations of
* kinematicly controlled joints
*/
public void setMassOffset(float q[])
{
mass = 0;
int iq = 0;
Vec3f.set(com, 0, 0, 0);
for (Branch b : branches)
{
synchronized (PhysicsSync.getSync())
{
mass += b.getMassOffset(q, iq, com);
}
iq += 4 * b.idBranch.getSize();
}
synchronized (PhysicsSync.getSync())
{
pHuman.setCOMOffset(com, mass);
}
}
/**
* Solves ID for kinematically steered objects Applies reactive torques to
* the physical part and sets the CoM on the physical part. Rotations,
* velocities and angular accelerations are to be provided in one array for
* all chains ordered as: chain1:joint1, chain1:joint2, ..,
* chain1:jointN,chain2:joint1, ... joint 1 is the joint that is the closest
* to the connector. Connector velocities and accelerations are calculated
* based on connector positions from the previous frame.
*
* @param timeDiff
* time since last update
* @param q
* rotations of the joints in the branches
* @param w
* angular velocity of the joints in the branches
* @param wDiff
* angular acceleration of the joints in the branches
*/
public void time(float timeDiff, float q[], float w[], float wDiff[])
{
int iq = 0;
int iw = 0;
for (Branch b : branches)
{
synchronized (PhysicsSync.getSync())
{
b.connector.getSpatialVelocityAndAcceleration(timeDiff,
spatialV0, spatialA0, gravity);
}
// System.out.println("SpatialV0 :"+SpatialVec.toString(spatialV0));
// System.out.println("SpatialA0 :"+SpatialVec.toString(spatialA0));
// TEST
// SpatialVec.set(spatialA0,0,0,0,0,0,0);
// SpatialVec.set(spatialV0,0,0,0,0,0,0);
// Solve inverse dynamics in the chain. Possible optimization: add
// indexing to solver
float qi[] = new float[b.idBranch.getSize() * 4];
float wi[] = new float[b.idBranch.getSize() * 3];
float diffwi[] = new float[b.idBranch.getSize() * 3];
System.arraycopy(q, iq, qi, 0, qi.length);
System.arraycopy(w, iw, wi, 0, wi.length);
System.arraycopy(wDiff, iw, diffwi, 0, diffwi.length);
f = new float[6 * b.idBranch.getSize()];
// b.idBranch.solver.solveChain(f, spatialV0, spatialA0, qi, wi,
// diffwi);
b.idBranch.solver.solve(f, spatialV0, spatialA0, qi, wi, diffwi);
// System.out.println(b.kChain.joints[0].getName());
// System.out.println(iq+": "+SpatialVec.toString(f));
synchronized (PhysicsSync.getSync())
{
// System.out.println("applying torque on "+b.idBranch.getRoot().name);
// System.out.println("torque: "+SpatialVec.toString(f));
b.connector.applyReactiveTorque(qi, f);
}
iq += qi.length;
iw += wi.length;
}
setMassOffset(q);
}
/**
* @return the branches
*/
public ArrayList<Branch> getBranches()
{
return branches;
}
/**
* Creates a IDSegment, overwrite in subclasses to create a specific
* subclass of IDSegment
*
* @return a new IDSegment
*/
public IDSegment createIDSegment()
{
return new IDSegment();
}
/**
* @return the pHuman
*/
public PhysicalHumanoid getPHuman()
{
return pHuman;
}
}
| 32.821029 | 138 | 0.527708 |
fb1b0705a1f7dac3da595e9ebed106b4c6d2557e
| 3,634 |
/*
* 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.openide.explorer.view;
import org.openide.nodes.Node;
import java.awt.Point;
import java.awt.dnd.*;
import javax.swing.JList;
/**
*
* @author Dafe Simonek, Jiri Rechtacek
*/
class ListViewDragSupport extends ExplorerDragSupport {
// Attributes
/** Holds selected indices - it's here only
* as a workaround for sun's bug */
/*int[] oldSelection;
int[] curSelection;*/
// Associations
/** The view that manages viewing the data in a tree. */
protected ListView view;
/** The tree which we are supporting (our client) */
protected JList list;
// Operations
/** Creates new TreeViewDragSupport, initializes gesture */
public ListViewDragSupport(ListView view, JList list) {
this.comp = list;
this.view = view;
this.list = list;
}
int getAllowedDropActions() {
return view.getAllowedDropActions();
}
protected int getAllowedDragActions() {
return view.getAllowedDragActions();
}
/** Initiating the drag */
public void dragGestureRecognized(DragGestureEvent dge) {
super.dragGestureRecognized(dge);
}
/** Utility method. Returns either selected nodes in the list
* (if cursor hotspot is above some selected node) or the node
* the cursor points to.
* @return Node array or null if position of the cursor points
* to no node.
*/
@Override
Node[] obtainNodes(DragGestureEvent dge) {
Point dragOrigin = dge.getDragOrigin();
int index = list.locationToIndex(dragOrigin);
if (index < 0) {
return null;
}
Object obj = list.getModel().getElementAt(index);
if (obj instanceof VisualizerNode) {
obj = ((VisualizerNode) obj).node;
}
// check conditions
if ((index < 0)) {
return null;
}
if (!(obj instanceof Node)) {
return null;
}
Node[] result = null;
if (list.isSelectedIndex(index)) {
// cursor is above selection, so return all selected indices
Object[] selected = list.getSelectedValues();
result = new Node[selected.length];
for (int i = 0; i < selected.length; i++) {
if (selected[i] instanceof VisualizerNode) {
result[i] = ((VisualizerNode) selected[i]).node;
} else {
if (!(selected[i] instanceof Node)) {
return null;
}
result[i] = (Node) selected[i];
}
}
} else {
// return only the node the cursor is above
result = new Node[] { (Node) obj };
}
return result;
}
}
// end of ListViewDragSupport
| 28.390625 | 72 | 0.609246 |
048329da00e30455941cc851fcfb7b7af3c8db1a
| 2,080 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008 jOpenDocument, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU
* General Public License Version 3 only ("GPL").
* You may not use this file except in compliance with the License.
* You can obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.html
* See the License for the specific language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*
*/
package org.jopendocument.util;
import java.util.HashMap;
import java.util.Map;
import org.jopendocument.util.StringUtils.Escaper;
public final class FileUtils {
private FileUtils() {
// all static
}
// **io
private static final Map<String, String> ext2mime;
static {
ext2mime = new HashMap<>();
ext2mime.put(".xml", "text/xml");
ext2mime.put(".jpg", "image/jpeg");
ext2mime.put(".png", "image/png");
ext2mime.put(".tiff", "image/tiff");
}
/**
* Try to guess the media type of the passed file name (see <a
* href="http://www.iana.org/assignments/media-types">iana</a>).
*
* @param fname a file name.
* @return its mime type.
*/
public static final String findMimeType(String fname) {
for (final Map.Entry<String, String> e : ext2mime.entrySet()) {
if (fname.toLowerCase().endsWith(e.getKey()))
return e.getValue();
}
return null;
}
/**
* An escaper suitable for producing valid filenames.
*/
public static final Escaper FILENAME_ESCAPER = new StringUtils.Escaper('\'', 'Q');
static {
// from windows explorer
FILENAME_ESCAPER.add('"', 'D').add(':', 'C').add('/', 'S').add('\\', 'A');
FILENAME_ESCAPER.add('<', 'L').add('>', 'G').add('*', 'R').add('|', 'P').add('?', 'M');
}
}
| 32 | 102 | 0.597115 |
13e384690f7b5658a7dccf316e130411a9c5eb52
| 1,352 |
package com.dragovorn.dotaapi;
import com.dragovorn.dotaapi.match.IMatch;
import java.util.List;
/**
* Represents the basic API Object this is here for
* people that want to make their own implementations
* of the API. Default implementation: {@link Dota}.
*
* @author Andrew Burr
* @version 0.3
* @since 0.0.1
*/
public interface IDota {
/**
* Gets the a match by it's ID. (Doesn't cache the result, you'll have to do that)
*
* @param id The ID of the match you wish to get.
* @return The {@link IMatch} of the match.
*/
IMatch getMatchById(long id);
/**
* Gets the a match by it's Sequence ID. (Doesn't cache the result, you'll have to do that)
*
* @param id The Sequence ID of the match you wish to get.
* @return The {@link IMatch} of the match.
*/
IMatch getMatchBySeqId(long id);
/**
* Gets the a list of matches starting at the given Sequence ID. (Doesn't cache the results, you'll have to do that)
*
* @param id The Sequence ID to start at when bulk fetching matches.
* @param num The number of matches you want to fetch.
* @return A {@link List} of {@link IMatch}es of the matches.
*/
List<IMatch> getMatchesStartingAtSeqId(long id, int num);
List<IMatch> getMatchHistory();
List<IMatch> getMatchHistory(int num);
}
| 29.391304 | 120 | 0.653107 |
a39d8777355a5f9daa96a808059fb45bf5d48808
| 1,656 |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.language.process;
/**
* A single token produced by the tokenizer.
*
* @author Mathias Mølster Lidal
*/
public interface Token {
/** Returns the type of this token - word, space or punctuation etc. */
TokenType getType();
/** Returns the original form of this token */
String getOrig();
/** Returns the number of stem forms available for this token. */
int getNumStems();
/** Returns the stem at position i */
String getStem(int i);
/**
* Returns the number of components, if this token is a compound word
* (e.g. german "kommunikationsfehler". Otherwise, return 0
*
* @return number of components, or 0 if none
*/
int getNumComponents();
/** Returns a component token of this */
Token getComponent(int i);
/** Returns the offset position of this token */
long getOffset();
/** Returns the script of this token */
TokenScript getScript();
/**
* Returns the token string in a form suitable for indexing: The
* most lowercased variant of the most processed token form available,
* If called on a compound token this returns a lowercased form of the
* entire word.
* If this is a special token with a configured replacement,
* this will return the replacement token.
*/
String getTokenString();
/** Returns whether this is an instance of a declared special token (e.g. c++) */
boolean isSpecialToken();
/** Whether this token should be indexed */
boolean isIndexable();
}
| 29.052632 | 104 | 0.663043 |
3cdca14fb1d54b123f1522053d2a98b2205a20f2
| 3,609 |
/*
* Copyright 2016 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.manager.api.es.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author ewittman
*/
public class SearchSourceBuilder extends AbstractQueryBuilder {
private QueryBuilder query;
private Integer from;
private Integer size;
private List<SortInfo> sorts = new ArrayList<>();
private String[] fetchIncludes;
@SuppressWarnings("unused")
private String[] fetchExcludes;
private boolean fetchSource;
/**
* Constructor.
*/
public SearchSourceBuilder() {
}
public SearchSourceBuilder query(QueryBuilder query) {
this.query = query;
return this;
}
public SearchSourceBuilder size(int size) {
this.size = size;
return this;
}
public SearchSourceBuilder fetchSource(String[] includes, String[] excludes) {
this.fetchIncludes = includes;
this.fetchExcludes = excludes;
return this;
}
public SearchSourceBuilder sort(String fieldName, SortOrder order) {
sorts.add(new SortInfo(fieldName, order));
return this;
}
public SearchSourceBuilder from(int from) {
this.from = from;
return this;
}
public SearchSourceBuilder fetchSource(boolean fetch) {
this.fetchSource = fetch;
return this;
}
/**
* @see io.apiman.manager.api.es.util.AbstractQueryBuilder#doXContent(io.apiman.manager.api.es.util.XContentBuilder)
*/
@SuppressWarnings("nls")
@Override
protected void doXContent(XContentBuilder builder) throws IOException {
if (from != null) {
builder.field("from", from);
}
if (size != null) {
builder.field("size", size);
}
if (query != null) {
builder.field("query");
query.toXContent(builder);
}
if (!sorts.isEmpty()) {
builder.startArray("sort");
for (SortInfo sortInfo : sorts) {
builder.startObject();
builder.startObject(sortInfo.sortFieldName);
builder.field("order", sortInfo.sortOrder.toString());
builder.endObject();
builder.endObject();
}
builder.endArray();
}
if (fetchSource) {
builder.field("_source", true);
}
if (fetchIncludes != null) {
builder.field("_source");
builder.startObject();
builder.array("include", fetchIncludes);
builder.endObject();
}
}
private static class SortInfo {
public String sortFieldName;
public SortOrder sortOrder;
/**
* Constructor.
* @param fieldName
* @param order
*/
public SortInfo(String fieldName, SortOrder order) {
this.sortFieldName = fieldName;
this.sortOrder = order;
}
}
}
| 26.932836 | 120 | 0.598781 |
35ea90901793c50742c812304612e7a177e22536
| 140 |
package ru.dragonestia.dguard.custom;
import cn.nukkit.Player;
public interface CanDoAllCondition {
boolean check(Player player);
}
| 14 | 37 | 0.771429 |
47738f86e2dcaf95ba4ac513f0ee62a9a3157de6
| 1,139 |
package com.BankingApp.util;
public final class QueryMapper {
public static final String getUser="FROM User where userId=:uid and Password=:password and lockStatus=:lock";
public static final String validateUser="FROM User where userId=:uid and lockStatus=:lock";
public static final String checkAnswer="FROM User where secretQues=:secretquest and Ans=:answer";
public static final String getCustomer="FROM Customer where accountid=:accountId";
public static final String checkUser="FROM User where Password=:pwd and userId=:uid";
public static final String getMultipleServcie="FROM ServiceTracker where accId=:accountid";
public static final String getAdmin="From BankAdmin where adminid=:adminId and adminpassword=:adminPassword";
public static final String getRequests="FROM CustomerRequests where status=:status";
public static final String getOpenService="FROM ServiceTracker where serviceStatus=:status";
public static final String findRequest="From ServiceTracker where accId=:accountid and serviceDesc=:servdesc and serviceStatus=:status";
public static final String getTransactions="FROM Transactions where accountNo=:accid";
}
| 75.933333 | 136 | 0.823529 |
fb37c78d436b5aaf0f648953c081d61ee0218c8f
| 202 |
package org.jesperancinha.jtd.jee.mastery1.exception;
public class NotIndieMusicException extends RuntimeException {
public NotIndieMusicException(String message) {
super(message);
}
}
| 25.25 | 62 | 0.767327 |
bb92c1e6930751a82a4d3f9a64c98bbddde5297e
| 2,382 |
package com.winterwell.nlp.chat;
import java.util.List;
import java.util.Map;
import com.winterwell.nlp.classifier.LSlice;
import com.winterwell.nlp.io.Tkn;
import com.winterwell.utils.Key;
import com.winterwell.utils.containers.ArrayMap;
import com.winterwell.utils.containers.ListMap;
import com.winterwell.utils.containers.Slice;
import com.winterwell.utils.containers.Tree;
/**
*
* Stackable Has text speaker-ids anaphora-references / entity-references
* annotations/tags speaker obligations??
*
* @author daniel
*
*/
public class Discourse extends Tree<Slice> {
public static final class DRef {
Discourse context;
String id;
}
public static final Key<String> PROP_ANAPHORA = new Key("anaphora");
public static final Key<String> PROP_POS = Tkn.POS;
public static final Key<String> PROP_SPEAKER = new Key("person");
private final Map<String, Thingy> name2thing = new ArrayMap();
final ListMap<String, LSlice> tags = new ListMap();
public Discourse(Discourse parent, Slice text) {
super(parent, text);
assert text != null : this;
// check text inclusion
if (parent != null) {
assert parent.getValue().contains(text) : parent.getValue()
+ " vs " + text;
}
}
public Discourse(String text) {
this(null, new Slice(text));
}
/**
* @param <X>
* @param property
* @param value
* A span with the property value as it's label. This labelled
* region can spill beyond the slice covered by this Discourse
* object.
*/
public <X> void annotate(Key<X> property, LSlice<X> value) {
assert getValue().overlap(value) != null : value + " not in "
+ getText();
tags.add(property.getName(), value);
}
public <X> List<LSlice<X>> getAnnotations(Key<X> property) {
List annos = tags.get(property.getName());
return annos;
}
@Override
public List<Discourse> getChildren() {
return (List<Discourse>) super.getChildren();
}
@Override
public Discourse getParent() {
return (Discourse) super.getParent();
}
public Slice getText() {
return getValue();
}
/**
* Recursive de-ref of name.
*
* @param name
* What is it?
* @return Thingy or null
*/
public Thingy getThing(String name) {
Thingy thing = name2thing.get(name);
if (thing != null)
return thing;
if (getParent() == null)
return null;
return getParent().getThing(name);
}
}
| 23.82 | 74 | 0.680521 |
473bbc1fab5c967ff7c2f5565b7f8e89401552df
| 3,570 |
/*
* 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.reef.io.network.group.api.driver;
import org.apache.reef.annotations.Provided;
import org.apache.reef.annotations.audience.DriverSide;
import org.apache.reef.driver.context.ActiveContext;
import org.apache.reef.io.network.group.impl.driver.GroupCommDriverImpl;
import org.apache.reef.tang.Configuration;
import org.apache.reef.tang.annotations.DefaultImplementation;
import org.apache.reef.tang.annotations.Name;
/**
* The driver side interface of Group Communication.
* which is the entry point for the service
*/
@DriverSide
@Provided
@DefaultImplementation(value = GroupCommDriverImpl.class)
public interface GroupCommDriver {
/**
* Create a new communication group with the specified name.
* and the minimum number of tasks needed in this group before
* communication can start
*
* @param groupName
* @param numberOfTasks
* @return
*/
CommunicationGroupDriver newCommunicationGroup(Class<? extends Name<String>> groupName, int numberOfTasks);
/**
* Create a new communication group with the specified name,
* the minimum number of tasks needed in this group before
* communication can start, and a custom fanOut.
*
* @param groupName
* @param numberOfTasks
* @param customFanOut
* @return
*/
CommunicationGroupDriver newCommunicationGroup(Class<? extends Name<String>> groupName, int numberOfTasks,
int customFanOut);
/**
* Create a new communication group with the specified name, topology implementation,
* the minimum number of tasks needed in this group before
* communication can start, and a custom fanOut.
*
* @param groupName
* @param topologyClass
* @param numberOfTasks
* @param customFanOut
* @return
*/
CommunicationGroupDriver newCommunicationGroup(Class<? extends Name<String>> groupName,
Class<? extends Topology> topologyClass,
int numberOfTasks,
int customFanOut);
/**
* Tests whether the activeContext is a context configured.
* using the Group Communication Service
*
* @param activeContext
* @return
*/
boolean isConfigured(ActiveContext activeContext);
/**
* @return Configuration needed for a Context that should have
* Group Communication Service enabled
*/
Configuration getContextConfiguration();
/**
* @return Configuration needed to enable
* Group Communication as a Service
*/
Configuration getServiceConfiguration();
/**
* @return Configuration needed for a Task that should have
* Group Communication Service enabled
*/
Configuration getTaskConfiguration(Configuration partialTaskConf);
}
| 33.679245 | 109 | 0.716246 |
32a3204d17156856d62ab020ff1c2d130209d03d
| 5,806 |
package com.alicegabbana.cahierenligne.services.role;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.apache.log4j.Logger;
import com.alicegabbana.cahierenligne.dto.RoleDto;
import com.alicegabbana.cahierenligne.entities.Role;
@Stateless
public class RoleService implements RoleServiceRemote, RoleServiceLocal {
private static final long serialVersionUID = -7710388624873133691L;
@PersistenceContext(unitName = "MariadbConnexion")
EntityManager em;
Logger logger = Logger.getLogger(RoleService.class);
public Role create(Role role) throws RoleException {
try {
get(role.getName());
throw new RoleException(409, "Role already created !");
} catch (Exception e) {
Role roleCreated = em.merge(role);
return roleCreated;
}
}
public Role get(String name) throws RoleException {
Role role = em.find(Role.class, name);
if (role == null) {
throw new RoleException(404, "Role "+name+" does not exist !");
}
return role;
}
public List<RoleDto> getAll() {
TypedQuery<Role> query_roles = em.createQuery("SELECT role FROM Role role", Role.class);
List<Role> loadedRoles = query_roles.getResultList();
List<RoleDto> roleDtoList = roleListToRoleDtoList(loadedRoles);
return roleDtoList;
}
public RoleDto daoToDto(Role role) {
RoleDto roleDto = new RoleDto();
if (role != null) {
if (role.getName() != null) roleDto.setName(role.getName());
}
return roleDto;
}
private List<RoleDto> roleListToRoleDtoList (List<Role> roleList) {
List<RoleDto> roleDtoList = new ArrayList<RoleDto>();
for (Role role : roleList) {
RoleDto roleDto = daoToDto(role);
roleDtoList.add(roleDto);
}
return roleDtoList;
}
// @EJB
// RoleDao roleDao;
//
//// @EJB
//// ActionServiceLocal actionService;
//
// public Role create (Role role) {
// Role roleCreated = roleDao.create(role);
// return roleCreated;
// }
//
// @PersistenceContext(unitName = "MariadbConnexion")
// EntityManager em;
//
// @EJB
// AuthService authService;
//
// public boolean nameExist (String name) {
//
// if ( roleDao.getRoleByName(name) == null ) return false;
// return true;
// }
//
// public RoleDto daoToDto (Role role) {
//
// RoleDto roleDto = new RoleDto();
// if (role != null) {
// roleDto.setId(role.getId());
// roleDto.setName(role.getName());
// if (role.getActions() != null) {
// final List<String> actionsList = new ArrayList<String>();
// role.getActions().forEach(new Consumer<Action>() {
// public void accept(Action action) {
// actionsList.add(action.getName());
// }
// });
// roleDto.setActions(actionsList);
// }
// }
//
// return roleDto;
// }
//
// public Role dtoToDao (RoleDto roleDto) {
//
// Role role = new Role();
// if (roleDto != null) {
// if (roleDto.getId() != null) role.setId(roleDto.getId());
// if (roleDto.getName() != null) role.setName(roleDto.getName());
// }
// return role;
// }
//
// public List<RoleDto> daoListToDtoList (List<Role> roleList) {
//
// List<RoleDto> roleDtoList = new ArrayList<RoleDto>();
// for (Role role : roleList) {
// RoleDto roleDto = daoToDto(role);
// roleDtoList.add(roleDto);
// }
//
// return roleDtoList;
// }
//
// public RoleDto createService ( RoleDto roleDto) {
// Role role = dtoToDao(roleDto);
// Role roleCreated = em.merge(role);
// RoleDto roleDtoCreated = daoToDto(roleCreated);
// return roleDtoCreated;
// }
//
// public void deleteService ( Long roleId) {
// Role role = em.find(Role.class, roleId);
// em.remove(role);
// }
//
// public RoleDto updateService ( RoleDto roleDto) {
// Role roleToUpdate = getDaoByIdService(roleDto.getId());
// roleToUpdate.setName(roleDto.getName());
// Role updatedRole = em.merge(roleToUpdate);
// RoleDto roleDtoUpdated = daoToDto(updatedRole);
// return roleDtoUpdated;
// }
//
//// public RoleDto addActionService ( Long roleId, List<Long> actionsIdToAdd ) {
//// Role role = getDaoByIdService(roleId);
////
//// final List<Action> actionsList = role.getActions();
////
//// actionsIdToAdd.forEach(new Consumer<Long>() {
//// public void accept(Long actionID) {
//// Action action = actionService.getByIdService(actionID);
//// if ( !actionsList.contains(action)) actionsList.add(action);
//// }
//// });
////
//// role.setActions(actionsList);
//// Role roleUpdated = em.merge(role);
//// return daoToDto(roleUpdated);
//// }
////
//// public RoleDto removeActionService ( Long roleId, List<Long> actionsIdToremove ) {
//// Role role = getDaoByIdService(roleId);
//// final List<Action> roleActionsList = role.getActions();
////
//// actionsIdToremove.forEach(new Consumer<Long>() {
//// public void accept(Long actionID) {
//// Action action = actionService.getByIdService(actionID);
//// if ( roleActionsList.contains(action)) roleActionsList.remove(action);
//// }
//// });
////
//// role.setActions(roleActionsList);
//// Role roleUpdated = em.merge(role);
//// return daoToDto(roleUpdated);
//// }
//
// public Role getDaoByIdService (Long roleId) {
// Role role = roleDao.getRoleById(roleId);
// return role;
// }
//
// public Role getDaoByName (String name) {
// return roleDao.getRoleByName(name);
// }
//
// public List<RoleDto> getAllService () {
// List<Role> loadedRoles = roleDao.getAllRoles();
// if ( loadedRoles != null) {
// List<RoleDto> roleDtoList = daoListToDtoList(loadedRoles);
// return roleDtoList;
// }
// return null;
// }
//
// public List<Action> getActionService ( RoleDto roleDto) {
//
// List<Action> actionList = roleDao.getActionFromRole(roleDto.getId());
// return actionList;
// }
}
| 27.516588 | 90 | 0.671547 |
402b508efe466689bb2c374b7d3e52bc3f52cb65
| 162 |
package com.iaz.HIgister.ui.login;
import com.iaz.HIgister.ui.base.MvpView;
public interface AuthMvpView extends MvpView {
AuthActivity getActivity();
}
| 14.727273 | 46 | 0.765432 |
e8b9781670677fbac8ca54b1bf54114f4d03bc70
| 27,991 |
/*
* The MIT License
*
* Copyright (c) 2016, AbsInt Angewandte Informatik GmbH
* Author: Dr.-Ing. Joerg Herter
* Email: herter@absint.com
*
* 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.absint.astree;
import hudson.Proc;
import hudson.Launcher;
import hudson.Extension;
import hudson.FilePath;
import hudson.util.FormValidation;
import hudson.model.AbstractProject;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import javax.servlet.ServletException;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
*
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked
* and a new {@link AstreeBuilder} is created. The created
* instance is persisted to the project configuration XML by using
* XStream, so this allows you to use instance fields
* to remember the configuration.
*
* When a build is performed, the {@link #perform} method will be invoked.
*
* @author AbsInt Angewandte Informatik GmbH
*/
public class AstreeBuilder extends Builder implements SimpleBuildStep {
private static final String PLUGIN_NAME = "Astrée for C Jenkins PlugIn";
private static final String BUILD_NR = "18.10";
private static final String TMP_REPORT_FILE = "absint_astree_analysis_report";
private static final String TMP_PREPROCESS_OUTPUT = "absint_astree_preprocess_output.txt";
private String dax_file, output_dir, analysis_id;
private FailonSwitch failonswitch;
private boolean genXMLOverview, genXMLCoverage, genXMLAlarmsByOccurence,
genXMLAlarmsByCategory, genXMLAlarmsByFile, genXMLRulechecks,
genPreprocessOutput, dropAnalysis;
private boolean skip_analysis;
private Proc proc; // reference to an associated a3c client process
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public AstreeBuilder( String dax_file, String analysis_id, String output_dir, boolean skip_analysis,
boolean genXMLOverview, boolean genXMLCoverage, boolean genXMLAlarmsByOccurence,
boolean genXMLAlarmsByCategory, boolean genXMLAlarmsByFile, boolean genXMLRulechecks,
boolean dropAnalysis, boolean genPreprocessOutput, FailonSwitch failonswitch,
AnalysisServerConfiguration analysisSrv
)
{
this.dax_file = dax_file;
this.analysis_id = analysis_id;
this.output_dir = output_dir;
this.skip_analysis = skip_analysis;
this.failonswitch = failonswitch;
this.genXMLOverview = genXMLOverview;
this.genXMLCoverage = genXMLCoverage;
this.genXMLAlarmsByOccurence = genXMLAlarmsByOccurence;
this.genXMLAlarmsByCategory = genXMLAlarmsByCategory;
this.genXMLAlarmsByFile = genXMLAlarmsByFile;
this.genXMLRulechecks = genXMLRulechecks;
this.dropAnalysis = dropAnalysis;
this.genPreprocessOutput = genPreprocessOutput;
}
/*
* Interface to <tt>config.jelly</tt>.
*/
/**
* Returns the currently set path to the DAX file used for the analysis run.
*
* @return java.lang.String
*/
public String getDax_file() {
return dax_file;
}
/**
* Returns the currently set analysis ID used for the analysis run.
*
* @return java.lang.String
*/
public String getAnalysis_id() {
return analysis_id;
}
/**
* Returns the currently set path used as output directory for the analyses.
*
* @return java.lang.String
*/
public String getOutput_dir() {
return output_dir;
}
/**
* Indicates whether the analysis run is configured to potentially fail a build.
*
* @return boolean
*/
public boolean isFailonswitch() {
return (this.failonswitch != null);
}
/**
* @return java.lang.String
*/
public String getFailon() {
if(this.failonswitch == null) return "";
return this.failonswitch.getFailon();
}
/**
* Indicates whether the analysis run is configured to
* be temporarily skipped (i.e., no analysis is to be done).
*
* @return boolean
*/
public boolean isSkip_analysis() {
return this.skip_analysis;
}
/**
* Indicates whether the analysis run is configured to produce the
* XML overview summary.
*
* @return boolean
*/
public boolean isGenXMLOverview() {
return this.genXMLOverview;
}
/**
* Indicates whether the analysis run is configured to produce the
* XML coverage summary.
*
* @return boolean
*/
public boolean isGenXMLCoverage() {
return this.genXMLCoverage;
}
/**
* Indicates whether the analysis run is configured to produce the
* XML alarms-by-occurence summary.
*
* @return boolean
*/
public boolean isGenXMLAlarmsByOccurence() {
return this.genXMLAlarmsByOccurence;
}
/**
* Indicates whether the analysis run is configured to produce the
* XML alarms-by-category summary.
*
* @return boolean
*/
public boolean isGenXMLAlarmsByCategory() {
return this.genXMLAlarmsByCategory;
}
/**
* Indicates whether the analysis run is configured to produce the
* XML alarms-by-file summary.
*
* @return boolean
*/
public boolean isGenXMLAlarmsByFile() {
return this.genXMLAlarmsByFile;
}
/**
* Indicates whether the analysis run is configured to produce the
* XML rule checks summary.
*
* @return boolean
*/
public boolean isGenXMLRulechecks() {
return this.genXMLRulechecks;
}
/**
* Indicates whether the analysis run is configured to produce the
* (text) preprocess output report.
*
* @return boolean
*/
public boolean isGenPreprocessOutput() {
return this.genPreprocessOutput;
}
/**
* Indicates whether the project is to be deleted on the server after
* the analysis run.
*
* @return boolean
*/
public boolean isDropAnalysis() {
return this.dropAnalysis;
}
/*
* end interface to <tt>config.jelly</tt>.
*/
/**
* Expands environment variables of the form
* ${VAR_NAME}
* by their current value.
*
* @param cmdln the java.lang.String, usually a command line,
* in which to expand variables
* @param envMap a java.util.Map containing the environment variables
* and their current values
* @param isUnix boolean
* @return the input String with environment variables expanded to their current value
*/
private static final String expandEnvironmentVarsHelper(
String cmdln, Map<String, String> envMap, boolean isUnix ) {
final String pattern = "\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}";
final Pattern expr = Pattern.compile(pattern);
Matcher matcher = expr.matcher(cmdln);
String envValue;
Pattern subexpr;
while (matcher.find()) {
envValue = envMap.get(matcher.group(1).toUpperCase());
if (envValue == null) {
envValue = "";
} else {
envValue = envValue.replace("\\", "\\\\");
}
subexpr = Pattern.compile(Pattern.quote(matcher.group(0)));
cmdln = subexpr.matcher(cmdln).replaceAll(envValue);
}
if(isUnix) {
return cmdln.replace('\\','/');
} else {
return cmdln.replace('/','\\');
}
}
/**
*/
private String constructCommandLineCall(String reportfile, String preprocessoutput ) {
String cmd = getDescriptor().getAlauncher();
boolean c1610 = getDescriptor().getComp1610();
cmd = cmd + " " + (c1610 ? "-a " : "") + "-b -s " +
getDescriptor().getAstree_server() + " " +
((!getDescriptor().getUser().trim().equals("") && !getDescriptor().getPassword().trim().equals("")) ?
( "--user " + getDescriptor().getUser() + "@" + getDescriptor().getPassword() ) : "") +
((this.analysis_id != null && !this.analysis_id.trim().equals("")) ?
(" --id " + this.analysis_id) : "" ) +
((this.dax_file != null && !this.dax_file.trim().equals("") ) ?
(" --import \"" + this.dax_file + "\"") : "") +
" --report-file " + "\"" + reportfile + ".txt\"" +
" --xml-report-file " + "\"" + reportfile + ".xml\"";
if(this.genPreprocessOutput)
cmd += " --preprocess-report-file " + "\"" + preprocessoutput + "\"";
if(this.dropAnalysis)
cmd += " --drop";
if(!c1610)
return cmd;
if(this.genXMLOverview)
cmd += " --report-overview " + "\"" + output_dir + "/Overview.xml\"";
if(this.genXMLCoverage)
cmd += " --report-coverage " + "\"" + output_dir + "/Coverage.xml\"";
if(this.genXMLAlarmsByOccurence)
cmd += " --report-alarmsByOccurence " + "\"" + output_dir + "/AlarmsByOccurence.xml\"";
if(this.genXMLAlarmsByCategory)
cmd += " --report-alarmsByCategory " + "\"" + output_dir + "/AlarmsByCategory.xml\"";
if(this.genXMLAlarmsByFile)
cmd += " --report-alarmsByFile " + "\"" + output_dir + "/AlarmsByFile.xml\"";
if(this.genXMLRulechecks)
cmd += " --report-rulechecks " + "\"" + output_dir + "/Rulechecks.xml\"";
return cmd;
}
@Override
public void perform(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) {
int exitCode = -1;
// Set some defaults and parameters.
if(output_dir == null || output_dir.equals(""))
output_dir = workspace.toString();
String reportfile = workspace.toString() + (launcher.isUnix() ? "/" : "\\") + TMP_REPORT_FILE;
FilePath rfile;
try {
// Analysis run started. ID plugin in Jenkins output.
listener.getLogger().println("This is " + PLUGIN_NAME + " in version " + BUILD_NR);
// Clear log file
rfile = new FilePath(workspace, TMP_REPORT_FILE + ".txt");
if( rfile.delete() )
listener.getLogger().println("Old log file erased.");
rfile.touch(System.currentTimeMillis());
listener.getLogger().println("New log file created.");
// Create log file reader thread
StatusPoller sp = new StatusPoller(1000, listener, rfile);
if(this.skip_analysis) {
listener.getLogger().println("Analysis run has been (temporarily) deactivated. Skipping analysis run.");
return; // nothing to do, exit method.
}
// Print some configuration info.
if(failonswitch != null)
listener.getLogger().println( "Astrée fails build on " + failonswitch.getFailon() );
String infoStringSummaryDest = "Summary reports will be generated in " + output_dir;
infoStringSummaryDest = expandEnvironmentVarsHelper(
"Summary reports will be generated in " + output_dir,
build.getEnvironment(listener),
launcher.isUnix());
listener.getLogger().println(infoStringSummaryDest);
String cmd = this.constructCommandLineCall( reportfile,
workspace.toString() + "/" + TMP_PREPROCESS_OUTPUT );
cmd = expandEnvironmentVarsHelper(cmd, build.getEnvironment(listener), launcher.isUnix());
sp.start(); // Start log file reader
proc = launcher.launch( cmd, // Command line call to Astree
build.getEnvironment(listener),
listener.getLogger(),
workspace );
exitCode = proc.join(); // Wait for Astree to finish
sp.kill(); // Stop log file reader
sp.join(); // Wait for log file reader to finish
if(exitCode == 0)
listener.getLogger().println("Analysis run succeeded.");
else
listener.getLogger().println("Analysis run failed.");
} catch (IOException e) {
e.printStackTrace();
listener.getLogger().println("IOException caught during analysis run.");
} catch (InterruptedException e) {
e.printStackTrace();
listener.getLogger().println("InterruptedException caught during analysis run.");
}
if(exitCode == 0) { // activities after successful analysis run
/* Read analysis summary and
check whether Astrée shall fail the build due to reported errors etc */
AnalysisSummary summary = AnalysisSummary.readFromReportFile(reportfile + ".txt");
if( failonswitch != null && failonswitch.failOnErrors()
&& summary.getNumberOfErrors() > 0) {
listener.getLogger().println( "Errors reported! Number of errors: " +
summary.getNumberOfErrors());
build.setResult(hudson.model.Result.FAILURE);
}
else if( failonswitch != null && failonswitch.failOnAlarms()
&& summary.getNumberOfAlarms() > 0) {
listener.getLogger().println( "Alarms reported! Number of alarms: " +
summary.getNumberOfAlarms());
build.setResult(hudson.model.Result.FAILURE);
}
else if( failonswitch != null && failonswitch.failOnFlowAnomalies()
&& ( summary.getNumberOfFlowAnomalies()
+ summary.getNumberOfAlarms() > 0) ) {
build.setResult(hudson.model.Result.FAILURE);
}
} else { // activities after unsuccessful analysis run
// If Astrée cannot be invoked, conservatively fail the build...
build.setResult(hudson.model.Result.FAILURE);
}
}
/**
* Override finalize method to ensure existing a3c client processes are killed upon destruction
* of AstreeBuilder objects.
*/
protected void finalize() {
try {
if(proc != null)
proc.kill();
} catch(Exception e) {
}
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
private void copyText2PrintStream( PrintStream dest, String srcPath ) {
dest.println("Appending analysis report.");
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(srcPath), "UTF-8" ));
String line = br.readLine() ;
while(line != null) {
dest.println(line);
line = br.readLine();
}
br.close();
} catch(IOException e) {
}
}
/**
* Descriptor for {@link AstreeBuilder}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*
* <br>
*/
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
/*
* To persist global configuration information,
* simply store it in a field and call save().
*
*
* If you don't want fields to be persisted, use "transient".
*/
/*
* Properties set by the Astree configuration mask:
* Jenkins~~~Manage Jenkins~~~Configure System
*/
private String alauncher;
private boolean comp1610;
private String astree_server;
private String user, password;
/**
* Constructor.
* <br>
* Constructs a new object of this class and
* loads the persisted global configuration.
*/
public DescriptorImpl() {
load();
}
/**
* Return the human readable name used in the configuration screen.
*
* @return java.lang.String
*/
public String getDisplayName() {
return "Astrée Analysis Run";
}
/**
* Performs on-the-fly validation of the form field 'astree_server'.
*
* @param value The value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
* <br>
* Note that returning {@link FormValidation#error(String)} does not
* prevent the form from being saved. It just means that a message
* will be displayed to the user.
* @throws IOException as super class
* @throws ServletException as super class
**/
public FormValidation doCheckAstree_server(@QueryParameter String value)
throws IOException, ServletException {
if(value == null || value.trim().equals("") )
return FormValidation.error("Please set a valid server of form <hostname>:<port>");
if ( !( value.matches("[a-zA-Z][a-zA-Z0-9\\.\\-]{0,22}[a-zA-Z0-9]:\\d{1,5}") /* hostname */
|| value.matches("(\\d{1,3}\\.){3,3}\\d{1,3}:\\d{1,5}" /* ip address */) ) )
return FormValidation.warning("The Astrée Server needs to be specified as a hostname followed by a colon followed by a port number.");
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'alauncher'.
*
* @param value The value that the user has typed.
* @param project unused
* @return
* Indicates the outcome of the validation. This is sent to the browser.
* <br>
* Note that returning {@link FormValidation#error(String)} does not
* prevent the form from being saved. It just means that a message
* will be displayed to the user.
* @throws IOException as super class
* @throws ServletException as super class
**/
public FormValidation doCheckAlauncher(@QueryParameter String value, AbstractProject project)
throws IOException, ServletException {
if(value == null || value.trim().equals("") )
return FormValidation.error("No file specified.");
File ftmp = new File(value);
if (!ftmp.exists())
return FormValidation.error("Specified file not found.");
if(!ftmp.isFile())
return FormValidation.error("Specified file is not a normal file.");
if (!ftmp.canExecute())
return FormValidation.error("Specified file cannot be executed.");
return FormValidation.ok();
}
/**
* Helper method to check whether a string contains an environment variable of form
* <br>${IDENTIFIER}<br>
*
* @param s String to scan for environment variable expressions
* @return Outcome of the check as a boolean (true if such an expression
* was found, otherwise false).
*/
public static final boolean containsEnvVars(String s)
{
final String pattern = "\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}";
final Pattern expr = Pattern.compile(pattern);
Matcher matcher = expr.matcher(s);
return matcher.find();
}
/**
* Performs on-the-fly validation of the form field 'dax_file'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
* <br>
* Note that returning {@link FormValidation#error(String)} does not
* prevent the form from being saved. It just means that a message
* will be displayed to the user.
* @throws IOException as super class
* @throws ServletException as super class
**/
public FormValidation doCheckDax_file(@QueryParameter String value)
throws IOException, ServletException {
if(value == null || value.trim().equals("") )
return FormValidation.warning("No file specified.");
if(containsEnvVars(value)) {
return FormValidation.warning("The specified path contains an environment variable, please make sure the constructed paths are correct.");
}
File ftmp = new File(value);
if (!ftmp.exists())
return FormValidation.error("Specified file not found.");
if (!ftmp.canRead())
return FormValidation.error("Specified file cannot be read.");
if (!value.endsWith(".dax"))
return FormValidation.warning("The specified file exists, but does not have the expected suffix (.dax).");
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'analysis_id'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
* <br>
* Note that returning {@link FormValidation#error(String)} does not
* prevent the form from being saved. It just means that a message
* will be displayed to the user.
* @throws IOException as super class
* @throws ServletException as super class
**/
public FormValidation doCheckAnalysis_id(@QueryParameter String value)
throws IOException, ServletException {
if(value == null || value.trim().equals("") )
return FormValidation.warning("No ID specified.");
if(containsEnvVars(value)) {
return FormValidation.warning("The ID contains an environment variable, please make sure that the constructed IDs are valid.");
}
if(!value.matches("\\d*"))
return FormValidation.error("ID is not valid.");
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'output_dir'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
* <br>
* Note that returning {@link FormValidation#error(String)} does not
* prevent the form from being saved. It just means that a message
* will be displayed to the user.
* @throws IOException as super class
* @throws ServletException as super class
**/
public FormValidation doCheckOutput_dir(@QueryParameter String value)
throws IOException, ServletException {
if(value == null || value.trim().equals("") )
return FormValidation.warning("No directory specified.");
if(containsEnvVars(value)) {
return FormValidation.warning("The specified path contains an environment variable, please make sure that the constructed paths are correct.");
}
File ftmp = new File(value);
if (!ftmp.exists())
return FormValidation.error("Specified directory not found.");
if (!ftmp.isDirectory())
return FormValidation.error("Specified path is no directory.");
if (!ftmp.canRead() || !ftmp.canWrite())
return FormValidation.warning("No permissions to read/write the specified directory.");
return FormValidation.ok();
}
/**
* Indicates that this builder can be used with all kinds of project types.
*
* @return boolean
*/
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
/**
* Sets a new configuration.
*
* @throws FormException as super class
*/
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
// To persist global configuration information,
// set that to properties and call save().
this.alauncher = formData.getString("alauncher");
this.comp1610 = formData.getBoolean("comp1610");
this.astree_server = formData.getString("astree_server");
this.user = formData.getString("user");
this.password = formData.getString("password");
// ... data set, so call save():
save();
return super.configure(req,formData);
}
/**
* Returns the currently configured Astrée server
* (as <i>host:port</i>).
*
* @return java.lang.String
*/
public String getAstree_server() {
return this.astree_server;
}
/**
* Returns the currently configured alauncher.
*
* @return java.lang.String
*/
public String getAlauncher() {
return this.alauncher;
}
/**
* Returns the status of compatibility mode with release 16.10.
*
* @return boolean
*/
public boolean getComp1610() {
return this.comp1610;
}
/**
* Returns the currently configured Astrée user.
*
* @return java.lang.String
*/
public String getUser() {
return this.user;
}
/**
* Returns the currently configured Astrée (user) password.
*
* @return java.lang.String
*/
public String getPassword() {
return this.password;
}
}
}
| 37.321333 | 158 | 0.593441 |
c44c1c898e36b7327614b6839e65fe611871d5e8
| 3,793 |
package com.example.application.views.order;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.example.application.data.entity.Envio;
import com.example.application.data.entity.Producto;
import com.example.application.views.Mainshop.MainViewShop;
import com.example.application.views.login.LoginView;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.router.AfterNavigationEvent;
import com.vaadin.flow.router.AfterNavigationObserver;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.VaadinSession;
@Route(value = "TotalOrders", layout = MainViewShop.class)
@PageTitle("Total Orders")
@CssImport("./views/orders/totalorders-view.css")
public class TotalOrdersView extends Div {
//Inicialización parametros conexión BBDD
String url = "jdbc:postgresql://localhost:5432/postgres";
String user = "postgres";
String pass = "1234";
Grid<Envio> grid = new Grid<>();
List<Envio> totalOrders = new ArrayList<>();
ListDataProvider<Envio> data = new ListDataProvider<>(totalOrders);
public TotalOrdersView() {
setId("totalorders-view");
addClassName("totalorders-view");
SplitLayout splitLayout = new SplitLayout();
splitLayout.setSizeFull();
createGridLayout(splitLayout);
add(splitLayout);
try {
PreparedStatement pst;
Connection con = DriverManager.getConnection(url, user, pass);
pst = con.prepareStatement("SELECT * from \"NEWDDBB1\".\"Order\" o WHERE o.username = '" + VaadinSession.getCurrent().getAttribute("user") + "'" );
ResultSet rs = pst.executeQuery();
while (rs.next()) {
Envio envio= new Envio(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getInt(5),rs.getString(6));
this.totalOrders.add(envio);
}
} catch (SQLException e1) {
e1.printStackTrace();
//Notification.show(e1.getMessage());
}
grid.setDataProvider(data);
grid.addColumn(Envio::getIdOrder).setHeader("Nº Pedido").setAutoWidth(true);
grid.addColumn(Envio::getUsername).setHeader("Usuario").setAutoWidth(true);
grid.addColumn(Envio::getAddress).setHeader("Direccion").setAutoWidth(true);
grid.addColumn(Envio::getTrackingNumber).setHeader("Nº Seguimiento").setAutoWidth(true);
grid.addColumn(Envio::getPrice).setHeader("Precio").setAutoWidth(true);
grid.addColumn(Envio::getState).setHeader("Estado").setAutoWidth(true);
grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);
grid.setHeightFull();
}
private void createGridLayout(SplitLayout splitLayout) {
Div wrapper = new Div();
wrapper.setId("grid-wrapper");
wrapper.setWidthFull();
splitLayout.addToPrimary(wrapper);
wrapper.add(grid);
}
}
| 34.171171 | 152 | 0.700501 |
af291014279fbf1fc260403c97b4bd9648c6b175
| 400 |
package model;
public class Man extends Person {
private boolean beforeAgeEleven;
public Man(boolean man, boolean diabetic, boolean beforeAgeEleven) {
super(man, diabetic);
this.beforeAgeEleven = beforeAgeEleven;
}
public boolean isBeforeAgeEleven() {
return beforeAgeEleven;
}
public void setBeforeAgeEleven(boolean beforeAgeEleven) {
this.beforeAgeEleven = beforeAgeEleven;
}
}
| 20 | 69 | 0.7725 |
0a9bc9e8531d5de88bdeb5dfe758f153b75a5372
| 2,268 |
package com.googlecode.javaewah32;
import com.googlecode.javaewah.EWAHCompressedBitmap;
import com.googlecode.javaewah.IntIterator;
import java.util.BitSet;
import com.googlecode.javaewah.BackwardBitSetIterator;
import com.googlecode.javaewah.ForwardBitSetIterator;
// credit @svanmald
public class EWAH32BitSetPair {
private EWAHCompressedBitmap bitmap;
private BitSet bitSet;
public EWAH32BitSetPair() {
bitmap = new EWAHCompressedBitmap();
bitSet = new BitSet();
}
public void validate() {
assert bitmap.cardinality() == bitSet.cardinality();
ForwardBitSetIterator forwardBitSetIterator = new ForwardBitSetIterator(bitSet);
for (Integer current : bitmap) {
Integer next = forwardBitSetIterator.next();
assert bitmap.get(current);
assert next.equals(current);
}
BackwardBitSetIterator backwardBitSetIterator = new BackwardBitSetIterator(bitSet);
IntIterator reverseIterator = bitmap.reverseIntIterator();
while (reverseIterator.hasNext()) {
int nextBitMap = reverseIterator.next();
Integer nextBitSet = backwardBitSetIterator.next();
assert nextBitSet == nextBitMap;
}
assert !backwardBitSetIterator.hasNext();
EWAHCompressedBitmap result = new EWAHCompressedBitmap().or(bitmap);
assert result.equals(bitmap);
assert bitmap.equals(result);
assert bitmap.isEmpty() || bitmap.getFirstSetBit() == bitmap.iterator().next();
}
public void or(EWAH32BitSetPair other) {
bitmap = bitmap.or(other.bitmap);
bitSet.or(other.bitSet);
}
public void and(EWAH32BitSetPair other) {
bitmap = bitmap.and(other.bitmap);
bitSet.and(other.bitSet);
}
public void andNot(EWAH32BitSetPair other) {
bitmap = bitmap.andNot(other.bitmap);
bitSet.andNot(other.bitSet);
}
public void xor(EWAH32BitSetPair other) {
bitmap = bitmap.xor(other.bitmap);
bitSet.xor(other.bitSet);
}
public void set(int value) {
bitSet.set(value);
bitmap.set(value);
}
public void clear(int value) {
bitSet.clear(value);
bitmap.clear(value);
}
}
| 31.068493 | 91 | 0.66358 |
5ab2e9bf7d1b61d6afd4ef546c3c95b25cd0f701
| 7,174 |
package com.ak47007.service.impl;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.ak47007.mapper.*;
import com.ak47007.model.*;
import com.ak47007.model.base.Result;
import com.ak47007.model.query.UserQuery;
import com.ak47007.security.UserEntity;
import com.ak47007.service.UserService;
import com.ak47007.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author AK47007
* @date 2019/7/13
*/
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class UserServiceImpl implements UserService, UserDetailsService {
private final SysUserMapper sysUserMapper;
private final SysRoleMapper sysRoleMapper;
private final SysAuthorityMapper sysAuthorityMapper;
private final SysRoleAuthorityMapper sysRoleAuthorityMapper;
private final UserUtil userUtil;
private final SysLoginLogMapper logLoginMapper;
private final LocationUtil locationUtil;
@Override
public Result<?> login(String userName, String loginIp, Boolean remember) {
// 使用用户名和加密后的密码与数据库中的用户名密码匹配
SysUser user = findByUserName(userName);
AssertUtil.notNull(user, "用户名或密码错误");
roleAndPermission(user);
String loginPlace = locationUtil.getPlace(loginIp);
int result = logLoginMapper.insert(SysLoginLog.builder().userId(user.getId()).ipAddr(loginIp).loginAddr(loginPlace).build());
if (result > 0) {
// 将token存入redis并将token返回给前端
return Result.success("登录成功", userUtil.setUser(user, remember));
} else {
return Result.error("登录失败,服务器出现异常");
}
}
@Override
public List<SysUser> findList(UserQuery query) {
LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
String sql = ElementUISortUtil.sortSql(query.getColumnName(), query.getOrder(), " id DESC ");
wrapper.last(sql);
String nickName = query.getNickName();
if (StrUtil.isNotBlank(nickName)) {
wrapper.like(SysUser::getNickName, nickName);
}
query.startPage();
List<SysUser> userList = sysUserMapper.selectList(wrapper);
List<SysRole> sysRoles = sysRoleMapper.selectList(null);
for (SysUser sysUser : userList) {
sysRoles.stream().filter(l -> l.getId().equals(sysUser.getRoleId())).findFirst().ifPresent(sysRole -> sysUser.setRoleName(sysRole.getRoleNameCn()));
}
return userList;
}
@Override
public Result<?> save(int type, SysUser user) {
int result;
switch (type) {
case 1:
// MD5加密密码
user.setUserPass(SecureUtil.md5(user.getUserPass()).toUpperCase());
user.setCreateTime(LocalDateTime.now());
result = sysUserMapper.insert(user);
if (result > 0) {
return Result.success("保存成功");
}
break;
case 2:
result = sysUserMapper.updateById(user);
if (result > 0) {
return Result.success("保存成功");
}
break;
case 3:
result = sysUserMapper.deleteById(user.getId());
if (result > 0) {
return Result.success("删除成功");
}
break;
default:
return Result.error("非法操作");
}
return Result.error("操作失败");
}
@Override
public SysUser userInfo(long id) {
SysUser user = sysUserMapper.selectById(id);
AssertUtil.notNull(user, "用户信息获取失败");
return user;
}
/**
* 查询用户名是否存在
*
* @param userName 用户名
* @return 实现了UserDetails 的实体类
* @throws UsernameNotFoundException 未找到用户异常
*/
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
SysUser user = findByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException("用户名或密码错误");
}
SysRole role = sysRoleMapper.selectById(user.getRoleId());
UserEntity userEntity = new UserEntity(user);
if (role != null) {
user.setRole(role);
// 找出该角色所拥有的权限
List<SysRoleAuthority> roleAuthorityList = sysRoleAuthorityMapper.findAllByRoleId(role.getId());
List<Long> authorityIds = roleAuthorityList.stream().map(SysRoleAuthority::getAuthorityId).collect(Collectors.toList());
List<SysAuthority> sysAuthorities = getAuthorities(authorityIds);
// 权限集合 如果他们提供了正确的用户名和密码并且启用了用户,则应授予调用者权限。不是空的。
ArrayList<GrantedAuthority> grantedAuthorityList = sysAuthorities.stream().map(l -> new SimpleGrantedAuthority(l.getAuthorityNameEn())).collect(Collectors.toCollection(ArrayList::new));
// 角色需要ROLE_前缀
grantedAuthorityList.add(new SimpleGrantedAuthority(role.getRoleNameEn()));
userEntity.setAuthorities(grantedAuthorityList);
}
// 为了不影响原来的实体类,这里重新进行赋值
return userEntity;
}
private SysUser findByUserName(String userName) {
LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
wrapper.eq(SysUser::getUserName, userName);
return sysUserMapper.selectOne(wrapper);
}
/**
* 为用户注入角色与权限
*
* @param user 用户
*/
private void roleAndPermission(SysUser user) {
// 找出所属角色
SysRole role = sysRoleMapper.selectById(user.getRoleId());
if (role != null) {
// 找出角色拥有的权限
List<SysRoleAuthority> roleAuthorityList = sysRoleAuthorityMapper.findAllByRoleId(role.getId());
if (!roleAuthorityList.isEmpty()) {
List<Long> authorityIds = roleAuthorityList.stream().map(SysRoleAuthority::getAuthorityId).collect(Collectors.toList());
List<SysAuthority> sysAuthorities = getAuthorities(authorityIds);
// 为角色注入拥有的权限
role.setAuthorityList(sysAuthorities);
}
// 为用户注入所属角色
user.setRole(role);
}
}
/**
* 获得权限信息列表
*
* @param authorityIds 权限id集合
* @return
*/
private List<SysAuthority> getAuthorities(List<Long> authorityIds) {
LambdaQueryWrapper<SysAuthority> wrapper = Wrappers.lambdaQuery();
wrapper.in(SysAuthority::getId, authorityIds);
return sysAuthorityMapper.selectList(wrapper);
}
}
| 34.325359 | 197 | 0.652495 |
8927ab293512fb052bfc01e084f75a9511827885
| 5,626 |
/**
* Copyright 2013 deib-polimi
* Contact: deib-polimi <marco.miglierina@polimi.it>
*
* 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 it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders;
import it.polimi.modaclouds.cpimlibrary.entitymng.ReflectionUtils;
import it.polimi.modaclouds.cpimlibrary.entitymng.migration.SeqNumberProvider;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.InsertStatement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.lexer.Token;
import lombok.extern.slf4j.Slf4j;
import javax.persistence.CascadeType;
import javax.persistence.JoinTable;
import javax.persistence.Query;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
/**
* Builder for INSERT statements.
*
* @author Fabio Arcidiacono.
* @see it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.StatementBuilder
*/
@Slf4j
public class InsertBuilder extends StatementBuilder {
/**
* Read the builder configuration and instantiate the builder accordingly.
*
* @see it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.BuildersConfiguration
*/
public InsertBuilder() {
super();
if (BuildersConfiguration.getInstance().isFollowingCascades()) {
super.followCascades(Arrays.asList(CascadeType.ALL, CascadeType.PERSIST));
}
}
/* (non-Javadoc)
*
* @see StatementBuilder#initStatement()
*/
@Override
protected Statement initStatement() {
return new InsertStatement();
}
/* (non-Javadoc)
*
* @see StatementBuilder#onFiled(it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement, Object, java.lang.reflect.Field)
*/
@Override
protected void onFiled(Statement statement, Object entity, Field field) {
super.addField(statement, entity, field);
}
/* (non-Javadoc)
*
* @see StatementBuilder#onRelationalField(it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement, Object, java.lang.reflect.Field)
*/
@Override
protected void onRelationalField(Statement statement, Object entity, Field field) {
super.addRelationalFiled(statement, entity, field);
}
/* (non-Javadoc)
*
* @see StatementBuilder#onIdField(it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement, Object, java.lang.reflect.Field)
*/
@Override
protected void onIdField(Statement statement, Object entity, Field idFiled) {
String fieldName = ReflectionUtils.getJPAColumnName(idFiled);
String generatedId = generateId(statement.getTable());
ReflectionUtils.setEntityField(entity, idFiled, generatedId);
log.debug("{} will be {} = {}", idFiled.getName(), fieldName, generatedId);
statement.addField(fieldName, generatedId);
}
private String generateId(String tableName) {
int id = SeqNumberProvider.getInstance().getNextSequenceNumber(tableName);
String generatedId = String.valueOf(id);
log.info("generated Id for {} is {}", tableName, generatedId);
return generatedId;
}
/* (non-Javadoc)
*
* @see StatementBuilder#generateJoinTableStatement(Object, Object, javax.persistence.JoinTable)
*/
@Override
protected Statement generateJoinTableStatement(Object entity, Object element, JoinTable joinTable) {
String joinTableName = joinTable.name();
String joinColumnName = joinTable.joinColumns()[0].name();
String inverseJoinColumnName = joinTable.inverseJoinColumns()[0].name();
Field joinColumnField = ReflectionUtils.getJoinColumnField(entity, joinColumnName);
Object joinColumnValue = ReflectionUtils.getFieldValue(entity, joinColumnField);
Statement statement = initStatement();
statement.setTable(joinTableName);
statement.addField(joinColumnName, joinColumnValue);
Field inverseJoinColumnField = ReflectionUtils.getJoinColumnField(element, inverseJoinColumnName);
Object inverseJoinColumnValue = ReflectionUtils.getFieldValue(element, inverseJoinColumnField);
statement.addField(inverseJoinColumnName, inverseJoinColumnValue);
log.debug("joinTable {}, joinColumn {} = {}, inverseJoinColumn {} = {}", joinTableName, joinColumnName, joinColumnValue, inverseJoinColumnName, inverseJoinColumnValue);
return statement;
}
/* (non-Javadoc)
*
* @see StatementBuilder#generateInverseJoinTableStatement(Object, javax.persistence.JoinTable)
*/
@Override
protected Statement generateInverseJoinTableStatement(Object entity, JoinTable joinTable) {
/* do nothing */
return null;
}
/* (non-Javadoc)
*
* @see StatementBuilder#handleQuery(javax.persistence.Query, java.util.ArrayList)
*/
@Override
protected Statement handleQuery(Query query, List<Token> tokens) {
/* do nothing, no need to handle this case */
return null;
}
}
| 38.8 | 176 | 0.718628 |
2f8e2c3051efaeb9c78760039e42be190273e55d
| 1,583 |
package eu.linksmart.services.payloads.ogc.sensorthing.links;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonSetter;
import eu.linksmart.services.payloads.ogc.sensorthing.CommonControlInfo;
/**
* Created by José Ángel Carvajal on 26.07.2017 a researcher of Fraunhofer FIT.
*/
public interface HistoricalLocationsNavigationLink extends CommonControlInfo{
/**
* navigationLink is the relative or absolute URL that retrieves content of the HistoricalLocations.
*
* @param str a string that represents the relative or absolute URL that retrieves content of the HistoricalLocations
*/
@JsonPropertyDescription("navigationLink is the relative or absolute URL that retrieves content of the FeatureOfInterest.")
@JsonSetter(value = "HistoricalLocations@iot.navigationLink")
default void setHistoricalLocationsNavigationLink(String str){}
/**
* navigationLink is the relative or absolute URL that retrieves content of the FeatureOfInterest.
*
* @return a string that represents the relative or absolute URL that retrieves content of the HistoricalLocations
*/
@JsonPropertyDescription("navigationLink is the relative or absolute URL that retrieves content of the HistoricalLocations.")
@JsonSetter(value = "HistoricalLocations@iot.navigationLink")
default String getHistoricalLocationsNavigationLink(){return getSelfLink(this.getClass().getSimpleName(),getId().toString(), "HistoricalLocations");}
}
| 54.586207 | 153 | 0.78964 |
20ff55ed632d6b77ad7b85c4d9e3c3b126a163ca
| 9,040 |
/**
* @FileName: MybatisDaoContext.java
* @Package com.asura.framework.dao.mybatis.base
*
* @author zhangshaobin
* @created 2015年6月14日 下午2:47:23
*
* Copyright 2011-2015 asura
*/
package com.asura.framework.dao.mybatis.base;
import java.util.List;
import java.util.Map;
import com.asura.framework.base.entity.BaseEntity;
import com.asura.framework.base.paging.PagingResult;
import com.asura.framework.dao.mybatis.paginator.domain.PageBounds;
import com.asura.framework.dao.mybatis.paginator.domain.PageList;
/**
* <p>
* mybatis基类
* 从库操作:findAll findForPage count findXXXSlave
* 主库操作:其他方法全部主库主库操作
* </p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhangshaobin
* @since 1.0
* @version 1.0
*/
public class MybatisDaoContext extends BaseMybatisDaoSupport implements IBaseDao{
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#findAll(java.lang.String)
*/
@Override
public <T extends BaseEntity> List<T> findAll(String sqlId) {
return getReadSqlSessionTemplate().selectList(sqlId);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#findAll(java.lang.String, java.lang.Class, java.lang.Object)
*/
@Override
public <T extends BaseEntity> List<T> findAll(String sqlId, Object params) {
return getReadSqlSessionTemplate().selectList(sqlId, params);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#findForPage(java.lang.String, java.lang.Class, java.lang.Object, com.asura.framework.dao.mybatis.paginator.domain.PageBounds)
*/
@Override
public <T extends BaseEntity> PagingResult<T> findForPage(String sqlId,
Class<T> clazz, Object params, PageBounds pageBounds) {
List<T> list = getReadSqlSessionTemplate().selectList(sqlId, params, pageBounds);
// 后端如果不分页,直接返回的类型为ArrayList,需要作出判断
if (list instanceof PageList) {
PageList<T> pl = (PageList<T>) list;
return new PagingResult<>(pl.getPaginator().getTotalCount(), pl);
} else {
return new PagingResult<>(0, list);
}
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#findOne(java.lang.String, java.lang.Class, java.util.Map)
*/
@SuppressWarnings("unchecked")
@Override
public <T> T findOne(String sqlId, Class<T> clazz,
Map<String, Object> params) {
return (T)getWriteSqlSessionTemplate().selectOne(sqlId, params);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#findOne(java.lang.String, java.lang.Class, Object)
*/
@SuppressWarnings("unchecked")
@Override
public <T> T findOne(String sqlId, Class<T> clazz,
Object params) {
return (T)getWriteSqlSessionTemplate().selectOne(sqlId, params);
}
@SuppressWarnings("unchecked")
public <T> T findOne(String sqlId, Class<T> clazz){
return (T)getWriteSqlSessionTemplate().selectOne(sqlId);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#findOne(java.lang.String, java.lang.Class, int)
*/
@SuppressWarnings("unchecked")
@Override
public <T> T findOne(String sqlId, Class<T> clazz, int param) {
return (T)getWriteSqlSessionTemplate().selectOne(sqlId, param);
}
@SuppressWarnings("unchecked")
@Override
public <T> T findOneSlave(String sqlId, Class<T> clazz,
Map<String, Object> params) {
return (T)getWriteSqlSessionTemplate().selectOne(sqlId, params);
}
@SuppressWarnings("unchecked")
@Override
public <T> T findOneSlave(String sqlId, Class<T> clazz,
Object params) {
return (T)getReadSqlSessionTemplate().selectOne(sqlId, params);
}
@SuppressWarnings("unchecked")
public <T> T findOneSlave(String sqlId, Class<T> clazz){
return (T)getReadSqlSessionTemplate().selectOne(sqlId);
}
@SuppressWarnings("unchecked")
@Override
public <T> T findOneSlave(String sqlId, Class<T> clazz, int param) {
return (T)getReadSqlSessionTemplate().selectOne(sqlId, param);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#count(java.lang.String)
*/
@Override
public long count(String sqlId) {
final Object obj = getWriteSqlSessionTemplate().selectOne(sqlId);
if (obj instanceof Long) {
return (Long) obj;
} else if (obj instanceof Integer) {
return Long.parseLong(((Integer) obj).toString());
} else {
return (Long) obj;
}
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#count(java.lang.String, java.util.Map)
*/
@Override
public long count(String sqlId, Map<String, Object> params) {
final Object obj = getWriteSqlSessionTemplate().selectOne(sqlId, params);
if (obj instanceof Long) {
return (Long) obj;
} else if (obj instanceof Integer) {
return Long.parseLong(((Integer) obj).toString());
} else {
return (Long) obj;
}
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#save(java.lang.String)
*/
@Override
public int save(String sqlId) {
return getWriteSqlSessionTemplate().insert(sqlId);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#save(java.lang.String, com.asura.framework.base.entity.BaseEntity)
*/
@Override
public int save(String sqlId, BaseEntity entity) {
return getWriteSqlSessionTemplate().insert(sqlId,entity);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#update(java.lang.String)
*/
@Override
public int update(String sqlId) {
return getWriteSqlSessionTemplate().update(sqlId);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#update(java.lang.String, com.asura.framework.base.entity.BaseEntity)
*/
@Override
public int update(String sqlId, BaseEntity entity) {
return getWriteSqlSessionTemplate().update(sqlId,entity);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#update(java.lang.String, java.util.Map)
*/
@Override
public int update(String sqlId, Map<String, Object> params) {
return getWriteSqlSessionTemplate().update(sqlId,params);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#delete(java.lang.String)
*/
@Override
public int delete(String sqlId) {
return getWriteSqlSessionTemplate().delete(sqlId);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#delete(java.lang.String, java.util.Map)
*/
@Override
public int delete(String sqlId, Map<String, Object> params) {
return getWriteSqlSessionTemplate().delete(sqlId,params);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#delete(java.lang.String, java.util.Map)
*/
@Override
public int delete(String sqlId, BaseEntity entity) {
return getWriteSqlSessionTemplate().delete(sqlId,entity);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#batchDelete(java.lang.String, java.util.List)
*/
@Override
public int batchDelete(String sqlId, List<? extends BaseEntity> params) {
int count = 0;
for (int i = 0; i < params.size(); i++) {
count = count + delete(sqlId, params.get(i));
}
return count;
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#batchUpdate(java.lang.String, java.util.List)
*/
@Override
public int batchUpdate(String sqlId, List<? extends BaseEntity> params) {
int count = 0;
for (int i = 0; i < params.size(); i++) {
count = count + update(sqlId, params.get(i));
}
return count;
}
/**
*
* 查询指定SQL语句的所有记录
*
* @author zhangshaobin
* @created 2012-12-19 下午5:51:23
*
* @param sqlId SQL语句ID
* @param clazz 返回值类型
* @param params 条件参数
* @return 查询到的结果集合
*/
@SuppressWarnings("unchecked")
public <T> List<T> findAll(String sqlId, Class<T> clazz, Object params){
return (List<T>)getReadSqlSessionTemplate().selectList(sqlId, params);
}
/**
*
* 查询指定SQL语句的所有记录
*
* @author zhangshaobin
* @created 2012-12-19 下午5:51:23
*
* @param sqlId SQL语句ID
* @param clazz 返回值类型
* @param params 条件参数
* @return 查询到的结果集合
*/
@SuppressWarnings("unchecked")
@Override
public <T> List<T> findAllByMaster(String sqlId, Class<T> clazz, Object params){
return (List<T>)getWriteSqlSessionTemplate().selectList(sqlId, params);
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#count(java.lang.String)
*/
@Override
public long countBySlave(String sqlId) {
final Object obj = getReadSqlSessionTemplate().selectOne(sqlId);
if (obj instanceof Long) {
return (Long) obj;
} else if (obj instanceof Integer) {
return Long.parseLong(((Integer) obj).toString());
} else {
return (Long) obj;
}
}
/* (non-Javadoc)
* @see com.asura.framework.dao.mybatis.base.IBaseDao#count(java.lang.String, java.util.Map)
*/
@Override
public long countBySlave(String sqlId, Map<String, Object> params) {
final Object obj = getReadSqlSessionTemplate().selectOne(sqlId, params);
if (obj instanceof Long) {
return (Long) obj;
} else if (obj instanceof Integer) {
return Long.parseLong(((Integer) obj).toString());
} else {
return (Long) obj;
}
}
}
| 28.338558 | 180 | 0.704867 |
8e415040572f606f7709beb99f53110b1029a4bc
| 919 |
package de.jformchecker.utils;
import java.util.Map;
import de.jformchecker.FormChecker;
import de.jformchecker.request.Request;
import de.jformchecker.request.SampleRequest;
public class RequestBuilders {
public static final String FC_ID = "id44";
public static Request buildExampleHttpRequest() {
SampleRequest request = new SampleRequest();
request.setParameter("firstname", "Jochen Pier<bold>");
return request;
}
public static Request buildExampleHttpRequest(Map<String, String> reqVals) {
SampleRequest request = new SampleRequest();
for (String key : reqVals.keySet()) {
request.setParameter(key, reqVals.get(key));
}
return request;
}
public static Request buildEmptyHttpRequest() {
SampleRequest request = new SampleRequest();
return request;
}
public static FormChecker buildFcWithEmptyRequest() {
return new FormChecker(RequestBuilders.buildEmptyHttpRequest());
}
}
| 24.184211 | 77 | 0.764962 |
5d9d4259f5578f0c84e9073b54db3eef9c44ecbc
| 469 |
package org.zstack.core.cloudbus;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class CanonicalEventEmitter {
@Autowired
private EventFacade eventf;
public void fire(String path, Object data) {
eventf.fire(path, data);
}
}
| 29.3125 | 66 | 0.780384 |
577c597264e343e95f7e2c53b654876a5b919e5d
| 20,935 |
package at.mep.editor;
import at.mep.KeyReleasedHandler;
import at.mep.Matlab;
import at.mep.debug.Debug;
import at.mep.gui.AutoSwitcher;
import at.mep.gui.ClickHistory;
import at.mep.gui.bookmarks.Bookmarks;
import at.mep.gui.ContextMenu;
import at.mep.gui.fileStructure.FileStructure;
import at.mep.gui.recentlyClosed.RecentlyClosed;
import at.mep.localhistory.LocalHistory;
import at.mep.mepr.MEPR;
import at.mep.prefs.Settings;
import com.mathworks.matlab.api.editor.Editor;
import com.mathworks.matlab.api.editor.EditorApplicationListener;
import com.mathworks.matlab.api.editor.EditorEvent;
import com.mathworks.mde.editor.EditorSyntaxTextPane;
import com.mathworks.widgets.editor.breakpoints.BreakpointView;
import matlabcontrol.MatlabInvocationException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/** Created by Andreas Justin on 2016 - 02 - 09. */
public class EditorApp {
public static final Color ENABLED = new Color(179, 203, 111);
public static final Color DISABLED = new Color(240, 240, 240);
private static final int WF = JComponent.WHEN_FOCUSED;
private static List<String> mCallbacks = new ArrayList<>();
private static List<KeyStroke> keyStrokes = new ArrayList<>();
private static List<String> actionMapKeys = new ArrayList<>();
private static EditorApp INSTANCE;
private static List<Editor> editors = new ArrayList<>();
public static EditorApp getInstance() {
if (INSTANCE != null) return INSTANCE;
INSTANCE = new EditorApp();
INSTANCE.addListener();
return INSTANCE;
}
/** adds a matlab function call to the matlab call stack */
@SuppressWarnings("unused") // is used from Matlab
public static void addMatlabCallback(String string, KeyStroke keyStroke, String actionMapKey) throws Exception {
if (!testMatlabCallback(string)) {
throw new Exception("'" + string + "' is not a valid function");
}
if (!mCallbacks.contains(string)) {
mCallbacks.add(string);
keyStrokes.add(keyStroke);
actionMapKeys.add(actionMapKey);
EditorApp.getInstance().setCallbacks();
} else System.out.println("'" + string + "' already added");
}
/**
* user can test if the passed string will actually be called as intended. will call the function w/o passing any
* input arguments. Make sure that passed function has a return statement at the beginning if no arguments are passed
*/
private static boolean testMatlabCallback(String string) {
try {
Matlab.getInstance().proxyHolder.get().feval(string);
return true;
} catch (MatlabInvocationException e) {
e.printStackTrace();
}
return false;
}
/**
* on clear classes this listener will just be added to the editor application, which isn't the general idea of "good"
* TODO: fix me
*/
private void addListener() {
EditorWrapper.getMatlabEditorApplication().addEditorApplicationListener(new EditorApplicationListener() {
@Override
public void editorOpened(Editor editor) {
if (Debug.isDebugEnabled()) {
System.out.println("EditorApp: " + editor.getLongName() + " has been opened");
}
setCallbacks();
Bookmarks.getInstance().setEditorBookmarks(editor);
Bookmarks.getInstance().enableBookmarksForMatlab(editor);
if (Settings.getPropertyBoolean("feature.enableRecentlyClosed")) {
RecentlyClosed.remFile(EditorWrapper.getFile(editor));
}
if (Settings.getPropertyBoolean("feature.enableClickHistory")) {
ClickHistory.getINSTANCE().add(editor);
}
}
@Override
public void editorClosed(Editor editor) {
if (Debug.isDebugEnabled()) {
System.out.println("EditorApp: " + editor.getLongName() + " has been closed");
}
editors.remove(editor);
if (Settings.getPropertyBoolean("feature.enableRecentlyClosed")) {
RecentlyClosed.addFile(EditorWrapper.getFile(editor));
}
}
@Override
public String toString() {
return this.getClass().toString();
}
});
}
public Editor getActiveEditor() {
return EditorWrapper.getActiveEditorSafe();
}
public Editor openEditor(File file) {
return EditorWrapper.openEditor(file);
}
public void setCallbacks() {
// EditorWrapper.getActiveEditor().addEventListener();
// even worse than DocumentListener
List<Editor> openEditors = EditorWrapper.getOpenEditors();
for (final Editor editor : openEditors) {
EditorSyntaxTextPane editorSyntaxTextPane = EditorWrapper.getEditorSyntaxTextPane(editor);
if (editorSyntaxTextPane == null) continue;
addKeyStrokes(editorSyntaxTextPane);
addCustomKeyStrokes(editorSyntaxTextPane);
if (editors.contains(editor)) {
// editor already has listeners, don't any new listeners
continue;
}
if (Debug.isDebugEnabled()) {
System.out.println("EditorApp:setCallbacks() " + editor.getShortName());
}
if (EditorWrapper.isFloating(editor)) {
// System.out.println("floating");
}
editors.add(editor);
// AutoSwitcher
AutoSwitcher.addCheckbox();
// Mouse Listener
editorSyntaxTextPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// clicked doesn't not get fired while mouse is moving
}
@Override
public void mouseReleased(MouseEvent e) {
switch (e.getButton()) {
case 1: {
// left
if (Settings.getPropertyBoolean("feature.enableClickHistory")) {
ClickHistory.getINSTANCE().add(editor);
}
break;
}
case 2: {
// middle
break;
}
case 3: {
// right
ContextMenu.contribute(editor);
break;
}
case 4: {
// backward
if (Settings.getPropertyBoolean("feature.enableClickHistory")) {
ClickHistory.getINSTANCE().locationPrevious();
}
break;
}
case 5: {
// forward
if (Settings.getPropertyBoolean("feature.enableClickHistory")) {
ClickHistory.getINSTANCE().locationNext();
}
break;
}
}
}
});
// Editor event (AutoSwitcher)
editor.addEventListener(editorEvent -> {
// Matlab.getInstance().proxyHolder.get().feval("assignin", "base", "editorEvent", editorEvent);
switch (editorEvent){
case ACTIVATED: {
if (Debug.isDebugEnabled()) {
System.out.println("event ACTIVATED occurred");
}
if (Settings.getPropertyBoolean("feature.enableDockableWindows")) {
FileStructure.getInstance().populateTree();
}
remKeyStrokes(EditorWrapper.getOpenEditors());
CustomShortCutKey.reload();
addKeyStrokes(EditorWrapper.getEditorSyntaxTextPane());
if (Settings.getPropertyBoolean("feature.enableAutoDetailViewer")
|| Settings.getPropertyBoolean("feature.enableAutoCurrentFolder")) {
AutoSwitcher.doYourThing();
EditorWrapper.setDirtyIfLastEditorChanged(editor);
EditorWrapper.setIsActiveEditorDirty(true);
}
break;
}
case CLOSED: {
if (Debug.isDebugEnabled()) {
System.out.println("event CLOSED occurred");
}
LocalHistory.addHistoryEntry(editor);
break;
}
}
});
boolean useListener = true;
if (useListener) {
KeyListener[] keyListeners = editorSyntaxTextPane.getKeyListeners();
for (KeyListener keyListener1 : keyListeners) {
if (keyListener1.toString().equals(KeyReleasedHandler.getKeyListener().toString())) {
editorSyntaxTextPane.removeKeyListener(keyListener1);
// this will assure that the new key listener is added and the previous one is removed
// while matlab is still running and the .jar is replaced
}
}
editorSyntaxTextPane.addKeyListener(KeyReleasedHandler.getKeyListener());
}
// document listener
editorSyntaxTextPane.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
if (Debug.isDebugEnabled()) {
System.out.println("EditorApp: " + "insertUpdate");
}
Bookmarks.getInstance().adjustBookmarks(e, true);
try {
String insertString = e.getDocument().getText(e.getOffset(), e.getLength());
if (insertString.equals("%")) MEPR.doReplace();
} catch (BadLocationException ignored) {
ignored.printStackTrace();
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (Debug.isDebugEnabled()) {
System.out.println("EditorApp: " + "removeUpdate");
}
Bookmarks.getInstance().adjustBookmarks(e, false);
}
@Override
public void changedUpdate(DocumentEvent e) {
if (Debug.isDebugEnabled()) {
System.out.println("EditorApp: " + "changedUpdate");
}
EditorWrapper.setDirtyIfLastEditorChanged(editor);
EditorWrapper.setIsActiveEditorDirty(true);
}
});
}
// breakpointview color
if (Settings.containsKey("bpColor")) {
colorizeBreakpointView(Settings.getPropertyColor("bpColor"));
} else {
colorizeBreakpointView(ENABLED);
}
}
private void addDocumentListener() {
}
private void addCustomKeyStrokes(EditorSyntaxTextPane editorSyntaxTextPane) {
for (int i = 0; i < mCallbacks.size(); i++) {
editorSyntaxTextPane.getInputMap(WF).put(keyStrokes.get(i), actionMapKeys.get(i));
final int finalI = i;
editorSyntaxTextPane.getActionMap().put(actionMapKeys.get(i), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Matlab.getInstance().proxyHolder.get().feval(mCallbacks.get(finalI), e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}
private void remKeyStrokes(List<Editor> editors) {
for (Editor e : editors) {
EditorSyntaxTextPane estp = EditorWrapper.getEditorSyntaxTextPane(e);
}
}
private void remKeyStrokes(EditorSyntaxTextPane editorSyntaxTextPane) {
if (editorSyntaxTextPane == null) {
return;
}
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getDEBUG());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getExecuteCurrentLines());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getDeleteLines());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getDuplicateLine());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getMoveLineUp());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getMoveLineDown());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getFileStructure());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getRecentlyClosed());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getClipboardStack());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getCopySelectedText());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getCutSelectedText());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getLiveTemplateViewer());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getQuickSearchMepr());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getBookmarkViewer());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getToggleBookmark());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getBreakpointViewer());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getSave());
editorSyntaxTextPane.getInputMap(WF).remove(CustomShortCutKey.getLocalHistory());
}
private void addKeyStrokes(EditorSyntaxTextPane editorSyntaxTextPane) {
// NOTE: enable/disable feature cannot be checked here. the problem in the current design is, that matlab would
// need a restart after enabling features afterwards. that's why the features are checked in the
// "EMEPAction" Class
if (editorSyntaxTextPane == null) {
return;
}
// DEBUG
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getDEBUG(), "MEP_DEBUG");
editorSyntaxTextPane.getActionMap().put("MEP_DEBUG", EMEPAction.MEP_DEBUG.getAction());
// CURRENT LINES
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getExecuteCurrentLines(), "MEP_EXECUTE_CURRENT_LINE");
editorSyntaxTextPane.getActionMap().put("MEP_EXECUTE_CURRENT_LINE", EMEPAction.MEP_EXECUTE_CURRENT_LINE.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getDeleteLines(), "MEP_DELETE_CURRENT_LINES");
editorSyntaxTextPane.getActionMap().put("MEP_DELETE_CURRENT_LINES", EMEPAction.MEP_DELETE_CURRENT_LINES.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getDuplicateLine(), "MEP_DUPLICATE_CURRENT_LINE_OR_SELECTION");
editorSyntaxTextPane.getActionMap().put("MEP_DUPLICATE_CURRENT_LINE_OR_SELECTION", EMEPAction.MEP_DUPLICATE_CURRENT_LINE_OR_SELECTION.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getMoveLineUp(), "MEP_MOVE_CURRENT_LINE_UP");
editorSyntaxTextPane.getActionMap().put("MEP_MOVE_CURRENT_LINE_UP", EMEPAction.MEP_MOVE_CURRENT_LINE_UP.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getMoveLineDown(), "MEP_MOVE_CURRENT_LINE_DOWN");
editorSyntaxTextPane.getActionMap().put("MEP_MOVE_CURRENT_LINE_DOWN", EMEPAction.MEP_MOVE_CURRENT_LINE_DOWN.getAction());
// FILE STRUCTURE
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getFileStructure(), "MEP_SHOW_FILE_STRUCTURE");
editorSyntaxTextPane.getActionMap().put("MEP_SHOW_FILE_STRUCTURE", EMEPAction.MEP_SHOW_FILE_STRUCTURE.getAction());
// RECENTLY CLOSED
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getRecentlyClosed(), "MEP_SHOW_RECENTLY_CLOSED");
editorSyntaxTextPane.getActionMap().put("MEP_SHOW_RECENTLY_CLOSED", EMEPAction.MEP_SHOW_RECENTLY_CLOSED.getAction());
// CLIPBOARD
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getClipboardStack(), "MEP_SHOW_CLIP_BOARD_STACK_EDT");
editorSyntaxTextPane.getActionMap().put("MEP_SHOW_CLIP_BOARD_STACK_EDT", EMEPAction.MEP_SHOW_CLIP_BOARD_STACK_EDT.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getCopySelectedText(), "MEP_COPY_CLIP_BOARD");
editorSyntaxTextPane.getActionMap().put("MEP_COPY_CLIP_BOARD", EMEPAction.MEP_COPY_CLIP_BOARD.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getCutSelectedText(), "MEP_CUT_CLIP_BOARD");
editorSyntaxTextPane.getActionMap().put("MEP_CUT_CLIP_BOARD", EMEPAction.MEP_CUT_CLIP_BOARD.getAction());
// MEPR
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getLiveTemplateViewer(), "MEP_MEPR_INSERT");
editorSyntaxTextPane.getActionMap().put("MEP_MEPR_INSERT", EMEPAction.MEP_MEPR_INSERT.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getQuickSearchMepr(), "MEP_MEPR_QUICK_SEARCH");
editorSyntaxTextPane.getActionMap().put("MEP_MEPR_QUICK_SEARCH", EMEPAction.MEP_MEPR_QUICK_SEARCH.getAction());
// BOOKMARKS
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getBookmarkViewer(), "MEP_SHOW_BOOKMARKS");
editorSyntaxTextPane.getActionMap().put("MEP_SHOW_BOOKMARKS", EMEPAction.MEP_SHOW_BOOKMARKS.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getToggleBookmark(), "MEP_BOOKMARK");
editorSyntaxTextPane.getActionMap().put("MEP_BOOKMARK", EMEPAction.MEP_BOOKMARK.getAction());
// BREAKPOINTS
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getBreakpointViewer(), "MEP_SHOW_BREAKPOINTS");
editorSyntaxTextPane.getActionMap().put("MEP_SHOW_BREAKPOINTS", EMEPAction.MEP_SHOW_BREAKPOINTS.getAction());
// File History
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getSave(), "MEP_SAVE");
editorSyntaxTextPane.getActionMap().put("MEP_SAVE", EMEPAction.MEP_SAVE.getAction());
editorSyntaxTextPane.getInputMap(WF).put(CustomShortCutKey.getLocalHistory(), "MEP_LOCAL_HISTORY");
editorSyntaxTextPane.getActionMap().put("MEP_LOCAL_HISTORY", EMEPAction.MEP_LOCAL_HISTORY.getAction());
}
public void removeCallbacks() {
List<Editor> openEditors = EditorWrapper.getMatlabEditorApplication().getOpenEditors();
for (Editor editor : openEditors) {
EditorSyntaxTextPane editorSyntaxTextPane = EditorWrapper.getEditorSyntaxTextPane(editor);
editorSyntaxTextPane.removeKeyListener(KeyReleasedHandler.getKeyListener());
}
colorizeBreakpointView(DISABLED);
}
public void colorizeBreakpointView(Color color) {
List<Editor> openEditors = EditorWrapper.getMatlabEditorApplication().getOpenEditors();
for (Editor editor : openEditors) {
BreakpointView.Background breakpointView = EditorWrapper.getBreakpointView(editor);
if (breakpointView != null) breakpointView.setBackground(color);
}
}
}
//////////////////////////////////////////
// UNUSED CODE
// old breakpointview color
// List<Component> list = Matlab.getInstance().getComponents("BreakpointView$2");
// for (Component component : list) {
// component.setBackground(color);
// }
| 47.579545 | 156 | 0.607738 |
bbd24cfd475a837aa8a744ddb227d5234ec8ecb9
| 975 |
/*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.corba.ee.impl.misc;
import org.omg.CORBA.ORB;
import java.io.Serializable;
import java.net.MalformedURLException;
/**
* Methods on specific instances of RepositoryId. Hides
* versioning of our RepositoryId class.
*/
public interface RepositoryIdInterface
{
Class getClassFromType() throws ClassNotFoundException;
Class getClassFromType(String codebaseURL)
throws ClassNotFoundException, MalformedURLException;
Class getClassFromType(Class expectedType,
String codebaseURL)
throws ClassNotFoundException, MalformedURLException;
String getClassName();
}
| 28.676471 | 78 | 0.742564 |
8b0702a149ddae2f94ffcc25390d6a5b562242cb
| 754 |
package artistry.models;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
@NodeEntity
public class JiraFilter {
@Id
@GeneratedValue
private Long id;
private String filterkey;
private String filtervalue;
public String getFilterkey() {
return filterkey;
}
public void setFilterkey(String filterkey) {
this.filterkey = filterkey;
}
public String getFiltervalue() {
return filtervalue;
}
public void setFiltervalue(String filtervalue) {
this.filtervalue = filtervalue;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| 18.390244 | 52 | 0.655172 |
5eda6a89f981a0e24087cd463d36ca69571c3382
| 5,882 |
package uk.gov.justice.hmpps.datacompliance.services.deletion;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import uk.gov.justice.hmpps.datacompliance.config.DataComplianceProperties;
import uk.gov.justice.hmpps.datacompliance.dto.OffenderDeletionGrant;
import uk.gov.justice.hmpps.datacompliance.events.listeners.dto.OffenderDeletionComplete;
import uk.gov.justice.hmpps.datacompliance.events.publishers.dto.OffenderDeletionComplete.Booking;
import uk.gov.justice.hmpps.datacompliance.events.publishers.dto.OffenderDeletionComplete.OffenderWithBookings;
import uk.gov.justice.hmpps.datacompliance.events.publishers.sns.OffenderDeletionCompleteEventPusher;
import uk.gov.justice.hmpps.datacompliance.events.publishers.sqs.DataComplianceEventPusher;
import uk.gov.justice.hmpps.datacompliance.repository.jpa.model.referral.OffenderDeletionReferral;
import uk.gov.justice.hmpps.datacompliance.repository.jpa.model.referral.ReferredOffenderAlias;
import uk.gov.justice.hmpps.datacompliance.repository.jpa.repository.referral.OffenderDeletionReferralRepository;
import uk.gov.justice.hmpps.datacompliance.services.duplicate.detection.image.ImageDuplicationDetectionService;
import uk.gov.justice.hmpps.datacompliance.utils.TimeSource;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkState;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toSet;
import static uk.gov.justice.hmpps.datacompliance.repository.jpa.model.referral.ReferralResolution.ResolutionStatus.DELETED;
import static uk.gov.justice.hmpps.datacompliance.repository.jpa.model.referral.ReferralResolution.ResolutionStatus.DELETION_GRANTED;
import static uk.gov.justice.hmpps.datacompliance.utils.Exceptions.illegalState;
@Slf4j
@Service
@Transactional
@AllArgsConstructor
public class DeletionService {
private final TimeSource timeSource;
private final OffenderDeletionReferralRepository referralRepository;
private final OffenderDeletionCompleteEventPusher deletionCompleteEventPusher;
private final DataComplianceEventPusher deletionGrantedEventPusher;
private final DataComplianceProperties properties;
private final ImageDuplicationDetectionService imageDuplicationDetectionService;
public void grantDeletion(final OffenderDeletionReferral referral) {
if (!properties.isDeletionGrantEnabled()) {
log.info("Deletion grant is disabled for: '{}'", referral.getOffenderNo());
return;
}
log.info("Granting deletion of offender: '{}'", referral.getOffenderNo());
deletionGrantedEventPusher.grantDeletion(OffenderDeletionGrant.builder()
.offenderNumber(referral.getOffenderNumber())
.referralId(referral.getReferralId())
.offenderIds(referral.getOffenderAliases().stream()
.map(ReferredOffenderAlias::getOffenderId)
.collect(toSet()))
.offenderBookIds(referral.getOffenderAliases().stream()
.map(ReferredOffenderAlias::getOffenderBookId)
.filter(Objects::nonNull)
.collect(toSet()))
.build());
}
public void handleDeletionComplete(final OffenderDeletionComplete event) {
final var referral = referralRepository.findById(event.getReferralId())
.orElseThrow(illegalState("Cannot retrieve referral record for id: '%s'", event.getReferralId()));
checkState(Objects.equals(event.getOffenderIdDisplay(), referral.getOffenderNo()),
"Offender number '%s' of referral '%s' does not match '%s'",
referral.getOffenderNo(), referral.getReferralId(), event.getOffenderIdDisplay());
if (properties.isImageRecognitionDeletionEnabled()) {
imageDuplicationDetectionService.deleteOffenderImages(referral.getOffenderNumber());
}
recordDeletionCompletion(referral);
publishDeletionCompleteEvent(referral);
}
private void recordDeletionCompletion(final OffenderDeletionReferral referral) {
log.info("Updating destruction log with deletion confirmation for: '{}'", referral.getOffenderNo());
final var referralResolution = referral.getReferralResolution()
.filter(resolution -> resolution.isType(DELETION_GRANTED))
.orElseThrow(illegalState("Referral '%s' does not have expected resolution type", referral.getReferralId()));
referralResolution.setResolutionDateTime(timeSource.nowAsLocalDateTime());
referralResolution.setResolutionStatus(DELETED);
referralRepository.save(referral);
}
private void publishDeletionCompleteEvent(final OffenderDeletionReferral deletionCompletion) {
log.info("Publishing deletion complete event for: '{}'", deletionCompletion.getOffenderNo());
final var deletionCompleteEvent =
uk.gov.justice.hmpps.datacompliance.events.publishers.dto.OffenderDeletionComplete.builder()
.offenderIdDisplay(deletionCompletion.getOffenderNo());
deletionCompletion.getOffenderAliases().stream()
.collect(groupingBy(ReferredOffenderAlias::getOffenderId))
.forEach((offenderId, bookings) -> {
final var offenderWithBookings = OffenderWithBookings.builder().offenderId(offenderId);
bookings.forEach(booking -> offenderWithBookings.booking(new Booking(booking.getOffenderBookId())));
deletionCompleteEvent.offender(offenderWithBookings.build());
});
deletionCompleteEventPusher.sendEvent(deletionCompleteEvent.build());
}
}
| 51.596491 | 133 | 0.748385 |
3c2971d43e9e2dba0ad34c19241aa6e457ea8fd3
| 746 |
package ynn.mylogo.parser.ast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Script implements ASTVisitable{
private final List<AbstractStatement> statements;
public Script(List<AbstractStatement> statements) {
this.statements = new ArrayList<AbstractStatement>(statements);
}
public List<AbstractStatement> getStatements() {
return Collections.unmodifiableList(statements);
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (AbstractStatement statement : statements) {
sb.append(String.valueOf(statement)).append("\n");
}
return sb.toString();
}
}
| 21.314286 | 65 | 0.75067 |
9247f00307a2eeca23faf246e6b598973eb9081c
| 2,068 |
package org.firstinspires.ftc.teamcode.subsystems;
import com.disnodeteam.dogecv.CameraViewDisplay;
import com.disnodeteam.dogecv.DogeCV;
import com.disnodeteam.dogecv.detectors.roverrukus.GoldDetector;
import com.qualcomm.robotcore.hardware.HardwareMap;
import org.opencv.core.Point;
import static org.firstinspires.ftc.teamcode.subsystems.Detector.MineralPosition.RIGHT;
public class Detector {
public GoldDetector detector;
public Detector(HardwareMap hardwareMap){
detector = new GoldDetector(); // Create detector
detector.init(hardwareMap.appContext, CameraViewDisplay.getInstance(), DogeCV.CameraMode.FRONT,false); // Initialize it with the app context and camera
detector.useDefaults(); // Set detector to use default settings
detector.cropTLCorner = new Point(200, 200); //Sets the top left corner of the new image, in pixel (x,y) coordinates
detector.cropBRCorner = new Point(400, 400);
// Optional tuning
detector.downscale = 1; // How much to downscale the input frames
detector.areaScoringMethod = DogeCV.AreaScoringMethod.MAX_AREA; // Can also be PERFECT_AREA
//detector.perfectAreaScorer.perfectArea = 10000; // if using PERFECT_AREA scoring
detector.maxAreaScorer.weight = 0.005; //
detector.ratioScorer.weight = 5; //
detector.ratioScorer.perfectRatio = 1.0; // Ratio adjustment
}
public void enable(){
detector.enable();
}
public void disable(){
detector.disable();
}
public void setCrop(Point TLCorner, Point BRCorner){
detector.cropBRCorner = TLCorner;
detector.cropTLCorner = BRCorner;
}
public boolean isDetected(int width, int height){
if(width < detector.getFoundRect().width && height < detector.getFoundRect().height){
return true;
} else {
return false;
}
}
public MineralPosition getMineralPosition(){
return RIGHT;
}
public enum MineralPosition {
LEFT,RIGHT,MIDDLE
}
}
| 31.333333 | 159 | 0.691006 |
a8fe0fd0cae1167da5ce709f8004c1d65d99d1f4
| 237 |
package com.jivesoftware.os.tasmo.reference.lib;
/**
*
* @author jonathan
*/
public interface ReferenceStream {
ReferenceWithTimestamp stream(ReferenceWithTimestamp value) throws Exception;
void failure(Exception cause);
}
| 18.230769 | 81 | 0.759494 |
754542fd838bf6ba7c6e6fcf6e701562d95f510d
| 374 |
package com.fxforbiz.softphone.core.beans;
/**
* This class is a bean containing the result of a login request.
*/
public class LoginRequestResult {
/**
* Either the login request is successful or note.
*/
public boolean success;
/**
* The application key returned by the login request if the request was successful.
*/
public String appKey;
}
| 23.375 | 85 | 0.692513 |
40b9d068be3c886e4a0e26ffe8b857491ee715dc
| 2,759 |
package com.huawei.oo;
import java.util.Scanner;
/**
* # 【服务器问题】----【本题的题意和求岛屿的最大面积是一样的,算法思路也相同:https://leetcode-cn.com/problems/max-area-of-island/】 在一机屋中、服务器的作置标识再
* n*m矩阵网络中,1表示单元格上有服务四,0表示没有, 如果两台服务器位于同一行,或者同一列中紧邻的位置,则认为他们之间可以组或一个局域,请你统计机房中最大的局城网包含的服务器个数,
* <p>
* 【注意】:此题和leetCode上的不一致 【注意点1】:如果两台服务器位于同一行,或者同一列中紧邻的位置,则认为他们之间可以组或一个局域---必须紧邻,才能构成一个局域网
* 【注意点2】:请你统计机房中最大的局城网包含的服务器个数---输出结果为最大局域网的服务器个数 - 输入描述,: 第1行输入两个正整数,n和m,n大于0,m<=100. 之后为n*m得二维数组,,代表服务器信息,
* <p>
* - 输出 最大局城网包含的服务器个数,
* <p>
* 输入 2 2 1 0 0 0 输出:0 输入 2 2 1 0 1 1 输出:3
* <p>
* 输入: 4 4 1 1 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 0 1 1 输出: 5
* <p>
* 输入: 4 4 1 1 0 1 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 1 输出: 3
*/
public class Huawei_20200603_06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String[] input = sc.nextLine().trim().split(" ");
int n = Integer.valueOf(input[0]);
int m = Integer.valueOf(input[1]);
// 收集数据
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
String[] temp = sc.nextLine().trim().split(" ");
for (int j = 0; j < m; j++) {
grid[i][j] = Integer.valueOf(temp[j]);
}
}
// 进行逻辑计算
int count = maxAreaOfIsland(grid);
System.out.println(count);
}
// int[][] grid = {{1, 0}, {0, 0}};
// int[][] grid = {{1, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
// int[][] grid = {{1, 1, 0, 1, 0}, {1, 0, 0, 1, 0}, {0, 0, 0, 0, 0}, {1, 0, 0, 1, 1}};
// int count = maxAreaOfIsland(grid);
// System.out.println(count);
}
public static int maxAreaOfIsland(int[][] grid) {
// 岛屿的最大面积
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
int value = dfs(grid, i, j);
if (value > 1) {
res = Math.max(res, dfs(grid, i, j));
}
}
}
}
return res;
}
private static int dfs(int[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == 0) {
return 0;
}
// 标识子节点已经遍历过了
grid[i][j] = 0;
// 每次调用的时候默认num为1,进入后判断如果不是岛屿,则直接返回0,就可以避免预防错误的情况。
// 每次找到岛屿,则直接把找到的岛屿改成0,这是传说中的沉岛思想,就是遇到岛屿就把他和周围的全部沉默。
int num = 1;
num += dfs(grid, i - 1, j);
num += dfs(grid, i + 1, j);
num += dfs(grid, i, j - 1);
num += dfs(grid, i, j + 1);
return num;
}
}
| 31.352273 | 113 | 0.47191 |
d816bf66133a54e43d8b5ac5a50aa788787000e4
| 1,504 |
package com.general_hello.commands.commands.MusicPlainCommand;
import com.general_hello.commands.commands.CommandContext;
import com.general_hello.commands.commands.CommandType;
import com.general_hello.commands.commands.ICommand;
import com.general_hello.commands.commands.Music.AudioManager;
import com.general_hello.commands.commands.Music.GuildAudioPlayer;
import com.general_hello.commands.commands.Utils.EmbedUtil;
import net.dv8tion.jda.api.entities.Member;
import java.io.IOException;
import java.sql.SQLException;
public class VolumeCommand implements ICommand
{
@Override
public void handle(CommandContext event) throws InterruptedException, IOException, SQLException {
Member member = event.getMember();
String option = event.getArgs().get(0);
int volume = Math.max(1, Math.min(100, Integer.parseInt(option)));
GuildAudioPlayer guildAudioPlayer = AudioManager.getAudioPlayer(event.getGuild().getIdLong());
guildAudioPlayer.getPlayer().setVolume(volume);
event.getMessage().replyEmbeds(EmbedUtil.successEmbed("The volume has been adjusted to `" + volume + "%`!")).queue();
}
@Override
public String getName() {
return "volume";
}
@Override
public String getHelp(String prefix) {
return "Change the volume of the bot\n" +
"Usage: `" + prefix + getName() + " [volume 1-100]`";
}
@Override
public CommandType getCategory() {
return CommandType.MUSIC;
}
}
| 35.809524 | 125 | 0.722739 |
aa6bc462ff52f9203acd02013eb8e2b31d947132
| 1,773 |
package org.raml.ramltopojo;
import com.google.common.base.Optional;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
/**
* Created. There, you have it.
*/
public class CreationResult {
private final String packageName;
private final TypeSpec interf;
private final TypeSpec impl;
private final ArrayList<CreationResult> internalTypes = new ArrayList<>();
public static CreationResult forType(String packageName, TypeSpec interf, TypeSpec impl) {
return new CreationResult(packageName, interf, impl);
}
public static CreationResult forEnumeration(String packageName, TypeSpec enumeration) {
return new CreationResult(packageName, enumeration, null);
}
CreationResult(String packageName, TypeSpec interf, TypeSpec impl) {
this.packageName = packageName;
this.interf = interf;
this.impl = impl;
}
public void internalType(CreationResult creationResult) {
this.internalTypes.add(creationResult);
}
public TypeSpec getInterface() {
return interf;
}
public Optional<TypeSpec> getImplementation() {
return Optional.fromNullable(impl);
}
public void createType(String rootDirectory) throws IOException {
createJavaFile(packageName, interf, rootDirectory);
if ( impl != null ) {
createJavaFile(packageName, impl, rootDirectory);
}
}
protected void createJavaFile(String packageName, TypeSpec typeSpec, String rootDirectory ) throws IOException {
JavaFile.builder(packageName, typeSpec).skipJavaLangImports(true).build().writeTo(Paths.get(rootDirectory));
}
}
| 27.703125 | 118 | 0.711224 |
e2e73a056b0b993c56ba0266e62c7fa03b32a0db
| 1,911 |
package nl.datavisual.dto;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class OrganisationUnitDTO implements Serializable {
private static final long serialVersionUID = 1L;
private int idOrgUnits;
private String code;
private Date efectiveYear;
private String name;
private List<OrganisationSubunitDTO> organisationSubunitDTOS;
private CompanyDTO companyDTO;
public OrganisationUnitDTO() {
}
public int getIdOrgUnits() {
return this.idOrgUnits;
}
public void setIdOrgUnits(int idOrgUnits) {
this.idOrgUnits = idOrgUnits;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Date getEfectiveYear() {
return this.efectiveYear;
}
public void setEfectiveYear(Date efectiveYear) {
this.efectiveYear = efectiveYear;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<OrganisationSubunitDTO> getOrganisationSubunitDTOS() {
return this.organisationSubunitDTOS;
}
public void setOrganisationSubunitDTOS(List<OrganisationSubunitDTO> organisationSubunitDTOS) {
this.organisationSubunitDTOS = organisationSubunitDTOS;
}
public OrganisationSubunitDTO addOrganisationSubunit(OrganisationSubunitDTO organisationSubunitDTO) {
getOrganisationSubunitDTOS().add(organisationSubunitDTO);
organisationSubunitDTO.setOrganisationUnitDTO(this);
return organisationSubunitDTO;
}
public OrganisationSubunitDTO removeOrganisationSubunit(OrganisationSubunitDTO organisationSubunitDTO) {
getOrganisationSubunitDTOS().remove(organisationSubunitDTO);
organisationSubunitDTO.setOrganisationUnitDTO(null);
return organisationSubunitDTO;
}
public CompanyDTO getCompanyDTO() {
return this.companyDTO;
}
public void setCompanyDTO(CompanyDTO companyDTO) {
this.companyDTO = companyDTO;
}
}
| 21.47191 | 105 | 0.790686 |
9d197d7b60c1fe0fe316fb8c1b51fe736ffa2c0a
| 4,901 |
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.binding;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.beans.factory.support.AutowireCandidateQualifier;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.cloud.stream.annotation.Bindings;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import org.springframework.util.StringUtils;
/**
* Utility class for registering bean definitions for message channels.
*
* @author Marius Bogoevici
* @author Dave Syer
*/
public abstract class BindingBeanDefinitionRegistryUtils {
public static void registerInputChannelBeanDefinition(String qualifierValue,
String name, String channelInterfaceBeanName,
String channelInterfaceMethodName, BeanDefinitionRegistry registry) {
registerChannelBeanDefinition(Input.class, qualifierValue, name,
channelInterfaceBeanName, channelInterfaceMethodName, registry);
}
public static void registerOutputChannelBeanDefinition(String qualifierValue,
String name, String channelInterfaceBeanName,
String channelInterfaceMethodName, BeanDefinitionRegistry registry) {
registerChannelBeanDefinition(Output.class, qualifierValue, name,
channelInterfaceBeanName, channelInterfaceMethodName, registry);
}
private static void registerChannelBeanDefinition(
Class<? extends Annotation> qualifier, String qualifierValue, String name,
String channelInterfaceBeanName, String channelInterfaceMethodName,
BeanDefinitionRegistry registry) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
rootBeanDefinition.setFactoryBeanName(channelInterfaceBeanName);
rootBeanDefinition.setUniqueFactoryMethodName(channelInterfaceMethodName);
rootBeanDefinition.addQualifier(new AutowireCandidateQualifier(qualifier,
qualifierValue));
registry.registerBeanDefinition(name, rootBeanDefinition);
}
public static void registerChannelBeanDefinitions(Class<?> type,
final String channelInterfaceBeanName, final BeanDefinitionRegistry registry) {
ReflectionUtils.doWithMethods(type, new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException,
IllegalAccessException {
Input input = AnnotationUtils.findAnnotation(method, Input.class);
if (input != null) {
String name = getChannelName(input, method);
registerInputChannelBeanDefinition(input.value(), name,
channelInterfaceBeanName, method.getName(), registry);
}
Output output = AnnotationUtils.findAnnotation(method, Output.class);
if (output != null) {
String name = getChannelName(output, method);
registerOutputChannelBeanDefinition(output.value(), name,
channelInterfaceBeanName, method.getName(), registry);
}
}
});
}
public static void registerChannelsQualifiedBeanDefinitions(Class<?> parent,
Class<?> type, final BeanDefinitionRegistry registry) {
if (type.isInterface()) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(
BindableProxyFactory.class);
rootBeanDefinition.addQualifier(new AutowireCandidateQualifier(
Bindings.class, parent));
rootBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(
type);
registry.registerBeanDefinition(type.getName(), rootBeanDefinition);
}
else {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(type);
rootBeanDefinition.addQualifier(new AutowireCandidateQualifier(
Bindings.class, parent));
registry.registerBeanDefinition(type.getName(), rootBeanDefinition);
}
}
public static String getChannelName(Annotation annotation, Method method) {
Map<String, Object> attrs = AnnotationUtils.getAnnotationAttributes(annotation,
false);
if (attrs.containsKey("value")
&& StringUtils.hasText((CharSequence) attrs.get("value"))) {
return (String) attrs.get("value");
}
return method.getName();
}
}
| 39.845528 | 82 | 0.792899 |
b42d88861a95fa1e4836f3b03a1c0907597b9292
| 368 |
package com.blogspot.applications4android.comicreader.comics.GoComics;
import java.util.Calendar;
import com.blogspot.applications4android.comicreader.comictypes.DailyGoComicsCom;
public class Andertoons extends DailyGoComicsCom {
public Andertoons() {
super();
mComicName = "andertoons";
mFirstCal = Calendar.getInstance();
mFirstCal.set(2011, 8, 1);
}
}
| 26.285714 | 81 | 0.788043 |
886de43f087011ff8ea5cbd646edaff132a629d9
| 1,575 |
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.cdi.tests;
import java.io.IOException;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.inject.Inject;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
public class MyFilter implements Filter
{
@Inject
BeanManager manager;
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
if (manager == null)
throw new IllegalStateException();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// copy attribute from MyListener to see if it was decorated.
request.setAttribute("filter", manager);
chain.doFilter(request, response);
}
@Override
public void destroy()
{
}
}
| 29.716981 | 130 | 0.661587 |
5604536272cd241bd8113d1ad46247954c7637f6
| 1,540 |
package edu.cmu.sv.ws.ssnoc.data.po;
import com.google.gson.Gson;
//import java.sql.Timestamp;
public class MemoryPO {
private String crumbID;
private long usedVolatile;
private long freeVolatile;
private long usedNonVolatile;
private long freeNonVolatile;
private String createdAt;
// private int minutes;
public void setCrumbID(String crumbID){
this.crumbID = crumbID;
}
public String getCrumbID(){
return crumbID;
}
public void setUsedVolatile(long usedVolatile){
this.usedVolatile = usedVolatile;
}
public long getUsedVolatile(){
return usedVolatile;
}
public void setFreeVolatile(long freeVolatile){
this.freeVolatile = freeVolatile;
}
public long getFreeVolatile(){
return freeVolatile;
}
public void setUsedNonVolatile(long usedNonVolatile){
this.usedNonVolatile = usedNonVolatile;
}
public long getUsedNonVolatile(){
return usedNonVolatile;
}
public void setFreeNonVolatile(long freeNonVolatile){
this.freeNonVolatile = freeNonVolatile;
}
public long getFreeNonVolatile(){
return freeNonVolatile;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
@Override
public String toString() {
return new Gson().toJson(this);
}
// public int getMinutes() {
// return minutes;
// }
//
// public void setMinutes(int minutes) {
// this.minutes = minutes;
// }
}
| 20 | 57 | 0.680519 |
34cfd5ccc218a7108093845faac4ff16de6acded
| 342 |
package github.nikhilbhutani.usingactiveandroid;
import android.app.Application;
import com.activeandroid.ActiveAndroid;
/**
* Created by Nikhil Bhutani on 6/23/2016.
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ActiveAndroid.initialize(this);
}
}
| 19 | 48 | 0.716374 |
0a9ae3dfa3af7279d0691348fe5f9ec7c415764b
| 7,627 |
// Copyright 2015-2021 Nkisi inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nkisi.system.agent;
import nkisi.api.Downlink;
import nkisi.api.auth.Identity;
import nkisi.api.lane.SupplyLane;
import nkisi.api.policy.Policy;
import nkisi.concurrent.Schedule;
import nkisi.concurrent.Stage;
import nkisi.store.StoreBinding;
import nkisi.structure.Value;
import nkisi.system.LaneAddress;
import nkisi.system.LaneBinding;
import nkisi.system.LaneContext;
import nkisi.system.LinkBinding;
import nkisi.system.Metric;
import nkisi.system.NodeBinding;
import nkisi.system.Push;
import nkisi.system.reflect.LogEntry;
import nkisi.uri.Uri;
public class AgentLane implements LaneContext {
protected final AgentNode node;
protected final LaneBinding lane;
protected final LaneAddress laneAddress;
SupplyLane<LogEntry> metaTraceLog;
SupplyLane<LogEntry> metaDebugLog;
SupplyLane<LogEntry> metaInfoLog;
SupplyLane<LogEntry> metaWarnLog;
SupplyLane<LogEntry> metaErrorLog;
SupplyLane<LogEntry> metaFailLog;
public AgentLane(AgentNode node, LaneBinding lane, LaneAddress laneAddress) {
this.node = node;
this.lane = lane;
this.laneAddress = laneAddress;
this.metaTraceLog = null;
this.metaDebugLog = null;
this.metaInfoLog = null;
this.metaWarnLog = null;
this.metaErrorLog = null;
this.metaFailLog = null;
}
@Override
public final NodeBinding node() {
return this.node;
}
@Override
public final LaneBinding laneWrapper() {
return this.lane.laneWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapLane(Class<T> laneClass) {
if (laneClass.isAssignableFrom(this.getClass())) {
return (T) this;
} else {
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public <T> T bottomLane(Class<T> laneClass) {
if (laneClass.isAssignableFrom(this.getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public final LaneAddress cellAddress() {
return this.laneAddress;
}
@Override
public final String edgeName() {
return this.laneAddress.edgeName();
}
@Override
public final Uri meshUri() {
return this.laneAddress.meshUri();
}
@Override
public final Value partKey() {
return this.laneAddress.partKey();
}
@Override
public final Uri hostUri() {
return this.laneAddress.hostUri();
}
@Override
public final Uri nodeUri() {
return this.laneAddress.nodeUri();
}
@Override
public final Uri laneUri() {
return this.laneAddress.laneUri();
}
@Override
public final Identity identity() {
return this.node.identity();
}
@Override
public Policy policy() {
return this.node.policy();
}
@Override
public Schedule schedule() {
return this.node;
}
@Override
public Stage stage() {
return this.node;
}
@Override
public StoreBinding store() {
return this.node.store();
}
@Override
public void openMetaLane(LaneBinding lane, NodeBinding metaLane) {
this.openMetaLanes(lane, (AgentNode) metaLane);
this.node.openMetaLane(lane, metaLane);
}
protected void openMetaLanes(LaneBinding lane, AgentNode metaLane) {
this.openLogLanes(lane, metaLane);
}
protected void openLogLanes(LaneBinding lane, AgentNode metaLane) {
this.metaTraceLog = metaLane.supplyLane().valueForm(LogEntry.form());
metaLane.openLane(LogEntry.TRACE_LOG_URI, this.metaTraceLog);
this.metaDebugLog = metaLane.supplyLane().valueForm(LogEntry.form());
metaLane.openLane(LogEntry.DEBUG_LOG_URI, this.metaDebugLog);
this.metaInfoLog = metaLane.supplyLane().valueForm(LogEntry.form());
metaLane.openLane(LogEntry.INFO_LOG_URI, this.metaInfoLog);
this.metaWarnLog = metaLane.supplyLane().valueForm(LogEntry.form());
metaLane.openLane(LogEntry.WARN_LOG_URI, this.metaWarnLog);
this.metaErrorLog = metaLane.supplyLane().valueForm(LogEntry.form());
metaLane.openLane(LogEntry.ERROR_LOG_URI, this.metaErrorLog);
this.metaFailLog = metaLane.supplyLane().valueForm(LogEntry.form());
metaLane.openLane(LogEntry.FAIL_LOG_URI, this.metaFailLog);
}
@Override
public void openMetaUplink(LinkBinding uplink, NodeBinding metaUplink) {
this.node.openMetaUplink(uplink, metaUplink);
}
@Override
public void openMetaDownlink(LinkBinding downlink, NodeBinding metaDownlink) {
this.node.openMetaDownlink(downlink, metaDownlink);
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.node.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.node.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushDown(Push<?> push) {
this.node.pushDown(push);
}
@Override
public void reportDown(Metric metric) {
this.node.reportDown(metric);
}
@Override
public void trace(Object message) {
final SupplyLane<LogEntry> metaTraceLog = this.metaTraceLog;
if (metaTraceLog != null) {
metaTraceLog.push(LogEntry.trace(message));
}
this.node.trace(message);
}
@Override
public void debug(Object message) {
final SupplyLane<LogEntry> metaDebugLog = this.metaDebugLog;
if (metaDebugLog != null) {
metaDebugLog.push(LogEntry.debug(message));
}
this.node.debug(message);
}
@Override
public void info(Object message) {
final SupplyLane<LogEntry> metaInfoLog = this.metaInfoLog;
if (metaInfoLog != null) {
metaInfoLog.push(LogEntry.info(message));
}
this.node.info(message);
}
@Override
public void warn(Object message) {
final SupplyLane<LogEntry> metaWarnLog = this.metaWarnLog;
if (metaWarnLog != null) {
metaWarnLog.push(LogEntry.warn(message));
}
this.node.warn(message);
}
@Override
public void error(Object message) {
final SupplyLane<LogEntry> metaErrorLog = this.metaErrorLog;
if (metaErrorLog != null) {
metaErrorLog.push(LogEntry.error(message));
}
this.node.error(message);
}
@Override
public void fail(Object message) {
final SupplyLane<LogEntry> metaFailLog = this.metaFailLog;
if (metaFailLog != null) {
metaFailLog.push(LogEntry.fail(message));
}
this.node.fail(message);
}
@Override
public void close() {
this.node.closeLane(this.laneAddress.laneUri());
}
@Override
public void willOpen() {
this.lane.open();
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
this.lane.load();
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
this.lane.start();
}
@Override
public void didStart() {
// nop
}
@Override
public void willStop() {
this.lane.stop();
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
this.lane.unload();
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
this.lane.close();
}
}
| 23.042296 | 80 | 0.697784 |
0f7cf682c2d64b0b767758d7b3a57709ceaa25bc
| 19,579 |
package com.fanxin.huangfangyi.main.ulive.upload;
import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.fanxin.huangfangyi.DemoApplication;
import com.fanxin.huangfangyi.R;
import com.fanxin.huangfangyi.main.FXConstant;
import com.fanxin.huangfangyi.main.adapter.LiveMessageAdapter;
import com.fanxin.huangfangyi.main.ulive.preference.Log2FileUtil;
import com.fanxin.huangfangyi.main.ulive.preference.Settings;
import com.fanxin.huangfangyi.ui.BaseActivity;
import com.fanxin.easeui.EaseConstant;
import com.fanxin.easeui.controller.EaseUI;
import com.fanxin.easeui.utils.EaseCommonUtils;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.ucloud.common.util.DeviceUtils;
import com.ucloud.common.util.StringUtil;
import com.ucloud.live.UEasyStreaming;
import com.ucloud.live.UStreamingProfile;
import com.ucloud.live.widget.UAspectFrameLayout;
import java.util.List;
public abstract class BasePublishDemo extends BaseActivity implements UEasyStreaming.UStreamingStateListener {
private static final String TAG = "BasePublishDemo";
public static final int MSG_UPDATE_COUNTDOWN = 1;
public static final int COUNTDOWN_DELAY = 1000;
public static final int COUNTDOWN_START_INDEX = 3;
public static final int COUNTDOWN_END_INDEX = 1;
protected Settings mSettings;
protected String rtmpPushStreamDomain = "publish3.cdn.ucloud.com.cn";
//Views
protected ImageView mCameraToggleIv;
protected ImageView mLampToggleIv;
protected ImageButton mCloseRecorderImgBtn;
protected ImageButton mToggleFilterImgBtn;
protected Button mBackImgBtn;
protected View mFocusIndex;
protected TextView mBitrateTxtv;
protected TextView mCountDownTxtv;
protected TextView mRecordedTimeTxtv;
protected TextView mOutputStreamInfoTxtv;
protected TextView mBufferOverfloInfoTxtv;
protected ViewGroup mContainer;
protected UAspectFrameLayout mPreviewContainer;
protected boolean isShutDownCountdown = false;
protected UEasyStreaming mEasyStreaming;
protected UStreamingProfile mStreamingProfile;
protected UiHandler uiHandler;
public abstract void initEnv();
private ListView listView;
private int chatType = EaseConstant.CHATTYPE_CHATROOM;
private String toChatUsername;
private Button btn_send;
private EditText et_content;
private List<EMMessage> msgList;
LiveMessageAdapter adapter;
private EMConversation conversation;
protected int pagesize = 20;
private ProgressDialog progressDialog;
@Override
public void onStateChanged(int type, Object event) {
switch (type) {
case UEasyStreaming.State.START_PREVIEW:
Log.i(TAG, event.toString());
handleShowStreamingInfo();
if (this instanceof PublishDemo4MediaCodec) {
mEasyStreaming.applyFilter(UEasyStreaming.FILTER_BEAUTIFY_HIGH_PERFORMANCE);
// mEasyStreaming.applyFilter(UEasyStreaming.FILTER_BEAUTIFY);
}
break;
case UEasyStreaming.State.START_RECORDING:
Log.i(TAG, event.toString());
break;
case UEasyStreaming.State.BUFFER_OVERFLOW:
mBufferOverfloInfoTxtv.setText("unstable network stats:" + mEasyStreaming.getNetworkUnstableStats());
Log.w(TAG, "unstable network");
Toast.makeText(this, "unstable network", Toast.LENGTH_SHORT).show();
break;
case UEasyStreaming.State.MEDIA_MUXER_PREPARED_ERROR:
Log.e(TAG, "prepare error, the publish stream id may be reuse, server error or network disconnect, try change one.");
Toast.makeText(this, "the publish stream id may be reuse, server error or network disconnect, try change one.", Toast.LENGTH_LONG).show();
break;
case UEasyStreaming.State.MEDIA_MUXER_PREPARED_SUCCESS:
Log.i(TAG, event.toString());
break;
case UEasyStreaming.State.MEDIA_INFO_SIGNATRUE_FAILED:
Toast.makeText(this, event.toString(), Toast.LENGTH_LONG).show();
break;
case UEasyStreaming.State.MEDIA_INFO_NETWORK_SPEED:
if (mBitrateTxtv != null) {
mBitrateTxtv.setVisibility(View.VISIBLE);
long speed = Long.valueOf(event.toString());
if (speed > 1024) {
mBitrateTxtv.setText(speed / 1024 + "K/s");
}
else {
mBitrateTxtv.setText(speed + "B/s");
}
}
break;
case UEasyStreaming.State.MEDIA_INFO_PUBLISH_STREAMING_TIME:
if (mRecordedTimeTxtv != null) {
mRecordedTimeTxtv.setVisibility(View.VISIBLE);
long time = Long.valueOf(event.toString());
String retVal = StringUtil.getTimeFormatString(time);
mRecordedTimeTxtv.setText(retVal);
}
break;
case UEasyStreaming.State.MEDIA_ERROR_CAMERA_PREVIEW_SIZE_UNSUPPORT:
Log.e(TAG, "MEDIA_ERROR_CAMERA_PREVIEW:" + event.toString());
break;
}
}
private class UiHandler extends Handler {
public UiHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_COUNTDOWN:
handleUpdateCountdown(msg.arg1);
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("正在进入直播间...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
mSettings = new Settings(this);
setContentView(R.layout.live_layout_live_room_view);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mSettings.getVideoCaptureOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
init();
new Thread(){
public void run() {
int i = COUNTDOWN_START_INDEX;
do {
try {
Thread.sleep(COUNTDOWN_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = Message.obtain();
msg.what = MSG_UPDATE_COUNTDOWN;
msg.arg1 = i;
uiHandler.sendMessage(msg);
i--;
}while(i >= COUNTDOWN_END_INDEX);
}
}.start();
initViewChat();
}
private void init() {
uiHandler = new UiHandler(getMainLooper());
initView();
initEnv();
}
private void initViewChat(){
toChatUsername = FXConstant.FXLIVE_CHATROOM_ID;
listView = (ListView) findViewById(R.id.list);
listView.getBackground().setAlpha(100);
btn_send = (Button) this.findViewById(R.id.btn_send);
et_content = (EditText) this.findViewById(R.id.et_content);
EMClient.getInstance().chatroomManager().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {
@Override
public void onSuccess(EMChatRoom emChatRoom) {
runOnUiThread(new Runnable() {
@Override
public void run() {
getAllMessage();
}
});
}
@Override
public void onError(int i, String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(progressDialog!=null&&progressDialog.isShowing()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"初始化互动模块失败...",Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void initView() {
mCameraToggleIv = (ImageView) findViewById(R.id.img_bt_switch_camera);
mLampToggleIv = (ImageView) findViewById(R.id.img_bt_lamp);
mCloseRecorderImgBtn = (ImageButton) findViewById(R.id.img_bt_close_record);
mFocusIndex = findViewById(R.id.focus_index);
mBitrateTxtv = (TextView) findViewById(R.id.bitrate_txtv);
mPreviewContainer = (UAspectFrameLayout)findViewById(R.id.container);
mCountDownTxtv = (TextView) findViewById(R.id.countdown_txtv);
mRecordedTimeTxtv = (TextView) findViewById(R.id.recorded_time_txtv);
mOutputStreamInfoTxtv = (TextView) findViewById(R.id.output_url_txtv);
mToggleFilterImgBtn = (ImageButton) findViewById(R.id.img_bt_filter);
mBufferOverfloInfoTxtv = (TextView) findViewById(R.id.network_overflow_count);
mBackImgBtn = (Button) findViewById(R.id.btn_finish);
mContainer = (ViewGroup) findViewById(R.id.live_finish_container);
mCameraToggleIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mEasyStreaming != null) {
mEasyStreaming.switchCamera();
}
}
});
mLampToggleIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mEasyStreaming != null) {
mEasyStreaming.toggleFlashMode();
}
}
});
mCloseRecorderImgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isShutDownCountdown = true;
mCloseRecorderImgBtn.setEnabled(false);
if (mEasyStreaming != null) {
mEasyStreaming.stopRecording();
}
mContainer.setVisibility(View.VISIBLE);
}
});
mToggleFilterImgBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (BasePublishDemo.this instanceof PublishDemo4MediaCodec) {
mEasyStreaming.toggleFilter();
} else {
Toast.makeText(BasePublishDemo.this, "Sorry, just support for mediacodec.", Toast.LENGTH_SHORT).show();
}
}
});
mBackImgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected void onPause() {
super.onPause();
mEasyStreaming.onPause();
}
@Override
protected void onResume() {
super.onResume();
mEasyStreaming.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mSettings.isOpenLogRecoder()) {
Log2FileUtil.getInstance().stopLog();
}
mEasyStreaming.onDestory();
EMClient.getInstance().chatManager().removeMessageListener(msgListener);
}
public String bitrateMode(int value) {
switch (value) {
case UStreamingProfile.VIDEO_BITRATE_LOW: return "VIDEO_BITRATE_LOW";
case UStreamingProfile.VIDEO_BITRATE_NORMAL: return "VIDEO_BITRATE_NORMAL";
case UStreamingProfile.VIDEO_BITRATE_MEDIUM: return "VIDEO_BITRATE_MEDIUM";
case UStreamingProfile.VIDEO_BITRATE_HIGH: return "VIDEO_BITRATE_HIGH";
default: return value +"";
}
}
public void handleShowStreamingInfo() {
if (mOutputStreamInfoTxtv != null) {
mOutputStreamInfoTxtv.setVisibility(View.VISIBLE);
String info = "video width:" + mSettings.getVideoCaptureWidth()+ "\n" +
"video height:" + mSettings.getVideoCaptureHeight() + "\n" +
"video bitrate:" + bitrateMode(mSettings.getVideoEncodingBitRate()) + "\n" +
"video fps:" + mSettings.getVideoFrameRate() + "\n" +
"url:" + "rtmp://" + mStreamingProfile.getStream().getPublishDomain() + "/" + mStreamingProfile.getStream().getStreamId() + "\n" +
"brand:" + DeviceUtils.getDeviceBrand() + "_" + DeviceUtils.getDeviceModel() + "\n" +
"sdk version:" + com.ucloud.live.Build.VERSION + "\n" +
"android sdk version:" + android.os.Build.VERSION.SDK_INT + "\n" +
"codec type:" + (BasePublishDemo.this instanceof PublishDemo4MediaCodec ? "mediacodec" : "x264") + "\n";
mOutputStreamInfoTxtv.setText(info);
Log.e(TAG, "@@" + info);
}
}
public void handleUpdateCountdown(final int count) {
if (mCountDownTxtv != null) {
mCountDownTxtv.setVisibility(View.VISIBLE);
mCountDownTxtv.setText(String.format("%d", count));
ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f,0f, 1.0f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(COUNTDOWN_DELAY);
scaleAnimation.setFillAfter(false);
scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mCountDownTxtv.setVisibility(View.GONE);
if (count == COUNTDOWN_END_INDEX && mEasyStreaming != null && !isShutDownCountdown) {
mEasyStreaming.startRecording();
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
if (!isShutDownCountdown) {
mCountDownTxtv.startAnimation(scaleAnimation);
} else {
mCountDownTxtv.setVisibility(View.GONE);
}
}
}
protected void getAllMessage() {
// 获取当前conversation对象
conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername,
EaseCommonUtils.getConversationType(chatType), true);
// 把此会话的未读数置为0
conversation.markAllMessagesAsRead();
// 初始化db时,每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
// 这个数目如果比用户期望进入会话界面时显示的个数不一样,就多加载一些
final List<EMMessage> msgs = conversation.getAllMessages();
int msgCount = msgs != null ? msgs.size() : 0;
if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
String msgId = null;
if (msgs != null && msgs.size() > 0) {
msgId = msgs.get(0).getMsgId();
}
conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
}
msgList = conversation.getAllMessages();
adapter = new LiveMessageAdapter(msgList, BasePublishDemo.this);
listView.setAdapter(adapter);
listView.setSelection(listView.getCount() - 1);
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = et_content.getText().toString().trim();
if (TextUtils.isEmpty(content)) {
return;
}
setMesaage(content);
}
});
EMClient.getInstance().chatManager().addMessageListener(msgListener);
if(progressDialog!=null&&progressDialog.isShowing()){
progressDialog.dismiss();
}
}
private void setMesaage(String content) {
// 创建一条文本消息,content为消息文字内容,toChatUsername为对方用户或者群聊的id,后文皆是如此
EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == EaseConstant.CHATTYPE_CHATROOM)
message.setChatType(EMMessage.ChatType.ChatRoom);
message.setAttribute(FXConstant.KEY_USER_INFO, DemoApplication.getInstance().getUserJson().toJSONString());
// 发送消息
EMClient.getInstance().chatManager().sendMessage(message);
msgList.add(message);
adapter.notifyDataSetChanged();
if (msgList.size() > 0) {
listView.setSelection(listView.getCount() - 1);
}
et_content.setText("");
}
EMMessageListener msgListener = new EMMessageListener() {
@Override
public void onMessageReceived(List<EMMessage> messages) {
for (EMMessage message : messages) {
String username = null;
// 群组消息
if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
username = message.getTo();
} else {
// 单聊消息
username = message.getFrom();
}
// 如果是当前会话的消息,刷新聊天页面
if (username.equals(toChatUsername)) {
msgList.addAll(messages);
adapter.notifyDataSetChanged();
if (msgList.size() > 0) {
et_content.setSelection(listView.getCount() - 1);
}
}else {
// 如果消息不是和当前聊天ID的消息
EaseUI.getInstance().getNotifier().onNewMsg(message);
}
}
// 收到消息
}
@Override
public void onCmdMessageReceived(List<EMMessage> messages) {
// 收到透传消息
}
@Override
public void onMessageReadAckReceived(List<EMMessage> messages) {
// 收到已读回执
}
@Override
public void onMessageDeliveryAckReceived(List<EMMessage> message) {
// 收到已送达回执
}
@Override
public void onMessageChanged(EMMessage message, Object change) {
// 消息状态变动
}
};
}
| 37.579655 | 154 | 0.605802 |
e814e223e0df43b9b4245acf7315fde15a935b53
| 3,729 |
package com.eduardocode.jasonviewerapi.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.sql.DataSource;
/**
* <h1>SecurityConfiguration</h1>
* Clase de configuracion para el manejo de seguridad en la aplicacion
* Hereda de {@code WebSecurityConfigurerAdapter}.
*
* @author Eduardo Rasgado Ruiz
* @version 1.0
* @since april/2019
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private BCryptPasswordEncoder encoder;
@Value("${spring.queries.users-query}")
private String usernameQuery;
@Value("${spring.queries.roles-query}")
private String authoritiesQuery;
private String loginUrl;
private String failureLoginUrl;
private String homePage;
public SecurityConfiguration() {
this.loginUrl = "/app/login";
this.failureLoginUrl = "/app/login?error=true";
this.homePage = "/app/home";
}
/**
* Metodo para una configuracion de logueo basica de spring security
* @param http objeto principal de configuracion
* @throws Exception
*/
protected void configure(HttpSecurity http) throws Exception {
// desactivacion de la proteccion cross site request forgery
http .csrf().disable()
// autorizar todas las request, tiene que estar auntenticado
.authorizeRequests()
.anyRequest()
.authenticated()
// una vez logueado
.and()
.formLogin().loginPage(loginUrl).permitAll()
// en caso de fallar la autorizacion
.failureUrl(failureLoginUrl)
// una vez logueado, a donde ir, true es para alwaysUse
.defaultSuccessUrl(homePage, true)
.and()
// salir de la session, solo basta con poner un link a '/logout'
.logout();
}
/**
* Configuracion de acceso a la base de datos para spring, con el fin de loguear al administrador
* o usuarios que van a acceder al sistema
* @param auth Instancia de configuracion de acceso
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(usernameQuery)
.authoritiesByUsernameQuery(authoritiesQuery)
.passwordEncoder(encoder);
}
/**
* Metodo que defie las rutas de la applicacion que deben de ser ignoradas por la logica del
* login
* @param web instancia de configuracion web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/resources/**",
"/static/**",
"/css/**",
"/js/**",
"/images/**"
);
}
}
| 35.855769 | 107 | 0.667471 |
c78633c2098a24585c4c96e220c41ba04c942348
| 1,343 |
/**
This program demonstrates how to install an action listener.
*/
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CurrencyConvertor
{
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 200;
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(2, 5));
frame.add(pane);
InputConverter inputA = new InputConverter(300,30,false);
InputConverter inputB = new InputConverter(300,30,true);
pane.add(inputA);
pane.add(inputB);
CreateButton(pane,inputA,inputB);
frame.setMinimumSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void CreateButton(JPanel pane,InputConverter inputA, InputConverter inputB)
{
JButton button = new JButton("Convert");
button.setPreferredSize(new Dimension(200, 40));
ActionListener listener = new ClickListener(inputA,inputB);
button.addActionListener(listener);
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
pane.add(buttonPanel);
}
}
| 28.574468 | 90 | 0.731199 |
10f95b42b4c18461c0899118a78d43bdb8928172
| 5,023 |
/*
* 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.geode.cache.execute;
import java.util.concurrent.TimeUnit;
import org.apache.geode.distributed.DistributedMember;
/**
* <p>
* Defines the interface for a container that gathers results from function execution.<br>
* GemFire provides a default implementation for ResultCollector. Applications can choose to
* implement their own custom ResultCollector. A custom ResultCollector facilitates result sorting
* or aggregation. Aggregation functions like sum, minimum, maximum and average can also be applied
* to the result using a custom ResultCollector. Results arrive as they are sent using the
* {@link ResultSender#sendResult(Object)} and can be used as they arrive. To indicate that all
* results have been received {@link #endResults()} is called.
*
* </p>
* Example: <br>
*
* <pre>
* Region region ;
* Set keySet = Collections.singleton("myKey");
* Function multiGetFunction ;
* Object args ;
* ResultCollector rc = FunctionService.onRegion(region)
* .setArguments(args)
* .withFilter(keySet)
* .withCollector(new MyCustomResultCollector())
* .execute(multiGetFunction.getId());
* Application can do something else here before retrieving the result
* Or it can have some logic in {{@link #addResult(DistributedMember, Object)} to use the partial results.
* If it wants to see all the results it can use
* Object functionResult = rc.getResult();
* or
* Object functionResult = rc.getResult(timeout,TimeUnit);
* depending on if it wants to wait for all the results or wait for a timeout period.
* </pre>
*
* GemFire provides default implementation of ResultCollector which collects results in Arraylist.
* There is no need to provide a synchronization mechanism in the user implementations of
* ResultCollector
*
* @since GemFire 6.0
*
*/
public interface ResultCollector<T, S> {
/**
* Method used to pull results from the ResultCollector. It returns the result of function
* execution, potentially blocking until {@link #endResults() all the results are available} has
* been called.
*
* @return the result
* @throws FunctionException if result retrieval fails
* @since GemFire 6.0
*/
S getResult() throws FunctionException;
/**
* Method used to pull results from the ResultCollector. It returns the result of function
* execution, blocking for the timeout period until {@link #endResults() all the results are
* available}. If all the results are not received in provided time a FunctionException is thrown.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the result
* @throws FunctionException if result retrieval fails within timeout provided
* @throws InterruptedException if the current thread was interrupted while waiting
* @since GemFire 6.0
*
*/
S getResult(long timeout, TimeUnit unit) throws FunctionException, InterruptedException;
/**
* Method used to feed result to the ResultCollector. It adds a single function execution result
* to the ResultCollector It is invoked every time a result is sent using ResultSender.
*
* @since GemFire 6.0
* @param memberID DistributedMember ID to which result belongs
*/
void addResult(DistributedMember memberID, T resultOfSingleExecution);
/**
* GemFire will invoke this method when function execution has completed and all results for the
* execution have been obtained and {@link #addResult(DistributedMember, Object) added to the
* ResultCollector} Unless the {@link ResultCollector} has received
* {@link ResultSender#lastResult(Object) last result} from all the executing nodes, it keeps
* waiting for more results to come.
*
* @since GemFire 6.0
*
* @see ResultSender#lastResult(Object)
*/
void endResults();
/**
* GemFire will invoke this method before re-executing function (in case of Function Execution
* HA). This is to clear the previous execution results from the result collector
*
* @since GemFire 6.5
*/
void clearResults();
}
| 42.210084 | 107 | 0.721282 |
232c5a791e106d2045902d68f752bbab322ec24f
| 743 |
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class L1_ParkingLot {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Set<String> parking = new LinkedHashSet<>();
String input = "";
while(!"END".equals(input = scan.nextLine())){
String[] tokens = input.split(", ");
if(tokens[0].equals("IN")){
parking.add(tokens[1]);
}else{
parking.remove(tokens[1]);
}
}
if(parking.isEmpty()){
System.out.println("Parking Lot is Empty");
}
for (String s : parking) {
System.out.println(s);
};
}
}
| 23.967742 | 55 | 0.51817 |
9b3d8382be8a893854bd86e6b52ad428acf23d90
| 3,973 |
package client.indexnode;
import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import common.Util.FileSize;
import common.Util.NiceMagnitude;
/**
* This class provides a table model that shows statistics for each connected indexnode.
* It is guaranteed that this will use the same row indices as the IndexNodeCommunicator's table.
* @author gp
*/
public class IndexNodeStatsTableModel implements TableModel, TableModelListener {
IndexNodeCommunicator comm;
public IndexNodeStatsTableModel(IndexNodeCommunicator comm) {
this.comm = comm;
this.comm.addTableModelListener(this);
}
HashSet<IndexNode> knownNodes = new HashSet<IndexNode>();
/**
* We piggyback of the indexnode communicator tablemodel to get notified when events happen.
*
* This method will always be called in the swing thread, by contract.
*/
@Override
public void tableChanged(TableModelEvent ev) {
if (ev.getType()==TableModelEvent.INSERT) { //adding a stats update listener only appropriate for the insert event
final IndexNode n = comm.getNodeForRow(ev.getFirstRow());
if (knownNodes.add(n)) {
n.addStatsListener(new StatsListener() {
/**
* When the indexnode has fresh stats, update that row of the table.
*/
@Override
public void statsUpdated() {
synchronized (listeners) {
for (TableModelListener l : listeners) {
int rowIdx = comm.getRowForNode(n); //have to look up the index every time... uh.
l.tableChanged(new TableModelEvent(IndexNodeStatsTableModel.this, rowIdx, rowIdx, TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE)); ///notify of changed row.
}
}
}
});
}
}
//Pass on the event.
synchronized (listeners) {
for (TableModelListener l : listeners) {
l.tableChanged(ev);
}
}
}
ArrayList<TableModelListener> listeners = new ArrayList<TableModelListener>();
@Override
public void addTableModelListener(TableModelListener l) {
synchronized (listeners) {
listeners.add(l);
}
}
private Class<?>[] columnClasses = {String.class, FileSize.class, FileSize.class, NiceMagnitude.class, NiceMagnitude.class}; //Name, size, unique size, files, unique files
private String[] columnNames = {"Indexnode", "Total Size", "Unique Size", "File count", "Unique files"};
private static final int NAME_IDX=0;
private static final int SIZE_IDX=1;
private static final int UNIQUE_SIZE_IDX=2;
private static final int COUNT_IDX=3;
private static final int UNIQUE_COUNT_IDX=4;
@Override
public Class<?> getColumnClass(int colIdx) {
return columnClasses[colIdx];
}
@Override
public int getColumnCount() {
return columnClasses.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public int getRowCount() {
return comm.getRowCount();
}
@Override
public Object getValueAt(int row, int col) {
IndexNode node = comm.getNodeForRow(row);
switch (col) {
case NAME_IDX:
return node.getName();
case SIZE_IDX:
return new FileSize(node.getStats().getSize());
case UNIQUE_SIZE_IDX:
return new FileSize(node.getStats().getUniqueSize());
case COUNT_IDX:
return new NiceMagnitude((long)node.getStats().getIndexedFiles(),"");
case UNIQUE_COUNT_IDX:
return new NiceMagnitude((long)node.getStats().getUniqueFiles(),"");
}
return null;
}
@Override
public boolean isCellEditable(int row, int col) {
return false; //nothing user editable
}
@Override
public void removeTableModelListener(TableModelListener l) {
synchronized (listeners) {
listeners.remove(l);
}
}
@Override
public void setValueAt(Object val, int row, int col) {
//nothing to do, as it's a readonly table.
}
}
| 28.789855 | 173 | 0.699471 |
61365f3d60a033bd89b1bc2d7124eac8b83a6d53
| 4,733 |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.execution.context.ExecutionContext;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.modern.BuildCellRelativePathFactory;
import com.facebook.buck.rules.modern.Buildable;
import com.facebook.buck.rules.modern.HasBrokenInputBasedRuleKey;
import com.facebook.buck.rules.modern.ModernBuildRule;
import com.facebook.buck.rules.modern.OutputPath;
import com.facebook.buck.rules.modern.OutputPathResolver;
import com.facebook.buck.shell.ShellStep;
import com.facebook.buck.step.Step;
import com.facebook.buck.zip.ZipScrubberStep;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import javax.annotation.Nullable;
/** Perform the "aapt2 compile" step of a single Android resource. */
public class Aapt2Compile extends ModernBuildRule<Aapt2Compile.Impl> {
public Aapt2Compile(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
SourcePathRuleFinder ruleFinder,
Tool aapt2ExecutableTool,
SourcePath resDir) {
super(buildTarget, projectFilesystem, ruleFinder, new Impl(aapt2ExecutableTool, resDir));
}
/** internal buildable implementation */
static class Impl
implements Buildable,
// more details in the task: T47360608
HasBrokenInputBasedRuleKey {
@AddToRuleKey private final Tool aapt2ExecutableTool;
@AddToRuleKey private final SourcePath resDir;
@AddToRuleKey private final OutputPath output = new OutputPath("resources.flata");
private Impl(Tool aapt2ExecutableTool, SourcePath resDir) {
this.aapt2ExecutableTool = aapt2ExecutableTool;
this.resDir = resDir;
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext buildContext,
ProjectFilesystem filesystem,
OutputPathResolver outputPathResolver,
BuildCellRelativePathFactory buildCellPathFactory) {
Path outputPath = outputPathResolver.resolvePath(output);
SourcePathResolver sourcePathResolver = buildContext.getSourcePathResolver();
Aapt2CompileStep aapt2CompileStep =
new Aapt2CompileStep(
filesystem.getRootPath(),
aapt2ExecutableTool.getCommandPrefix(sourcePathResolver),
sourcePathResolver.getAbsolutePath(resDir),
outputPath);
ZipScrubberStep zipScrubberStep = ZipScrubberStep.of(filesystem.resolve(outputPath));
return ImmutableList.of(aapt2CompileStep, zipScrubberStep);
}
}
private static class Aapt2CompileStep extends ShellStep {
private final ImmutableList<String> commandPrefix;
private final Path resDirPath;
private final Path outputPath;
Aapt2CompileStep(
Path workingDirectory,
ImmutableList<String> commandPrefix,
Path resDirPath,
Path outputPath) {
super(workingDirectory);
this.commandPrefix = commandPrefix;
this.resDirPath = resDirPath;
this.outputPath = outputPath;
}
@Override
public String getShortName() {
return "aapt2_compile";
}
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
builder.addAll(commandPrefix);
builder.add("compile");
builder.add("--legacy"); // TODO(dreiss): Maybe make this an option?
builder.add("-o");
builder.add(outputPath.toString());
builder.add("--dir");
builder.add(resDirPath.toString());
return builder.build();
}
}
@Nullable
@Override
public SourcePath getSourcePathToOutput() {
return getSourcePath(getBuildable().output);
}
}
| 36.407692 | 93 | 0.744771 |
d7eee2b94e5dafae2da52e63cfefc5ed62def045
| 405 |
package com.eshop.ordering.domain.aggregatesmodel.buyer.snapshot;
import com.eshop.ordering.domain.base.Snapshot;
import lombok.Builder;
import lombok.Getter;
import java.util.List;
@Builder
@Getter
public class BuyerSnapshot implements Snapshot {
private final String id;
private final String userId;
private final String buyerName;
private final List<PaymentMethodSnapshot> paymentMethods;
}
| 23.823529 | 65 | 0.812346 |
2bf3c9e295045b102566dc54feffebe0e158b62f
| 698 |
package mekanism.common.recipe.machines;
import mekanism.common.MekanismFluids;
import mekanism.common.recipe.inputs.AdvancedMachineInput;
import mekanism.common.recipe.outputs.ItemStackOutput;
import net.minecraft.item.ItemStack;
public class OsmiumCompressorRecipe extends AdvancedMachineRecipe<OsmiumCompressorRecipe>
{
public OsmiumCompressorRecipe(AdvancedMachineInput input, ItemStackOutput output)
{
super(input, output);
}
public OsmiumCompressorRecipe(ItemStack input, ItemStack output)
{
super(input, MekanismFluids.LiquidOsmium, output);
}
@Override
public OsmiumCompressorRecipe copy()
{
return new OsmiumCompressorRecipe(getInput().copy(), getOutput().copy());
}
}
| 26.846154 | 89 | 0.813754 |
5faf06919fe9efa5e94d9024c580e43f3991d9c2
| 2,628 |
package com.thekoldar.aoe_rms_spoon.ast.abstract_nodes.commands;
import com.thekoldar.aoe_rms_spoon.ast.RMSNodeType;
import com.thekoldar.aoe_rms_spoon.ast.abstract_nodes.AbstractRMSNoArgumentCommand;
import com.thekoldar.aoe_rms_spoon.ast.abstract_nodes.AbstractRMSSingleOptionalBooleanArgumentCommand;
import com.thekoldar.aoe_rms_spoon.ast.abstract_nodes.AbstractRMSSingleOptionalIntArgumentCommand;
import com.thekoldar.aoe_rms_spoon.framework.AbstractAoEVersion;
import com.thekoldar.aoe_rms_spoon.framework.models.exceptions.AbstractRMSException;
import com.thekoldar.aoe_rms_spoon.framework.models.exceptions.RMSErrorCode;
import com.thekoldar.aoe_rms_spoon.framework.semantic_analysis.LongSetPossible;
import com.thekoldar.aoe_rms_spoon.framework.semantic_analysis.SemanticCheckInput;
import com.thekoldar.aoe_rms_spoon.framework.semantic_analysis.SemanticCheckOutput;
/**
* The abstract version of the associated RMS command. The semantic analysis and code geneation are tuned with Age of empires 2: DE version. Still,
* you can create a command performing code generation and semantic analysis of another version by extending this class. Then, you can create a new age of empries version by extending
* {@link AbstractAoEVersion} abstract class.
*
* @author massi
*
*/
public abstract class AbstractNumberOfGroups extends AbstractRMSSingleOptionalIntArgumentCommand{
protected AbstractNumberOfGroups() {
super(RMSNodeType.NUMBER_OF_GROUPS);
}
@Override
public String getArgumentName() {
return "amount";
}
@Override
public Object getDefaultValue() {
return "individual object. no groups";
}
@Override
public String getArgumentComment() {
return "";
}
@Override
public String getComment() {
return "Place the specified number of groups, which each consist of the number of individual objects chosen in number_of_objects. Total objects = number_of_objects x number_of_groups";
}
@Override
public SemanticCheckOutput semanticCheck(SemanticCheckInput input) throws AbstractRMSException {
var result = input.createOutput();
result.ensureItIsOnlyInstructionOfTypeInDict(this);
result.ensureArgumentGreaterThan0(this.getArgument(0));
if (this.hasAtLeastOneSiblingOfTypes(RMSNodeType.SET_SCALING_TO_MAP_SIZE)) {
var n = LongSetPossible.of(this.getArgumentAsInt(0, input));
if (n.isAtLeastOneGreaterThan(9320)) {
result.addError(this, RMSErrorCode.INVALID_ARGUMENT, "When %s is set, the %s cannot go over %d", RMSNodeType.SET_SCALING_TO_MAP_SIZE, RMSNodeType.NUMBER_OF_GROUPS, 9320);
}
}
return result.merge(this.semanticCheckChildren(input));
}
}
| 39.818182 | 186 | 0.814307 |
c6c7113cc34940a85e0b030602ee4bc7d357b09b
| 1,098 |
package frc.robot.commands.autocommands;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.RobotContainer;
public class SpinShooterMotor extends CommandBase {
Timer t;
public SpinShooterMotor() {
addRequirements(RobotContainer.m_robotDrive);
}
@Override
public void initialize() {
t = new Timer();
t.start();
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
RobotContainer.m_shooter.shoot(-0.85);
if (t.get() > 1.4) {
RobotContainer.m_shooter.tower(-0.5);
}
else {
RobotContainer.m_shooter.tower(0);
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
t.stop();
RobotContainer.m_shooter.shoot(0);
RobotContainer.m_shooter.tower(0);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return t.hasElapsed(2.0);
}
}
| 24.4 | 75 | 0.638434 |
6bfa61400c2f94d0dca8e81167fdfc13ffcd4d64
| 2,914 |
package com.alipay.api.domain;
import java.util.Date;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 明细的查询结果
*
* @author auto create
* @since 1.0, 2016-10-26 17:43:42
*/
public class QueryDetailAopResult extends AlipayObject {
private static final long serialVersionUID = 8731392882258763854L;
/**
* 批次编号;此单据对应的批次编号
*/
@ApiField("batch_no")
private String batchNo;
/**
* 明细编号
*/
@ApiField("detail_no")
private String detailNo;
/**
* 扩展属性;创建付款单时传入的数据
*/
@ApiField("ext_param")
private String extParam;
/**
* 失败原因:在status为fail时此字段不为空
*/
@ApiField("fail_message")
private String failMessage;
/**
* 明细最后一次变更的时间
*/
@ApiField("last_modified")
private Date lastModified;
/**
* 单据号
*/
@ApiField("order_no")
private String orderNo;
/**
* 收/付款金额;单位为元
*/
@ApiField("pay_amount")
private String payAmount;
/**
* 收款人userId
*/
@ApiField("payee_id")
private String payeeId;
/**
* 付款人userId
*/
@ApiField("payer_id")
private String payerId;
/**
* 服务费,单位为元
*/
@ApiField("service_charge")
private String serviceCharge;
/**
* 批次明细状态;注:AVAILABLE:可付款;SUCCESS:付款成功;FAIL:失败
*/
@ApiField("status")
private String status;
public String getBatchNo() {
return this.batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
public String getDetailNo() {
return this.detailNo;
}
public void setDetailNo(String detailNo) {
this.detailNo = detailNo;
}
public String getExtParam() {
return this.extParam;
}
public void setExtParam(String extParam) {
this.extParam = extParam;
}
public String getFailMessage() {
return this.failMessage;
}
public void setFailMessage(String failMessage) {
this.failMessage = failMessage;
}
public Date getLastModified() {
return this.lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public String getOrderNo() {
return this.orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getPayAmount() {
return this.payAmount;
}
public void setPayAmount(String payAmount) {
this.payAmount = payAmount;
}
public String getPayeeId() {
return this.payeeId;
}
public void setPayeeId(String payeeId) {
this.payeeId = payeeId;
}
public String getPayerId() {
return this.payerId;
}
public void setPayerId(String payerId) {
this.payerId = payerId;
}
public String getServiceCharge() {
return this.serviceCharge;
}
public void setServiceCharge(String serviceCharge) {
this.serviceCharge = serviceCharge;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
}
| 17.987654 | 68 | 0.661977 |
2f5bc7b24f6d318c2f672f50234954b9937f484b
| 405 |
package io.guill.uniovi.ds.practica9.nodos;
import io.guill.uniovi.ds.practica9.visitor.Visitor;
public class Division implements Expresion {
public Expresion left, right;
public Division(Expresion left, Expresion right) {
this.left = left;
this.right = right;
}
@Override
public Object accept(Visitor v, Object param) {
v.visitDivision(this, null);
return null;
}
}
| 20.25 | 53 | 0.706173 |
e1ecb1e1dbad0e9a978c0fd42c63bcfd8a9c3e02
| 4,334 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.connect.mirror;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.protocol.types.Schema;
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.protocol.types.Type;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import java.nio.ByteBuffer;
public class OffsetSync {
public static final String TOPIC_KEY = "topic";
public static final String PARTITION_KEY = "partition";
public static final String UPSTREAM_OFFSET_KEY = "upstreamOffset";
public static final String DOWNSTREAM_OFFSET_KEY = "offset";
public static final Schema VALUE_SCHEMA = new Schema(
new Field(UPSTREAM_OFFSET_KEY, Type.INT64),
new Field(DOWNSTREAM_OFFSET_KEY, Type.INT64));
public static final Schema KEY_SCHEMA = new Schema(
new Field(TOPIC_KEY, Type.STRING),
new Field(PARTITION_KEY, Type.INT32));
private final TopicPartition topicPartition;
private final long upstreamOffset;
private final long downstreamOffset;
public OffsetSync(TopicPartition topicPartition, long upstreamOffset, long downstreamOffset) {
this.topicPartition = topicPartition;
this.upstreamOffset = upstreamOffset;
this.downstreamOffset = downstreamOffset;
}
public TopicPartition topicPartition() {
return topicPartition;
}
public long upstreamOffset() {
return upstreamOffset;
}
public long downstreamOffset() {
return downstreamOffset;
}
@Override
public String toString() {
return String.format("OffsetSync{topicPartition=%s, upstreamOffset=%d, downstreamOffset=%d}",
topicPartition, upstreamOffset, downstreamOffset);
}
ByteBuffer serializeValue() {
Struct struct = valueStruct();
ByteBuffer buffer = ByteBuffer.allocate(VALUE_SCHEMA.sizeOf(struct));
VALUE_SCHEMA.write(buffer, struct);
buffer.flip();
return buffer;
}
ByteBuffer serializeKey() {
Struct struct = keyStruct();
ByteBuffer buffer = ByteBuffer.allocate(KEY_SCHEMA.sizeOf(struct));
KEY_SCHEMA.write(buffer, struct);
buffer.flip();
return buffer;
}
public static OffsetSync deserializeRecord(ConsumerRecord<byte[], byte[]> record) {
Struct keyStruct = KEY_SCHEMA.read(ByteBuffer.wrap(record.key()));
String topic = keyStruct.getString(TOPIC_KEY);
int partition = keyStruct.getInt(PARTITION_KEY);
Struct valueStruct = VALUE_SCHEMA.read(ByteBuffer.wrap(record.value()));
long upstreamOffset = valueStruct.getLong(UPSTREAM_OFFSET_KEY);
long downstreamOffset = valueStruct.getLong(DOWNSTREAM_OFFSET_KEY);
return new OffsetSync(new TopicPartition(topic, partition), upstreamOffset, downstreamOffset);
}
private Struct valueStruct() {
Struct struct = new Struct(VALUE_SCHEMA);
struct.set(UPSTREAM_OFFSET_KEY, upstreamOffset);
struct.set(DOWNSTREAM_OFFSET_KEY, downstreamOffset);
return struct;
}
private Struct keyStruct() {
Struct struct = new Struct(KEY_SCHEMA);
struct.set(TOPIC_KEY, topicPartition.topic());
struct.set(PARTITION_KEY, topicPartition.partition());
return struct;
}
byte[] recordKey() {
return serializeKey().array();
}
byte[] recordValue() {
return serializeValue().array();
}
}
| 35.818182 | 102 | 0.70743 |
aaf98767ef1cbc8b817e53a86cbc557438588a67
| 4,580 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2020-2022 Rice University, Baylor College of Medicine, Aiden Lab
*
* 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 NON-INFRINGEMENT. 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 hic.tools.utils.merge.merger;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class GraphsMerger extends Merger {
private final long[] A = new long[2000];
private final long[][] B = new long[3][200];
private final long[][] D = new long[4][100];
private final long[] x = new long[100];
@Override
public void parse(String s) {
Scanner scanner = new Scanner(s);
try {
skipUntilNextArray(scanner);
addTo1DArray(A, scanner);
skipUntilNextArray(scanner);
addTo2DArray(B, scanner);
skipUntilNextArray(scanner);
addTo2DArray(D, scanner);
skipUntilNextArray(scanner);
for (int idx = 0; idx < x.length; idx++) {
long newX = scanner.nextLong();
if (x[idx] > 0L) {
if (x[idx] != newX) {
System.err.println("X mismatch error? " + x[idx] + " - " + newX);
}
}
x[idx] = newX;
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void printToMergedFile(String filename) {
try {
BufferedWriter histWriter = new BufferedWriter(new FileWriter(filename));
histWriter.write("A = [\n");
write1DArray(A, histWriter);
histWriter.write("\n];\n");
histWriter.write("B = [\n");
write2DArray(B, histWriter);
histWriter.write("\n];\n");
histWriter.write("D = [\n");
write2DArray(D, histWriter);
histWriter.write("\n];");
histWriter.write("x = [\n");
write1DArray(x, histWriter);
histWriter.write("\n];\n");
histWriter.close();
} catch (IOException error) {
error.printStackTrace();
}
}
private void addTo1DArray(long[] arr, Scanner scanner) {
for (int idx = 0; idx < arr.length; idx++) {
arr[idx] += scanner.nextLong();
}
}
private void write1DArray(long[] arr, BufferedWriter histWriter) throws IOException {
for (long tmp : arr) {
histWriter.write(tmp + " ");
}
}
private void addTo2DArray(long[][] arr, Scanner scanner) {
int numRows = arr.length;
int len = arr[0].length;
for (int idx = 0; idx < len; idx++) {
for (int r = 0; r < numRows; r++) {
try {
arr[r][idx] += scanner.nextLong();
} catch (Exception e) {
System.err.println(scanner.next());
e.printStackTrace();
}
}
}
}
private void write2DArray(long[][] arr, BufferedWriter histWriter) throws IOException {
int numRows = arr.length;
int len = arr[0].length;
for (int idx = 0; idx < len; idx++) {
StringBuilder s = new StringBuilder("" + arr[0][idx]);
for (int r = 1; r < numRows; r++) {
s.append(" ").append(arr[r][idx]);
}
histWriter.write(s + "\n");
}
}
private void skipUntilNextArray(Scanner scanner) {
while (!scanner.next().equals("[")) ;
}
}
| 33.676471 | 91 | 0.568122 |
e343d6f6c3bd8cb6cfccca2e04f6d594eeac56b8
| 582 |
package org.earthChem.presentation.jsf;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
/*********
* JSF Backing Bean for Logout Page
*
*
*/
@ManagedBean(name="logoutBean")
@SessionScoped
public class LogoutBean implements Serializable {
private static final long serialVersionUID = -5818671124700032389L;
public String logout(){
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "/faces/ECAdmin.xhtml/logout?faces-redirect=true";
}
}
| 23.28 | 77 | 0.776632 |
179852719165c31850b5c6416eccc89bd95ba223
| 5,676 |
/**
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: shulie@shulie.io
* 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,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shulie.instrument.module.config.fetcher.config.event.model;
import com.pamirs.pradar.ConfigNames;
import com.pamirs.pradar.PradarSwitcher;
import com.pamirs.pradar.internal.config.ShadowJob;
import com.pamirs.pradar.pressurement.agent.event.impl.ShadowJobDisableEvent;
import com.pamirs.pradar.pressurement.agent.event.impl.ShadowJobRegisterEvent;
import com.pamirs.pradar.pressurement.agent.shared.service.EventRouter;
import com.pamirs.pradar.pressurement.agent.shared.service.GlobalConfig;
import com.shulie.instrument.module.config.fetcher.config.impl.ApplicationConfig;
import com.shulie.instrument.module.config.fetcher.config.utils.ObjectUtils;
import com.shulie.instrument.simulator.api.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author: wangjian
* @since : 2020/9/8 17:36
*/
public class ShadowJobConfig implements IChange<Set<ShadowJob>, ApplicationConfig> {
private static final Logger LOGGER = LoggerFactory.getLogger(ShadowJobConfig.class.getName());
private static ShadowJobConfig INSTANCE;
public static ShadowJobConfig getInstance() {
if (INSTANCE == null) {
synchronized (ShadowJobConfig.class) {
if (INSTANCE == null) {
INSTANCE = new ShadowJobConfig();
}
}
}
return INSTANCE;
}
public static void release() {
INSTANCE = null;
}
@Override
public Boolean compareIsChangeAndSet(ApplicationConfig applicationConfig, Set<ShadowJob> newValue) {
Set<ShadowJob> oldShadowJobs = new HashSet<ShadowJob>(GlobalConfig.getInstance().getRegisteredJobs().values());
/**
* 影子job不支持热更新, 即不支持如果job已经存在,不支持该job的配置更新
*/
if (ObjectUtils.equals(oldShadowJobs.size(), newValue.size())) {
Map<Long, ShadowJob> oldShadowJobMap = new HashMap<Long, ShadowJob>(16, 1);
for (ShadowJob shadowJob : oldShadowJobs) {
oldShadowJobMap.put(shadowJob.getId(), shadowJob);
}
Map<Long, ShadowJob> newShadowJobMap = new HashMap<Long, ShadowJob>(16, 1);
for (ShadowJob shadowJob : newValue) {
newShadowJobMap.put(shadowJob.getId(), shadowJob);
}
boolean change = false;
for (Map.Entry<Long, ShadowJob> entry : newShadowJobMap.entrySet()) {
if (!oldShadowJobMap.containsKey(entry.getKey()) || !oldShadowJobMap.get(entry.getKey()).toString().equals(entry.getValue().toString())) {
change = true;
}
if (change) {
break;
}
}
if (!change) {
return Boolean.FALSE;
}
}
applicationConfig.setShadowJobs(newValue);
Set<ShadowJob> addShadowJobs = calculateAddJobs(newValue, oldShadowJobs);
Set<ShadowJob> removeShadowJobs = calculateRemoveJobs(newValue, oldShadowJobs);
for (ShadowJob shadowJob : addShadowJobs) {
ShadowJobRegisterEvent registerEvent = new ShadowJobRegisterEvent(shadowJob);
EventRouter.router().publish(registerEvent);
}
for (ShadowJob shadowJob : removeShadowJobs) {
ShadowJobDisableEvent disableEvent = new ShadowJobDisableEvent(shadowJob);
EventRouter.router().publish(disableEvent);
}
PradarSwitcher.turnConfigSwitcherOn(ConfigNames.SHADOW_JOB_CONFIGS);
if (LOGGER.isInfoEnabled()) {
if (CollectionUtils.isNotEmpty(removeShadowJobs)) {
for (ShadowJob delete : removeShadowJobs) {
LOGGER.info("need delete job:" + delete.toString());
}
}
if (CollectionUtils.isNotEmpty(addShadowJobs)) {
for (ShadowJob newJob : addShadowJobs) {
LOGGER.info("need add job:" + newJob.toString());
}
}
LOGGER.info("publish shadow job config successful. config={}", newValue);
}
return Boolean.TRUE;
}
private Set<ShadowJob> calculateAddJobs(Set<ShadowJob> newShadowJobs, Set<ShadowJob> oldShadowJobs) {
Set<ShadowJob> shadowJobs = new HashSet<ShadowJob>();
//只添加启动的job
for (ShadowJob shadowJob : newShadowJobs) {
if ("0".equals(shadowJob.getStatus())) {
shadowJobs.add(shadowJob);
}
}
shadowJobs.removeAll(oldShadowJobs);
return shadowJobs;
}
private Set<ShadowJob> calculateRemoveJobs(Set<ShadowJob> newShadowJobs, Set<ShadowJob> oldShadowJobs) {
Set<ShadowJob> shadowJobs = new HashSet<ShadowJob>();
shadowJobs.addAll(oldShadowJobs);
//去除禁用的job 0是启用 1是禁用,如果任务在控制台被删除,也将被停止
for (ShadowJob shadowJob : newShadowJobs) {
if ("0".equals(shadowJob.getStatus())) {
shadowJobs.remove(shadowJob);
}
}
return shadowJobs;
}
}
| 39.971831 | 154 | 0.648344 |
901755bbdaa0dec0f4ec9cc66c8fc8382a651fe1
| 53 |
package cn.badguy.dream.vo;
public class TestVo {
}
| 10.6 | 27 | 0.735849 |
cd89032feeb58055480c13657137a668b39b5f18
| 778 |
package com.example.model.bo;
import java.math.BigDecimal;
/**
* <pre>
*
* </pre>
* @author 杨帮东
* @since 1.0
* @date 2020/04/08 18:10
**/
public class UserBO {
private Double balance;
private BigDecimal bd;
private Short s;
private Character c;
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public BigDecimal getBd() {
return bd;
}
public void setBd(BigDecimal bd) {
this.bd = bd;
}
public Short getS() {
return s;
}
public void setS(Short s) {
this.s = s;
}
public Character getC() {
return c;
}
public void setC(Character c) {
this.c = c;
}
}
| 14.145455 | 44 | 0.547558 |
1941a492a4c65a325a9cdc62107ec16aa9c5f17e
| 856 |
package de.davelee.trams.operations.response;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* This class tests the PurchaseVehicleResponse class and ensures that its works correctly.
* @author Dave Lee
*/
public class PurchaseVehicleResponseTest {
/**
* Ensure that a PurchaseVehicleResponse class can be correctly instantiated.
*/
@Test
public void testCreateResponse() {
PurchaseVehicleResponse purchaseVehicleResponse = new PurchaseVehicleResponse();
purchaseVehicleResponse.setPurchased(true);
purchaseVehicleResponse.setPurchasePrice(200000);
assertTrue(purchaseVehicleResponse.isPurchased());
assertEquals(200000, purchaseVehicleResponse.getPurchasePrice());
}
}
| 31.703704 | 91 | 0.759346 |
d10dae78fc356f119df7c7056731ce1998ad4a1e
| 645 |
package br.ufal.ic.easy.calc;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
public class CalcTest {
private Calc calc;
@Before
public void setUp() {
this.calc = new Calc();
}
@Test
public void sumZeroAndZeroTest() {
Assert.assertEquals(0, calc.sum(0, 0));
}
@Test
public void sumTwoAndTwoTest() {
Assert.assertEquals(4, calc.sum(2, 2));
}
@Test
public void sumZeroAndOneTest() {
Assert.assertEquals(1, calc.sum(0, 1));
}
@Test
public void sumOneAndZeroTest() {
Assert.assertEquals(1, calc.sum(1, 0));
}
}
| 17.432432 | 47 | 0.6 |
4bb15da82e8ab7b4ffa4e7cc39b889d186b66127
| 2,441 |
/*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.internal.executor.api;
import java.util.Date;
import java.util.List;
/**
* Top level facade that aggregates operations defined in:
* <ul>
* <li><code>Executor</code></li>
* <li><code>ExecutorQueryService</code></li>
* <li><code>ExecutorAdminService</code></li>
* </ul>
* @see Executor
* @see ExecutorQueryService
* @see ExecutorAdminService
*/
public interface ExecutorService {
public List<RequestInfo> getQueuedRequests();
public List<RequestInfo> getCompletedRequests();
public List<RequestInfo> getInErrorRequests();
public List<RequestInfo> getCancelledRequests();
public List<ErrorInfo> getAllErrors();
public List<RequestInfo> getAllRequests();
public List<RequestInfo> getRequestsByStatus(List<STATUS> statuses);
public List<RequestInfo> getRequestsByBusinessKey(String businessKey);
public int clearAllRequests();
public int clearAllErrors();
public Long scheduleRequest(String commandName, CommandContext ctx);
public void cancelRequest(Long requestId);
public void init();
public void destroy();
public boolean isActive();
public int getInterval();
public void setInterval(int waitTime);
public int getRetries();
public void setRetries(int defaultNroOfRetries);
public int getThreadPoolSize();
public void setThreadPoolSize(int nroOfThreads);
public List<RequestInfo> getPendingRequests();
public List<RequestInfo> getPendingRequestById(Long id);
public Long scheduleRequest(String commandId, Date date, CommandContext ctx);
public List<RequestInfo> getRunningRequests();
public List<RequestInfo> getFutureQueuedRequests();
public RequestInfo getRequestById(Long requestId);
public List<ErrorInfo> getErrorsByRequestId(Long requestId);
}
| 26.247312 | 81 | 0.7288 |
33d53a072e7368818721db6869e49bd5cc79ebd1
| 2,802 |
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.program.model.symbol;
/**
* Interface to define methods that are called when references are
* added or removed.
*/
public interface ReferenceListener {
/**
* Notification that the given memory reference has been added.
* @param ref the reference that was added.
*/
public void memReferenceAdded(Reference ref);
/**
* Notification that the given memory reference has bee removed.
* @param ref the reference that was removed.
*/
public void memReferenceRemoved(Reference ref);
/**
* Notification that the reference type on the given memory reference
* has changed.
* @param newRef the reference with the new reference type.
* @param oldRef the reference with the old reference type.
*/
public void memReferenceTypeChanged(Reference newRef, Reference oldRef);
/**
* Notification that the given memory reference has been set as
* the primary reference.
* @param ref the reference that is now primary.
*/
public void memReferencePrimarySet(Reference ref);
/**
* Notification that the given memory reference is no longer the primary
* reference.
* @param ref the reference that was primary but now is not.
*/
public void memReferencePrimaryRemoved(Reference ref);
/**
* Notification that the given stack reference has been added.
* @param ref the stack reference that was added.
*/
public void stackReferenceAdded(Reference ref);
/**
* Notification tbat the given stack reference has been removed.
* @param ref The stack reference that was removed
*/
public void stackReferenceRemoved(Reference ref);
/**
* Notification that the given external reference has been added.
* @param ref the external reference that was added.
*/
public void externalReferenceAdded(Reference ref);
/**
* Notification that the given external reference has been removed.
* @param ref the external reference that was removed.
*/
public void externalReferenceRemoved(Reference ref);
/**
* Notification that the external program name in the reference
* has changed.
* @param ref the external reference with its new external name.
*/
public void externalReferenceNameChanged(Reference ref);
}
| 31.133333 | 75 | 0.732334 |
f046d842267e94953dd0c243bc75f610edd052fd
| 319 |
package jjcard.text.game.util;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Indicates that this element is Experimental and subject to change.
*
*/
@Retention(RetentionPolicy.CLASS)
@Documented
public @interface Experimental {
}
| 21.266667 | 69 | 0.793103 |
764af1dbb37c90d3b47f60f684f19968d8e61ba0
| 14,640 |
/**
*
* @author grog (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the Apache License 2.0 as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Apache License 2.0 for more details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.service.abstracts;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.myrobotlab.framework.Registration;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.math.MapperLinear;
import org.myrobotlab.math.interfaces.Mapper;
import org.myrobotlab.sensor.EncoderData;
import org.myrobotlab.sensor.EncoderListener;
import org.myrobotlab.sensor.EncoderPublisher;
import org.myrobotlab.service.Runtime;
import org.myrobotlab.service.config.AbstractMotorConfig;
import org.myrobotlab.service.config.ServiceConfig;
import org.myrobotlab.service.data.AnalogData;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.AnalogPublisher;
import org.myrobotlab.service.interfaces.ButtonDefinition;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.MotorController;
import org.myrobotlab.service.interfaces.PinArrayControl;
import org.myrobotlab.service.interfaces.PinDefinition;
import org.myrobotlab.service.interfaces.PinListener;
import org.slf4j.Logger;
/**
* @author GroG
*
* AbstractMotor - this class contains all the data necessary for
* MotorController to run a motor. Functions of the MotorController are
* proxied through this class, with itself as a parameter
*
*/
abstract public class AbstractMotor extends Service implements MotorControl, EncoderListener, PinListener {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(AbstractMotor.class);
protected transient MotorController controller = null;
/**
* list of names of possible controllers
*/
final protected Set<String> controllers = new HashSet<>();
/**
* list of possible ports
*/
protected List<String> motorPorts = new ArrayList<>();
/**
* if motor is locked - no position or power commands will work
*/
protected boolean locked = false;
/**
* attached analog publishers to this service - functionally its a simple
* "lock" to avoid cyclic attach/detaches - works well
*/
// final protected Set<String> analogPublishers = new HashSet<>();
// bad idea publishers internally will need to know about subscribers
// but not the other way around ... could this be a general pattern for
// how to manage attach? ie publishers attach "always" needs to be called
// subscribers can just call publishers attach with their attach
/**
* the power level requested - varies between -1.0 <--> 1.0
*/
protected Double powerInput = 0.0;
protected Double positionInput; // aka targetPos
protected Double positionCurrent; // aka currentPos
/**
* a new "un-set" mapper for merging with default motorcontroller
*/
protected MapperLinear mapper = new MapperLinear();
/**
* name of the currently attached motor controller
*/
protected String controllerName;
/**
* min - defaults to -1.0 equivalent of 100% power rotation ccw
*/
protected double min = -1.0;
/**
* max - defaults to 1.0 equivalent of 100% power cw rotation
*/
protected double max = 1.0;
private String axisName;
public AbstractMotor(String n, String id) {
super(n, id);
// subscribeToRuntime("registered");
// "top" half of the mapper is set by the control
// so that we "try" to maintain a standard default of -1.0 <=> 1.0 with same
// input limits
// "bottom" half of the mapper will be set by the controller
mapper.map(min, max, -1.0, 1.0);
Runtime.getInstance().subscribeToLifeCycleEvents(getName());
refreshControllers();
}
@Override
public void onRegistered(Registration s) {
if (s.hasInterface(MotorController.class)) {
controllers.add(s.getName());
broadcastState();
}
}
@Override
public void onReleased(String s) {
if (controllers.contains(s)) {
controllers.remove(s);
broadcastState();
}
}
public Set<String> refreshControllers() {
controllers.clear();
controllers.addAll(Runtime.getServiceNamesFromInterface(MotorController.class));
broadcastState();
return controllers;
}
public MotorController getController() {
return controller;
}
// FIXME - repair input/output
@Override
public double getPowerLevel() {
return powerInput;
}
@Override
public boolean isAttached(MotorController controller) {
return this.controller == controller;
}
@Override
public boolean isInverted() {
return mapper.isInverted();
}
@Override
public void lock() {
locked = true;
broadcastState();
}
@Override
public void move(double powerInput) {
if (locked) {
info("%s is locked - will not move");
return;
}
if (powerInput < min) {
warn("requested power %.2f is under minimum %.2f", powerInput, min);
return;
}
if (powerInput > max) {
warn("requested power %.2f is over maximum %.2f", powerInput, max);
return;
}
log.info("{}.move({})", getName(), powerInput);
this.powerInput = powerInput;
if (controller != null) {
invoke("publishPowerChange", powerInput);
controller.motorMove(this);
}
broadcastState();
}
@Override
public double publishPowerChange(double powerInput) {
return powerInput;
}
@Override
public void setInverted(boolean invert) {
log.warn("setting {} inverted = {}", getName(), invert);
mapper.setInverted(invert);
broadcastState();
}
@Override
public void setMinMax(double min, double max) {
this.min = min;
this.max = max;
info("updated min %.2f max %.2f", min, max);
broadcastState();
}
public void map(double minX, double maxX, double minY, double maxY) {
mapper.map(minX, maxX, minY, maxY);
broadcastState();
}
@Override
public void stop() {
// log.info("{}.stop()", getName());
powerInput = 0.0;
if (controller != null) {
controller.motorStop(this);
}
broadcastState();
}
// FIXME - proxy to MotorControllerx
@Override
public void stopAndLock() {
info("stopAndLock");
move(0.0);
lock();
broadcastState();
}
@Override
public void unlock() {
info("unLock");
locked = false;
broadcastState();
}
@Override
public boolean isLocked() {
return locked;
}
@Override
public void stopService() {
super.stopService();
if (controller != null) {
stopAndLock();
}
}
// FIXME - related to update(SensorData) no ?
public int updatePosition(int position) {
positionCurrent = (double) position;
return position;
}
public double updatePosition(double position) {
positionCurrent = position;
return position;
}
@Override
public double getTargetPos() {
return positionInput;
}
@Override
public void onEncoderData(EncoderData data) {
// TODO Auto-generated method stub
}
@Override
public void setEncoder(EncoderPublisher encoder) {
// TODO Auto-generated method stub
}
public void detachMotorController(MotorController controller) {
controller.detach(this);
controller = null;
controllerName = null;
broadcastState();
}
/**
* routing attach
*/
@Override
public void attach(Attachable service) throws Exception {
log.info("routing attach in Abstractmotor");
if (MotorController.class.isAssignableFrom(service.getClass())) {
attachMotorController((MotorController) service);
return;
} else if (AnalogPublisher.class.isAssignableFrom(service.getClass())) {
attachAnalogPublisher((AnalogPublisher) service);
return;
}
error("%s doesn't know how to attach a %s", getClass().getSimpleName(), service.getClass().getSimpleName());
}
@Override
public void attachAnalogPublisher(AnalogPublisher publisher) {
publisher.attachAnalogListener(this);
}
@Override
public void detachAnalogPublisher(AnalogPublisher publisher) {
publisher.detachAnalogListener(this);
}
@Deprecated /*
* I think this was an attempt to control via an analog pin -
* should be updated to use attachAnalogPublisher
*/
public void onPin(PinData data) {
Double pwr = null;
pwr = data.value.doubleValue();
move(pwr);
}
public void attach(PinDefinition pindef) {
// SINGLE PIN MAN !! not ALL PINS !
// must be local now :P
// FIXME this "should" be cable of adding vi
// e.g send(pindef.getName(), "attach", getName(), pindef.getAddress());
// attach(pindef.getName(), pindef.getAddress)
PinArrayControl pac = (PinArrayControl) Runtime.getService(pindef.getName());
pac.attach(this, pindef.getAddress());
// subscribe(pindef.getName(), "publishPin", getName(), "move");
}
public void attach(ButtonDefinition buttondef) {
subscribe(buttondef.getName(), "publishButton", getName(), "move");
}
@Override
public void attachMotorController(MotorController controller) throws Exception {
if (controller == null) {
error("motor.attach(controller) - controller cannot be null");
return;
}
if (isAttached(controller)) {
log.info("motor {} already attached to motor controller {}", getName(), controller.getName());
return;
}
log.info("attachMotorController {}", controller.getName());
this.controller = controller;
controllerName = controller.getName();
motorPorts = controller.getPorts();
// TODO: KW: set a reasonable mapper. for pwm motor it's probable -1 to 1 to
// 0 to 255 ? not sure.
/**
* <pre>
* Cannot directly assign - we just want the output values of the controller's mapper
* The process is as follows:
* 1. user creates a motor
* 2. user creates a motor controller
* 3. the motor controllers map value inputs minX & minY are -1.0 to 1.0
* but it has no idea what the controller needs to map that range
* 4. hopefully the motor controller's developer created a map for the motor controller which
* sanely maps -1.0, 1.0 to values needed by the controller .. e.g. Saber-tooth is -128, 127
* 5 the end user attaches the motor and motor controller - we then copy in the controllers output
* values to the motor control's output of its map.
* So, the controller gave sane defaults, but the motor control has all the necessary configuration
* </pre>
*/
Mapper defaultControllerMapper = controller.getDefaultMapper();
mapper.map(mapper.getMinX(), mapper.getMaxX(), defaultControllerMapper.getMinY(), defaultControllerMapper.getMaxY());
broadcastState();
controller.attach(this);
}
@Override
public boolean isAttached() {
return controller != null;
}
public void detach() {
super.detach();
if (controller != null) {
detach(controller.getName());
}
}
// FIXME - clean up the attach/detach
// TODO - this could be Java 8 default interface implementation
@Override
public void detach(String name) {
if (controller == null || !name.equals(controller.getName())) {
return;
}
controller.detach(this); // FIXME - call
// detachMotorController(MotorController
controllerName = null;
controller = null;
broadcastState();
}
@Override
public boolean isAttached(String name) {
return (controller != null && controller.getName().equals(name));
}
@Override
public Set<String> getAttached() {
HashSet<String> ret = new HashSet<String>();
if (controller != null) {
ret.add(controller.getName());
}
return ret;
}
// FIXME promote to interface
public Mapper getMapper() {
return mapper;
}
// FIXME promote to interface
public void setMapper(MapperLinear mapper) {
this.mapper = mapper;
}
// FIXME promote to interface
public double calcControllerOutput() {
return mapper.calcOutput(getPowerLevel());
}
@Override
public void setAnalogId(String name) {
axisName = name;
}
@Override
public String getAnalogId() {
return axisName;
}
@Override
public void onAnalog(AnalogData data) {
move(data.value);
}
@Override /* incoming config is from derived motor type */
protected ServiceConfig initConfig(ServiceConfig c) {
super.initConfig(c);
AbstractMotorConfig config = (AbstractMotorConfig) c;
config.locked = locked;
if (mapper != null) {
config.clip = mapper.isClip();
config.maxIn = mapper.getMaxX();
config.maxOut = mapper.getMaxY();
config.minIn = mapper.getMinX();
config.minOut = mapper.getMinY();
config.inverted = mapper.isInverted();
}
return config;
}
public ServiceConfig load(ServiceConfig c) {
AbstractMotorConfig config = (AbstractMotorConfig) c;
mapper = new MapperLinear(config.minIn, config.maxIn, config.minOut, config.maxOut);
mapper.setInverted(config.inverted);
mapper.setClip(config.clip);
if (locked) {
lock();
}
return c;
}
}
| 28.59375 | 122 | 0.656148 |
01fc40fe4e929235a4687a214f3a5f7fe8800fd8
| 466 |
package org.acme.quarkus.sample;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.acme.quarkus.sample.extension.ConfigReport;
@Path("/hello")
public class HelloResource {
@Inject
ConfigReport configReport;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "builder-image is " + configReport.builderImage;
}
}
| 21.181818 | 63 | 0.727468 |
71ae03b11dcb852066c7dd371a9a830c3a2ee679
| 488 |
package org.zmsoft.framework.role;
import org.zmsoft.framework.beans.UserBean;
import org.zmsoft.framework.beans.db.MyDataBaseObjectSupport3;
/**
* 用户职能身份权限模型
*
* @author ZMSoft
*
*/
public interface ISIdentityRoleSupport {
/**
* 整理用户数据权限
*
* @param bean
*/
public boolean prepareUserIdentityRole(MyDataBaseObjectSupport3 dataBean);
/**
* 加载当前用户的数据权限<br>
* Redis缓存模型
*
* @param currentUser
*/
public boolean loadUserIdentityRole(UserBean currentUser);
}
| 16.827586 | 75 | 0.72541 |
118001d3d7bfb88a6d518f298376554a194ff775
| 179 |
package com.jeffmony.async.http.server;
public class MimeEncodingException extends Exception {
public MimeEncodingException(String message) {
super(message);
}
}
| 22.375 | 54 | 0.743017 |
bc73744cd0ab043862465d14737b0dd0f16cb091
| 199 |
package science.atlarge.opencraft.opencraft.generator.ground;
public class MycelGroundGenerator extends GroundGenerator {
public MycelGroundGenerator() {
setTopMaterial(MYCEL);
}
}
| 22.111111 | 61 | 0.763819 |
7033323fc79da8b032a06b624549552133a2fb10
| 696 |
package com.example.supervideo;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.widget.TextView;
import com.example.supervideo.base.BaseFragment;
/**
* Created by 15110 on 2019/5/14.
*/
public class AboutFragment extends BaseFragment {
@Override
protected int getLayoutId() {
return R.layout.fragment_about;
}
@Override
protected void initView() {
TextView textView=bindViewId(R.id.tv_app_description);
textView.setAutoLinkMask(Linkify.ALL);//表示文字中有链接可点
textView.setMovementMethod(LinkMovementMethod.getInstance());//表示文字可以滚动
}
@Override
protected void initData() {
}
}
| 21.75 | 79 | 0.716954 |
18f8bb50ad37071512ecc083ed468ffce19ebf1e
| 1,619 |
package io.github.qy8502.jetcacheplus;
import com.alicp.jetcache.anno.aop.JetCacheInterceptor;
import com.alicp.jetcache.anno.config.JetCacheProxyConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
@Configuration
@AutoConfigureBefore(JetCacheProxyConfiguration.class)
public class MultiJetCacheProxyAutoConfiguration {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AutoMatchJetCacheInterceptorInjector autoMatchJetCacheInterceptorInjector() {
return new AutoMatchJetCacheInterceptorInjector();
}
public class AutoMatchJetCacheInterceptorInjector implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory factory) throws BeansException {
String[] names = factory.getBeanNamesForType(JetCacheInterceptor.class);
for (String name : names) {
BeanDefinition bd = factory.getBeanDefinition(name);
bd.setBeanClassName(MultiJetCacheInterceptor.class.getName());
bd.setFactoryBeanName(null);
bd.setFactoryMethodName(null);
}
}
}
}
| 41.512821 | 113 | 0.781347 |
5d858d938fe6d73c5e4dd35d2b199edae6116e79
| 817 |
package com.turkcell.rentacar.core.utilities.mapping;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.stereotype.Service;
@Service
public class ModelMapperManager implements ModelMapperService {
private ModelMapper modelMapper;
public ModelMapperManager(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
@Override
public ModelMapper forDto() {
this.modelMapper.getConfiguration().setAmbiguityIgnored(true).setMatchingStrategy(MatchingStrategies.LOOSE);
return modelMapper;
}
@Override
public ModelMapper forRequest() {
this.modelMapper.getConfiguration().setAmbiguityIgnored(true).setMatchingStrategy(MatchingStrategies.STANDARD);
return modelMapper;
}
}
| 29.178571 | 119 | 0.766218 |
d866dc9f5190d983cebc76faa1cd771f2e76585b
| 4,853 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package ai.instance.beshmundirTemple;
import ai.AggressiveNpcAI2;
import com.aionemu.gameserver.ai2.AIName;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.services.NpcShoutsService;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import java.util.ArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
@AIName("macunbello")
public class MacunbelloAI2 extends AggressiveNpcAI2 {
private AtomicBoolean isHome = new AtomicBoolean(true);
private boolean wave1 = false;
private boolean wave2 = false;
private ArrayList<Npc> wave_npcs = new ArrayList<Npc>();
private Future<?> wave1_task;
private Future<?> wave2_task;
@Override
protected void handleAttack(Creature creature) {
super.handleAttack(creature);
if (isHome.compareAndSet(true, false)) {
NpcShoutsService.getInstance().sendMsg(getOwner(), 1500060, getObjectId(), 0, 1000);
}
checkPercentage(getLifeStats().getHpPercentage());
}
@Override
protected void handleDied() {
cancelWaveTasks();
super.handleDied();
NpcShoutsService.getInstance().sendMsg(getOwner(), 1500063, getObjectId(), 0, 1000);
}
@Override
protected void handleBackHome() {
cancelWaveTasks();
isHome.set(true);
super.handleBackHome();
}
private void cancelWaveTasks() {
if (wave1_task != null && !wave1_task.isDone()) {
wave1_task.cancel(true);
}
if (wave2_task != null && !wave2_task.isDone()) {
wave2_task.cancel(true);
}
killAllAdds();
}
private void killAllAdds() {
if (wave_npcs.size() == 0) {
return;
}
for (Npc npc : wave_npcs) {
if (npc != null && npc.isSpawned()) {
npc.getController().onDelete();
}
}
wave_npcs.clear();
}
private synchronized void checkPercentage(int hpPercentage) {
if (hpPercentage <= 70 && !wave1) {
wave1 = true;
NpcShoutsService.getInstance().sendMsg(getOwner(), 1500061, getObjectId(), 0, 0);
wave1_task = ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (!isAlreadyDead()) {
// Macunbello's Right Hand.
wave_npcs.add((Npc) spawn(281698, 955.97986f, 160.24693f, 241.77303f, (byte) 108));
wave_npcs.add((Npc) spawn(281698, 1003.958f, 159.76878f, 241.77016f, (byte) 30));
wave_npcs.add((Npc) spawn(281698, 1007.1438f, 109.738075f, 242.7066f, (byte) 30));
wave_npcs.add((Npc) spawn(281698, 952.05365f, 109.55048f, 242.7103f, (byte) 30));
NpcShoutsService.getInstance().sendMsg(getOwner(), 1500062, getObjectId(), 0, 4000);
}
}
}, 4000);
return;
}
if (hpPercentage <= 30 && !wave2) {
wave2 = true;
NpcShoutsService.getInstance().sendMsg(getOwner(), 1500061, getObjectId(), 0, 0);
wave2_task = ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (!isAlreadyDead()) {
wave_npcs.add((Npc) spawn(281698, 955.97986f, 160.24693f, 241.77303f, (byte) 108));
wave_npcs.add((Npc) spawn(281698, 1003.958f, 159.76878f, 241.77016f, (byte) 30));
wave_npcs.add((Npc) spawn(281698, 1007.1438f, 109.738075f, 242.7066f, (byte) 30));
wave_npcs.add((Npc) spawn(281698, 952.05365f, 109.55048f, 242.7103f, (byte) 30));
NpcShoutsService.getInstance().sendMsg(getOwner(), 1500062, getObjectId(), 0, 4000);
}
}
}, 4000);
return;
}
}
}
| 39.137097 | 108 | 0.599217 |
45c4a479797970514b6c378ce326d00deac91eed
| 1,593 |
package com.udacity.jdnd.critter.service;
import com.udacity.jdnd.critter.data.entity.Customer;
import com.udacity.jdnd.critter.data.entity.Pet;
import com.udacity.jdnd.critter.data.repository.CustomerRepository;
import com.udacity.jdnd.critter.data.repository.PetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class PetService {
@Autowired
PetRepository petRepository;
@Autowired
CustomerRepository customerRepository;
public Pet getPetById(Long petId) {
return petRepository.getById(petId);
}
public Pet savePet(Pet pet) {
pet = petRepository.save(pet);
Customer customer = pet.getCustomer();
//Once the pet has been saved then add it to the customer entity
List<Pet> pets = customer.getPets();
if (pets != null)
pets.add(pet);
else {
pets = new ArrayList<Pet>();
pets.add(pet);
}
customer.setPets(pets);
customerRepository.save(customer);
return pet;
}
public Pet getPet(Long petId) {
return petRepository.getById(petId);
}
public List<Pet> getPets() {
return petRepository.findAll();
}
public List<Pet> getPetsByOwner(Long ownerId) {
Customer customer = customerRepository.getById(ownerId);
return petRepository.findByCustomer(customer);
}
}
| 21.821918 | 72 | 0.674827 |
a3fa2388927d495dcb4aaec7190f62cb04d347a2
| 1,331 |
package org.biopax.validator.web.service;
import org.biopax.paxtools.normalizer.Normalizer;
import org.biopax.validator.api.beans.Behavior;
import org.biopax.validator.api.beans.Validation;
import org.springframework.core.io.Resource;
import java.io.IOException;
public interface ValidatorAdapter {
/**
* Parses and checks BioPAX data from the given resource
* and returns the validation report.
*
* @param data input biopax model source
* @param maxErrors optional, if greater than 0, abort once the number of critical errors exceeds the threshold
* @param fixErrors optional, when true, some validator rules can auto-fix the model (issues still get reported)
* @param level optional, if 'ERROR' then warnings are ignored; 'WARNING' - both errors and warnings are reported.
* @param profile optional, validation rules' behavior settings profile, e.g., 'notstrict', 'default'
* @param normalizer optional, pre-configured biopax normalizer
* @return validation report
* @throws IOException when fails to read the data
*/
Validation validate(Resource data, int maxErrors, boolean fixErrors,
Behavior level, String profile,
Normalizer normalizer) throws IOException;
/**
* @return Validator results XML schema.
*/
String getSchema();
}
| 40.333333 | 116 | 0.733283 |
5ec7b9991850f8056de2a693385cae540010a3d5
| 376 |
package app.hack.eightballpool;
import android.content.Context;
import android.content.Intent;
class Helper {
static void startGame(Context context) {
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.miniclip.eightballpool");
if (launchIntent != null) {
context.startActivity(launchIntent);
}
}
}
| 25.066667 | 114 | 0.704787 |
c5e9fad2eff637337f9ce0c303cac5594bbbdcad
| 2,664 |
package gui;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.alibaba.fastjson.JSONObject;
import test.Demo;
public class SubmitGUI extends JFrame{
// 定义组件
JPanel jp1, jp2, jp3, jp4, jp5;
JLabel type, url, data, result;
JButton submit, cancel;
JTextField type_text, url_text, data_text;
JTextArea result_text;
public static void main(String[] args) {
// TODO Auto-generated method stub
SubmitGUI d1 = new SubmitGUI();
}
// 构造函数
public SubmitGUI() {
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jp4 = new JPanel();
jp5 = new JPanel();
type = new JLabel("请求类型");
url = new JLabel("URL");
data = new JLabel("参数");
result = new JLabel("返回值");
submit = new JButton("提交");
cancel = new JButton("取消");
type_text = new JTextField(10);
url_text = new JTextField(10);
data_text = new JTextField(10);
result_text = new JTextArea(2, 10);
this.setLayout(new GridLayout(5, 1));
// 加入各个组件
jp1.add(type);
jp1.add(type_text);
jp2.add(url);
jp2.add(url_text);
jp3.add(data);
jp3.add(data_text);
jp4.add(result);
jp4.add(result_text);
jp5.add(submit);
jp5.add(cancel);
// 加入到JFrame
this.add(jp1);
this.add(jp2);
this.add(jp3);
this.add(jp4);
this.add(jp5);
this.setSize(500, 300);
this.setTitle("测试工具");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String p1 = type_text.getText();
String p2 = url_text.getText();
String p3 = data_text.getText();
JSONObject jsStr = JSONObject.parseObject(p3);
try {
String code = Demo.Login(p1, p2, jsStr);
result_text.setText(code);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
}
| 24 | 61 | 0.570946 |
786e06b7ee5dafa0f610106d76229376bd669a89
| 792 |
package com.github.wrdlbrnft.modularadapter.itemmanager.sortedlist;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Created with Android Studio<br>
* User: Xaver<br>
* Date: 27/03/2017
*/
class FacadeImpl<T> implements SortedListItemManager.Facade<T> {
private List<T> mCurrentState = null;
@Override
public synchronized T getItem(int position) {
if (mCurrentState != null) {
return mCurrentState.get(position);
}
throw new NoSuchElementException();
}
@Override
public synchronized int size() {
if (mCurrentState != null) {
return mCurrentState.size();
}
return 0;
}
@Override
public void setState(List<T> data) {
mCurrentState = data;
}
}
| 22 | 67 | 0.636364 |
86f48756430dfae15d2e422a769d3b934459b7c1
| 2,062 |
/*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.ibm.ws.batch.container.checkpoint;
import com.ibm.batch.container.services.IPersistenceDataKey;
public class CheckpointDataKey implements IPersistenceDataKey {
private long _jobInstanceId;
private String _batchDataStreamName;
private String _stepName;
public CheckpointDataKey(long jobId) {
this._jobInstanceId = jobId;
}
public CheckpointDataKey(long jobId, String stepName, String bdsName) {
this._jobInstanceId = jobId;
this._stepName = stepName;
this._batchDataStreamName = bdsName;
}
public long getJobInstanceId() {
return _jobInstanceId;
}
public void setJobInstanceId(long id) {
_jobInstanceId = id;
}
public String getBatchDataStreamName() {
return _batchDataStreamName;
}
public void setBatchDataStreamName(String dataStreamName) {
_batchDataStreamName = dataStreamName;
}
public String getStepName() {
return _stepName;
}
public void setStepName(String name) {
_stepName = name;
}
public String getCommaSeparatedKey() {
return _jobInstanceId + "," + _stepName + "," + _batchDataStreamName;
}
public String toString() {
return this.getKeyPrimitive();
}
@Override
public String getKeyPrimitive() {
return _jobInstanceId + "," + _stepName + "," + _batchDataStreamName;
}
}
| 29.042254 | 79 | 0.728419 |
98c5a3c2e76a0b0b507d9c8bb3f9b60b03be7c93
| 416 |
package ru.otus.vsh.knb.dbCore.dao;
import ru.otus.vsh.knb.dbCore.model.Model;
import ru.otus.vsh.knb.dbCore.sessionmanager.SessionManager;
import java.util.List;
import java.util.Optional;
public interface Dao<T extends Model> {
Optional<T> findById(long id);
List<T> findAll();
long insert(T t);
void update(T t);
void insertOrUpdate(T t);
SessionManager getSessionManager();
}
| 18.909091 | 60 | 0.709135 |
6a6589fb798de8b8ed688f4e429f497300106188
| 2,317 |
package com.alab.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.alab.model.UserModel;
import com.alab.util.SQLUtil;
@Repository
public class UserDAOImpl implements UserDAO {
/*
* final static private String REGISTER_USER_QRY =
* "INSERT INTO MF_USER VALUES(?,?,?,?,?,?,?)";
*/
@Autowired
private JdbcTemplate jt;
@Override
public int registerUser(UserModel user) {
int count = 0;
count = jt.update(SQLUtil.REGISTER_USER_QRY, user.getUsername(), user.getPassword(), user.getFirstname(),
user.getLastname(), user.getEmail(), user.getAddress(), user.getPhone());
return count;
}
@Override
public List<UserModel> getAllUsers() {
// System.out.println("in dao");
// System.out.println(jt.getClass().getName());
List<UserModel> userList = null;
userList = jt.query(SQLUtil.GET_ALL_USER_QRY, (rs) -> {
// .out.println("in lambda");
List<UserModel> list = new ArrayList<>();
// System.out.println(list.size());
UserModel user = null;
while (rs.next()) {
user = new UserModel();
user.setUsername(rs.getString(1));
user.setPassword(rs.getString(2));
user.setFirstname(rs.getString(3));
user.setLastname(rs.getString(4));
user.setEmail(rs.getString(5));
user.setAddress(rs.getString(6));
user.setPhone(rs.getLong(7));
list.add(user);
}
return list;
});
return userList;
}
@Override
public UserModel getUserById(String username) {
UserModel userModel = null;
userModel = jt.query(SQLUtil.GET_USER_BY_ID_QRY, new Object[] { username }, (rs) -> {
UserModel user = new UserModel();
while (rs.next()) {
user.setUsername(rs.getString(1));
user.setPassword(rs.getString(2));
user.setFirstname(rs.getString(3));
user.setLastname(rs.getString(4));
user.setEmail(rs.getString(5));
user.setAddress(rs.getString(6));
user.setPhone(rs.getLong(7));
}
return user;
});
return userModel;
}
@Override
public int updateUser(UserModel user) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int deleteUser(String username) {
// TODO Auto-generated method stub
return 0;
}
}
| 25.184783 | 107 | 0.691411 |
1b65618c32cfb6c6d2de1083d1a5f911e4242750
| 200 |
package com.jishukezhan.core.date;
import java.time.ZoneId;
public class ZoneIdConstant {
/**
* 上海
*/
public static final ZoneId ASIA_SHANGHHAI = ZoneId.of("Asia/Shanghai");
}
| 13.333333 | 75 | 0.665 |
4b5306763a234b26d520e3dd70b0b45436aa2ef8
| 7,678 |
/*
* Copyright 2018-2020 The Code Department.
*
* 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.tcdng.unify.web.ui.widget;
import java.util.HashMap;
import java.util.Map;
import com.tcdng.unify.core.UnifyException;
import com.tcdng.unify.core.annotation.UplAttribute;
import com.tcdng.unify.core.annotation.UplAttributes;
import com.tcdng.unify.core.util.ValueStoreUtils;
import com.tcdng.unify.web.ControllerPathParts;
import com.tcdng.unify.web.ui.PageBean;
import com.tcdng.unify.web.ui.UnifyWebUIErrorConstants;
import com.tcdng.unify.web.ui.widget.panel.AbstractStandalonePanel;
import com.tcdng.unify.web.ui.widget.panel.StandalonePanel;
/**
* Serves as the base class for a page component.
*
* @author Lateef Ojulari
* @since 1.0
*/
@UplAttributes({
@UplAttribute(name = "subCaption", type = String.class),
@UplAttribute(name = "subCaptionBinding", type = String.class),
@UplAttribute(name = "type", type = String.class, defaultVal = "ui-page"),
@UplAttribute(name = "remote", type = boolean.class, defaultVal = "false") })
public abstract class AbstractPage extends AbstractStandalonePanel implements Page {
private Map<String, StandalonePanel> standalonePanels;
private Map<String, Object> attributes;
private ControllerPathParts controllerPathParts;
@Override
public String getSubCaption() throws UnifyException {
String subCaption = null;
String subCaptionBinding = getUplAttribute(String.class, "subCaptionBinding");
if (subCaptionBinding != null) {
subCaption = getStringValue(subCaptionBinding);
}
return subCaption != null ? subCaption : getUplAttribute(String.class, "subCaption");
}
@Override
public void setPathParts(ControllerPathParts controllerPathParts) {
this.controllerPathParts = controllerPathParts;
}
@Override
public String getPathId() {
if (controllerPathParts != null) {
return controllerPathParts.getControllerPathId();
}
return null;
}
@Override
public String getPathVariable() {
if (controllerPathParts != null) {
return controllerPathParts.getPathVariable();
}
return null;
}
@Override
public void setPageBean(PageBean pageBean) throws UnifyException {
setValueStore(ValueStoreUtils.getValueStore(pageBean, null, -1));
}
@Override
public PageBean getPageBean() throws UnifyException {
return (PageBean) getValueStore().getValueObject();
}
@Override
public StandalonePanel getStandalonePanel(String name) throws UnifyException {
if (standalonePanels != null) {
StandalonePanel standalonePanel = standalonePanels.get(name);
if (standalonePanel != null) {
if (!standalonePanel.isSourceInvalidated()) {
return standalonePanel;
}
standalonePanels.remove(name);
}
}
return null;
}
@Override
public void addStandalonePanel(String name, StandalonePanel standalonePanel) throws UnifyException {
if (standalonePanels == null) {
standalonePanels = new HashMap<String, StandalonePanel>();
}
standalonePanels.put(name, standalonePanel);
}
@Override
public StandalonePanel removeStandalonePanel(String name) throws UnifyException {
if (standalonePanels != null) {
return standalonePanels.remove(name);
}
return null;
}
@Override
public void resolvePageActions(EventHandler[] eventHandlers) throws UnifyException {
super.resolvePageActions(eventHandlers);
if (standalonePanels != null && eventHandlers != null) {
for (StandalonePanel standalonePanel : standalonePanels.values()) {
standalonePanel.resolvePageActions(eventHandlers);
}
}
}
@Override
public Panel getPanelByLongName(String longName) throws UnifyException {
if (isWidget(longName)) {
return (Panel) getWidgetByLongName(longName);
}
// Fix refresh panels bug #0001
// Check stand-alone panels
if (standalonePanels != null) {
StandalonePanel panel = standalonePanels.get(longName);
if (panel != null) {
return panel;
}
// Check stand-alone panel widgets
for (StandalonePanel standalonePanel : standalonePanels.values()) {
if (standalonePanel.isWidget(longName)) {
return (Panel) standalonePanel.getWidgetByLongName(longName);
}
}
}
throw new UnifyException(UnifyWebUIErrorConstants.PAGE_PANEL_WITH_ID_NOT_FOUND, longName);
}
@Override
public Panel getPanelByShortName(String shortName) throws UnifyException {
try {
return (Panel) getWidgetByShortName(shortName);
} catch (Exception e) {
throw new UnifyException(UnifyWebUIErrorConstants.PAGE_PANEL_WITH_ID_NOT_FOUND, shortName);
}
}
@Override
public void setAttribute(String name, Object value) {
if (attributes == null) {
attributes = new HashMap<String, Object>();
}
attributes.put(name, value);
}
@Override
public Object getAttribute(String name) {
if (attributes != null) {
return attributes.get(name);
}
return null;
}
@Override
public Object clearAttribute(String name) {
if (attributes != null) {
return attributes.remove(name);
}
return null;
}
@Override
public boolean isDocument() {
return false;
}
@Override
public Widget getWidgetByLongName(String longName) throws UnifyException {
if (isWidget(longName)) {
return super.getWidgetByLongName(longName);
}
if (standalonePanels != null) {
StandalonePanel panel = standalonePanels.get(longName);
if (panel != null) {
return panel;
}
for (StandalonePanel standalonePanel : standalonePanels.values()) {
if (standalonePanel.isWidget(longName)) {
return standalonePanel.getWidgetByLongName(longName);
}
}
}
throw new UnifyException(UnifyWebUIErrorConstants.WIDGET_WITH_LONGNAME_UNKNOWN, longName, getLongName());
}
@Override
public String getPopupBaseId() throws UnifyException {
return getPrefixedId("popb_");
}
@Override
public String getPopupWinId() throws UnifyException {
return getPrefixedId("popw_");
}
@Override
public String getPopupSysId() throws UnifyException {
return getPrefixedId("pops_");
}
}
| 31.858921 | 114 | 0.628158 |
950a0dde31c544f63cb9cb359c013d695f296389
| 13,476 |
/*
* Copyright 2002-2010 The Rector and Visitors of the
* University of Virginia. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package edu.virginia.speclab.juxta.author.view;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import edu.virginia.speclab.diff.document.LocationMarker;
import edu.virginia.speclab.juxta.author.model.JuxtaDocument;
import edu.virginia.speclab.juxta.author.model.JuxtaSession;
import edu.virginia.speclab.juxta.author.model.SearchResults;
import edu.virginia.speclab.juxta.author.model.SearchResults.SearchResult;
import edu.virginia.speclab.juxta.author.view.collation.CollationViewTextArea;
import edu.virginia.speclab.juxta.author.view.compare.DocumentCompareView;
import edu.virginia.speclab.juxta.author.view.ui.JuxtaUserInterfaceStyle;
import edu.virginia.speclab.ui.PanelTitle;
import edu.virginia.speclab.util.SimpleLogger;
/**
* Display the Search Results Panel
* @author Nick
*
*/
public class SearchResultsPanel extends JPanel implements JuxtaUserInterfaceStyle {
private JTable resultsTable;
private JuxtaSession session;
private JuxtaAuthorFrame juxtaFrame;
private static final int DOCUMENT_NAME = 0;
private static final int LINE_NUM = 1;
private static final int FRAGMENT = 2;
private static final int NUM_COLS = 3;
private static final String BASE_TITLE = "Search Results";
private PanelTitle titlePanel = null;
private JCheckBox highlightButton;
public SearchResultsPanel(JuxtaAuthorFrame frame) {
this.juxtaFrame = frame;
initUI();
}
public void setSession(JuxtaSession session) {
this.session = session;
setSearchResults(null);
}
public void setSearchResults(SearchResults searchResults) {
if (searchResults == null) {
resultsTable.setModel(new ResultsTable(new SearchResults("")));
titlePanel.setTitleText(BASE_TITLE);
} else {
resultsTable.setModel(new ResultsTable(searchResults));
titlePanel.setTitleText(BASE_TITLE + " - \"" + searchResults.getOriginalQuery() + "\" ("
+ searchResults.getSearchResults().size() + " found)");
// re-check highlight box and show results
this.highlightButton.setSelected(true);
DocumentCompareView compareView = juxtaFrame.getDocumentCompareView();
CollationViewTextArea collationView = juxtaFrame.getCollationView();
compareView.setHighlightAllSearchResults(true);
collationView.setHighlightAllSearchResults(true);
}
DocumentCompareView view = juxtaFrame.getDocumentCompareView();
view.searchHighlightRemoval();
}
private void initUI() {
titlePanel = new PanelTitle();
titlePanel.setFont(TITLE_FONT);
titlePanel.setBackground(TITLE_BACKGROUND_COLOR);
titlePanel.setTitleText(BASE_TITLE);
//toolbar = new SearchToolBar();
//resultsTable = new JTable(new ResultsTable(new SearchResults("")));
resultsTable = new JTable(new ResultsTable(new SearchResults(""))) {
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
if (colIndex == FRAGMENT) {
String str = (String) getValueAt(rowIndex, colIndex);
return str;
}
return "";
}
};
resultsTable.setFont(SMALL_FONT);
resultsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTable.addMouseListener(new ClickTracker());
resultsTable.addKeyListener(new KeyTracker());
JScrollPane scrollPane = new JScrollPane(resultsTable);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
setLayout(new BorderLayout());
add(titlePanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add( createSearchToolBar(), BorderLayout.SOUTH);
}
private void clearResults() {
DocumentCompareView view = juxtaFrame.getDocumentCompareView();
view.clearSearchResults();
CollationViewTextArea collationView = juxtaFrame.getCollationView();
collationView.clearSearchResults();
setSearchResults(null);
}
public JToolBar createSearchToolBar() {
JToolBar bar = new JToolBar();
bar.setLayout( new BoxLayout(bar, BoxLayout.X_AXIS));
bar.setFloatable(false);
bar.setBorder( BorderFactory.createEmptyBorder(1,0,1,2));
this.highlightButton = new JCheckBox("Highlight All Results", true);
this.highlightButton.setFont(SMALL_FONT);
this.highlightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DocumentCompareView compareView = juxtaFrame.getDocumentCompareView();
CollationViewTextArea collationView = juxtaFrame.getCollationView();
boolean showHighlights = ((JCheckBox)e.getSource()).isSelected();
if ( showHighlights == false ) {
collationView.setHighlightAllSearchResults(false);
compareView.setHighlightAllSearchResults(false);
} else {
compareView.setHighlightAllSearchResults(true);
collationView.setHighlightAllSearchResults(true);
}
}
});
bar.add(this.highlightButton);
bar.add( Box.createHorizontalGlue() );
JButton trash = new JButton(REMOVE_ANNOTATION);
trash.setToolTipText("Clear search results");
trash.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clearResults();
}
});
bar.add(trash);
return bar;
}
private class KeyTracker extends KeyAdapter {
public void keyReleased(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_ENTER) || (e.getKeyCode() == KeyEvent.VK_DOWN)
|| (e.getKeyCode() == KeyEvent.VK_UP) || (e.getKeyCode() == KeyEvent.VK_PAGE_UP)
|| (e.getKeyCode() == KeyEvent.VK_PAGE_DOWN)) {
int selectedRow = resultsTable.getSelectedRow();
ResultsTable model = (ResultsTable) resultsTable.getModel();
if (model.empty())
return;
SearchResults.SearchResult result = model.getSearchResult(selectedRow);
SimpleLogger.logInfo("Clicked on: " + model.getDocumentName(result) + " "
+ Integer.toString(result.getOffset()));
selectSearchResult(result);
}
}
}
private class ClickTracker extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
int selectedRow = resultsTable.getSelectedRow();
ResultsTable model = (ResultsTable) resultsTable.getModel();
if (model.empty())
return;
SearchResults.SearchResult result = model.getSearchResult(selectedRow);
SimpleLogger.logInfo("Clicked on: " + model.getDocumentName(result) + " "
+ Integer.toString(result.getOffset()));
selectSearchResult(result);
}
}
private void selectSearchResult(SearchResults.SearchResult result) {
// If the comparison view is visible, and the target document is one of
// the documents visible, then don't change the view.
// Otherwise, change to collation view, with the target document as the base.
int targetViewMode = JuxtaAuthorFrame.VIEW_MODE_COMPARISON;
DocumentCompareView view = juxtaFrame.getDocumentCompareView();
if (juxtaFrame.getViewMode() == JuxtaAuthorFrame.VIEW_MODE_COLLATION) {
targetViewMode = JuxtaAuthorFrame.VIEW_MODE_COLLATION;
} else if ((view.getBaseDocument() == null) || (view.getWitnessDocument() == null)) {
targetViewMode = JuxtaAuthorFrame.VIEW_MODE_COLLATION;
} else if ((view.getBaseDocument().getID() != result.getDocumentID())
&& (view.getWitnessDocument().getID() != result.getDocumentID())) {
targetViewMode = JuxtaAuthorFrame.VIEW_MODE_COLLATION;
}
if (targetViewMode == JuxtaAuthorFrame.VIEW_MODE_COLLATION) {
juxtaFrame.setLocation(targetViewMode, result.getDocumentID(), result.getOffset(), result.getLength(),
result.getDocumentID(), result.getOffset(), result.getLength());
} else {
int baseId = view.getBaseDocument().getID();
int witnessId = view.getWitnessDocument().getID();
// Check if the documents are already visible
if (baseId == result.getDocumentID() ) {
this.juxtaFrame.setLocation(targetViewMode,
baseId, result.getOffset(), result.getLength(),
witnessId, -1, -1);
} else if( witnessId == result.getDocumentID()) {
this.juxtaFrame.setLocation(targetViewMode,
baseId, -1, -1,
witnessId, result.getOffset(), result.getLength() );
} else {
this.juxtaFrame.setLocation(targetViewMode, view.getBaseDocument().getID(), 0, 0, result.getDocumentID(),
result.getOffset(), result.getLength());
}
}
}
private class ResultsTable extends AbstractTableModel {
private SearchResults searchResults;
public ResultsTable(SearchResults results) {
searchResults = results;
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
public int getColumnCount() {
return NUM_COLS;
}
public boolean empty() {
return searchResults.getSearchResults().size() == 0;
}
public int getRowCount() {
if (empty())
return 1;
return searchResults.getSearchResults().size();
}
public String getColumnName(int column) {
switch (column) {
case DOCUMENT_NAME:
return "Text";
case LINE_NUM:
return "Location";
case FRAGMENT:
return "Passage";
}
return null;
}
public Object getValueAt(int rowIndex, int columnIndex) {
List<SearchResult> results = this.searchResults.getSearchResults();
if (empty() && (columnIndex == DOCUMENT_NAME))
return "No results found";
if (rowIndex < results.size()) {
SearchResults.SearchResult result = (SearchResults.SearchResult) results.get(rowIndex);
switch (columnIndex) {
case DOCUMENT_NAME:
return getDocumentName(result);
case LINE_NUM:
return getLineNum(result);
case FRAGMENT:
return "<html>" + getFragment(result) + "</html>";
}
}
return null;
}
private Object getFragment(SearchResult result) {
return result.getTextFragment();
}
public Object getDocumentName(SearchResult result) {
JuxtaDocument document = session.getDocumentManager().lookupDocument(result.getDocumentID());
return document.getDocumentName();
}
public Object getLineNum(SearchResult result) {
JuxtaDocument document = session.getDocumentManager().lookupDocument(result.getDocumentID());
LocationMarker loc = document.getLocationMarker(result.getOffset());
if (loc == null)
return "n/a";
return loc.getLocationName(); // + " " + result.dump();
}
public SearchResults.SearchResult getSearchResult(int iRow) {
return (SearchResult) searchResults.getSearchResults().get(iRow);
}
}
}
| 39.635294 | 121 | 0.631864 |
a7ee77f572852e58cd45ab823809484719843115
| 9,648 |
package main.java.Graph.parsers;
import main.java.Graph.*;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.*;
/**
* @author herald
* @since 1.0
*/
public class PegasusDaxParser {
/**
* A mapping of AbstractOperator names and their Concrete Operator names
*/
public final Map<String, List<String>> abstractConcreteOperatorsMap =
Collections.unmodifiableMap(new HashMap<String, List<String>>() {
{
put("mAdd", Collections.unmodifiableList(Arrays.asList("mAdd")));
put("mBackground", Collections.unmodifiableList(Arrays.asList("mBackground")));
put("mBgModel", Collections.unmodifiableList(Arrays.asList("mBgModel")));
put("mConcatFit", Collections.unmodifiableList(Arrays.asList("mConcatFit")));
put("mDiffFit", Collections.unmodifiableList(Arrays.asList("mDiffFit")));
put("mImgTbl", Collections.unmodifiableList(Arrays.asList("mImgTbl")));
put("mJPEG", Collections.unmodifiableList(Arrays.asList("mJPEG")));
put("mProjectPP", Collections.unmodifiableList(Arrays.asList("mProjectPP")));
put("mShrink", Collections.unmodifiableList(Arrays.asList("mShrink")));
}
});
private final Logger LOG = Logger.getLogger(PegasusDaxParser.class);
//
// static {
// }
long sumdata;
double multiply_by_time ;
int multiply_by_data ;
public PegasusDaxParser(double mulTIME,int mulDATA) {
multiply_by_time = mulTIME;
multiply_by_data = mulDATA;
sumdata=0;
}
public DAG parseDax(String url, Long dagId) throws Exception {
sumdata=0;
DAG graph = new DAG(dagId);
graph.name = url+multiply_by_time+"_"+multiply_by_data;
ArrayList<main.java.Graph.Edge> edges = new ArrayList<>();
HashMap<String,HashMap<String,tempFile>> opin = new HashMap<>();
HashMap<String,HashMap<String,tempFile>> opout = new HashMap<>();
HashMap<String,ArrayList<String>> optoop = new HashMap<>();
LinkedHashMap<String, Long> operatorNameMap = new LinkedHashMap<>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(url);
doc.getDocumentElement().normalize();
NodeList jobList = doc.getElementsByTagName("job");
for (int s = 0; s < jobList.getLength(); s++) {
double runTimeValue = 0;
int memoryValue = 40;
Node job = jobList.item(s);
Element jobElement = (Element) job;
String name = jobElement.getAttribute("id");
String application = jobElement.getAttribute("namespace");
String className = jobElement.getAttribute("name");
runTimeValue =
Double.parseDouble(jobElement.getAttribute("runtime")) * multiply_by_time;
long runtime_MS = (long) (runTimeValue * 1000);
ResourcesRequirements res = new ResourcesRequirements(runtime_MS,memoryValue);
Long opid = graph.addOperator(new Operator(name,res));
graph.getOperator(opid).setDAGId(dagId);
Operator op = graph.getOperator(opid);
operatorNameMap.put(name, opid);
op.className=className;
op.cpuBoundness = getCpuBoundness(application,className);
NodeList useElementList = jobElement.getElementsByTagName("uses");
for (int i = 0; i < useElementList.getLength(); i++) {
Node use = useElementList.item(i);
Element useElement = (Element) use;
long dataSize = (long) Double.parseDouble(useElement.getAttribute("size"));
long data_B = dataSize*multiply_by_data;
sumdata+=data_B;
String filename = useElement.getAttribute("file");
if (useElement.getAttribute("link").equals("output")) {
if(!opout.containsKey(name)){
opout.put(name,new HashMap<String, tempFile>());
}
opout.get(name).put(filename,new tempFile(null,name,data_B,filename));
}
else {
if(!opin.containsKey(name)){
opin.put(name,new HashMap<String, tempFile>());
}
opin.get(name).put(filename,new tempFile(name,"",data_B,filename));
}
}
}
NodeList childList = doc.getElementsByTagName("child");
for (int c = 0; c < childList.getLength(); c++) {
Node child = childList.item(c);
Element childElement = (Element) child;
String to = childElement.getAttribute("ref");
Long toOpId = operatorNameMap.get(to);
NodeList parentList = childElement.getElementsByTagName("parent");
/* Input port names */
for (int p = 0; p < parentList.getLength(); p++) {
Node parent = parentList.item(p);
Element parentElement = (Element) parent;
String from = parentElement.getAttribute("ref");
Long fromOpId = operatorNameMap.get(from);
edges.add(new main.java.Graph.Edge(fromOpId,toOpId,new Data("",-1)));
if(!optoop.containsKey(from)){
optoop.put(from,new ArrayList<String>());
}
optoop.get(from).add(to);
}//all the parents
}
Long f,t;
for(String fs:optoop.keySet()){
f = operatorNameMap.get(fs);
for(String ts:optoop.get(fs)){
t = operatorNameMap.get(ts);
ArrayList<String> names = new ArrayList<>();
long csize = 0;
for(String StmpflOUT: opout.get(fs).keySet()){
if(opin.containsKey(ts) && opin.get(ts).containsKey(StmpflOUT)){
names.add(StmpflOUT);
csize+=opout.get(fs).get(StmpflOUT).file_B;
}
}
graph.addEdge(new Edge(f,t,new Data(names,csize)));
}
}
graph.sumdata_B = sumdata;
return graph;
}
private double getCpuBoundness(String application, String className){
double cpuBoundness=1.0;
if ("SIPHT".equals(application))
{
if(className.equals("Patser"))
cpuBoundness = 0.8348;
else if(className.equals("Patser_concate"))
cpuBoundness = 0.1889;
else if(className.equals("Transterm"))
cpuBoundness = 0.9479;
else if(className.equals("Findterm"))
cpuBoundness = 0.9520;
else if(className.equals("RNAMotif"))
cpuBoundness = 0.9505;
else if(className.equals("Blast"))
cpuBoundness = 0.9387;
else if(className.equals("SRNA"))
cpuBoundness = 0.9348;
else if(className.equals("FFN_Parse"))
cpuBoundness = 0.8109;
else if(className.equals("Blast_synteny"))
cpuBoundness = 0.6101;
else if(className.equals("Blast_candidate"))
cpuBoundness = 0.4361;
else if(className.equals("Blast_QRNA"))
cpuBoundness = 0.8780;
else if(className.equals("Blast_paralogues"))
cpuBoundness = 0.4430;
else if(className.equals("SRNA_annotate"))
cpuBoundness = 0.5596;
}
if ("MONTAGE".equals(application))
{
if(className.equals("mProjectPP"))
cpuBoundness = 0.8696;
else if(className.equals("mDiffFit"))
cpuBoundness = 0.2839;
else if(className.equals("mConcatFit"))
cpuBoundness = 0.5317;
else if(className.equals("mBgModel"))
cpuBoundness = 0.9989;
else if(className.equals("mBackground"))
cpuBoundness = 0.0846;
else if(className.equals("mImgTbl"))
cpuBoundness = 0.0348;
else if(className.equals("mAdd"))
cpuBoundness = 0.0848;
else if(className.equals("mShrink"))
cpuBoundness = 0.0230;
else if(className.equals("mJPEG"))
cpuBoundness = 0.7714;
}
if ("LIGO".equals(application))
{
if(className.equals("TmpltBank"))
cpuBoundness = 0.9894;
else if(className.equals("Inspiral"))
cpuBoundness = 0.8996;
else if(className.equals("Thinca"))
cpuBoundness = 0.4390;
else if(className.equals("Inca"))
cpuBoundness = 0.3793;
else if(className.equals("Data_Find"))
cpuBoundness = 0.5555;
else if(className.equals("Inspinj"))
cpuBoundness = 0.0832;
else if(className.equals("TrigBank"))
cpuBoundness = 0.1744;
else if(className.equals("Sire"))
cpuBoundness = 0.1415;
else if(className.equals("Coire"))
cpuBoundness = 0.0800;
}
return cpuBoundness;
}
}
| 35.866171 | 95 | 0.559494 |
49afaebcc27ae394006b0bcb3597a95a81c1b955
| 223 |
package net.n2oapp.framework.api.metadata.global.view.widget.table;
/**
* Место расположения пагинации
*/
public enum Place {
topLeft,
topRight,
bottomLeft,
bottomRight,
topCenter,
bottomCenter
}
| 15.928571 | 67 | 0.695067 |
d10a29f8034ca6a562de172d3e1db95c596a5682
| 1,593 |
package com.appleframework.data.hbase;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.springframework.data.hadoop.hbase.RowMapper;
import org.springframework.util.Assert;
import com.appleframework.model.page.Paginator;
/**
* Adapter encapsulating the RowMapper callback.
*
* @author Costin Leau
*/
@SuppressWarnings("deprecation")
class PageMapperResultsExtractor<T> implements PageExtractor<T> {
private final RowMapper<T> rowMapper;
/**
* Create a new RowMapperResultSetExtractor.
* @param rowMapper the RowMapper which creates an object for each row
*/
public PageMapperResultsExtractor(RowMapper<T> rowMapper) {
Assert.notNull(rowMapper, "RowMapper is required");
this.rowMapper = rowMapper;
}
public Paginator<T> extractData(ResultScanner results, HTableInterface htable, long pageNo, long pageSize) throws Exception {
List<T> rs = new ArrayList<T>();
long firstIndex = (pageNo - 1) * pageSize;
long endIndex = firstIndex + pageSize;
int rowNum = 0;
for (Result result : results) {
if (rowNum >= firstIndex && rowNum < endIndex) {
byte[] row = result.getRow();
Get get = new Get(row);
rs.add(this.rowMapper.mapRow(htable.get(get), rowNum));
}
rowNum++;
}
Paginator<T> page = new Paginator<T>(pageNo, pageSize, rowNum);
page.setList(rs);
return page;
}
}
| 30.056604 | 127 | 0.715003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.