method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
b20e010a-cb80-4e7c-8a49-f783ca1d4991 | 4 | public boolean prove(int evenNumber) {
if(evenNumber<2){
throw new IllegalArgumentException();
}
for (int i = 0; i < evenNumber; i++) {
int number1 = i;
int number2 = evenNumber - i;
if (MathUtil.isPrime(number1) && MathUtil.isPrime(number2)) {
System.out.println(evenNumber + "=" + number1 + "+" + number2);
return true;
}
}
return false;
} |
542c515e-bd2d-4e0a-b703-628fc98c512d | 9 | public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
for (String ln;(ln=in.readLine())!=null;) {
StringTokenizer st=new StringTokenizer(ln);
int n=parseInt(st.nextToken()),m=parseInt(st.nextToken()),s=parseInt(st.nextToken()),v=parseInt(st.nextToken());
double[][] gopher=new double[n][];
double[][] holes=new double[m][];
for(int i=0;i<n;i++) {
st=new StringTokenizer(in.readLine());
gopher[i]=new double[]{Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())};
}
for(int i=0;i<m;i++) {
st=new StringTokenizer(in.readLine());
holes[i]=new double[]{Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())};
}
int[][] cap=new int[n+m+2][n+m+2];
ArrayList<Integer> [] lAdy=new ArrayList[n+m+2];
for(int i=0;i<n+m+2;i++)lAdy[i]=new ArrayList<Integer>();
for(int i=0;i<n;i++)
for(int j=0;j<m;j++) {
if(dist(gopher[i],holes[j])/v<=s) {
cap[i][j+n]=1;
lAdy[i].add(j+n);
lAdy[j+n].add(i);
}
}
for(int i=0;i<n;i++) {
cap[n+m][i]=1;
lAdy[n+m].add(i);
lAdy[i].add(n+m);
}
for(int j=0;j<m;j++) {
cap[n+j][n+m+1]=1;
lAdy[n+j].add(n+m+1);
lAdy[n+m+1].add(n+j);
}
sb.append(n-maxFlow(cap,n+m,n+m+1,n+m+2,lAdy)).append("\n");
}
System.out.print(new String(sb));
} |
973e0464-089f-4975-8b31-551735ae65d4 | 5 | private byte[] HandleRevealSubscriptionCommands(short transId, byte api, byte opcode)
{
switch(opcode)
{
case 0x01:
break;
case 0x02:
break;
case 0x03:
break;
case 0x04: return GetSubscribeListVersion(transId,(byte)0xED,api,opcode)
;
case 0x05: return SendAck(transId, (byte)0xED, api, opcode);
}
return null;
} |
ab5f21ab-7347-41f9-afd1-fbb9f65b292c | 6 | public void buildMateriiProf() {
// materia is the key
for (Materie m : materii) {
// map is the value
HashMap<Clasa, Profesor> map = new HashMap<Clasa, Profesor>();
// seek teachers with corresponding materie
for (Profesor p : profesori) {
if (p.getMaterie().equals(m)) {
// in the classes where they teach
for (String s : p.getClase()) {
for (Clasa c : this.getClasa()) {
if (c.getIdClasa().equals(s)) {
// if we have found a fitting entry
// put in dictionary
map.put(c, p);
}
}
}
}
}
materii_prof.put(m, map);
}
} |
62521366-bf66-447a-8a02-960f1ca5eaab | 7 | private int[][] dijkstras(int source){
//TODO: Stop once we reach the right planet
int numVertices = G.numVertices();
int[] dist = new int[numVertices];
int[] prev = new int[numVertices];
HashSet<Integer> Q = new HashSet<Integer>(numVertices);
for(int v = 0; v < numVertices; v++){
dist[v] = Integer.MAX_VALUE;
prev[v] = -1;
Q.add(v);
}
dist[source] = 0;
while (!Q.isEmpty()){
int u = max(dist);
for(int v : Q){
if(dist[v] <= dist[u]){
u = v;
}
}
Q.remove(u);
if(dist[u] == Integer.MAX_VALUE){
continue;
}
for (VertexIterator iter = G.neighbors(u); iter.hasNext();){
int v = iter.next();
int alt = dist[u] + G.cost(u, v);
if(alt < dist[v]){
dist[v] = alt;
prev[v] = u;
}
}
}
int[][] r = {dist,prev};
return r;
} |
44159b02-5602-4962-9380-5cd066741e46 | 1 | final Object pop() {
int size = stack.size();
return size == 0 ? null : stack.remove(size - 1);
} |
6d046eac-935f-4895-ae9f-94160ae2f3b1 | 2 | public String getTheme() {
if (theme == 1) {
return "Животные";
} else if (theme == 2) {
return "Марки автомобилей";
} else {
return "Рок-группы";
}
} |
fe5a843a-564d-4d81-97be-c1e6c2fb083b | 2 | private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
int res = JOptionPane.showConfirmDialog(
this,
"Seguro que deseas eliminar el personal",
"Advertencia",
JOptionPane.YES_NO_OPTION
);
if(res==JOptionPane.YES_OPTION){
try{
Libros p = (Libros) jTable1.getModel().getValueAt(
jTable1.getSelectedRow(),
5
);
LibrosCRUD libcrud = new LibrosCRUD(MyConnection.getConnection());
libcrud.delete(p);
ArrayList<Libros> libros = libcrud.getAll();
volcarDatos(libros);
}catch(Exception e){
System.out.print("Selecciona el elemento a elimnar");
}
}
}//GEN-LAST:event_btnEliminarActionPerformed |
9179c6a8-38af-494f-bbb2-83b4a93708b1 | 8 | public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
DataServer dataServer = (DataServer)Naming.lookup("//localhost:1111/showScore");
System.out.println("create table student");
dataServer.CreateTable();
System.out.println("Create succeed。。");
boolean isrunning = true;
while(isrunning)
{
System.out.println("Choose。\n1.insert 2.retrieve 3.find by name 0.quit");
int select = sc.nextInt();
if(select == 1)
{
System.out.println("please input the student's number/name/score:");
int num = sc.nextInt();
String name = sc.next();
double score = sc.nextDouble();
dataServer.insert(num, name, score);
}
else if(select == 2)
{
System.out.println("please input the student's number :");
int num = sc.nextInt();
double score = dataServer.select(num);
System.out.println("name: "+num +" score为: "+ score);
}
else if(select == 3)
{
System.out.println("please input the student's name:");
String name = sc.next();
double score = dataServer.select(name);
System.out.println("name: "+name +" score: "+ score);
}
else if(select == 0)
{
isrunning = false;
}
else
{
System.out.println("input error!");
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
d6d637e7-fed0-4809-94b0-89e59a1026e2 | 5 | void changeBackground() {
String background = backgroundCombo.getText();
if (background.equals(bundle.getString("White"))) {
imageCanvas.setBackground(whiteColor);
} else if (background.equals(bundle.getString("Black"))) {
imageCanvas.setBackground(blackColor);
} else if (background.equals(bundle.getString("Red"))) {
imageCanvas.setBackground(redColor);
} else if (background.equals(bundle.getString("Green"))) {
imageCanvas.setBackground(greenColor);
} else if (background.equals(bundle.getString("Blue"))) {
imageCanvas.setBackground(blueColor);
} else {
imageCanvas.setBackground(null);
}
} |
f599c996-e8cb-44ca-8dff-7aa281da1ec5 | 1 | public Queue<E> enqueue(E e){
Node current = last;
last = new Node();
last.e = e;
if(total++ ==0) first = last;
else current.next = last;
return this;
} |
032d5428-0f21-46e7-b3ab-a630775a51bb | 0 | @Test
public void testGetAnthillCells() {
System.out.println("getAnthillCells");
World instance = new World();
instance.generateRandomContestWorld();
List expResult = new ArrayList<>();
List result = instance.getAnthillCells();
assertEquals(expResult, result);
} |
8e196819-df8f-4a58-807a-c5fc5d360bc4 | 2 | private String getAvailableShares() {
Share[] bufferShare = sharepriceinfo.getAvailableShare();
String s = "";
for (int j = 0; j < bufferShare.length; j++) {
if(bufferShare[j].getExchange()!=null){
s += bufferShare[j].name +"<pre>"+ (float)bufferShare[j].getActualSharePrice()/100+" "+bufferShare[j].getExchange()+"</pre>" + "<br>";
}else{
s += bufferShare[j].name +"<pre>"+ (float)bufferShare[j].getActualSharePrice()/100+"</pre>" + "<br>";
}
}
return s;
} |
142449c5-449b-4e15-9715-182149509e89 | 7 | public void mousePressed(MouseEvent e) {
if (isRunning) {
if (player.canShoot)
player.shoot();
player.canShoot = false;
} else if (isIntro) {
int x = (int) e.getX();
int y = (int) e.getY();
if (x>=172 && x<=438 && y>=400 && y<=464) {
isIntro=false;
isRunning=true;
}
} else {
}
} |
aeda96ab-ef39-42c7-9d43-5c8f27fbe42c | 2 | public void generateTerrain() {
for (int row = 26; row < thisTick.length; row++) {
for (int col = 0; col < thisTick[row].length; col++) {
//thisTick[row][col] = new Entity(EntityType.ground.id);
}
}
} |
fb4e9031-5665-4631-baa0-c14d334af777 | 3 | public static void benchmarkFloatLargeArrayInANewThread()
{
System.out.println("Benchmarking FloatLargeArray in a new thread.");
final long length = (long) Math.pow(2, 32);
long start = System.nanoTime();
final FloatLargeArray array = new FloatLargeArray(length);
System.out.println("Constructor time: " + (System.nanoTime() - start) / 1e9 + " sec");
final int iters = 5;
for (int it = 0; it < iters; it++) {
start = System.nanoTime();
Thread thread = new Thread(new Runnable()
{
public void run()
{
for (long k = 0; k < length; k++) {
array.setFloat(k, 1.0f);
array.setFloat(k, (array.getFloat(k) + 1.0f));
}
}
});
thread.start();
try {
thread.join();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Computation time: " + (System.nanoTime() - start) / 1e9 + " sec");
}
} |
d2336074-94c1-49ee-87ce-c2f8c2c56250 | 8 | public void startCountdown(PhoneFriendResult phoneFriendResult) {
final String[] conversation = getConversation(phoneFriendResult);
setVisible(true);
if (conversation != null) {
friendConversationLabel.setText(setForLabel(conversation[0]));
friendConversationLabel.setVisible(true);
}
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
countdownLabel.setText(String.valueOf(remainingSecs));
if (conversation != null && remainingSecs == 20) {
friendConversationLabel.setText(setForLabel(conversation[1]));
}
if (conversation != null && remainingSecs == 15) {
friendConversationLabel.setText(setForLabel(conversation[2]));
}
if (conversation != null && remainingSecs == 10) {
friendConversationLabel.setText(setForLabel(conversation[3]));
}
if (remainingSecs < 0) {
stopTimer();
countdownLabel.setText("");
friendConversationLabel.setText("");
}
remainingSecs--;
}
});
timer.start();
} |
87f718d8-e2aa-4c74-a37c-a0a3b4cdd196 | 7 | private void renderSchedule() {
try {
ArrayList<ScheduleInfo> info = new ArrayList<ScheduleInfo>();
Staff stf = new Staff();
stf.setId(Integer.valueOf(Controller.Instance().getLoggedIn().getId()));
for (Flight f : Controller.Instance().getFlights()) {
if (f.getPilot().getId() == stf.getId()) {
info.add(new ScheduleInfo(f, "Pilot", false));
info.add(new ScheduleInfo(f, "Pilot", true));
}
if (f.getCopilot().getId() == stf.getId()) {
info.add(new ScheduleInfo(f, "Copilot", false));
info.add(new ScheduleInfo(f, "Copilot", true));
}
if (f.findOtherPersonal(stf)) {
info.add(new ScheduleInfo(f, "Attendant", false));
info.add(new ScheduleInfo(f, "Attendant", true));
}
if (f.findAirmarshalls(stf)){
info.add(new ScheduleInfo(f, "Airmarshall", false));
info.add(new ScheduleInfo(f, "Airmarshall", true));
}
}
if(!info.isEmpty()){
GenericTableModel<ScheduleInfo> model = new GenericTableModel<ScheduleInfo>(info);
tblSchedule.setModel(model);
}else{
tblSchedule.setVisible(false);
lblMessage.setText("<html><b> No schedule available for \"" + Controller.Instance().getLoggedIn().getUsername() + "\"</b> </html>");
}
} catch (Exception ex) {
}
} |
462a1313-63a1-4128-86a9-8eece9c93646 | 0 | private void SetStopBusStop(int stopBusStop)
{
this.stopBusStop = stopBusStop;
} |
c6ea1411-0948-41f2-bae2-313de219c0d4 | 7 | static private int jjMoveStringLiteralDfa6_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(4, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(5, active0);
return 6;
}
switch(curChar)
{
case 95:
return jjMoveStringLiteralDfa7_0(active0, 0x4000000L);
case 97:
return jjMoveStringLiteralDfa7_0(active0, 0x22000000L);
case 110:
return jjMoveStringLiteralDfa7_0(active0, 0x400000L);
case 114:
return jjMoveStringLiteralDfa7_0(active0, 0x200000L);
case 116:
return jjMoveStringLiteralDfa7_0(active0, 0x40000000L);
default :
break;
}
return jjStartNfa_0(5, active0);
} |
9223ba30-65a5-4513-bc9c-77732b2d3f60 | 2 | public JSONObject getData() {
JSONObject o = new JSONObject();
try {
for (Attribute a : Attribute.values())
o.put(a.name(), get(a));
} catch (JSONException e) {
e.printStackTrace();
}
return o;
} |
42791b61-78ee-48f1-bc8c-1a61149b89b1 | 0 | public void setPartnerList(final List<Partner> partnerList) {
this.partnerList = partnerList;
} |
eadf0ed1-4d73-48b8-a56a-d31babe001a0 | 5 | private void readDataFromDecoder() {
try {
while (decoder.hasNext()) {
InterfaceHttpData data = decoder.next();
if (data != null) {
switch (data.getHttpDataType()) {
case Attribute:
requestBody.attributes().add((Attribute) data);
break;
case FileUpload:
requestBody.files().add((FileUpload) data);
break;
}
}
}
} catch (EndOfDataDecoderException e1) {
}
} |
51da395f-234b-4ebd-8b9f-1ffb08394489 | 7 | @SuppressWarnings("unchecked")
public GridSpace(Settings settings, int width, int height, Class siteClass) {
this.settings = settings;
if (width < 1)
throw new IllegalArgumentException("width must be > 0");
if (height < 1)
throw new IllegalArgumentException("height must be > 0");
if (siteClass == null)
siteClass = Site.class;
this.width=width;
this.height=height;
sites = new Site[height*width];
Constructor siteConstructor;
try {
siteConstructor = siteClass.getConstructor(Integer.class, GridSpace.class);
} catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(ex);
}
try {
// Creates nodes and adds to the HashMap
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int id = (i * width) + j;
sites[id] = (Site)siteConstructor.newInstance(id, this);
}
}
} catch (Throwable ex) {
throw new IllegalArgumentException(ex);
}
} |
ecf57588-1ec3-468a-8a7c-f0bec0884cb7 | 1 | public void setCity(String city)
{
city = city.trim();
if ( city.isEmpty() ) {
throw new RuntimeException( "'city' should not be empty" );
}
this.city = city;
} |
ca75277e-a07d-4c9f-b023-79e769853434 | 5 | public static int numTrees(int n) {
if (n < 0) return 0;
if (0 == n || 1 == n) return 1;
int[] result = new int[n + 1];
result[0] = 1; result[1] = 1;
for (int i = 2; i < n + 1; i++) {
for (int j = 0; j < i; j++) {
result[i] = result[i] + result[j] * result[i - j - 1];
}
}
return result[n];
} |
d359bf53-6b41-46f6-aac3-b98a7ad656f8 | 5 | private void variableMutation(){
//Check if any max fitness the last few generations has differed greatly. If not increase mutation, if yes then reduce
HashMap temp = (HashMap) stats.get(stats.size()-1);
double lastFitness = (Double) temp.get("maxFitness");
boolean thresholdBreached = false;
for (int i = 2; i < 6; i++){
double someFitness = (Double) temp.get("maxFitness");
if (Math.max(lastFitness, someFitness) -
Math.min(lastFitness, someFitness) > 0.05) thresholdBreached = true;
}
if(thresholdBreached){
if(rep.getMutationRate() - 0.01 > baseMutationRate){
rep.setMutationRate(baseMutationRate);
System.out.println("Mutation rate reduced to "+ rep.getMutationRate() +"!");
}
}else{
if(rep.getMutationRate() + 0.01 < 1.0){
rep.setMutationRate(rep.getMutationRate() + 0.01);
System.out.println("Mutation rate increased to "+ rep.getMutationRate() +"!");
}
}
} |
3c42bfb5-9087-47ea-8e83-1d75350c9602 | 8 | private int priorityTree(int y, int x, int level, boolean turn, Pezzi[][] campo, int direction) {
//se la direzione è -1 la pedina non può muoversi, di conseguenza il thread terminerà con 0
// se invece ha un valore diverso compreso tra 0 e 3 il calcolo delle possibilità inizierà
if (direction == -1) {
return 0;
}
//inizio valutazione mossa
int n = 0;
if (level > 0) {
Integer[] posPossible = campo[y][x].posPosible();
if (posPossible[direction * 2] != null) {
//controllare in che direzzione sto andando
n += nextPositionGhost(y, x, posPossible[direction * 2], posPossible[direction * 2 + 1], turn, campo);
}
//zona ciclica dove si iniziera il gioco virtuale
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (campo[i][j] != null && campo[i][j].getColore() == Color.BLACK) {
int cd;
int cal = 0;
if (campo[i][j] instanceof Pedina) {
cd = controlDirection(campo[i][j].posPosible(), 0, campo[i][j]); // controllo nelle posizioni dei sottoalberi, se non sono possibili altre mosse in quella direzione il Thread si killa
cal = priorityTree(i, j, level - 1, !turn, cloneCampo(campo), cd);
cd = controlDirection(campo[i][j].posPosible(), 1, campo[i][j]);
cal += priorityTree(i, j, level - 1, !turn, cloneCampo(campo), cd);
} else {
cd = controlDirection(campo[i][j].posPosible(), 0, campo[i][j]);
cal = priorityTree(i, j, level - 1, !turn, cloneCampo(campo), cd);
cd = controlDirection(campo[i][j].posPosible(), 1, campo[i][j]);
cal += priorityTree(i, j, level - 1, !turn, cloneCampo(campo), cd);
cd = controlDirection(campo[i][j].posPosible(), 2, campo[i][j]);
cal += priorityTree(i, j, level - 1, !turn, cloneCampo(campo), cd);
cd = controlDirection(campo[i][j].posPosible(), 3, campo[i][j]);
cal += priorityTree(i, j, level - 1, !turn, cloneCampo(campo), cd);
}
n += cal;
}
}
}
}
return n;
} |
7db1a0da-ab0c-42a9-aaf9-f7c8fc7e847b | 7 | @Override
public void delScript(ScriptingEngine S)
{
if(scripts!=null)
{
if(scripts.remove(S))
{
if(scripts.isEmpty())
scripts=new SVector(1);
if(((behaviors==null)||(behaviors.isEmpty()))&&((scripts==null)||(scripts.isEmpty())))
CMLib.threads().deleteTick(this,Tickable.TICKID_ITEM_BEHAVIOR);
}
}
} |
3d0091a7-e869-4e72-9b94-ce4de592a185 | 3 | public boolean addAll(Collection<? extends T> c) {
// the reason we have to write "? extends E" is because we don't really
// care what class is passed in -- just as long as it inherits from type
// T at some point.
boolean retVal = false; // see official documentation for return value
// specs
for (T value : c) { // because c is a Collection, we can do this
// (Collection implements *iterable*)
if (this.add(value)) { // this performs the addition as well as
// tells us if something changed
retVal = true;
}
}
return retVal;
} |
4e1335ed-45f9-46fc-b3b1-d7b3b93980e0 | 9 | public static TreeNode buildTree() {
TreeBuilder builder = new TreeBuilder("Animations");
for (Building bld : Building.getAll()) {
if (!bld.hasAnimation()) continue;
String name = bld.getName();
if (name.startsWith("comp_"))
builder.add(bld, false, "Buildings", "comp", name);
else if (name.startsWith("deco_"))
builder.add(bld, false, "Buildings", "deco", name);
else if (name.startsWith("map_"))
builder.add(bld, false, "Buildings", "map", name);
else if (name.startsWith("terrain_"))
builder.add(bld, false, "Buildings", "terrain", name);
else {
String menu = bld.getBuildMenu();
if (menu == null) menu = "Other";
builder.add(bld, true, "Buildings", menu, name, bld.getTag());
}
}
for (Unit unit : Unit.getAll()) {
builder.add(unit, true, unit.getSide() + " Units",
unit.getName(), unit.getTag());
}
for (String name : Timeline.getAllNames()) {
builder.add(name, false, "all", name.substring(0,1), name);
}
return builder.getTree();
} |
f9128652-8586-4fe3-83c8-dbba426244a6 | 1 | public static Class<?> getClass(String fqn) throws ClassNotFoundException {
return Class.forName(fqn);
} |
92ca1a0a-73e7-4292-ae58-d74ab5b9e98c | 0 | public void continueGame(){
this.running = true;
this.lastLoopTime = System.currentTimeMillis();
this.showGame();
} |
ee3ce7aa-3868-47d1-9969-68883a997a97 | 9 | public boolean checkContinuous(Player myHand) {
boolean continuous = true;
int i = 0;
while (continuous = true && i <= 3) {
int rank1 = myHand.getCard(i).getRank();
int rank2 = myHand.getCard(i + 1).getRank();
if ((rank1++) == rank2) {
continuous = true;
} else {
continuous = false;
}
// this only works because it runs the loop again, after throwing
// the A to the end after checking for the king at the end.
/*
* if (myHand.getCard(0).getRank() == 1) { if
* (myHand.getCard(4).getRank() == 13) { continuous = true; } }
*/
i++;
}
//checks specifically for a royal flush
if (!continuous) {
i = 0;
int j = myHand.getCard(0).getRank();
int k = myHand.getCard(1).getRank();
int l = myHand.getCard(2).getRank();
int m = myHand.getCard(3).getRank();
int n = myHand.getCard(4).getRank();
if ((j == 1) && (k == 10) && (l == 11) && (m == 12) && (n == 13)) {
continuous = true;
}
}
return continuous;
} |
1a529d1e-aa7d-47a8-a758-d0abecae2f09 | 2 | @Override
public String getSynopsis() {
if (synopsis == null || isEmpty(synopsis.getText())) {
return "";
}
return synopsis.getText();
} |
f7cdd5e1-f5e9-4ac4-bc25-859855dbfd4d | 8 | public void create(Telecommunications telecommunications) throws PreexistingEntityException, RollbackFailureException, Exception {
if (telecommunications.getItItemCollection() == null) {
telecommunications.setItItemCollection(new ArrayList<ItItem>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Collection<ItItem> attachedItItemCollection = new ArrayList<ItItem>();
for (ItItem itItemCollectionItItemToAttach : telecommunications.getItItemCollection()) {
itItemCollectionItItemToAttach = em.getReference(itItemCollectionItItemToAttach.getClass(), itItemCollectionItItemToAttach.getItSerie());
attachedItItemCollection.add(itItemCollectionItItemToAttach);
}
telecommunications.setItItemCollection(attachedItItemCollection);
em.persist(telecommunications);
for (ItItem itItemCollectionItItem : telecommunications.getItItemCollection()) {
Telecommunications oldTelecommunicationsidTelecomOfItItemCollectionItItem = itItemCollectionItItem.getTelecommunicationsidTelecom();
itItemCollectionItItem.setTelecommunicationsidTelecom(telecommunications);
itItemCollectionItItem = em.merge(itItemCollectionItItem);
if (oldTelecommunicationsidTelecomOfItItemCollectionItItem != null) {
oldTelecommunicationsidTelecomOfItItemCollectionItItem.getItItemCollection().remove(itItemCollectionItItem);
oldTelecommunicationsidTelecomOfItItemCollectionItItem = em.merge(oldTelecommunicationsidTelecomOfItItemCollectionItItem);
}
}
em.getTransaction().commit();
} catch (Exception ex) {
try {
em.getTransaction().rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findTelecommunications(telecommunications.getIdTelecom()) != null) {
throw new PreexistingEntityException("Telecommunications " + telecommunications + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} |
51570928-b723-4fa3-b335-2f75f5d908ff | 9 | public static void findPotentials(String data_file) {
ChainMRFPotentials p = new ChainMRFPotentials(data_file);
SumProduct sp = new SumProduct(p);
for(int i=1; i<=p.chainLength(); i++) {
double[] marginal = sp.marginalProbability(i);
if(marginal.length-1 != p.numXValues()) // take off 1 for 0 index which is not used
throw new RuntimeException("length of probability distribution is incorrect: " + marginal.length);
System.out.println("marginal probability distribution for node " + i + " is:");
double sum = 0.0;
for(int k=1; k<=p.numXValues(); k++) {
if(marginal[k] < 0.0 || marginal[k] > 1.0)
throw new RuntimeException("illegal probability for x_" + i);
System.out.println("\tP(x = " + k + ") = " + marginal[k]);
sum += marginal[k];
}
double err = 1e-5;
if(sum < 1.0-err || sum > 1.0+err)
throw new RuntimeException("marginal probability distribution for x_" + i + " doesn't sum to 1");
}
MaxSum ms = new MaxSum(p);
for(int i=1; i<=p.chainLength(); i++) {
double maxProb = ms.maxProbability(i);
System.out.println("maxLogProbability="+maxProb);
int[] assignments = ms.getAssignments();
for (int j = 1; j<assignments.length; j++) {
System.out.println("x_"+j+"="+assignments[j]);
}
}
} |
1e61a358-6484-4595-b67a-3a9471f75b2d | 1 | @Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
} |
4e6b547a-31c5-4be7-9fba-fcff6d400a57 | 3 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
int LIM = 251;
BigInteger[] ans = new BigInteger[LIM];
ans[0] = BigInteger.ONE;
ans[1] = BigInteger.ONE;
BigInteger two = BigInteger.valueOf(2);
for (int i = 2; i < LIM; i++)
ans[i] = ans[i - 2].multiply(two).add(ans[i - 1]);
while ((line = in.readLine()) != null && line.length() != 0) {
int n = Integer.parseInt(line.trim());
out.append(ans[n] + "\n");
}
System.out.print(out);
} |
584ad4d3-eeca-4c11-87ab-051aac916dcb | 1 | public void Answer(final String channel) {
new Thread() {
public void run() {
HangupBridgeCalls();
PrintWriter writer = MainFrame.TelnetWriter();
writer.print("Action: Redirect\r\n");
writer.print("Channel: SIP/" + channel + "\r\n");
writer.print("Exten: " + Phone.MainExtension + "\r\n");
writer.print("Context: " + Phone.Context + "\r\n");
writer.print("Priority: 1\r\n\r\n");
writer.flush();
bridgeLines.remove(CallFrame.this);
List<String> bridgeList = new ArrayList<String>();
bridgeList.add(channel);
bridgeList.add(Phone.MainExtension);
bridgeLines.put(CallFrame.this, bridgeList);
if (initLinesForList.contains(channel))
initLinesForList.remove(channel);
initLinesForList.add(channel);
MakeFramesNotEnable(false);
new CallFramesTrue().start();
}
}.start();
} |
1a36fc03-0207-4d8c-b4b7-9f9f8b210fc2 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MultipleWritable other = (MultipleWritable) obj;
if (intField != other.intField)
return false;
if (Float.floatToIntBits(floatField) != Float
.floatToIntBits(other.floatField))
return false;
if (stringField == null) {
if (other.stringField != null)
return false;
} else if (!stringField.equals(other.stringField))
return false;
return true;
} |
87d93947-81ea-4085-8b70-6e7b3f58e70c | 4 | public void printLongString(int type, int max, String text) throws Exception
{
HashMap map = new HashMap();
String line = "";
int row_id = 0;
String[] words = text.split(" ");
for(int i = 0; i < words.length; i++)
{
line = "";
if (map.containsKey(row_id))
{
line = (String)map.get(row_id);
}
int length_of_word = words[i].length();
int length_of_line = line.length();
if ( (length_of_word + length_of_line) <= max)
{
line += " " + words[i];
map.put(row_id, line);
}
else
{
row_id += 1;
line = words[i];
map.put(row_id, line);
}
}
for (int i = 0; i < map.size(); i++)
{
this.printLine(type, (String)map.get(i));
}
} |
8fde2410-c3c7-46b0-acf5-81257537d800 | 3 | @Override
public void run() {
while (!interrupted) {
long time0 = System.currentTimeMillis();
rotation.mul(deltaRotation);
long duration = System.currentTimeMillis() - time0;
if (duration < FRAME_DELAY) {
try {
Thread.sleep(FRAME_DELAY - duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} |
4aec9ee6-ee53-462f-a63e-fa9b55942bc9 | 7 | public void execute() {
boolean skipHash = false;
String baseURL = "patch/" + patchName;
Map<String, File> patchedFiles = new Hashtable<String, File>();
InstallerPacker.collectFiles(patchedFiles, new File(patchedFolder), false);
Set<FileListEntry> patchedEntries = InstallerPacker.generateFileList(patchedFiles, baseURL, skipHash);
Map<String, File> baseFiles = new Hashtable<String, File>();
InstallerPacker.collectFiles(baseFiles, new File(getOutputFolder() + "/base_install"), false);
Set<FileListEntry> baseEntries = InstallerPacker.generateFileList(baseFiles, baseURL, skipHash);
List<FileListEntry> changedList = new ArrayList<FileListEntry>();
for (FileListEntry entry : patchedEntries) {
if (!baseEntries.contains(entry)) {
changedList.add(entry);
}
}
try {
Component component = new Component(patchName, "");
String patchFolder = getOutputFolder() + "/" + patchName;
for (FileListEntry changed : changedList) {
component.addFile(changed);
File target = new File(patchFolder + '/' + changed.getPath());
if (StringUtil.getExtension(changed.getFile().getName()).equals("zip")) {
target = new File(patchFolder + '/' + changed.getPath().substring(0,
changed.getPath().lastIndexOf(changed.getFile().getName())
+changed.getFile().getName().length()));
}
if (!target.exists() || target.length() != changed.getFile().length()) {
FileUtil.copyFile(changed.getFile(), target);
}
}
component.save(new File(getOutputFolder(), patchName + ".xml"));
} catch (IOException e) {
Log.e("Exception executing patch command", e);
}
} |
863c6d14-16d5-45c9-bb29-f0a8eed4e929 | 7 | private void logarUsuario(String usuario, String senha) {
String senhaAtual,usuarioAtual;
String senhaTeste = "";
int pontuacaoUsuario = 0;
boolean naoApareceu = true;
File dados = new File("data");
try {
Scanner reader = new Scanner(dados);
while ((reader.hasNextLine())&&(naoApareceu)){
pontuacaoUsuario = Integer.parseInt(reader.next());
usuarioAtual = reader.next();
senhaAtual = reader.next();
if(usuario.equals(usuarioAtual)){
naoApareceu = false;
senhaTeste = senhaAtual;
}
}
if (naoApareceu){
int resp = JOptionPane.showConfirmDialog(null, "Usuário não encontrado, desejar criar um novo?");
if(resp == JOptionPane.YES_OPTION){
criarNovoUsuario(usuario,senha);
}
} else {
if(senha.equals(senhaTeste)){
MenuInicial.setLogou(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.dispose();
} else {
JOptionPane.showMessageDialog(null, "Senha Incorreta!");
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
} |
74ed5da4-d4d7-41ce-b619-35fbc1dba874 | 3 | @Override
public int doStartTag() throws JspException {
User user = (User) pageContext.getSession().getAttribute(JSP_USER);
if (user != null) {
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
if (type == ClientType.USER || type == ClientType.ADMIN) {
return EVAL_BODY_INCLUDE;
}
}
return SKIP_BODY;
} |
894fa1b4-874b-4d9a-a45b-aae26e64d014 | 4 | public FiniteStateAutomaton convertToDFA(Automaton automaton) {
/** check if actually nfa. */
AutomatonChecker ac = new AutomatonChecker();
if (!ac.isNFA(automaton)) {
return (FiniteStateAutomaton) automaton.clone();
}
/** remove multiple character labels. */
if (FSALabelHandler.hasMultipleCharacterLabels(automaton)) {
FSALabelHandler.removeMultipleCharacterLabelsFromAutomaton(automaton);
}
/** create new finite state automaton. */
FiniteStateAutomaton dfa = new FiniteStateAutomaton();
State initialState = createInitialState(automaton, dfa);
/**
* get initial state and add to list of states that need to be expanded.
*/
ArrayList list = new ArrayList();
list.add(initialState);
/** while still more states to be expanded. */
while (!list.isEmpty()) {
ArrayList statesToExpand = new ArrayList();
Iterator it = list.iterator();
while (it.hasNext()) {
State state = (State) it.next();
/** expand state. */
statesToExpand.addAll(expandState(state, automaton, dfa));
it.remove();
}
list.addAll(statesToExpand);
}
return dfa;
} |
b6256f4c-7d66-4ef5-86ae-06bf7111e5a7 | 7 | @Override
protected void readChild(XMLStreamReader in) throws XMLStreamException {
String childName = in.getLocalName();
if (Limit.getXMLElementTagName().equals(childName)) {
if (limits == null) {
limits = new ArrayList<Limit>();
}
Limit limit = new Limit(getSpecification());
limit.readFromXML(in);
if (limit.getLeftHandSide().getType() == null) {
limit.getLeftHandSide().setType(getId());
}
limits.add(limit);
} else if ("required-ability".equals(childName)) {
String abilityId = in.getAttributeValue(null, ID_ATTRIBUTE_TAG);
boolean value = getAttribute(in, VALUE_TAG, true);
getAbilitiesRequired().put(abilityId, value);
getSpecification().addAbility(abilityId);
in.nextTag(); // close this element
} else if ("required-goods".equals(childName)) {
GoodsType type = getSpecification().getGoodsType(in.getAttributeValue(null, ID_ATTRIBUTE_TAG));
int amount = getAttribute(in, VALUE_TAG, 0);
AbstractGoods requiredGoods = new AbstractGoods(type, amount);
if (amount > 0) {
type.setBuildingMaterial(true);
if (getGoodsRequired() == null) {
setGoodsRequired(new ArrayList<AbstractGoods>());
}
getGoodsRequired().add(requiredGoods);
}
in.nextTag(); // close this element
} else {
super.readChild(in);
}
} |
d24c4749-1f55-44a4-9f49-7ec1f6cdbb44 | 5 | @Test
public void getIncome() {
Trainer test = null;
Trainer test1 = null;
try {
test = new Trainer("Franz", 3);
test1 = new Trainer("Karl", 5);
} catch (Exception e) {
fail("Unexpected Exception");
}
try {
Trainer test3 = new Trainer("Sepp", 12);
} catch (ValueException e) {
// expected
} catch (Exception e) {
fail("Unexpected Exception");
}
try {
Trainer test4 = new Trainer("Tony", -5);
} catch (ValueException e) {
// expected
} catch (Exception e) {
fail("Unexpected Exception");
}
assertEquals(120, test.getIncome(), 0);
assertEquals(120, test1.getIncome(), 0);
} |
20cbc411-88d2-49a5-9e6e-a1aa085b5277 | 8 | public ImagePlus applyWithMask()
{
final int width = input.getWidth();
final int height = input.getHeight();
final int depth = input.getStackSize();
//final ImagePlus imageOutput = input.duplicate();
//final ImageStack imageStackOutput = imageOutput.getStack();
final ImageStack inputStack = input.getStack();
final ImagePlus binaryOutput = input.duplicate();
final ImageStack binaryStackOutput = binaryOutput.getStack();
// Initialize binary output image
// Binarize output image
for (int k = 0; k < depth; ++k)
for (int i = 0; i < width; ++i)
for (int j = 0; j < height; ++j)
binaryStackOutput.setVoxel(i, j, k, 1);
// Apply 3x3x3 maximum filter
IJ.log(" Maximum filtering...");
final long t0 = System.currentTimeMillis();
final double[][][] localMaxValues = filterMax3D( input );
if( null == localMaxValues )
return null;
final long t1 = System.currentTimeMillis();
IJ.log(" Filtering took " + (t1-t0) + " ms.");
// find regional maxima
IJ.showStatus( "Finding regional maxima..." );
final AtomicInteger ai = new AtomicInteger(0);
final int n_cpus = Prefs.getThreads();
final int dec = (int) Math.ceil((double) depth / (double) n_cpus);
Thread[] threads = ThreadUtil.createThreadArray(n_cpus);
for (int ithread = 0; ithread < threads.length; ithread++)
{
threads[ithread] = new Thread() {
public void run() {
for (int k = ai.getAndIncrement(); k < n_cpus; k = ai.getAndIncrement())
{
int zmin = dec * k;
int zmax = dec * ( k + 1 );
if (zmin<0)
zmin = 0;
if (zmax > depth)
zmax = depth;
findMaximaRange( zmin, zmax, inputStack,
binaryStackOutput, localMaxValues, tabMask );
}
}
};
}
ThreadUtil.startAndJoin(threads);
IJ.showProgress(1.0);
//(new ImagePlus("valued maxima", imageStackOutput)).show();
return new ImagePlus("regional-maxima-" + input.getTitle(), binaryStackOutput);
} //apply |
3e33bfad-c739-4122-aeba-897df5036e73 | 5 | @Override
public void say(String toSay) {
int fileNum = 0;
for (String s : cut(conform(toSay))) {
try {
download(
BASE_URL + "?tl=" + lang + "&q=" + s,
TEMP_PATH+"part"+fileNum++ + ".mp3");
} catch (IOException e) {
Logger.w("Impossible de télécharger le fichier à lire de " +
"l'API de google" + e.getMessage());
}
}
Player p = null;
File f = null;
for (int i =0; i < fileNum; i++) {
f = new File(TEMP_PATH+"part"+i+".mp3");
try {
p = new Player(new FileInputStream(f));
} catch (FileNotFoundException | JavaLayerException e) {
Logger.w("Impossible d'accéder au fichier : " + e.getMessage());
}
try {
p.play();
} catch (JavaLayerException e) {
Logger.w("Impossible de lire le fichier audio : " +
e.getMessage());
}
f.delete();
}
} |
862be420-4ce3-423e-a809-6eac453a5b10 | 1 | public static void main(String[] args) {
double d = 0.05 ;
double sum = 0;
for (int i = 0; i < 60; i++) {
double t = ExponentialRandomNumber(d);
sum += t;
System.out.println(t);
}
System.out.println(sum/100);
} |
22156dd5-2568-4b6b-9e50-5cc44f1da6fc | 0 | public FilterFactory(Properties[] configs) {
this.configs = configs;
} |
4e90d66e-6fe3-4f37-9d77-51fde2b888a9 | 4 | @Before
public void setUp() {
TestHelper.signon(this);
MongoHelper.setDB("fote");
MongoHelper.getCollection("users").drop();
MongoHelper.getCollection("suggestions").drop();
for (User user : users) {
if(!MongoHelper.save(user, "users")) {
TestHelper.failed("user save failed!");
}
}
for (Suggestion suggestion : suggestions) {
if(!MongoHelper.save(suggestion, "suggestions")) {
TestHelper.failed("suggestion save failed!");
}
}
} |
772cfdff-4fa9-4c5d-844a-b98645f96675 | 1 | public static final int getIndex(String segment) {
if (isArraySegment(segment)) {
Matcher matcher = ARRAY_SYNTAX_PATTERN.matcher(segment);
matcher.find();
return Integer.parseInt(matcher.group(2));
}
return -1;
} |
c0562b15-0d88-471b-ba5c-7492ffb54fae | 4 | public static void setSelectedY(int y) {
if (Main.selectedId != -1 && !Main.getSelected().locked) {
RSInterface rsi = Main.getInterface();
if (rsi != null) {
if (rsi.children != null) {
rsi.childY.set(getSelectedIndex(), y);
}
}
}
} |
b1618ab0-d21c-4944-905b-6751f0b59df6 | 9 | @Override
public Object getValueAt(int arg0, int arg1) {
//return percent dl
Torrent t = allTorrents.toArray(new Torrent[0])[arg0];//slow
switch(arg1){
case 0:
return t.name;
case 1:
String s =null;
if(t.totalBytes/1024 <999){
s=""+dg.format(t.totalBytes/1024.0)+" KB";
}else if(t.totalBytes/(1024*1024)<999){
s=""+dg.format(t.totalBytes/(1024.0*1024.0))+" MB";
}else{
s=""+dg.format(t.totalBytes/(1024.0*1024.0*1024.0))+" GB";
}
return s;
case 2:
String st;
float f = 1.0f-(((float)t.getLeft())/t.totalBytes);
if(t.getStatus().equals("Checking files")){
st= ("Checking files "+dg.format((float)f*100.0)+"%");
}else{
st=(dg.format((float)f*100.0)+"%");
}
return st;
case 3:
return t.getRecentDownRate();// (bytes/ms)=kb/s
case 4:
return t.getRecentUpRate();
case 5:
return t.getPeers().size();
}
return null;
} |
531e1d0c-99cf-4ff2-a653-298aee227564 | 3 | private static Fontstyle getFontstyle(String s) {
Fontstyle ret = null;
if ((s != null) && !s.equals("")) {
try {
ret = Fontstyle.valueOf(s.trim().toUpperCase());
} catch (IllegalArgumentException e) {
ret = null;
}
}
return ret;
} |
c184df55-3ce8-461e-956f-2770838c22da | 2 | private void calculateEnabledState(JoeTree tree) {
if (tree.getComponentFocus() == OutlineLayoutManager.ICON) {
setEnabled(true);
} else {
if (tree.getCursorPosition() == tree.getCursorMarkPosition()) {
setEnabled(false);
} else {
setEnabled(true);
}
}
} |
08060135-8d6f-457c-8d60-570626925b0c | 3 | public boolean removeMovie(String title)
{
boolean deleted = false;
if (aMovieIndex.containsKey(title)) {
Item tempMovie = aMovieIndex.remove(title);
directorIndex.remove(((Movie)tempMovie).getDirector());
for (String s: ((Movie) tempMovie).getActors()) {
actorIndex.get(s).remove(tempMovie);
}
for (String s: tempMovie.keywords) {
keywordIndex.get(s).remove(tempMovie);
}
deleted = true;
}
return deleted;
} |
9e094900-e79e-4bf8-8cfa-a63825fd8073 | 6 | public static ArrayList<Planet> forShips(PlanetWars pw){
// Tested
ArrayList<Planet> asw = new ArrayList<Planet>(2);
asw.add(null);
asw.add(null);
// Find the biggest fleet to attack with and our weakest planet to know what is our goal of fleet to be destroyed in the enemey
int maxShips = 0;
int minShips = 1000;
for (Planet p : pw.MyPlanets()){
int ships = p.NumShips();
if (ships > maxShips){
maxShips = ships;
asw.add(0,p);
}
if (ships< minShips)
minShips = ships;
}
// Find the destination with a dangerous fleet
int maxDist = 0;
maxShips = 0;
for (Planet p : pw.NotMyPlanets()){
int ships = p.NumShips();
if ((ships/2)>minShips && ships>maxShips) {
// We choose the biggest Enemy to attack to defend more our planets
maxShips = ships;
}
}
return asw;
} |
590b8344-6ef5-4aa7-812d-33e3ae8454c7 | 8 | public static final boolean isDirect(Buffer buffer) {
if (buffer == null) {
return true;
}
if (!(buffer instanceof ByteBuffer)) {
if (buffer instanceof FloatBuffer) {
return ((FloatBuffer) buffer).isDirect();
}
if (buffer instanceof DoubleBuffer) {
return ((DoubleBuffer) buffer).isDirect();
}
if (!(buffer instanceof CharBuffer)) {
if (buffer instanceof ShortBuffer) {
return ((ShortBuffer) buffer).isDirect();
}
if (!(buffer instanceof IntBuffer)) {
if (buffer instanceof LongBuffer) {
return ((LongBuffer) buffer).isDirect();
} else {
throw new InvalidParameterException("Buffer " + buffer.getClass() + " is invalid");
}
} else {
return ((IntBuffer) buffer).isDirect();
}
} else {
return ((CharBuffer) buffer).isDirect();
}
} else {
return ((ByteBuffer) buffer).isDirect();
}
} |
83d2ae3f-e2d1-40f1-8b8a-809dc8a9e4ea | 1 | @Override
protected void logBindInfo(Method method) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("绑定" + getDescription() + "到方法[" + method + "]成功");
}
} |
c2d848cd-c337-4a16-937a-ecc361942a14 | 6 | private Pioche() {
for (Couleur c : Couleur.values()) {
if(c != Couleur.NOIR){
for (Label l : Label.values()) {
Carte carte = new Carte(CarteFactory.getCarte(l, c));
this.add(carte);
if(l != Label.ZERO && l != Label.PLUS4 && l != Label.JOKER) {
this.add(carte);
}
}
}
}
Collections.shuffle(this);
} |
05d5d9fe-9ce8-438f-8730-98d83252d00c | 7 | private void processDeskSave(RdpPacket_Localised data,
DeskSaveOrder desksave, int present, boolean delta)
throws RdesktopException {
int width = 0, height = 0;
if ((present & 0x01) != 0) {
desksave.setOffset(data.getLittleEndian32());
}
if ((present & 0x02) != 0) {
desksave.setLeft(setCoordinate(data, desksave.getLeft(), delta));
}
if ((present & 0x04) != 0) {
desksave.setTop(setCoordinate(data, desksave.getTop(), delta));
}
if ((present & 0x08) != 0) {
desksave.setRight(setCoordinate(data, desksave.getRight(), delta));
}
if ((present & 0x10) != 0) {
desksave
.setBottom(setCoordinate(data, desksave.getBottom(), delta));
}
if ((present & 0x20) != 0) {
desksave.setAction(data.get8());
}
width = desksave.getRight() - desksave.getLeft() + 1;
height = desksave.getBottom() - desksave.getTop() + 1;
if (desksave.getAction() == 0) {
int[] pixel = surface.getImage(desksave.getLeft(), desksave
.getTop(), width, height);
cache.putDesktop((int) desksave.getOffset(), width, height, pixel);
} else {
int[] pixel = cache.getDesktopInt((int) desksave.getOffset(),
width, height);
surface.putImage(desksave.getLeft(), desksave.getTop(), width,
height, pixel);
}
} |
c0411ff9-9e18-4dbe-9f34-c592fd537cbd | 6 | @Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.g = g;
width = getWidth();
height = getHeight();
if (drawAxis) {
drawVerticals();
}
if (click_state == STATE_DROPPED && edit) {
drawEdge(x0, y0, x1, y1, Color.RED);
click_state = STATE_IDLE;
}
drawPointer(current_x, current_y, Color.LIGHT_GRAY);
if (edit) {
drawVertex(relX(), relY(), "", -1, Color.GREEN);
}
for (Vertex v : graph.getVertices()) {
drawVertex(v.x, v.y, v.name, v.dist, v.vColor);
for (Edge e : v.adj) {
drawEdge2(e.src.x, e.src.y, e.dest.x, e.dest.y, e.cost, e.flow, e.eColor);
}
}
/*
Iterator it = coordToName.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
String name = (String) pairs.getValue();
Vertex v = graph.getVertex(name);
drawVertex(v.x, v.y, name, v.dist, v.vColor);
for (Edge e : v.adj) {
drawEdge2(e.src.x, e.src.y, e.dest.x, e.dest.y, e.cost, e.flow, e.eColor);
}
}
*/
} |
332cf8d2-33fc-4c1c-8f9c-56279206f229 | 2 | public void renderAll(){
Camera camera = this.raycaster.getCamera();
double x = camera.getX();
double z = camera.getZ();
double width = raycaster.getWidth();
for(int i = 0; i < width; i++){
double grad = ((double)i)/(width/2) - 1;
double angle = Math.atan(grad/camera.getProjectionDistance()) + camera.getAngle();
RayIntersect ray = raycaster.getWallfinder().fireRay(x, z, angle);
if(ray == null){
floorRender.renderPlanes(i, (raycaster.getHeight() / 2) - 1, (raycaster.getHeight() / 2) + 1);
continue;
}
double distance = ray.getDistance() * Math.cos(angle - camera.getAngle());
renderScreenSlice(ray, distance, i);
}
} |
b4cdec65-8836-4a62-92ee-0cd03b33e332 | 7 | @SuppressWarnings("rawtypes")
public static byte[] generateCanonicalRRsetData(RRset rrset, long ttl,
int labels) {
DNSOutput image = new DNSOutput();
if (ttl == 0) {
ttl = rrset.getTTL();
}
Name n = rrset.getName();
if (labels == 0) {
labels = n.labels();
} else {
// correct for Name()'s conception of label count.
labels++;
}
boolean wildcardName = false;
if (n.labels() != labels) {
n = n.wild(n.labels() - labels);
wildcardName = true;
log.trace("Detected wildcard expansion: " + rrset.getName()
+ " changed to " + n);
}
// now convert the wire format records in the RRset into a
// list of byte arrays.
ArrayList<byte[]> canonical_rrs = new ArrayList<byte[]>();
for (Iterator i = rrset.rrs(); i.hasNext();) {
Record r = (Record) i.next();
if ((r.getTTL() != ttl) || wildcardName) {
// If necessary, we need to create a new record with a new ttl
// or ownername.
// In the TTL case, this avoids changing the ttl in the
// response.
r = Record.newRecord(n, r.getType(), r.getDClass(), ttl, r
.rdataToWireCanonical());
}
byte[] wire_fmt = r.toWireCanonical();
canonical_rrs.add(wire_fmt);
}
// put the records into the correct ordering.
// Calculate the offset where the RDATA begins (we have to skip
// past the length byte)
int offset = rrset.getName().toWireCanonical().length + 10;
ByteArrayComparator bac = new ByteArrayComparator(offset, false);
Collections.sort(canonical_rrs, bac);
for (Iterator<byte[]> i = canonical_rrs.iterator(); i.hasNext();) {
byte[] wire_fmt_rec = i.next();
image.writeByteArray(wire_fmt_rec);
}
return image.toByteArray();
} |
4000c0a7-0b01-4894-9c07-bfc656cb107b | 1 | public boolean hitMe(){
if (getHandCount()<getHold())
hit = true;
else
hit = false;
return hit;
} |
952ede91-292a-4e28-a773-f682f7cdbab2 | 4 | private void setOrientation(String o) {
if ("isometric".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_ISOMETRIC);
} else if ("orthogonal".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_ORTHOGONAL);
} else if ("hexagonal".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_HEXAGONAL);
} else if ("shifted".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_SHIFTED);
} else {
System.out.println("Unknown orientation '" + o + "'");
}
} |
7aa7e4dd-eda0-4775-95ad-562548e8b26e | 9 | public void takeColor()
{
Object inputObj = null;
Integer outputObj = null;
// repeat until a Color is received and confirmation is sent
do {
// read the Color
try {
inputObj = in.readObject();
} catch ( Exception e ) {
// add better error detect later
System.err.println( "Error reading color from network"
+ " stream:\n" + e );
}
// make sure it's OK
if ( inputObj instanceof Color ) {
// DEBUG
System.out.println( "Received color: " + inputObj );
// Set this player's color
playerColor = ( Color ) inputObj;
// Set the other player's color
if ( this.playerNumber == 1 ) {
if ( this.playerColor == Color.white ) {
theDriver.setPlayerColor( 2, Color.blue );
} else {
theDriver.setPlayerColor( 2, Color.white );
}
} else if ( this.playerNumber == 2 ) {
if ( this.playerColor == Color.white ) {
theDriver.setPlayerColor( 1, Color.blue );
} else {
theDriver.setPlayerColor( 1, Color.white );
}
}
outputObj = new Integer( ROGER );
try {
out.writeObject( outputObj );
out.flush();
} catch ( IOException e ) {
System.err.println( "IOException while sending confirm"
+ " over network stream:\n" + e);
}
} else {
outputObj = new Integer( RESEND );
try {
out.writeObject( outputObj );
out.flush();
} catch ( IOException e ) {
System.err.println( "IOException while sending confirm"
+ " over network stream:\n" + e);
}
}
} while ( outputObj.intValue() == RESEND );
} |
76227602-d73e-4eda-b2c1-f2c17417c3c9 | 1 | public final void registerToNewObservables() {
for(PositionChangedObservable o : observables) {
o.register(observers);
}
observables.clear();
} |
34ce39a2-9c5b-4cad-b5a2-c2fc9250f746 | 6 | void copyUcs4ReadBuffer(int count, int shift1, int shift2, int shift3,
int shift4) throws java.lang.Exception
{
int j = readBufferPos;
int value;
if (count > 0 && (count % 4) != 0) {
encodingError(
"number of bytes in UCS-4 encoding not divisible by 4", -1,
count);
}
for (int i = 0; i < count; i += 4) {
value = (((rawReadBuffer[i] & 0xff) << shift1)
| ((rawReadBuffer[i + 1] & 0xff) << shift2)
| ((rawReadBuffer[i + 2] & 0xff) << shift3) | ((rawReadBuffer[i + 3] & 0xff) << shift4));
if (value < 0x0000ffff) {
readBuffer[j++] = (char) value;
if (value == (int) '\r') {
sawCR = true;
}
} else if (value < 0x000fffff) {
readBuffer[j++] = (char) (0xd8 | ((value & 0x000ffc00) >> 10));
readBuffer[j++] = (char) (0xdc | (value & 0x0003ff));
} else {
encodingError("value cannot be represented in UTF-16", value, i);
}
}
readBufferLength = j;
} |
39c2b21d-6edb-4729-96f9-7ea4a6ffd942 | 8 | @Parameters
public static Collection<Object[]> getParameters() throws Exception {
List<Object[]> res = new ArrayList<>();
SpdyNameValueBlock blockCorrect = new SpdyNameValueBlock();
SpdyNameValueBlock blockCorrect2 = new SpdyNameValueBlock();
SpdyNameValueBlock blockinCorrect = new SpdyNameValueBlock();
for (String[] arr : correctPairs) {
blockCorrect.getPairs().put(arr[0], arr[1]);
}
for (String[] arr : incorrectPairs) {
blockinCorrect.getPairs().put(arr[0], arr[1]);
}
for (int i = 0; i < STREAM_IDS_CORRECT.length; i++) {
for (int l = 0; l < PRIORITYINCORRECT.length; l++) {
for (int k = 0; k < priorityCorrect.length; k++) {
for (int t = 0; t < goodStatusCodes_rst.length; t++) {
for (int u = 0; u < goodStatusCode_GoAway.length; u++) {
Object[] o = new Object[13];
o[0] = STREAM_IDS_CORRECT[i];
o[1] = STREAM_IDS_CORRECT[i];
o[2] = STREAM_IDS_INCORRECT[i];
o[3] = STREAM_IDS_INCORRECT[i];
o[4] = priorityCorrect[k];
o[5] = PRIORITYINCORRECT[l];
o[6] = (byte) 0;
o[7] = (i % 2 == 0) ? blockCorrect : blockCorrect2;
o[8] = blockinCorrect;
o[9] = goodStatusCode_GoAway[u];
o[10] = badStatusCode_GoAway[u];
o[11] = goodStatusCodes_rst[t];
o[12] = badStatusCodes_rst[t];
res.add(o);
}
}
}
}
}
System.out.println(res.size());
return res;
} |
5a6e7bfb-4076-4342-a707-42cdfd16275b | 8 | @Override
public HashMap<Long, Float> getScores(HashMap<String, Integer> query) {
ArrayList<Long> ids = weighter.getAllIds();
HashMap<Long, Float> docScores = new HashMap<Long, Float>();
HashMap<String, Float> queryWeight = weighter.getWeightsForQuery(query);
float norm = 0;
if (normalized){
for (float key : queryWeight.values()){
norm += key * key;
}
norm = (float)Math.sqrt(norm);
if (norm == 0)
norm = 1;
}
for (Long id : ids) {
float currentWeight = 0;
HashMap<String, Float> docWeight = weighter.getDocWeightsForDoc(id);
for (String stem : queryWeight.keySet()) {
if (docWeight.containsKey(stem)) {
//currentWeight += docWeight.get(stem) * queryWeight.get(stem);
//currentWeight += qStem * dStem;
currentWeight += queryWeight.get(stem) * docWeight.get(stem);
}
}
if (normalized){
float docNorm;
try{
docNorm = weighter.getDocNorm(id);
} catch (Exception e){
docNorm = 1.0f;
}
currentWeight /= (docNorm * norm);
}
docScores.put(id, currentWeight);
}
return docScores;
} |
9aabfe27-8e17-443a-a526-e59a8ca7267f | 0 | public static void setSize(int w, int h){
WINDOW_HEIGHT = h;
WINDOW_WIDTH = w;
init();
} |
791b189b-3ac4-4302-b284-b797194e0da9 | 1 | public void init(int nplayers, int[] pref) {
this.nplayer=nplayers;
this.pref=pref;
this.position=this.getIndex();// position start from 0
this.record = new int[2*nplayer];
if(nplayers-position<=9)
magic=magic_table[nplayers-position];
else
magic=(int) Math.round(0.369*(nplayers-position) );
info.clear();
bowlIds.clear();
} |
207baf0a-e48f-4425-95b3-4a479ea29862 | 6 | public void loadUserDict(File userDict) {
InputStream is;
try {
is = new FileInputStream(userDict);
}
catch (FileNotFoundException e) {
System.err.println(String.format("could not find %s", userDict.getAbsolutePath()));
return;
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
long s = System.currentTimeMillis();
int count = 0;
while (br.ready()) {
String line = br.readLine();
String[] tokens = line.split("[\t ]+");
if (tokens.length < 3)
continue;
String word = tokens[0];
String tokenType = tokens[2];
double freq = Double.valueOf(tokens[1]);
word = addWord(word);
freqs.put(word, Word.createWord(word, Math.log(freq / total), tokenType));
count++;
}
System.out.println(String.format("user dict %s load finished, tot words:%d, time elapsed:%dms",
userDict.getAbsolutePath(), count, System.currentTimeMillis() - s));
}
catch (IOException e) {
System.err.println(String.format("%s: load user dict failure!", userDict.getAbsolutePath()));
}
finally {
try {
if (null != is)
is.close();
}
catch (IOException e) {
System.err.println(String.format("%s close failure!", userDict.getAbsolutePath()));
}
}
} |
c75d3d29-ba91-4b99-b503-4adc4d5bcd90 | 8 | @Override
public List<AdminCol> getColDsplTblList(String tblNm) {
log.debug("get column display table list for table = " + tblNm);
Connection conn = null;
PreparedStatement statement = null;
ResultSet rs = null;
ArrayList<AdminCol> list = new ArrayList<AdminCol>();
StringBuilder sql = new StringBuilder();
sql.append(" select tbl_nm, col_nm, dspl_nm, dspl_ord, data_type, sort_ind, sort_ord, sort_dir, srch_ind, key_ind, req_ind, meta_ind, meta_type, render_type, render_params, col_desc, max_len, dspl_tbl_ind");
sql.append(" from admin_col");
sql.append(" where tbl_nm = ?");
sql.append(" and dspl_tbl_ind = 'Y'");
sql.append(" order by dspl_ord");
try {
conn = DataSource.getInstance().getConnection();
statement = conn.prepareStatement(sql.toString());
statement.setString(1, tblNm);
log.debug(sql.toString());
rs = statement.executeQuery();
while (rs.next()) {
AdminCol col = new AdminCol();
col.setTblNm(rs.getString("tbl_nm"));
col.setColNm(rs.getString("col_nm"));
col.setDsplNm(rs.getString("dspl_nm"));
col.setDsplOrd(rs.getInt("dspl_ord"));
col.setDataType(rs.getString("data_type"));
col.setSortInd(rs.getString("sort_ind"));
col.setSortOrd(rs.getInt("sort_ord"));
col.setSortDir(rs.getString("sort_dir"));
col.setSrchInd(rs.getString("srch_ind"));
col.setKeyInd(rs.getString("key_ind"));
col.setReqInd(rs.getString("req_ind"));
col.setMetaInd(rs.getString("meta_ind"));
col.setMetaType(rs.getString("meta_type"));
col.setRenderType(rs.getString("render_type"));
col.setRenderParams(rs.getString("render_params"));
col.setColDesc(rs.getString("col_desc"));
col.setMaxLen(rs.getInt("max_len"));
col.setDsplTblInd(rs.getString("dspl_tbl_ind"));
list.add(col);
}
} catch (Exception e) {
log.error("failed to get column display table list for table = " + tblNm, e);
} finally {
if (rs != null) {
try { rs.close(); } catch (Exception e) {}
}
if (statement != null) {
try { statement.close(); } catch (Exception e) {}
}
if (conn != null) {
try { conn.close(); } catch (Exception e) {}
}
}
return list;
} |
6874c287-e705-4981-95f9-4201eea9c143 | 1 | public static int[] fill1(char[] c) {
int[] i = new int[c.length];
for (int x = 0; x < c.length; x++) {
i[x] = ((int) c[x]) - 65;
i[x] = h[i[x]];
}
return i;
} |
5db7b623-0e2c-434c-ad2d-46e14ebe54e5 | 8 | public ArrayList<Action> getPossibleActions() {
ArrayList<Action> possibleActions = new ArrayList<Action>();
if (this.movementCounter > 0){
for (Relative_Direction absoluteExitDirection : this.getCurrentRoom().getAbsoluteExits()) {
possibleActions.add(new MoveAction(absoluteExitDirection));
}
}
Set<Action> roomActions = this.getCurrentRoom().getRoomActions();
for(Action a : roomActions){
if (a.canPerform(this)){
possibleActions.add(a);
}
}
if (Game.getInstance().getCurrentCharacter() == this) {
possibleActions.add(new EndTurnAction());
}
DisplayItemCardsAction displayItems = new DisplayItemCardsAction();
if (displayItems.canPerform(this)) possibleActions.add(displayItems);
DisplayOmenCardsAction displayOmens = new DisplayOmenCardsAction();
if (displayOmens.canPerform(this)) possibleActions.add(displayOmens);
DisplayEventCardsAction displayEvents = new DisplayEventCardsAction();
if (displayEvents.canPerform(this)) possibleActions.add(displayEvents);
return possibleActions;
} |
982cb686-7c1a-4af9-8dff-d089f07c9c2c | 9 | public K findKey(Object value, boolean identity) {
V[] valueTable = this.valueTable;
if (value == null) {
K[] keyTable = this.keyTable;
for (int i = capacity + stashSize; i-- > 0;) {
if (keyTable[i] != null && valueTable[i] == null) {
return keyTable[i];
}
}
} else if (identity) {
for (int i = capacity + stashSize; i-- > 0;) {
if (valueTable[i] == value) {
return keyTable[i];
}
}
} else {
for (int i = capacity + stashSize; i-- > 0;) {
if (value.equals(valueTable[i])) {
return keyTable[i];
}
}
}
return null;
} |
2cff0b26-7d46-48d3-852f-7ff3060dbf72 | 9 | @Override
public int setup(XTreeCompiler compiler, XCodeGen codeGen) {
result = scope.get(ident, ident.name, access);
switch(result.r){
case DUPLICATED:
compiler.addDiagnostic(ident, "duplicated.var", ident.name, result.var.t.position.position.line);
break;
case FOUND:
break;
case DECLARED:
if(result.var.getClass()==XVar.class){
codeGen.addInstruction(t, XOpcode.LOADN);
codeGen.addInstruction(t, result.var);
}
break;
case NOT_FOUND:
compiler.addDiagnostic(ident, "var.not.found", ident.name);
return 0;
default:
break;
}
if(result.var instanceof XClassAttr){
XVar var = ((XClassAttr)result.var).getAccess();
getVar(t, var, codeGen);
//codeGen.addInstruction(t, XOpcode.GETBOTTOM1, 0);
return 1;
}else if(result.var instanceof XClosureVar){
XVar base = ((XClosureVar)result.var).base;
if(base instanceof XClassAttr){
if(base == ((XClosureVar)result.var).var){
codeGen.addInstructionB(t, XOpcode.GETBOTTOM1, 0);
}else{
codeGen.addInstruction2(t, XOpcode.GET_CLOSURE, result.var);
}
}
return 1;
}
return 0;
} |
38b8aaa8-8802-42e5-9ff6-6caa1b762b34 | 1 | public int labelIndex(final Label label) {
final Integer i = (Integer) labels.get(label);
if (i != null) {
return i.intValue();
}
throw new IllegalArgumentException("Label " + label + " not found");
} |
6b593062-85bc-4aa4-a92f-7fa09d4aaf69 | 5 | protected void push(char x, int num)
{
queueNode trc;
//Check if the element is forbidden
trc = iHead;
while(trc!=null)
{
if(trc.getData()==x)
return;
trc = trc.getNext();
}
//Check if the element is in the holding queue
trc = jHead;
while(trc!=null)
{
if(trc.getKeyNum()==num)
{
trc.setClicked(true);
return;
}
trc = trc.getNext();
}
//Put the element into the list
if(pTail!=null)
{
pTail.setNext(new queueNode(x, num));
pTail = pTail.getNext();
}
else
{
pHead = new queueNode(x,num);
pTail = pHead;
}
} |
ead3b859-beb6-4a91-b1c5-67d372fb3f68 | 4 | public int NumShips(int playerID) {
int numShips = 0;
for (Planet p : planets) {
if (p.Owner() == playerID) {
numShips += p.NumShips();
}
}
for (Fleet f : fleets) {
if (f.Owner() == playerID) {
numShips += f.NumShips();
}
}
return numShips;
} |
d9656abc-8160-471a-8053-fde48164c979 | 4 | public static void main(String[] args) throws Exception {
String hostAddress = args[0];
String namingAddress = args[1];
RemoteDrunkardCompanion companion = (RemoteDrunkardCompanion) Naming.lookup(hostAddress);
BufferedReader cmd = new BufferedReader(new InputStreamReader(System.in));
String ln;
while ((ln = cmd.readLine()) != null) {
if (ln.startsWith("q")) return;
int vertexId = Integer.parseInt(ln);
try {
IdCount[] top = companion.getTop(vertexId, 10);
System.out.println("Result:");
for(IdCount ic : top) {
System.out.println(ic.id + ": " + ic.count);
}
} catch (Exception err) {
err.printStackTrace();
}
}
cmd.close();
} |
2c08b620-87df-472d-94ac-e467f5ca87da | 0 | public String getType() {
return type;
} |
1ce5e1d0-8a5c-4962-a6fb-6d4c55b55dfc | 6 | private static <T> void handleWindows(final String framesetid, final Class<? extends Component> clz, Component comp) {
if (comp instanceof Window) {
TitleIconImage title = clz.getAnnotation(TitleIconImage.class);
if (title != null) {
setWindowTitle(comp, title);
setIconImage(comp, title);
}
boolean addWindowCloseListener=true;
if(comp instanceof JFrame){
if(((JFrame)comp).getDefaultCloseOperation()==JFrame.DO_NOTHING_ON_CLOSE){
addWindowCloseListener=false;
}
}
if(addWindowCloseListener){
((Window) comp).addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
FrameFactory.dispose(framesetid, clz);
super.windowClosing(e);
}
});
}
}
} |
b9cb3601-5852-4a38-973f-077e594b4b44 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RepeatNode other = (RepeatNode) obj;
if (exp1 == null) {
if (other.exp1 != null)
return false;
} else if (!exp1.equals(other.exp1))
return false;
if (stateSeq1 == null) {
if (other.stateSeq1 != null)
return false;
} else if (!stateSeq1.equals(other.stateSeq1))
return false;
return true;
} |
4f3c63c1-d8e9-4481-9852-5c7a0d18e322 | 9 | static void draw_priority_sprites(osd_bitmap bitmap, int prioritylayer)
{
int offs;
/* sprites must be drawn in this order to get correct priority */
for (offs = 0;offs < spriteram_size[0];offs += 8)
{
int i,incr,code,col,flipx,flipy,sx,sy;
if (prioritylayer==0 || (prioritylayer!=0 && (spriteram.read(offs) & 0x10)!=0))
{
code = spriteram.read(offs+4) + ((spriteram.read(offs+5) & 0x07) << 8);
col = spriteram.read(offs+0) & 0x0f;
sx = 256 * (spriteram.read(offs+7) & 1) + spriteram.read(offs+6);
sy = 256+128-15 - (256 * (spriteram.read(offs+3) & 1) + spriteram.read(offs+2));
flipx = spriteram.read(offs+5) & 0x40;
flipy = spriteram.read(offs+5) & 0x80;
i = sprite_height_prom.read((code >> 5) & 0x1f);
if (i == 1) /* double height */
{
code &= ~1;
sy -= 16;
}
else if (i == 2) /* quadruple height */
{
i = 3;
code &= ~3;
sy -= 3*16;
}
if (flipscreen != 0)
{
sx = 496 - sx;
sy = 242 - i*16 - sy; /* sprites are slightly misplaced by the hardware */
flipx = NOT(flipx);
flipy = NOT(flipy);
}
if (flipy != 0)
{
incr = -1;
code += i;
}
else incr = 1;
do
{
drawgfx(bitmap,Machine.gfx[1],
code + i * incr,col,
flipx,flipy,
sx,sy + 16 * i,
Machine.drv.visible_area,TRANSPARENCY_PEN,0);
i--;
} while (i >= 0);
}
}
} |
9e57d3e8-4300-437c-80d8-2e74ce8d3f47 | 1 | public void stop()
{
synchronized (routes)
{
for (Route route : routes)
{
route.stop();
}
}
} |
6166d44e-2e38-474c-82ab-88e170e5d983 | 7 | private void applyTransform(BufferedImage sourceImage, BufferedImage destinationImage, PerspectiveTransform transform) {
for(int x = 0; x < destinationImage.getWidth(); x++) {
for(int y = 0; y < destinationImage.getHeight(); y++) {
try {
final Point2D sourcePoint = new Point2D.Double(x, y);
final Point2D destPoint = new Point2D.Double();
transform.inverseTransform(sourcePoint, destPoint);
int destPointX = (int)destPoint.getX();
int destPointY = (int)destPoint.getY();
if (destPointX < 0 ||
destPointY < 0 ||
destPointX >= sourceImage.getWidth() ||
destPointY >= sourceImage.getHeight()) {
continue;
}
final int color = sourceImage.getRGB(destPointX, destPointY);
destinationImage.setRGB((int)sourcePoint.getX(), (int)sourcePoint.getY(), color);
} catch (Exception e) {
throw new RuntimeException("Error transforming image!", e);
}
}
}
} |
d20c34fa-7aa7-424f-a62f-3e1a6446fb36 | 7 | @Override
public void onNIOEvent(SelectionKey key)
{
if( key.isWritable() )
{
boolean removeEvent = false;
ChannelEvent event = writeQueue.peek();
try
{
if( removeEvent = (event != null && handleOutgoingEvent(event)) )
event.getFuture().onSuccess();
}
catch(Exception e)
{
removeEvent = true;
if( event != null )
event.getFuture().onException(e);
}
if( removeEvent )
{
writeQueue.remove();
if( writeQueue.isEmpty() )
dispatcher.setInterestOps(this, dispatcher.getInterestOps(this)
^ SelectionKey.OP_WRITE);
}
}
} |
036f4d4a-e330-4929-831e-a991df93253a | 6 | public static void enqueueEvent( String method, Object target, Object... parameters )
{
Event event = new Event(); // create the event
try
{
// determine the classes of our parameters
Class< ? >[] paramClasses = new Class< ? >[ parameters.length ];
for ( int i = 0; i < paramClasses.length; i++ )
{
paramClasses[ i ] = parameters[ i ].getClass();
}
if ( target instanceof Class )
{
// if the method is a static method, use the class object to get the method
event.action = ( ( Class< ? > ) target ).getMethod( method, paramClasses );
}
else
{
// otherwise, use the target's class to get the method
event.action = target.getClass().getMethod( method, paramClasses );
}
}
catch ( NoSuchMethodException | SecurityException e )
{
Lumberjack.throwable( "Scheduler", e );
}
event.target = target; // set the event's target object
event.executionTime = -1; // set the event's executing time (-1 because it has no priority to be executed)
event.parameters = parameters; // set the event's parameters
addEvent( event ); // add the event to the list
} |
a1dbfe6d-d3ae-4d63-8f65-444321727976 | 0 | @Override
@XmlElement(name="nachname")
public String getNachname() {
return this.nachname;
} |
fa0880ac-1346-4c12-a53f-d4f03a97daaf | 2 | private BeerResponseList(Iterable<Beer> beers) {
if (beers != null) {
for (Beer beer : beers) {
this.beers.add(BeerResponse.createBeerResponse(beer));
}
}
} |
eab11bd6-8048-438a-b68b-1ffe6eb89107 | 3 | void createToolBar(final Composite parent) {
final Display display = parent.getDisplay();
toolBar = new ToolBar(parent, SWT.FLAT);
ToolItem back = new ToolItem(toolBar, SWT.PUSH);
back.setText(getResourceString("Back")); //$NON-NLS-1$
back.setImage(loadImage(display, "back.gif")); //$NON-NLS-1$
back.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
int index = tabs_in_order.indexOf(tab) - 1;
if (index < 0)
index = tabs_in_order.size() - 1;
setTab(tabs_in_order.get(index));
}
});
ToolItem next = new ToolItem(toolBar, SWT.PUSH);
next.setText(getResourceString("Next")); //$NON-NLS-1$
next.setImage(loadImage(display, "next.gif")); //$NON-NLS-1$
next.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
int index = (tabs_in_order.indexOf(tab) + 1)%tabs_in_order.size();
setTab(tabs_in_order.get(index));
}
});
ColorMenu colorMenu = new ColorMenu();
// setup items to be contained in the background menu
colorMenu.setColorItems(true);
colorMenu.setPatternItems(checkAdvancedGraphics());
colorMenu.setGradientItems(checkAdvancedGraphics());
// create the background menu
backMenu = colorMenu.createMenu(parent, new ColorListener() {
public void setColor(GraphicsBackground gb) {
background = gb;
backItem.setImage(gb.getThumbNail());
if (canvas != null) canvas.redraw();
}
});
// initialize the background to the first item in the menu
background = (GraphicsBackground)backMenu.getItem(0).getData();
// background tool item
backItem = new ToolItem(toolBar, SWT.PUSH);
backItem.setText(getResourceString("Background")); //$NON-NLS-1$
backItem.setImage(background.getThumbNail());
backItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (event.widget == backItem) {
final ToolItem toolItem = (ToolItem) event.widget;
final ToolBar toolBar = toolItem.getParent();
Rectangle toolItemBounds = toolItem.getBounds();
Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
backMenu.setLocation(point.x, point.y + toolItemBounds.height);
backMenu.setVisible(true);
}
}
});
// double buffer tool item
dbItem = new ToolItem(toolBar, SWT.CHECK);
dbItem.setText(getResourceString("DoubleBuffer")); //$NON-NLS-1$
dbItem.setImage(loadImage(display, "db.gif")); //$NON-NLS-1$
dbItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
setDoubleBuffered(dbItem.getSelection());
}
});
} |
4c5c2542-0a8e-40ed-b112-ca4218ea76ae | 9 | public Wave06(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 65; i++){
if(i < 5){
if(i % 2 == 0)
add(m.buildMob(MobID.RATTATA));
else
add(m.buildMob(MobID.PIDGEY));
}
else if (i >= 5 && i < 45){
if(i % 2 == 0)
add(m.buildMob(MobID.PIDGEY));
else
add(m.buildMob(MobID.SPEAROW));
}
else if(i >= 45 && i < 64){
if(i % 2 == 0)
add(m.buildMob(MobID.MANKEY));
else
add(m.buildMob(MobID.SANDSHREW));
}
else
add(m.buildMob(MobID.JIGGLYPUFF));
}
} |
355b819b-d8f3-4a25-a94f-43ec8426ef7b | 1 | public static void main(final String[] args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
try {
final GUIrscGenerator frame = new GUIrscGenerator();
frame.setVisible(true);
} catch (final Exception e) {
e.printStackTrace();
}
}
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.