text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public String showColourOfDay(int Day){
String msg1;
try{
if(Day==1){
msg1 = new String("\nDay : Sanday = Red colour");
return msg1;
}
else if(Day==2){
msg1 = new String("\nDay : Monday = Yellor colour");
return msg1;
}
else if(Day==3){
msg1 = new String("\nDay : Tuesday = Pink colour");
return msg1;
}
else if(Day==4){
msg1 = new String("\nDay : Wednesday = Green colour");
return msg1;
}
else if(Day==5){
msg1 = new String("\nDay : Thursday = Orenge colour");
return msg1;
}
else if(Day==6){
msg1 = new String("\nDay : Friday = Blue colour");
return msg1;
}
else if(Day==7){
msg1 = new String("\nDay : Saturday = Violet colour");
return msg1;
}
else{
msg1 = new String("Error");
return msg1;
}
}catch(Exception e){
msg1 = new String("Error");
return msg1;
}
} | 8 |
public static Service SelectServiceByIdEntreprise(int id) throws SQLException {
String query = null;
Service service = new Service();
ResultSet resultat;
try {
query = "SELECT * from SERVICE where ID_ENTREPRISE=? ";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1, id);
resultat = pStatement.executeQuery();
while (resultat.next()) {
service = new Service(resultat.getInt("ID_SERVICE"),resultat.getInt("ID_ENTREPRISE"),resultat.getString("SERLIBELLE"));
}
} catch (SQLException ex) {
Logger.getLogger(RequetesService.class.getName()).log(Level.SEVERE, null, ex);
}
return service;
} | 2 |
protected static String detailedResponse(int status,String method,String resource) {
String response;
switch(status){
case 400:
response="Your browser sent a request that this server could not understand.";
break;
case 404:
response="The requested URL "+resource+" was not found on this server.";
break;
case 501:
response=method+" to "+resource+" not supported.";
break;
default:
response="Error detail not implemented";
break;
}
return response;
} | 3 |
public void topo() {
java.util.ArrayList<Vertex> s = new java.util.ArrayList<>();
int numOfVertices = vertices.length;
while (numOfVertices > 0) {
int tempNumOfVertices = numOfVertices;
Vertex noSuccessorVertex = noSuccessor();
if (noSuccessorVertex != null) {
for (int i = 0; i < vertices.length; i++) {
if (vertices[i] != null
&& vertices[i].getLabel() == noSuccessorVertex
.getLabel()) {
s.add(0, noSuccessorVertex);
deleteVertex(i, vertices);
numOfVertices--;
break;
}
}
} else {
if (tempNumOfVertices == numOfVertices
|| noSuccessorVertex == null) {
System.out.println("There is a cycle");
return;
}
}
}
CollectionsHelper.printCollection(s, "\n");
} | 7 |
public static void buildFrontier(final FlowGraph graph, boolean reverse) {
if (!reverse) {
DominanceFrontier.calcFrontier(graph.source(), graph, reverse);
} else {
DominanceFrontier.calcFrontier(graph.sink(), graph, reverse);
}
} | 1 |
@Override
public void positionnementAleatoire() {
this.difficulte = this._partie.getParametre().getDifficulte();
Iterator iterator = this._partie.getParametre().getBateaux(this._partie.getParametre().getEpoque()).keySet().iterator();
while(iterator.hasNext()) {
Random rand = new Random();
int sens = rand.nextInt(2)+1;
Bateau bateau = new Bateau((Bateau) this._partie.getParametre().getBateaux(this._partie.getParametre().getEpoque()).get(iterator.next()));
bateau.setNbCasesNonTouchees(bateau.getLongueur());
int xDepart = rand.nextInt(this._partie.getParametre().getNbCaseX()-1-bateau.getLongueur());
int yDepart = rand.nextInt(this._partie.getParametre().getNbCaseY()-1-bateau.getLongueur());
switch (sens) {
case 1:
// Place le bateau horizontalement
while(!this.testPositionBateau(bateau.getLongueur(), sens, xDepart, yDepart)) {
// On cherche des cases libres pour le bateau
xDepart = rand.nextInt(this._partie.getParametre().getNbCaseX()-1-bateau.getLongueur());
yDepart = rand.nextInt(this._partie.getParametre().getNbCaseY()-1-bateau.getLongueur());
}
for(int i=0;i<bateau.getLongueur();i++) {
// On place le bateau
CaseBateau caseBateau = new CaseBateau(bateau,this._partie);
caseBateau.setImage((String) bateau.getImagesBateau().get(i+1));
this._cases.set(xDepart+i+yDepart*this._partie.getParametre().getNbCaseX(), caseBateau);
}
break;
case 2:
// Place le bateau verticalement
while(!this.testPositionBateau(bateau.getLongueur(), sens, xDepart, yDepart)) {
// On cherche des cases libres pour le bateau
xDepart = rand.nextInt(this._partie.getParametre().getNbCaseX()-1-bateau.getLongueur());
yDepart = rand.nextInt(this._partie.getParametre().getNbCaseY()-1-bateau.getLongueur());
}
for(int i=0;i<bateau.getLongueur();i++) {
// On place le bateau
CaseBateau caseBateau = new CaseBateau(bateau,this._partie);
caseBateau.setImage((String) bateau.getImagesBateau().get(i+1));
this._cases.set(xDepart+(yDepart+i)*this._partie.getParametre().getNbCaseX(), caseBateau);
}
break;
case 3:
// Place le bateau a la diagonale
break;
default:
break;
}
}
} // positionnementAleatoire() | 8 |
@Override
public RoleSchool deserialize(JsonElement je, Type typeOfT, JsonDeserializationContext jdc) throws JsonParseException {
JsonObject jsonObject = je.getAsJsonObject();
String type = jsonObject.get("roleName").getAsString();
switch(type.toLowerCase()){
case "student":
String semester = jsonObject.get("semester").getAsString();
Student student = new Student();
student.setSemester(semester);
return student;
case "teacher":
String degree = jsonObject.get("degree").getAsString();
Teacher teacher = new Teacher();
teacher.setDegree(degree);
return teacher;
case "assistent teacher":
AssistentTeacher at = new AssistentTeacher();
return at;
default:
return null;
}
} | 3 |
private Map<Class<?>, Set<Class<?>>> buildDirectOwnedToOwnerdMap() {
Map<Class<?>, Set<Class<?>>> clsToOwnersMap = new HashMap<>();
for (Class<?> ownerCls : ownerToOwnedMap.keySet()) {
Map<String, Class<?>> ownedMap = ownerToOwnedMap.get(ownerCls);
for (Class<?> ownedCls : ownedMap.values()) {
CommonUtil.addToSetMap(clsToOwnersMap, ownedCls, ownerCls);
}
}
return clsToOwnersMap;
} | 9 |
public void listTranslateRules() {
try {
translateRulesFolder = (Folder) session.getObjectByPath("/TranslateRules");
} catch (CmisObjectNotFoundException e) {
System.out.println("translateRules folder not found, creating one.");
Map<String, String> properties = new HashMap<String, String>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
properties.put(PropertyIds.NAME, "TranslateRules");
try {
session.getRootFolder().createFolder(properties);
} catch (CmisContentAlreadyExistsException f) {
System.out.println("Could not create folder '"
+ "TranslateRules" + "': " + f.getMessage());
}
} catch (ClassCastException e) {
System.out.println("Object is not a CMIS folder.");
}
String ruleString = "";
StringBuffer returnValue = new StringBuffer("");
ItemIterable<CmisObject> children = translateRulesFolder.getChildren();
for (CmisObject o : children) {
returnValue.append(o.getName());
List<Property<?>> ruleProperies = o.getProperties();
for (Property<?> p : ruleProperies) {
if (p.getId().equalsIgnoreCase("trans:rule")) {
ruleString = (String) p.getFirstValue();
}
}
returnValue.append("\t");
returnValue.append(ruleString);
returnValue.append("\n");
}
System.out.println("List of translateRules: ");
System.out.println("--------------------------------------------");
System.out.println(returnValue.toString());
System.out.println("--------------------------------------------");
} | 8 |
public void run(){
try{
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(af);
line.start();
int num = 0;
while((ais != null) && ( num = ais.read(buff)) != -1){
{
interf.updateDiagram(buff);
line.write(buff, 0, num);
}
}
line.drain();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ais != null){
stopThread();
button.setText("Start Recording Sound");
if(Optiums.DISABLES_BUTTONS)
buttonRecorder.setEnabled(true);
interf.deleteMyWindowListener();
}
} | 6 |
public boolean addEntity(Entity e) {
for(Entity col : entities) {
if(e.isTouching(col)) {
return false;
}
}
entities.add(e);
return true;
} | 2 |
@Override
public void doAction(String choice) {
switch (choice) {
case "H": // display the help menu
HelpHuntGatherView HelpHuntGatherView = new HelpHuntGatherView();
HelpHuntGatherView.display();
break;
case "T": // hunt
// ********INSERT FUNCTION HERE**********
break;
case "G": // gather ingredients or food
// ********INSERT FUNCTION HERE**********
break;
case "Q": // Exit to previous menu
return;
default:
System.out.println("\n*** Invalid Selection *** Try again");
break;
}
} | 4 |
public void testConstructor_RD_RI5() throws Throwable {
DateTime dt = new DateTime(TEST_TIME_NOW);
Duration dur = new Duration(-1);
try {
new MutableInterval(dur, dt);
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
public Map<LinkedList<Candidate>, Integer> getDirectedGraph()
{
HashMap<Ranking, Integer> ranks = new HashMap<>();
for (IVoter voter : voters)
{
// make sure the voter has ordered the candidates
if (voter.getCurOrdering() == null)
voter.orderCand(cans);
// get the ordering
Ranking r = voter.getCurOrdering();
// check if another voter also ranked the
// candidates in the same way
if (ranks.containsKey(r))
{
ranks.put(r, ranks.get(r) + 1);
}
else
{
ranks.put(r, 1);
}
}
HashMap<LinkedList<Candidate>, Integer> directedGraph = new HashMap<>();
// create a directed graph of the pairwise preferences of the voters
// each edge says how many voters prefer c1 to c2
for (Candidate c1: cans)
{
for (Candidate c2: cans )
{
if (!(c1.getID().equals(c2.getID())))
{
int numVoters = 0;
for (Entry<Ranking, Integer> ranked : ranks.entrySet())
{
if (ranked.getKey().getRank(c1) > ranked.getKey().getRank(c2))
{
numVoters += ranked.getValue();
}
}
LinkedList<Candidate> edge = new LinkedList<>();
edge.push(c2);
edge.push(c1);
//System.out.println(c2.getID() + " --" + numVoters + "--> " + c1.getID());
// c2 --numVoters--> c1
directedGraph.put(edge, numVoters);
}
}
}
return directedGraph;
} | 8 |
public void addSong(Song song, Artist a){
List<String> terms = a.getTerms();
songCount++;
int tempYear = song.getYear();
String yearStr = "";
if(tempYear > 1000 && tempYear < 2050){
yearStr = String.valueOf(tempYear);
}
else{
yearStr = "None";
}
if(masterMap.get(yearStr + a.getArtist_continent() + a.getArtist_country()) != null){
masterMap.put(yearStr + a.getArtist_continent() + a.getArtist_country(), Integer.valueOf(masterMap.get(yearStr + a.getArtist_continent() + a.getArtist_country()) + 1));
masterMap.put("AllAllAll", Integer.valueOf(masterMap.get("AllAllAll") + 1));
// masterMap.put(yearStr + "AllAll", Integer.valueOf(masterMap.get(yearStr + "AllAll") + 1));
// masterMap.put("All" + a.getArtist_continent() + "All", Integer.valueOf(masterMap.get("All" + a.getArtist_continent() + "All") + 1));
// masterMap.put("AllAll" + a.getArtist_country(), Integer.valueOf(masterMap.get("AllAll" + a.getArtist_country()) + 1));
masterMap.put(yearStr + "All" + a.getArtist_country(), Integer.valueOf(masterMap.get(yearStr + "All" + a.getArtist_country()) + 1));
masterMap.put(yearStr + a.getArtist_continent() + "All",Integer.valueOf(masterMap.get(yearStr + a.getArtist_continent() + "All") + 1));
masterMap.put("All" + a.getArtist_continent() + a.getArtist_country(), Integer.valueOf(masterMap.get("All" + a.getArtist_continent() + a.getArtist_country()) + 1));
}
else{
masterMap.put(yearStr + a.getArtist_continent() + a.getArtist_country(), Integer.valueOf(1));
if(masterMap.get(yearStr + "All" + a.getArtist_country()) != null){
masterMap.put(yearStr + "All" + a.getArtist_country(), Integer.valueOf(masterMap.get(yearStr + "All" + a.getArtist_country()) + 1));
}
else{
masterMap.put(yearStr + "All" + a.getArtist_country(), Integer.valueOf(1));
}
if(masterMap.get(yearStr + a.getArtist_continent() + "All") != null){
masterMap.put(yearStr + a.getArtist_continent() + "All",Integer.valueOf(masterMap.get(yearStr + a.getArtist_continent() + "All") + 1));
}
else{
masterMap.put(yearStr + a.getArtist_continent() + "All",Integer.valueOf(1));
}
if(masterMap.get("All" + a.getArtist_continent() + a.getArtist_country()) != null){
masterMap.put("All" + a.getArtist_continent() + a.getArtist_country(), Integer.valueOf(masterMap.get("All" + a.getArtist_continent() + a.getArtist_country()) + 1));
}
else{
masterMap.put("All" + a.getArtist_continent() + a.getArtist_country(), Integer.valueOf(1));
}
}
if(yearsMap.get(Integer.valueOf(song.getYear())) == null){
yearsMap.put(Integer.valueOf(song.getYear()), Integer.valueOf(1));
masterMap.put(yearStr + "AllAll", Integer.valueOf(1));
}
else {
Integer newVal = yearsMap.get(Integer.valueOf(song.getYear())) + 1;
masterMap.put(yearStr + "AllAll", Integer.valueOf(masterMap.get(yearStr + "AllAll") + 1));
yearsMap.put(Integer.valueOf(song.getYear()), newVal);
}
if(continentMap.get(a.getArtist_continent()) == null){
continentMap.put(a.getArtist_continent(), Integer.valueOf(1));
masterMap.put("All" + a.getArtist_continent() + "All", Integer.valueOf(1));
}
else {
Integer newVal = continentMap.get(a.getArtist_continent()) + 1;
masterMap.put("All" + a.getArtist_continent() + "All", Integer.valueOf(masterMap.get("All" + a.getArtist_continent() + "All") + 1));
continentMap.put(a.getArtist_continent(), newVal);
}
if(countryMap.get(a.getArtist_country()) == null){
countryMap.put(a.getArtist_country(), Integer.valueOf(1));
masterMap.put("AllAll" + a.getArtist_country(), Integer.valueOf(1));
}
else {
Integer newVal = countryMap.get(a.getArtist_country()) + 1;
masterMap.put("AllAll" + a.getArtist_country(), Integer.valueOf(masterMap.get("AllAll" + a.getArtist_country()) + 1));
countryMap.put(a.getArtist_country(), newVal);
}
minListAdjust(terms);
double most = (((double)(songCount-1))/((double)(songCount)))*averageDuration;
averageDuration = most + ((1.0 /(double) songCount)*song.getDuration());
} | 9 |
public boolean SetDecoderProperties(byte[] properties)
{
if (properties.length < 5)
return false;
int val = properties[0] & 0xFF;
int lc = val % 9;
int remainder = val / 9;
int lp = remainder % 5;
int pb = remainder / 5;
int dictionarySize = 0;
for (int i = 0; i < 4; i++)
dictionarySize += ((properties[(1 + i)] & 0xFF) << i * 8);
if (!SetLcLpPb(lc, lp, pb))
return false;
return SetDictionarySize(dictionarySize);
} | 3 |
public static List<List<Token>> buildBoard(int size){
List<List<Token>> result = new ArrayList<List<Token>>();
if(size <= colorList.size()){
List<Color> colors = getColors(size);
colors = palettoShuffle(colors, size);
for(int i=0; i< size;i++){
List<Token> newList = new ArrayList<Token>();
for(int j=0; j < size;j++){
newList.add(new Token(colors.get((size*i)+j),j,i));
}
result.add(newList);
}
}
return result;
} | 3 |
public static Edge createBisectingEdge(Site site0, Site site1) {
double dx, dy, absdx, absdy;
double a, b, c;
dx = site1.get_x() - site0.get_x();
dy = site1.get_y() - site0.get_y();
absdx = dx > 0 ? dx : -dx;
absdy = dy > 0 ? dy : -dy;
c = site0.get_x() * dx + site0.get_y() * dy + (dx * dx + dy * dy) * 0.5;
if (absdx > absdy) {
a = 1.0;
b = dy / dx;
c /= dx;
} else {
b = 1.0;
a = dx / dy;
c /= dy;
}
Edge edge = Edge.create();
edge.set_leftSite(site0);
edge.set_rightSite(site1);
site0.addEdge(edge);
site1.addEdge(edge);
edge._leftVertex = null;
edge._rightVertex = null;
edge.a = a;
edge.b = b;
edge.c = c;
//trace("createBisectingEdge: a ", edge.a, "b", edge.b, "c", edge.c);
return edge;
} | 3 |
private void updateSelection() {
resetSelection();
switch (choiceSelected) {
case 1:
if (saveFileExists) {
regButton = new Sprite(selConButton);
regButton.setX(150);
regButton.setY(250);
} else {
regButton = new Sprite(selButton);
regButton.setX(150);
regButton.setY(400);
}
break;
case 2:
regButton2 = new Sprite(selButton);
if (saveFileExists) {
regButton2.setX(150);
regButton2.setY(150);
} else {
regButton2.setX(150);
regButton2.setY(300);
}
break;
case 3:
regButton3 = new Sprite(selButton);
if (saveFileExists) {
regButton3.setX(150);
regButton3.setY(50);
} else {
regButton3.setX(150);
regButton3.setY(200);
}
break;
}
} | 6 |
public void setName(String name) {
this.name = name;
} | 0 |
public int[] roomNeighbour(int roomNumber){
int room1,room2,room3,room4;
//room1=oben, room2=rechts, room3=unten, room4=links
if((roomNumber-6)>=0){
room1 = roomNumber-6;
}
else{
room1 = -1;//-1steht fuer eine ungueltige raumnummer
}
if((roomNumber+1)%6!=0){
room2 = roomNumber+1;
}
else{
room2 = -1;
}
if((roomNumber+6)<36){
room3 = roomNumber+6;
}
else{
room3 = -1;
}
if(roomNumber%6!=0){
room4 = roomNumber-1;
}
else{
room4 = -1;
}
int[] rooms = {room1,room2,room3,room4};
return rooms;
} | 4 |
public Object getKey() {
return key;
} | 0 |
public void inline(Object code) {
// First load the class for the inlined code.
Class codeClass = code.getClass();
String className = codeClass.getName().replace('.', '/') + ".class";
ClassLoader loader = codeClass.getClassLoader();
InputStream in;
if (loader == null) {
in = ClassLoader.getSystemResourceAsStream(className);
} else {
in = loader.getResourceAsStream(className);
}
if (in == null) {
throw new MissingResourceException("Unable to find class file", className, null);
}
ClassFile cf;
try {
cf = ClassFile.readFrom(in);
} catch (IOException e) {
MissingResourceException e2 = new MissingResourceException
("Error loading class file: " + e.getMessage(), className, null);
try {
e2.initCause(e);
} catch (NoSuchMethodError e3) {
}
throw e2;
}
// Now find the single "define" method.
MethodInfo defineMethod = null;
MethodInfo[] methods = cf.getMethods();
for (int i=0; i<methods.length; i++) {
MethodInfo method = methods[i];
if ("define".equals(method.getName())) {
if (defineMethod != null) {
throw new IllegalArgumentException("Multiple define methods found");
} else {
defineMethod = method;
}
}
}
if (defineMethod == null) {
throw new IllegalArgumentException("No define method found");
}
// Copy stack arguments to expected local variables.
TypeDesc[] paramTypes = defineMethod.getMethodDescriptor().getParameterTypes();
LocalVariable[] paramVars = new LocalVariable[paramTypes.length];
for (int i=paramVars.length; --i>=0; ) {
LocalVariable paramVar = createLocalVariable(paramTypes[i]);
storeLocal(paramVar);
paramVars[i] = paramVar;
}
Label returnLocation = createLabel();
CodeDisassembler cd = new CodeDisassembler(defineMethod);
cd.disassemble(this, paramVars, returnLocation);
returnLocation.setLocation();
} | 9 |
public BankBillet update(BankBillet billet)
throws CobreGratisBadRequestException,
CobreGratisUnauthorizedException, CobreGratisForbiddenException,
CobreGratisNotFoundException,
CobreGratisServiceUnavailableException,
CobreGratisInternalServerErrorException,
CobreGratisTooManyRequestsException,
CobreGratisUnprocessibleEntityException {
BankBilletWrapper wrapper = new BankBilletWrapper();
wrapper.setBankBillet(billet);
String json = gson.toJson(wrapper);
ClientResponse response = getWebResource().path("bank_billets")
.path(billet.getId().toString())
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).header("User-Agent", appId)
.put(ClientResponse.class, json);
switch (response.getStatus()) {
case 200:
return billet;
case 400:
throw new CobreGratisBadRequestException();
case 401:
throw new CobreGratisUnauthorizedException();
case 403:
throw new CobreGratisForbiddenException();
case 404:
throw new CobreGratisNotFoundException();
case 422:
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse( response.getEntity(String.class) );
throw new CobreGratisUnprocessibleEntityException(object.get("error").getAsString());
case 429:
throw new CobreGratisTooManyRequestsException();
case 503:
throw new CobreGratisServiceUnavailableException();
case 500:
throw new CobreGratisInternalServerErrorException();
default:
break;
}
return null;
} | 9 |
public static boolean validMulticast(String ip) {
if (ip == null || ip.isEmpty()) return false;
ip = ip.trim();
if ((ip.length() < 6) & (ip.length() > 15)) return false;
try {
Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} catch (PatternSyntaxException ex) {
return false;
}
} | 4 |
@SuppressWarnings("unchecked")
@Override
public void mouseClicked(MouseEvent e) {
JList<String> list = (JList<String>) e.getSource();
if(e.getClickCount() == 2){
int index = list.locationToIndex(e.getPoint());
ListModel<String> dlm = list.getModel();
String item = dlm.getElementAt(index);
list.ensureIndexIsVisible(index);
for(LearningPlugin plugin : loadedPlugins){
if(plugin.getName().equals(item)){
currentSelected = plugin;
updateLabel();
}
}
}
} | 3 |
public void harvest() {
for (ListenerHolder listener : listeners.values()) {
if (listener.getLiveUntil() < admin.calculateTime()) {
cancelListener(listener);
}
}
List<ISemiSpaceTuple> beforeEvict = new ArrayList<ISemiSpaceTuple>();
String[] groups = elements.retrieveGroupNames();
for ( String group : groups ) {
int evictSize = beforeEvict.size();
TupleCollectionById hc = elements.next(group);
for (ISemiSpaceTuple elem : hc) {
if (elem.getLiveUntil() < admin.calculateTime()) {
beforeEvict.add(elem);
}
}
long afterSize = beforeEvict.size() - evictSize ;
if ( afterSize > 0 ) {
List<Long>ids = new ArrayList<Long>();
for (ISemiSpaceTuple evict : beforeEvict) {
ids.add(Long.valueOf( evict.getId()) );
}
String moreInfo = "";
if ( ids.size() < 30 ) {
Collections.sort(ids);
moreInfo = "Ids: "+ids;
}
// log.logDebug("Testing group "+group+" gave "+afterSize+" element(s) to evict. "+moreInfo);
}
}
for (ISemiSpaceTuple evict : beforeEvict) {
cancelElement(Long.valueOf(evict.getId()), false, evict.getTag());
}
} | 9 |
private void updateGridletProcessing()
{
// Identify MI share for the duration (from last event time)
double time = GridSim.clock();
double timeSpan = time - lastUpdateTime_;
// if current time is the same or less than the last update time,
// then ignore
if (timeSpan <= 0.0) {
return;
}
// Update Current Time as Last Update
lastUpdateTime_ = time;
// update the GridResource load
int size = gridletInExecList_.size();
double load = super.calculateTotalLoad(size);
super.addTotalLoad(load);
// if no Gridlets in execution then ignore the rest
if (size == 0) {
return;
}
ResGridlet obj = null;
// a loop that allocates MI share for each Gridlet accordingly
Iterator iter = gridletInExecList_.iterator();
while ( iter.hasNext() )
{
obj = (ResGridlet) iter.next();
// Updates the Gridlet length that is currently being executed
load = getMIShare( timeSpan, obj.getMachineID() );
obj.updateGridletFinishedSoFar(load);
}
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EntityUniqueIdentifier other = (EntityUniqueIdentifier) obj;
if (clazz == null) {
if (other.clazz != null)
return false;
} else if (!clazz.equals(other.clazz))
return false;
if (uuid == null) {
if (other.uuid != null)
return false;
} else if (!uuid.equals(other.uuid))
return false;
return true;
} | 9 |
@SuppressWarnings("unchecked")
@Override
public String displayQuestionWithAnswer(int position, Object userAnswer) {
String questionStr = (String) question;
ArrayList<String> answerList = (ArrayList<String>) answer;
String userAnswerStr = (String) userAnswer;
boolean correct = false;
if (getScore(userAnswer) == score)
correct = true;
StringBuilder sb = new StringBuilder();
sb.append("<span class=\"dominant_text\">Feedback for Question " + position + " (Score: " + Math.round(getScore(userAnswer)*100)/100.0 + "/" + Math.round(score*100)/100.0 + ")" + ":</span><br /><br />\n");
sb.append("<span class=\"quiz_title\">\n");
sb.append(questionStr + "\n");
sb.append("<img src=\"" + questionURL + "\"" + " />\n");
sb.append("</span><br /><br />\n");
sb.append("<p class=\"answer\">Your answer is :\n");
if (correct) {
sb.append("<span class=\"correct answer\">" + userAnswerStr + "  </span>");
sb.append("<img class=\"small\" src=\"images/right.png\"></p><br /><br />");
} else {
sb.append("<span class=\"wrong answer\">" + userAnswerStr + "  </span>");
sb.append("<img class=\"small\" src=\"images/wrong.png\"><span class=\"wrong\">incorrect</span></p><br />\n");
sb.append("<p class=\"answer\">Correct answer : <span class=\"correct answer\">");
for (int i = 0; i < answerList.size(); i++) {
sb.append(answerList.get(i));
if (i < answerList.size() - 1)
sb.append(" OR ");
}
sb.append("</span></p>\n");
}
return sb.toString();
} | 4 |
private Collection<Library> allocateBooksForLibraries(final String book, final int quantity,
final Collection<Library> allLibrariesToBeAllocated) {
final Collection<Library> allocatedLibraries = new HashSet<Library>();
int remaningQty = quantity;
for (Library library : allLibrariesToBeAllocated) {
if (library.getWeighting() != null && library.getWeighting() > 0) {
int noOfBooksToBeAllocated = (int) (quantity * (library.getWeighting() * VALUE_HUNDRED_PERCENT));
// if there are books to be allocated and the weighting is low.
// Then, allocate books for less priority libraries
if (noOfBooksToBeAllocated == VALUE_ZERO) {
noOfBooksToBeAllocated = VALUE_ONE;
}
// If the book is already in the library,add the book
if (library.getAllocations().containsKey(book)) {
BookAllocation allocatedBook = library.getAllocations().get(book);
allocatedBook.setAllocatedQuantity(allocatedBook.getAllocatedQuantity() + noOfBooksToBeAllocated);
} else {
// New Book
final BookAllocation newAllocation = new BookAllocation();
newAllocation.setTitle(book);
newAllocation.setAllocatedQuantity(noOfBooksToBeAllocated);
library.getAllocations().put(book, newAllocation);
}
allocatedLibraries.add(library);
remaningQty = remaningQty - noOfBooksToBeAllocated;
// If the books are less than the libraries, exit.
if (remaningQty == VALUE_ZERO) {
break;
}
}
}
// If there is a remainder allocate one each for highest priority.
if (validateQuantity(remaningQty)) {
for (Library library : allLibrariesToBeAllocated) {
if (remaningQty == VALUE_ZERO) {
break;
}
remaningQty--;
final BookAllocation allocatedBook = library.getAllocations().get(book);
allocatedBook.setAllocatedQuantity(allocatedBook.getAllocatedQuantity() + VALUE_ONE);
allocatedLibraries.add(library);
}
}
return allocatedLibraries;
} | 9 |
public void initialize() {
// For each card
for ( int i = 0; i < ga.getNumberOfCards(); i++ ) {
int availableStock = 0;
int requiredStock = ga.getCardList().get( i ).getNumber();
for ( int j = 0; j < ga.getSellers().length; j++ ) {
this.availableStock[j][i] = ga.getAvailabilityConstraints()[j][i];
availableStock += this.availableStock[j][i];
}
if ( availableStock < requiredStock ) {
requiredStock = availableStock;
}
while ( requiredStock > 0 ) {
int seller = Random.random( 0, ga.getSellers().length - 1 );
if ( this.availableStock[seller][i] > 0 ) {
this.availableStock[seller][i]--;
this.genome[seller][i]++;
requiredStock--;
}
}
}
} | 5 |
public void loadLocations() {
Connection conn = plugin.getDbCtrl().getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT * FROM `%s`",
plugin.getDbCtrl().getTable(Table.LOCATION));
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
UUID uid = UUID.fromString(rs.getString("uid"));
double x = rs.getDouble("x");
double y = rs.getDouble("y");
double z = rs.getDouble("z");
float yaw = rs.getFloat("yaw");
float pitch = rs.getFloat("pitch");
int global = rs.getInt("global");
locations.put(uid, new Location(Bukkit.getServer().getWorld(uid), x, y, z, yaw, pitch));
if (global == 1)
globalUID = uid;
}
} catch (SQLException e) {
xAuthLog.severe("Failed to load teleport locations!", e);
} finally {
plugin.getDbCtrl().close(conn, ps, rs);
}
} | 3 |
private static Expr analyzeSeq(C context, ISeq form, String name) throws Exception{
Integer line = (Integer) LINE.deref();
if(RT.meta(form) != null && RT.meta(form).containsKey(RT.LINE_KEY))
line = (Integer) RT.meta(form).valAt(RT.LINE_KEY);
Var.pushThreadBindings(
RT.map(LINE, line));
try
{
Object me = macroexpand1(form);
if(me != form)
return analyze(context, me, name);
Object op = RT.first(form);
if(op == null)
throw new IllegalArgumentException("Can't call nil");
IFn inline = isInline(op, RT.count(RT.next(form)));
if(inline != null)
return analyze(context, preserveTag(form, inline.applyTo(RT.next(form))));
IParser p;
if(op.equals(FN))
return FnExpr.parse(context, form, name);
else if((p = (IParser) specials.valAt(op)) != null)
return p.parse(context, form);
else
return InvokeExpr.parse(context, form);
}
catch(Throwable e)
{
if(!(e instanceof CompilerException))
throw new CompilerException((String) SOURCE_PATH.deref(), (Integer) LINE.deref(), e);
else
throw (CompilerException) e;
}
finally
{
Var.popThreadBindings();
}
} | 9 |
public String getGoTo() {
return goTo;
} | 0 |
public BookingListResult(JSONObject json) throws JSONException {
super(json);
if (json.has("result")) {
JSONArray jsonArray = json.getJSONArray("result");
String packageId = null;
Vector packetItems = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject bookingJson = jsonArray.getJSONObject(i);
Booking elem = null;
if(bookingJson.has(TYPE)) {
String type = bookingJson.getString(TYPE);
if(type.equals(TYPE_FLIGHT)) {
elem = new FlightBooking(bookingJson);
this.flightBookings.addElement(elem);
} else if(type.equals(TYPE_HOTEL)) {
elem = new HotelBooking(bookingJson);
this.hotelBookings.addElement(elem);
} else if(type.equals(TYPE_RENTACAR)) {
elem = new RentacarBooking(bookingJson);
this.rentacarBookings.addElement(elem);
} else if(type.equals(TYPE_EXCURSION)) {
elem = new ExcursionBooking(bookingJson);
this.excursionBookings.addElement(elem);
}
}
// Build package
if(bookingJson.has(PACKAGE_ID)) {
String packId = bookingJson.getString(PACKAGE_ID);
if(!packId.equals(packageId)) {
packageId = packId;
packetItems = new Vector();
bookingPackages.addElement(packetItems);
}
packetItems.addElement(elem);
}
}
}
} | 9 |
public ArrayList<Trajet> rechercheTrajet(String villeDepart,
String villeArrivee,
DateTime dateDepart,
boolean avecConducteur,
boolean avecPlacesLibres){
ArrayList<Trajet> resultat = new ArrayList<Trajet>();
for(Trajet t : listeTrajets){
if(villeDepart.equalsIgnoreCase(t.getVilleDepart()) &&
villeArrivee.equalsIgnoreCase(t.getVilleArrivee()) &&
t.dateConcorde(dateDepart) &&
avecConducteur==t.hasConducteur() &&
avecPlacesLibres==t.hasPlacesLibres()){
resultat.add(t);
}
}
return resultat;
} | 6 |
public void addStock(Stock stock) throws StockAlreadyExistsException,
PortfolioFullException {
int countStockSymbol = 0;
// find the symbol's index and count
for (int i = 0; i < portfolioSize; i++) {
if (stocksStatus[i].getSymbol() == stock.getSymbol()) {
countStockSymbol++;
}
}
if (countStockSymbol == 1) {
throw new StockAlreadyExistsException(stock.getSymbol());
}
if (portfolioSize >= MAX_PORTFOLIO_SIZE) {
throw new PortfolioFullException();
}
stocksStatus[portfolioSize] = new StockStatus(stock.getSymbol(),
stock.getBid(), stock.getAsk(), stock.getDate(),
ALGO_RECOMMENDATION.DO_NOTHING, 0);
portfolioSize++;
} | 4 |
public SpriteSheet(String path){
BufferedImage image = null;
try {
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
if(image == null){
return;
}
this.path = path;
this.width = image.getWidth();
this.height = image.getHeight();
pixels = image.getRGB(0,0,width,height,null,0,width);
for(int i=0;i<pixels.length;i++){
pixels[i] = (pixels[i]&0xff)/64;
}
} | 3 |
public void targetActor() {
GameActor t = getTargetedActor();
if(t != null && withinRadius(t)) {
PhysicsComponent tPC = (PhysicsComponent)t.getComponent("PhysicsComponent");
if(tPC != null) {
PhysicsComponent ownPC = (PhysicsComponent)getOwningActor().getComponent("PhysicsComponent");
if(ownPC != null) {
ownPC.setTarget(tPC.getX(), tPC.getY());
if(ownPC.getAngleRad() < ownPC.getTargetAngle() + 0.1 && ownPC.getAngleRad() > ownPC.getTargetAngle() - 0.1) {
WeaponsComponent wc = (WeaponsComponent)getOwningActor().getComponent("WeaponsComponent");
if(wc != null && wc.ready()) {
Application.get().getEventManager().queueEvent(new FireWeaponEvent(owner));
}
}
}
}
}
else if(guardAngle >= 0) {
PhysicsComponent ownPC = (PhysicsComponent)getOwningActor().getComponent("PhysicsComponent");
ownPC.setTargetAngle(guardAngle);
}
} | 9 |
public static String removeChar(final char theChar, final String theString) {
final StringBuilder s = new StringBuilder();
for (int i = 0; i < theString.length(); i++) {
final char currentChar = theString.charAt(i);
if (currentChar != theChar) {
s.append(currentChar);
}
}
return s.toString();
} | 2 |
private void initFolder() {
// On crée le dossier temporaire contenant les images
String dirName = "img";
File dir = new File(dirName);
if ( !dir.mkdirs() )
JOptionPane.showMessageDialog(this,
"Impossible de créer le dossier temporaire contenant les images des cartes...",
"Erreur", JOptionPane.ERROR_MESSAGE);
// On crée le dossier contenant les positions s'il n'existe pas
dirName = "Positions";
File pos = new File(dirName);
if ( !pos.exists() ) {
if ( !pos.mkdirs() )
JOptionPane.showMessageDialog(this,
"Impossible de créer le dossier temporaire contenant les images des cartes...",
"Erreur", JOptionPane.ERROR_MESSAGE);
}
} | 3 |
public int compareTo(Point other)
{
return (distance > other.distance+0.01) ? 1 : (distance < other.distance-0.01) ? -1 : 0;
} | 2 |
public float[] analyzeBook(){
PDFTextStripper stripper;
float posMax = 0;
float negMax = 0;
int curPage = 0;
while (curPage <= bookGrain){ //while on page i
try {
stripper = new PDFTextStripper();
stripper.setStartPage(curPage);
stripper.setEndPage(curPage);
int curWord = 0;
String[] page = stripper.getText(book).split("[^A-Za-z]+");
pageGrain = page.length;
if (flag_block){
while (curWord < pageGrain - 4 ){
SentiWord wordColor = wordnet.test(page[curWord], page[curWord+1],
page[curWord+2], page[curWord+3]);
curWord+=wordColor.getWC();
double[] colors = wordColor.get();
if (colors[0] > posMax){ posMax = (float)colors[0]; }
if (colors[1] > negMax){ negMax = (float)colors[1]; }
};
} else {
while (curWord < pageGrain - 4 ){
SentiWord wordColor = wordnet.test(page[curWord], page[curWord+1],
page[curWord+2], page[curWord+3]);
curWord+=wordColor.getWC();
double[] colors = wordColor.get();
if (colors[0] > posMax){ posMax = (float)colors[0]; }
if (colors[1] > negMax){ negMax = (float)colors[1]; }
};
};
} catch (IOException e){
//
};
curPage++;
};
return new float[]{posMax, negMax};
} | 9 |
@Override
public String toString() {
if (isVertical) {
return "[x=" + value + "]";
} else if (isHorizontal) {
return "[y=" + value + "]";
} else {
String b = String.format("%+f", this.b);
return "[y=" + this.k + "*x" + b + "]";
}
} | 2 |
public ListNode merge(ListNode l1, ListNode l2) {
if (l1 == null){
return l2;
}
if (l2 == null){
return l1;
}
ListNode superHead = new ListNode(-1);
ListNode temp = superHead;
while (l1 != null&&l2 != null){
if(l1.val<l2.val){
temp.next = l1;
l1 = l1.next;
}
else {
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if (l1 != null){
temp.next = l1;
}
if (l2 != null){
temp.next = l2;
}
return superHead.next;
} | 7 |
@Override
public void act() {
getImage().scale(40, 40);
checkFall();
onTouchMovingBrick();
if (speed / 4 <= 0) speed = 4;
if (Greenfoot.isKeyDown("a")) {
move(-speed / 4, 0);
switchImageLeft();
}
if (Greenfoot.isKeyDown("d")) {
move(+speed / 4, 0);
switchImageRight();
}
if (Greenfoot.isKeyDown("space") && jumping == false) {
jump();
}
int waterOffset = 70 - ((SkyscraperWorld)getWorld()).getWaterLevel() / 2 / 10;
if (waterOffset <= getY()) {
((SkyscraperWorld)getWorld()).loseLife();
return;
}
Actor coin = getOneIntersectingObject(SkyscraperCoin.class);
if (coin != null) {
GreenfootSound coinSound = new GreenfootSound("Coin.wav");
coinSound.setVolume(75);
coinSound.play();
getWorld().removeObject(coin);
((SkyscraperWorld)getWorld()).getScoreCounter().add(10);
}
} | 7 |
private static double getIconRatio(BufferedImage originalImage,
BufferedImage icon)
{
double ratio=1;
if (originalImage.getWidth()>icon.getWidth())
{
ratio=(double)(icon.getWidth())/originalImage.getWidth();
}
else
{
ratio=icon.getWidth()/originalImage.getWidth();
}
if (originalImage.getHeight()>icon.getHeight())
{
double r2=(double)(icon.getHeight())/originalImage.getHeight();
if (r2<ratio)
{
ratio=r2;
}
}
else
{
double r2=icon.getHeight()/originalImage.getHeight();
if (r2<ratio)
{
ratio=r2;
}
}
return ratio;
} | 4 |
public void DeleteDiffFiles(DatabaseAccess JavaDBAccess, String TargetPHPFileSelectedComboBox) {
int TARGET_PHP_FILES_ID = 0;
PreparedStatement ps = null;
Connection conn = null;
try {
if ((conn = JavaDBAccess.setConn()) != null) {
System.out.println("Connected to database " + JavaDBAccess.getDatabaseName());
} else {
throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName());
}
conn.setAutoCommit(false);
// Start a transaction by inserting a record in the TARGET_PHP_FILES table
ps = conn.prepareStatement("SELECT ID FROM TARGET_PHP_FILES WHERE PATH = ?");
ps.setString(1, TargetPHPFileSelectedComboBox);
ResultSet rs = ps.executeQuery();
rs.next();
TARGET_PHP_FILES_ID = rs.getInt(1);
rs.close();
// Start a transaction by inserting a record in the TARGET_PHP_FILES table
ps = conn.prepareStatement("SELECT ID FROM VULNERABILITY_INJECTION_RESULTS WHERE TARGET_PHP_FILE = ?");
ps.setInt(1, TARGET_PHP_FILES_ID);
rs = ps.executeQuery();
while (rs.next()) {
// Open matches log file.
try {
boolean success = (new File(TargetPHPFileSelectedComboBox + "_" + rs.getRow() + ".diff")).delete();
if (!success) {
System.out.println("Expected file " + TargetPHPFileSelectedComboBox + "_" + rs.getRow() + ".diff" + " does not exist!");
}
} catch (Exception e) {
System.out.println("Unable to open matches Web Page log file.");
}
}
rs.close();
conn.commit();
conn.close();
} catch (Throwable e) {
System.out.println("Errors in DeleteDiffFiles!");
System.out.println("exception thrown:");
if (e instanceof SQLException) {
JavaDBAccess.printSQLError((SQLException) e);
} else {
e.printStackTrace();
}
}
} | 6 |
synchronized Class<?> defineClass(final String binaryName, final ClassNode cn) {
final ClassWriter cw = new ClassWriter(0);
cn.accept(cw);
final byte[] b = cw.toByteArray();
if (dumpClasses) {
final File f = new File(System.getProperty("user.home") + File.separator + "dump" + File.separator
+ binaryName.replace('.', File.separatorChar) + ".class");
final File dir = f.getParentFile();
if ((dir.exists() && dir.isDirectory()) || dir.mkdirs()) {
OutputStream out = null;
try {
out = new FileOutputStream(f);
out.write(b);
out.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
} else {
throw new IllegalStateException("Unable to create directory: " + f.getParent());
}
}
return defineClass(binaryName, b, 0, b.length);
} | 8 |
public boolean isUnit(){
boolean test = true;
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
if(this.matrix[i][j]!=1.0D)test = false;
}
}
return test;
} | 3 |
public void move()
{
if (path.size()<=1)
path=getLongestPath(getPos());
else
for (int n=path.size()-2;n>=0 && n>path.size()-10 ;n--)
{// path.size()-1 is always taken: the bike is there
if (path.get(n).notFree())
{
path=getLongestPath(getPos());
break;
}
}
path.remove(path.size()-1);
for (int n=1;n<path.size();n++)
{
Draw.draw(new Draw(Draw.Type.Line,
path.get(n).px()+10,path.get(n).py()+10,
path.get(n-1).px()+10,path.get(n-1).py()+10, Color.YELLOW));
}
if (path.size()>0)
{
move((path.get(path.size()-1)));
}
else
{
Draw.draw(new Draw("Shit.",getPos().px()-15,getPos().py()-5, 10, Color.BLACK, 1));
}
} | 6 |
private static boolean isInsideInSameHorizontalSpace(Positioned a, Positioned b)
{
return a.leftBorder() == b.leftBorder() &&
a.rightBorder() == b.rightBorder() &&
(pointInside(a, (b.leftBorder() + b.rightBorder()) / 2, b.topBorder(), true) ||
pointInside(a, (b.leftBorder() + b.rightBorder()) / 2, b.bottomBorder(), true));
} | 3 |
private PreferencesWindow() {
super(PREFERENCES, StdImage.PREFERENCES);
Container content = getContentPane();
mTabPanel = new JTabbedPane();
for (PreferenceCategoryProvider category : CATEGORIES) {
try {
addTab(category.create(this));
} catch (Exception exception) {
Log.error("Trying to load " + category, exception); //$NON-NLS-1$
}
}
mTabPanel.addChangeListener(this);
content.add(mTabPanel);
content.add(createResetPanel(), BorderLayout.SOUTH);
adjustResetButton();
restoreBounds();
} | 2 |
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(vert)
{
if(key == KeyEvent.VK_UP)
{
keyboardInput=true;
if(y<min)
{
y=min;
}
displacement-=32;
}
if(key == KeyEvent.VK_DOWN)
{
keyboardInput=true;
if(y+height>max)
{
y=max-height;
displacement = (y-min)*ratio;
}
else
{
displacement+=32;
y=(displacement/ratio) + min+64;
}
}
}
if(key == KeyEvent.VK_LEFT)
{
}
if(key == KeyEvent.VK_RIGHT)
{
}
} | 7 |
public static void binaryinsertsort(int[] a,int i){
int left = 0,right = i-1;
int temp = a[i];
while (left<=right) {
int middle=(left+right)/2;
if (temp<a[middle]) {
right= middle-1;
}else {
left = middle+1;
}
}
for (int k=i-1;k>=left;k--){
a[k+1] = a[k];
}
a[left] = temp;
} | 3 |
public static <A> Ord<Stream<A>> streamOrd(final Ord<A> oa) {
return ord(s1 -> s2 -> {
if (s1.isEmpty())
return s2.isEmpty() ? Ordering.EQ : Ordering.LT;
else if (s2.isEmpty())
return s1.isEmpty() ? Ordering.EQ : Ordering.GT;
else {
final Ordering c = oa.compare(s1.head(), s2.head());
return c == Ordering.EQ ? streamOrd(oa).f.f(s1.tail()._1()).f(s2.tail()._1()) : c;
}
});
} | 5 |
public ArrayList<String> placeDotCom(int comSize) {
// Declare Function Locals
ArrayList<String> alphaCells = new ArrayList<String>();
// String [] alphacoords = new String [comSize]; // ArrayList to Hold AlphaNumeric Coordinates
String temp = null; // Temporary String for concat
int [] coords = new int[comSize]; // current candidate coords
int attempts = 0 ; // current attempts counter
boolean success = false; // flag to indicate good location
int location = 0; // current starting location
comCount++; // nth dotcom is being placed
int incr = 1; // set horizontal increment
if ((comCount % 2)==1) { // if Statement that makes all odd numbered dotcoms
incr = gridLength; // into vertically placed targets by adding incrementing the next coordinate by a row length
}
while ( (!success) & (attempts++ < 200) ) {
location = (int) (Math.random()*gridSize); // Get Random location within `grid`
System.out.println("try "+location); // Output potential location
int x = 0 ; // Initialize counter to indicate which dotcom coordinate is being placed
success = true;
while (success && (x < comSize)){
if (grid[location]==0) { // Assumes that grid[int] initializes with 0's
coords[x++] = location;
location += incr; // add `incr` to original coordinate.
if (location >= gridSize) {
success = false;
}
if (x>0 && (location%gridLength==0)) {
success = false;
}
}
else {
System.out.print(" used "+location);
success = false;
}
}
}
int x = 0;
int row = 0;
int column = 0;
while (x < comSize) {
grid[coords[x]]=1;
row = (int) (coords[x] / gridLength);
column = coords[x] % gridLength;
temp = String.valueOf(alphabet.charAt(column));
alphaCells.add(temp.concat(Integer.toString(row)));
System.out.println(alphaCells.toString());
x++;
}
return alphaCells;
} | 9 |
public void writeToChannel(String text){
try{
bw.write("PRIVMSG "+ channel +" :"+text+"\n");
bw.flush();
}catch(IOException e){
System.out.println("IRC: Failure when trying to write to server: "+e.getMessage());
}
} | 1 |
public static String trimSectionEndBlanks(String text) {
if (isBlank(text)) {
return text;
}
boolean isBlank = false;
int endIndex = text.length();
if (text.length() >= 1) {
if (text.charAt(text.length() - 1) == ' ') {
isBlank = true;
endIndex--;
}
}
for (int i = text.length() - 1; i > 1; i--) {
if (!(text.charAt(i) == ' ' && isBlank)) {
break;
} else {
endIndex--;
}
}
if (endIndex + 1 < text.length()) {
endIndex++;
}
return text.substring(0, endIndex);
} | 7 |
public void updateRole( final long id, final String roleStr ) throws IOException {
if( id == 1 ) {
logger.warning("Can't update roles for admin");
return;
}
final UserRole neuRole = UserRole.roleForString(roleStr);
if( neuRole == null ) {
logger.warning("Unknown role.");
return;
}
(new SQLStatementProcessor<Void>("UPDATE user_roles SET role_id = ? WHERE uid = ?") {
public Void process( PreparedStatement s ) throws SQLException {
s.setLong(1, neuRole.getID());
s.setLong(2, id);
s.executeUpdate();
return null;
}}).doit();
/**
* Only once we've updated the DB!
*/
getAccountForID(id).setRoles(new String[]{neuRole.getTag()});
} | 2 |
public void setType(String type)
{
this.type = type;
} | 0 |
protected void processBackgroundReads() {
logger.info("Processing background reads...");
logger.info("Computing RPKM values using " + threads + " threads...");
long tstart = System.currentTimeMillis();
this.transcripts = new ArrayList<TranscriptRecord>();
GeneModelProducer producer = new GeneModelProducer();
producer.start();
// Leave one thread for the GTF producer
if (threads > 1)
threads--;
ArrayList<GeneModelConsumer> consumers = new ArrayList<GeneModelConsumer>();
for (int i = 0; i < threads; i++) {
GeneModelConsumer consumer = new GeneModelConsumer(backgroundFile);
consumer.start();
consumers.add(consumer);
}
try {
producer.join();
for (GeneModelConsumer c : consumers) {
c.join();
}
} catch (InterruptedException e) {}
// Reduce
for(GeneModelConsumer c : consumers) {
for(TranscriptRecord t : c.getTranscripts()) {
transcripts.add(t);
}
c.clearTranscripts();
}
long tend = System.currentTimeMillis();
double totalTime = ((tend - tstart)/1000);
logger.info("Finished processing background file in: "+totalTime + "s");
} | 6 |
@Override
public void render(Screen screen) {
super.render(screen);
int dist = getHeight() / SCORES_SHOWN;
int i = 0;
for (Long score : scores) {
if (scaleText)
Art.FONT.render(getX(), getY()+(dist*i), dist, Timer.longToTimeString(score), screen);
else {
Art.FONT.render(getX(), getY()+(Art.FONT.getHeight()*i), Timer.longToTimeString(score), screen);
}
i++;
}
} | 2 |
public static void main(String[] args) {
Assemble_dir ad = new Assemble_dir();
//if (args==null || args.length==0){
// System.out.println("Usage: java -jar BatchAssemble input directory> <output directory> <lookup table path> <regular expression filter> <overwrite=true/false>");
// System.out.println("Use # to use the default value");
// System.exit(1);
//}
ad.inputDir = args.length > 0 && !args[0].equalsIgnoreCase("#") ? args[0]
: ad.inputDir;
ad.outputDir = args.length > 1 && !args[1].equalsIgnoreCase("#") ? args[1]
: ad.outputDir;
ad.lookupTable = args.length > 2 && !args[2].equalsIgnoreCase("#") ? args[2]
: ad.lookupTable;
ad.rex = args.length > 3 && !args[3].equalsIgnoreCase("#") ? args[3]
: ad.rex;
ad.overwrite = args.length > 4 ? Boolean.parseBoolean(args[4]) : ad.overwrite;
ad.go();
System.out.println("All files complete.");
} | 9 |
private static void renderElements(int windowX, int windowY){
Font.render("Element", windowX + 16, windowY + height - 24);
GL11.glDisable(GL11.GL_TEXTURE_2D);
for(int i = 0; i < 3; i++){
GL11.glColor3f(0.5f, 0.5f, 0.5f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(windowX + 16 + i*32 + i*4, windowY + height - 26);
GL11.glVertex2f(windowX + 48 + i*32 + i*4, windowY + height - 26);
GL11.glVertex2f(windowX + 48 + i*32 + i*4, windowY + height - 58);
GL11.glVertex2f(windowX + 16 + i*32 + i*4, windowY + height - 58);
GL11.glEnd();
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
} | 1 |
public void selectSquibGroup(int index){
Universe u = sequence.getSquibGroups().get(index).getSquibs();
// Clear any previously selected squibs
visualSchematicController.deselect();
// And select the squibs from the given group
for (Firebox fb : u.getFireboxList())
{
for (Lunchbox lb : fb.getLunchboxList())
{
for (Squib s : lb.getSquibList())
{
for (Firebox uFb : visualSchematicController.universe.getFireboxList())
{
for(Lunchbox uLb : uFb.getLunchboxList())
{
for(Squib uS : uLb.getSquibList())
{
if(uS.getFirebox() == s.getFirebox() && uS.getLunchbox() == s.getLunchbox() && uS.getSquib() == s.getSquib())
{
uS.setSelected(1);
}
}
}
}
}
}
}
// Redraw the universe for the up to date selection list
visualSchematicController.drawUniverseSchematic();
visualSchematicController.drawUniverseVisual();
} | 9 |
private boolean method66(int i, int j, int k)
{
int i1 = i >> 14 & 0x7fff;
int j1 = worldController.method304(plane, k, j, i);
if(j1 == -1)
return false;
int k1 = j1 & 0x1f;
int l1 = j1 >> 6 & 3;
if(k1 == 10 || k1 == 11 || k1 == 22)
{
ObjectDef class46 = ObjectDef.forID(i1);
int i2;
int j2;
if(l1 == 0 || l1 == 2)
{
i2 = class46.anInt744;
j2 = class46.anInt761;
} else
{
i2 = class46.anInt761;
j2 = class46.anInt744;
}
int k2 = class46.anInt768;
if(l1 != 0)
k2 = (k2 << l1 & 0xf) + (k2 >> 4 - l1);
doWalkTo(2, 0, j2, 0, myPlayer.smallY[0], i2, k2, j, myPlayer.smallX[0], false, k);
} else
{
doWalkTo(2, l1, 0, k1 + 1, myPlayer.smallY[0], 0, 0, j, myPlayer.smallX[0], false, k);
}
crossX = super.saveClickX;
crossY = super.saveClickY;
crossType = 2;
crossIndex = 0;
return true;
} | 7 |
public static void pointIntersectsRectangleOuter(
float pointX, float pointY, float speedX, float speedY, float radius,
float rectX1, float rectY1, float rectX2, float rectY2,
float timeLimit, CollisionResponse response) {
// Assumptions:
assert (rectX1 < rectX2) && (rectY1 < rectY2): "Malformed rectangle!";
assert (pointX >= rectX1 + radius) && (pointX <= rectX2 - radius)
&& (pointY >= rectY1 + radius) && (pointY <= rectY2 - radius)
: "Point (with radius) is outside the rectangular container!";
assert (radius >= 0) : "Negative radius!";
assert (timeLimit > 0) : "Non-positive time";
response.reset(); // Reset detected collision time to infinity
// A outer rectangular container box has 4 borders.
// Need to look for the earliest collision, if any.
// Right border
pointIntersectsLineVertical(pointX, pointY, speedX, speedY, radius,
rectX2, timeLimit, tempResponse);
if (tempResponse.t < response.t) {
response.copy(tempResponse); // Copy into resultant response
}
// Left border
pointIntersectsLineVertical(pointX, pointY, speedX, speedY, radius,
rectX1, timeLimit, tempResponse);
if (tempResponse.t < response.t) {
response.copy(tempResponse); // Copy into resultant response
}
// Top border
pointIntersectsLineHorizontal(pointX, pointY, speedX, speedY, radius,
rectY1, timeLimit, tempResponse);
if (tempResponse.t < response.t) {
response.copy(tempResponse); // Copy into resultant response
}
// Bottom border
pointIntersectsLineHorizontal(pointX, pointY, speedX, speedY, radius,
rectY2, timeLimit, tempResponse);
if (tempResponse.t < response.t) {
response.copy(tempResponse); // Copy into resultant response
}
// FIXME: What if two collisions at the same time??
// The CollisionResponse object keeps the result of one collision, not both!
} | 8 |
@Override
public void close() throws IOException {
if (fileChannel != null) {
fileChannel.close();
}
if (rf != null) {
rf.close();
}
// GC
threadLocalByteBuffer.set(null);
threadLocalByteBuffer = null;
} | 2 |
synchronized public BlockTuple getNextToDoAndStart() throws InterruptedException{
BlockTuple res = null;
while(toDoList.isEmpty() && !workFinished)
wait();
if(workFinished)
//Schalte Thread aus, arbeit ist vorbei;
return null;
//
while(res == null){
if(workFinished)
Thread.currentThread().interrupt();
for(BlockTuple b : toDoList){
if(! ( currentlyDoneList.contains(b.getBlockOne())
|| currentlyDoneList.contains(b.getBlockTwo()))){
res = b;
break;
}
}
if(res == null)
wait();
}
toDoList.remove(res);
currentlyDoneList.add(res.getBlockOne());
currentlyDoneList.add(res.getBlockTwo());
return res;
} | 9 |
public synchronized void getAvgTempForStnsWithinTimeRange(Date fromDate, Date toDate){
PreparedStatement pstmt = null;
int avgTemp = 0;
String stn = "";
HashMap<Integer, String> hmResult = new HashMap<Integer, String>();
ResultSet rs = null;
try{
conn = DBConnectionMgr.getConnection();
if(conn != null && !conn.isClosed())
pstmt = conn.prepareStatement(WeatherDataConstants.SELECT_AVGTEMP_FORSTN_WITHDATERANGE);
pstmt.setDate(1, fromDate);
pstmt.setDate(2, toDate);
rs = pstmt.executeQuery();
if(rs != null){
while(rs.next()){
avgTemp = rs.getInt(1);
stn = rs.getString(2);
hmResult.put(avgTemp, stn);
}
}
if(hmResult.size() > 0)
System.out.println("The content in HashMap :"+hmResult.size());
}catch(SQLException ex){
ex.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}
} | 7 |
private void setGSState(String name) throws IOException {
// obj must be a string that is a key to the "ExtGState" dict
PDFObject gsobj = findResource(name, "ExtGState");
// get LW, LC, LJ, Font, SM, CA, ML, D, RI, FL, BM, ca
// out of the reference, which is a dictionary
PDFObject d;
if ((d = gsobj.getDictRef("LW")) != null) {
cmds.addStrokeWidth(d.getFloatValue());
}
if ((d = gsobj.getDictRef("LC")) != null) {
cmds.addEndCap(d.getIntValue());
}
if ((d = gsobj.getDictRef("LJ")) != null) {
cmds.addLineJoin(d.getIntValue());
}
if ((d = gsobj.getDictRef("Font")) != null) {
state.textFormat.setFont(getFontFrom(d.getAt(0).getStringValue()),
d.getAt(1).getFloatValue());
}
if ((d = gsobj.getDictRef("ML")) != null) {
cmds.addMiterLimit(d.getFloatValue());
}
if ((d = gsobj.getDictRef("D")) != null) {
PDFObject pdash[] = d.getAt(0).getArray();
float dash[] = new float[pdash.length];
for (int i = 0; i < pdash.length; i++) {
dash[i] = pdash[i].getFloatValue();
}
cmds.addDash(dash, d.getAt(1).getFloatValue());
}
if ((d = gsobj.getDictRef("CA")) != null) {
cmds.addStrokeAlpha(d.getFloatValue());
}
if ((d = gsobj.getDictRef("ca")) != null) {
cmds.addFillAlpha(d.getFloatValue());
}
// others: BM=blend mode
} | 9 |
public int readPackage(int depth, HashMap classes, String packageName,
int count) {
if (depth++ >= MAX_PACKAGE_LEVEL)
return count;
String prefix = packageName.length() == 0 ? "" : packageName + ".";
Enumeration enum_ = ClassInfo.getClassesAndPackages(packageName);
while (enum_.hasMoreElements()) {
// insert sorted and remove double elements;
String name = (String) enum_.nextElement();
String fqn = prefix + name;
if (ClassInfo.isPackage(fqn)) {
count = readPackage(depth, classes, fqn, count);
} else {
TreeElement elem = handleClass(classes, ClassInfo.forName(fqn));
if (progressBar != null)
progressBar.setValue(++count);
elem.inClassPath = true;
}
}
return count;
} | 5 |
public List<Entry> getEntryList() {
List<Entry> list = new LinkedList<>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM comments ORDER BY time");
if (resultSet == null) {
return list;
}
while (resultSet.next()) {
Entry entry = new Entry();
entry.setTime(resultSet.getTimestamp("time").toString());
entry.setText(resultSet.getString("comment"));
list.add(entry);
}
return list;
}
catch (SQLException ex) {
ex.printStackTrace();
return list;
}
} | 3 |
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AirlineException)) return false;
AirlineException other = (AirlineException) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
this.errorCode == other.getErrorCode() &&
((this.message1==null && other.getMessage1()==null) ||
(this.message1!=null &&
this.message1.equals(other.getMessage1())));
__equalsCalc = null;
return _equals;
} | 9 |
*/
protected void dragExitColumn(DropTargetEvent dte) {
List<Column> columns = mModel.getColumns();
if (columns.equals(mSavedColumns)) {
repaintColumn(mModel.getDragColumn());
} else {
columns.clear();
columns.addAll(mSavedColumns);
repaint();
if (mHeaderPanel != null) {
mHeaderPanel.repaint();
}
}
mSavedColumns = null;
mModel.setDragColumn(null);
} | 2 |
public static String uncompressUtf8(String str){
if (str == null || str.length() == 0) {
return str;
}
try{
int idx = str.indexOf('_');
String len = str.substring(0,idx);
String cont = str.substring(idx+1,str.length());
byte[] compressArr = new byte[Integer.parseInt(len)];
int i = 0;
for(int j=0;j<cont.length();j++){
char f0 = cont.charAt(j);
if(f0 == 'z'){
compressArr[i++] = (byte)(-(cont.charAt(++j)+30));
}else if(f0 =='{'){
compressArr[i++] = (byte)(cont.charAt(++j)+30);
}else if(f0 =='\n'){
compressArr[i++] = (byte)(cont.charAt(++j)-32);
}else if(f0 =='}'){
compressArr[i++] = (byte)(-(cont.charAt(++j)-32));
}else if(f0 =='~'){
compressArr[i++] = (byte)(-(cont.charAt(++j)-22));
}else{
compressArr[i++] = (byte)(f0-22);
}
}
byte[] decompressArr =ZlibUtil.decompress(compressArr);
return new String(decompressArr,CharsetConfig.UTF_8);
} catch (UnsupportedEncodingException e) {
log.error("",e);
}
return null;
} | 9 |
@EventHandler
public void onFlagTake(PlayerInteractEvent e) {
final Player p = e.getPlayer();
if (e.getAction()== Action.RIGHT_CLICK_BLOCK||e.getAction()==Action.LEFT_CLICK_BLOCK) {
final Block b = e.getClickedBlock();
if (CTF.gm.isPlaying(p)) {
if (b.getType()==Material.WOOL&&b.getData()==DyeColor.RED.getData()) {
CTF.fm.setFlag(p, Team.RED);
CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + "§r" + CTF.tm.getPlayerNameInTeamColor(p)
+ " §9picked up the §cRed flag§9!");
} else if (b.getType()==Material.WOOL&&b.getData()==DyeColor.BLUE.getData()) {
CTF.fm.setFlag(p, Team.BLUE);
CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + "§r" + CTF.tm.getPlayerNameInTeamColor(p)
+ " §9picked up the Blue flag!");
}
}
}
} | 7 |
private static void trimWSFromNode(Node node) {
NodeList children = node.getChildNodes();
for(int i = 0; i < children.getLength(); ++i) {
Node child = children.item(i);
if(child.getNodeType() == Node.TEXT_NODE) {
child.setTextContent(child.getTextContent().trim());
}
trimWSFromNode(child);
}
} | 2 |
private void open(final JFrame frame) {
final JFileChooser chooser = new JFileChooser(new File(GuiUtils.CURRENT_DIRECTORY));
chooser.setSelectedFile(new File("scsync.config"));
if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(frame)) {
final Gson gson = new GsonBuilder().create();
try {
GuiUtils.syncConfig = gson.fromJson(new FileReader(chooser.getSelectedFile()), SyncConfig.class);
if (!GuiUtils.syncConfig.getConfigs().isEmpty()) {
GuiUtils.currentFolderConfig = GuiUtils.syncConfig.getConfigs().get(0);
}
GuiUtils.CURRENT_DIRECTORY = chooser.getSelectedFile().getParent();
} catch (final Exception e) {
JOptionPane.showMessageDialog(frame, e.getMessage(), "Open Error", JOptionPane.ERROR_MESSAGE);
}
}
} | 3 |
public static ArrayList<Employee> showAll() {
ArrayList<Employee> employees = new ArrayList<Employee>();
Database db = dbconnect();
try {
db.prepare("SELECT * FROM employee WHERE bDeleted = 0 ORDER BY EID");
ResultSet rs = db.executeQuery();
while(rs.next()) {
employees.add(EmployeeObject(rs));
}
db.close();
} catch (SQLException e) {
Error_Frame.Error(e.toString());
}
return employees;
} | 2 |
@Test
public void testForcedMove() {
try {
Scanner sc = new Scanner(new File("./test/myBoard.txt"));
//
int xSize = sc.nextInt();
int ySize = sc.nextInt();
//
int [][] newField = new int[xSize][ySize];
for (int y = ySize - 1; y > -1; --y) {
for (int x = 0; x < xSize; ++x) {
newField[x][y] = sc.nextInt();
}
}
//
int [][] playersId = new int[xSize][ySize];
for (int y = ySize - 1; y > -1; --y) {
for (int x = 0; x < xSize; ++x) {
playersId[x][y] = sc.nextInt();
}
}
//
int [][] specialMovesId = new int[xSize][ySize];
for (int y = ySize - 1; y > -1; --y) {
for (int x = 0; x < xSize; ++x) {
specialMovesId[x][y] = sc.nextInt();
}
}
int ownTurn = sc.nextInt();
sc.close();
//
game = RulesParser.parse("./rules/Chess.xml");
game.forcedMove(newField, playersId, specialMovesId, ownTurn);
} catch(Exception e) { }
assertTrue(true);
} | 7 |
public CheckboxMenuItem getToolTipCheckBox() {
if (toolTipCheckBox == null) {
toolTipCheckBox = new CheckboxMenuItem("Set tooltip");
toolTipCheckBox.setState(true);
toolTipCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int toolTipCheckBoxId = e.getStateChange();
if (toolTipCheckBoxId == ItemEvent.SELECTED) {
trayIcon.setToolTip(TOOL_TIP);
} else {
trayIcon.setToolTip(null);
}
}
});
}
return toolTipCheckBox;
} | 2 |
public Point getRoute(int x, int y)
{
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return route[y][x];
} | 2 |
@Override
public IMatrix nInvert() {
/*
* inverz se računa kao umnožak inverza determinante matrice i
* transponirane adjungirane matrice početne matrice;
* ukoliko je determinanta 0, tada inverz ne postoji i takva matrica
* naziva se singularna matrica
*/
double determinant = this.determinant();
if (determinant == 0) {
throw new IncompatibleOperandException("Matrix is singular.");
}
IMatrix cofactorMatrix = new Matrix(this.getRowsCount(), this.getColsCount());
for (int row = 0; row < this.getRowsCount(); row++) {
for (int col = 0; col < this.getColsCount(); col++) {
cofactorMatrix.set(
row,
col,
(row+col)%2==0 ?
//ako je (i+j)%2 neparno, rezultat množimo s -1
subMatrix(row, col, true).determinant() :
-1*subMatrix(row, col, true).determinant());
}
}
return cofactorMatrix.nTranspose(true).scalarMultiply(1.0/determinant);
} | 4 |
@Override
public boolean onKeyDown(int key) {
if(super.onKeyDown(key)) {
return true;
}
if(key == Keyboard.KEY_ESCAPE || key == Keyboard.KEY_TAB) {
Application.get().getHumanView().popScreen();
return true;
}
return true;
} | 3 |
@Override
public void actionPerformed(ActionEvent arg0) {
switch(arg0.getActionCommand()) {
case ("Ok"): {
LAF = lookAndFeel.get(combo1.getSelectedIndex());
if(j != null) {
try {
UIManager.setLookAndFeel(LAF.getClassName());
} catch(ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
//noinspection UseOfSystemOutOrSystemErr
System.err.println(e);
}
SwingUtilities.updateComponentTreeUI(j);
j.pack();
j.revalidate();
}
setVisible(false);
return;
}
default: {
setVisible(false);
}
}
} | 3 |
public static void powMatrix(int[][] f, int n){
if(n<2) return;
powMatrix(f, n/2);
twoMatrix(f);
if(n%2 == 1)
oneMatrix(f);
} | 2 |
public synchronized void init() {
Object tmp = library.getObject(entries, "Pages");
pageTree = null;
if (tmp instanceof PageTree) {
pageTree = (PageTree) tmp;
}
// malformed core corner case, pages must not be references, but we
// have a couple cases that break the spec.
else if (tmp instanceof Hashtable) {
pageTree = new PageTree(library, (Hashtable) tmp);
}
try {
pageTree.init();
pageTree.initRootPageTree();
}
catch (NullPointerException e) {
logger.log(Level.FINE, "Error parsing page tree.", e);
}
} | 3 |
public LinkedList<Item> createLinkedList(int items) {
LinkedList<Item> list = new LinkedList<Item>();
for (int i=0;i<items;i++) {
Item item = genItem(i,items);
list.add(item);
}
return null;
} | 1 |
public void setFullscreen(boolean fullscreen) {
if (Client.instance.preferences.video.fullscreen == fullscreen) {
try {
Class<?> application = Class.forName("com.apple.eawt.Application");
Method getApplication = application.getMethod("getApplication");
Object app = getApplication.invoke(null);
Method requestToggleFullScreen = application.getMethod("requestToggleFullScreen", Window.class);
requestToggleFullScreen.invoke(app, window);
} catch(Exception e) {
e.printStackTrace();
}
}
} | 3 |
private String diffStateTreasure(GameState old, GameState curr, Card card)
{
Color faction = card.getFaction();
Loot oldLoot = old.getPlayer(faction).getLoot();
Loot currLoot = curr.getPlayer(faction).getLoot();
if(oldLoot.equals(currLoot))
return null;
for(String t : Treasure.allTreasures())
{
if(oldLoot.countTreasure(t) != currLoot.countTreasure(t))
{
return t;
}
}
return null;
} | 3 |
public static void main(String[] args) {
LiftOff launch = new LiftOff();
launch.run();
} | 0 |
public void forcePlus(Items items, int plus) {
if (plus < 0 || plus > 15)
return;
for (Shoes x : items.getShoes()) {
x.setPlus(plus);
}
for (Gloves x : items.getGloves()) {
x.setPlus(plus);
}
for (Pants x : items.getPants()) {
x.setPlus(plus);
}
for (Armor x : items.getArmors()) {
x.setPlus(plus);
}
for (Helm x : items.getHelms()) {
x.setPlus(plus);
}
System.out.println("Forced +" + plus);
} | 7 |
private void calculateSmoothingFactor(){
if (!vocab.isWordUpdated(ID)) {
clusterWords();
//zeros = (K+1)^2 - occupied contexts
//count nonZeros and find the minimum and its frequency
int nonZeros = 0;
int min = 0;
int minValues = 0;
for (int[] ai : clusterContexts){
for (int j : ai){
if (j!=0) {
nonZeros++;
//initialize min
if ((min==0) || (min>j)) {
min=j;
minValues=1;
} else if (j==min){
minValues++;
}
}
}
}
int zeros = (vocab.getCorpus().getLearner().getClusterContexts().size() -
nonZeros);
if (zeros!=0) {
smoothingCoefficent = 1 - (minValues * 1.0 / frequency);
smoothingFactor = minValues * 1.0 / (frequency * zeros);
} else {
//if there are no zeros, don't smoothe
smoothingFactor=0;
smoothingCoefficent= 1;
//Register in the vocabulary as calculated
vocab.registerWordUpdate(ID);
}
}
} | 8 |
public void merge(Map<String, Category> categoryMap) {
for (MergerInfo mi : miList) {
List<Player> mergedPlayers = new ArrayList<Player>();
AggregationGroup group = mi.getGroup();
String groupName = group.getKana();
Category category = categoryMap.get(groupName);
System.out.println(category);
Map<String, List<Player>> map = category.getMap();
for (String classification : mi.getList()) {
List<Player> players = map.get(classification);
if (players == null) {
System.err.println(String.format("Error in [%s]", classification));
System.err.println(mi);
}
mergedPlayers.addAll(players);
map.remove(classification);
for (Player player : players) {
switch (group) {
case TUL:
player.setTul(mi.getNewName());
break;
case MASSOGI:
player.setMassogi(mi.getNewName());
break;
default:
throw new AssertionError();
}
}
}
map.put(mi.getNewName(), mergedPlayers);
}
} | 6 |
public Form getForm(int formId) throws FormNotFoundException, ErrorRecreatingFormException {
try {
String q = "select formobject from form where formid = ?";
PreparedStatement st = conn.prepareStatement(q);
st.setInt(1, formId);
ResultSet rs = st.executeQuery();
conn.commit();
Form f;
rs.next();
byte[] buf = rs.getBytes(1);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf));
return (Form) in.readObject();
}
catch(SQLException e) {
e.printStackTrace();
throw new FormNotFoundException("Form does not exist");
}
catch(IOException e2) {
e2.printStackTrace();
throw new FormNotFoundException("IO Exception when retreiving form");
}
catch (ClassNotFoundException e3) {
e3.printStackTrace();
throw new ErrorRecreatingFormException("Error recreating form response");
}
} | 3 |
@Test
public void findUser(){
Connection conn = null;
Statement statement = null;
ResultSet reSet = null;
try{
conn = JDBCUtils.getConnection();
statement = conn.createStatement();
reSet = statement.executeQuery("select * from table_user");
while(reSet.next()){
String Id = reSet.getString("Id");
String name = reSet.getString("Name");
String Age = reSet.getString("Age");
String Address = reSet.getString("Address");
System.out.println(Id + " " + name +" "+ Age +" "+ Address + " ");
}
}catch (Exception e) {
e.printStackTrace();
}finally{
/* 关闭连接、传输对象和结果集。 */
JDBCUtils.close(conn, statement, reSet);
}
JDBCUtils.close(conn, statement, reSet);
} | 2 |
@Override
public boolean perform(GameEntity performer, GameEntity target) {
if (target instanceof Actor) {
Actor actor = (Actor) target;
if (hardAmount != 0) {
actor.addHealth(hardAmount);
} else if (dynamicAmount != null) {
int maxHealth = actor.getMaxHealth();
int eighth = maxHealth / 8;
int health = 0;
switch (dynamicAmount) {
case random:
// Add between 1/8th and 3/4th of the actor's max health
health += new Random().nextInt(eighth * 5) + eighth;
actor.addHealth(health);
break;
case eighth:
actor.addHealth(eighth);
break;
case quarter:
actor.addHealth(eighth * 2);
break;
case half:
actor.addHealth(eighth * 4);
break;
case threequarters:
actor.addHealth(eighth * 6);
break;
case full:
actor.addHealth(maxHealth);
break;
}
}
}
return true;
} | 9 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.