method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
3eb178b1-74e3-4731-82e1-601e9b7dc1ba | 5 | public Wizard(String password) throws IOException {
// Netzwerk initialisieren
LOG.debug("initializing ConnectionListener...");
cl = new ConnectionListener(Settings.getPortNumber(), password, packetqueue);
LOG.debug("initializing done");
// Warten auf Start Kommando. bis dahin Beitritt zum Spiel möglich.
LOG.debug("entering pre game loop... (lobby)");
while (inLobby) {
packetqueue.waitForPacket();
IPacket temp = packetqueue.getPacket();
if (!(temp instanceof PToServer)) {
LOG.warn(String.format("Server received packet of a client type: %s", temp.getClass().getSimpleName()));
}
PToServer p = (PToServer) temp;
p.doWork(this);
}
LOG.info("Shutting ConnectionListener down: Future joins not possible!");
cl.interrupt();
// In einer Schleife durch die Paket Schlange gehen.
// Abbruch wenn Spiel zu Ende
LOG.debug("entering game loop...");
while (!table.gameFinished() && inGame) {
packetqueue.waitForPacket();
IPacket temp = packetqueue.getPacket();
LOG.debug("Server received " + temp.getClass().getSimpleName());
if (!(temp instanceof PToServer)) {
LOG.fatal(String.format("Server received packet of a client type: %s", temp.getClass().getSimpleName()));
}
PToServer p = (PToServer) temp;
p.doWork(this);
}
LOG.debug("finished game loop.");
// Zusammenfassung vom Spiel ausgeben.
cl.interrupt();
LOG.debug("game done.");
} |
4d9944bd-4e99-4504-acdb-e118ada5b32c | 3 | public static String unobfuscatePasswd(byte[] obfuscated) {
DesCipher des = new DesCipher(obfuscationKey);
des.decrypt(obfuscated, 0, obfuscated, 0);
int len;
for (len = 0; len < 8; len++) {
if (obfuscated[len] == 0) break;
}
char[] plain = new char[len];
for (int i = 0; i < len; i++) {
plain[i] = (char)obfuscated[i];
}
return new String(plain);
} |
965f1e3a-5389-46da-95f7-6eebb2e42e0e | 7 | public void write(int bits, int width) throws IOException {
if (bits == 0 && width == 0) {
return;
}
if (width <= 0 || width > 32) {
throw new IOException("Bad write width.");
}
while (width > 0) {
int actual = width;
if (actual > this.vacant) {
actual = this.vacant;
}
this.unwritten |= ((bits >>> (width - actual)) &
BitInputStream.mask[actual]) << (this.vacant - actual);
width -= actual;
nrBits += actual;
this.vacant -= actual;
if (this.vacant == 0) {
this.out.write(this.unwritten);
this.unwritten = 0;
this.vacant = 8;
}
}
} |
fa3710b7-708f-47a5-aa2f-91181258ba05 | 7 | public static void main(JSONObject data)
{
String pr_string="";
payment = data;
Service.WriteLog(payment.toString());
try {
pr_string = payment.getString("params");
File fXmlFile = new File("/home/terminal/lib/print/print.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
Service.WriteLog("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("field");
DataTable= new String[nList.getLength()];
NameTable= new String[nList.getLength()];
JSONTable= new String[nList.getLength()];
count_field=nList.getLength();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
//Service.WriteLog("Current Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Service.WriteLog("data : " + eElement.getElementsByTagName("data").item(0).getTextContent());
Service.WriteLog("name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
DataTable[temp] = eElement.getElementsByTagName("data").item(0).getTextContent();
NameTable[temp] = eElement.getElementsByTagName("name").item(0).getTextContent();
try
{
JSONObject param = new JSONObject(pr_string);
JSONTable[temp]=param.getString(DataTable[temp]);
}
catch (Exception e)
{
JSONTable[temp]="Ошибка ответа!";
}
try
{
JSONObject param = new JSONObject(pr_string);
term=param.getString("id_terminal");
}
catch (Exception e)
{
term="Ошибка ответа!";
}
}
}
try
{
kol_chek=1;
JSONObject param = new JSONObject(pr_string);
kol_chek = param.getInt("copy_count");
}
catch (Exception e)
{
}
} catch (Exception e) {
e.printStackTrace();
}
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Paper paper = new Paper();
//pj.
paper.setSize(240, 350);
paper.setImageableArea(0,0, 240, 350);
pf.setPaper(paper);
pj.setPrintable(new FilePagePainter("test.doc"), pf);
try{
pj.print();
}
catch(PrinterException e)
{
}
// System.exit(0);
cashe_machine.send_json_cashe_answ = "{\"command\":\"print\",\"error\":\"0\"}";
} |
20f4e1b6-6139-4a99-8d9a-2c174fb2bcde | 5 | public String encode(String plain)
{
int[] key_num=Cadenus.generate_order(key);
// int last_digit=key_num[key_num.length-1];
char[][] trans_block=Gromark.build_trans_block(key_num,key);
char[] keyed_alphabet=build_keyed_alphabet(trans_block,key_num);
//int primer=get_num(key_num);
//int[] num_k=generate_num_k(plain,primer);
String plain_u=plain.toUpperCase();
StringBuilder sb=new StringBuilder();
for(int i=0;i<key_num.length;i++)
{
sb.append(key_num[i]);
}
int key_len=key.length();
int key_index=0;
//int last=0;
for(int i=0;i<plain.length();i+=key_len)
{
int end=i+key.length()>plain.length()?plain.length():i+key_len;
//last=end-i;
//String sub_str=plain.substring(i,end);
int alphabet_index=Generic_Func.find_char(keyed_alphabet, key.charAt(key_index));
sb.append(get_ct(plain_u,key_num,i,end,keyed_alphabet,alphabet_index));
if(key_index==key.length()-1)
{
key_index=0;
}
else
{
key_index++;
}
if(end==plain.length())
{
sb.append(key_num[end-i-1]);
}
else
{
update_num_k(key_num);
}
}
//sb.append(key_num[last]);
//Random r=new Random();
//int key_len=1+r.nextInt(7);
//sb.append(last_digit);
return sb.toString();
} |
b1108b5f-fa8b-4dcf-8111-e5de5edbba02 | 0 | public void unloadDimension(){
current.removeFromParent();
current = null;
} |
ed775268-8bd3-4ca4-8a4d-b2debbc81fe1 | 8 | private void string(String value) throws IOException {
String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
out.write("\"");
int last = 0;
int length = value.length();
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
String replacement;
if (c < 128) {
replacement = replacements[c];
if (replacement == null) {
continue;
}
} else if (c == '\u2028') {
replacement = "\\u2028";
} else if (c == '\u2029') {
replacement = "\\u2029";
} else {
continue;
}
if (last < i) {
out.write(value, last, i - last);
}
out.write(replacement);
last = i + 1;
}
if (last < length) {
out.write(value, last, length - last);
}
out.write("\"");
} |
f8b372d9-ef13-49ed-973e-db21769ba6ea | 4 | public void makeMuscles() {
Mass one;
Mass two;
double restLength;
double constant;
double amplitude;
NodeList nodes = myDoc.getElementsByTagName(MUSC);
for (int i = 0; i < nodes.getLength(); i++) {
restLength = -1;
constant = 1;
Node springItem = nodes.item(i);
NamedNodeMap nodeMap = springItem.getAttributes();
one = myMassMap.get(nodeMap.getNamedItem(A).getNodeValue());
two = myMassMap.get(nodeMap.getNamedItem(B).getNodeValue());
amplitude = Double.parseDouble(nodeMap.getNamedItem(AMP)
.getNodeValue());
try {
restLength = Double.parseDouble(nodeMap.getNamedItem(REST)
.getNodeValue());
} catch (Exception e) {
}
try {
constant = Double.parseDouble(nodeMap.getNamedItem(CONST)
.getNodeValue());
} catch (Exception e) {
}
if (restLength == -1) {
new Muscle(one, two, amplitude);
} else {
new Muscle(one, two, restLength, constant, amplitude);
}
}
} |
e032fe59-b148-4be7-8a00-544ee7e08fd2 | 9 | public void load(String fileLoc)
{
Scanner sc = null;
try
{
File file = new File("src/res/maps/" + fileLoc);
if (!file.exists())
{
System.out.println("No File! " + fileLoc);
return;
}
sc = new Scanner(file);
{
tileWidth = sc.nextInt();
tileHeight = sc.nextInt();
mapWidth = tileWidth * Tile.size;
mapHeight = tileHeight * Tile.size;
spawnX = sc.nextInt();
spawnY = sc.nextInt();
// System.out.println(tileWidth + " " + tileHeight);
int numEntities = sc.nextInt();
int numDecorations = sc.nextInt();
tileGrid = new Tile[tileHeight][tileWidth];
for(int j = 0; j < tileHeight; j++)
{
for(int i = 0; i < tileWidth; i++)
{
int id = sc.nextInt();
Tile t = TileGenerator.genTile(this, id, new Vector2f(i, j));
tileGrid[j][i] = t;
if(t == null)
{
System.out.println(i + " " + j + " Nope");
}
else if (t instanceof InteractiveTile)
interactionList.add((InteractiveTile) t);
}
}
for(int n = 0; n < numEntities; n++)
{
int id = sc.nextInt();
float x = sc.nextFloat();
float y = sc.nextFloat();
entityList.add(EntityGenerator.genEntity(GameState.world, id, new Vector2f(x, y)));
}
for(int n = 0; n < numDecorations; n++)
{
int id = sc.nextInt();
float x = sc.nextFloat();
float y = sc.nextFloat();
Decoration d = DecorationGenerator.genDecoration(GameState.world, id, new Vector2f(x, y));
decorations.add(d);
lightSources.add(d.light);
}
}
sc.close();
}
catch (IOException eio)
{
eio.printStackTrace();
}
catch (SlickException e)
{
e.printStackTrace();
}
} |
f02dc986-7e60-45c2-ad9a-736248a280b4 | 4 | public void movie(int level,int x,int y,int w,int h,char[][] board){
if(x-1>0){//can left
// board[x-1][y];
movie(level+1,x-1,y,w,h,board);
}
if(x+1<w){//can right
}
if(y-1>0){//can up
}
if(y+1<h){//can down
}
} |
6d4a0706-c56a-4acb-b4ab-b881f6517241 | 6 | public void startSimStepMode() {
if (turn < 73000 && endSim == false) {
year = turn / 3650;
day = turn / 10;
turnByDay = turn % 10;
// Updates the time on the GUI
time = "Turn: " + turnByDay + " Day: " + day + " Year: " + year;
simGUI.setTime(time);
// Colony ants take their turn first
antTurn();
// Bala ants take their turn second
balaTurn();
// Decreases pheromone by half in each node every new day
if (turnByDay == 0) {
for (int x = 0; x < 27; x++) {
for (int y = 0; y < 27; y++) {
node[x][y].setPheromoneLevel(node[x][y].amtPheromone / 2);
}
}
}
if (endSim == true)
endSimulation();
turn++;
}
} |
be52d3c0-ef3f-49b0-8bc8-9ebde3ba039d | 9 | protected List<String> getHeaderBodyText(String type, List<String> text)
{
List<String> resultTextList = new ArrayList<String>();
boolean foundNonHeaderLine = false;
int currentIndex = 0;
String currentLine;
while (currentIndex < text.size()
&& ((type.equals(GET_HEADERS) && !foundNonHeaderLine) || type.equals(GET_BODY)))
{
currentLine = text.get(currentIndex);
currentIndex++;
// once we start the body part of the text everything else is considered part of the body
if (!foundNonHeaderLine) {
foundNonHeaderLine = containsNonHeaderText(currentLine);
}
if (type.equals(GET_HEADERS) && !foundNonHeaderLine)
{
resultTextList.add(currentLine);
} else if (type.equals(GET_BODY) && foundNonHeaderLine)
{
resultTextList.add(currentLine);
}
}
return resultTextList;
} |
c0cbf890-f64b-438d-b31c-4c86852927dc | 2 | public static double chiSquareMode(int nu) {
if (nu <= 0) throw new IllegalArgumentException("The degrees of freedom [nu], " + nu + ", must be greater than zero");
double mode = 0.0D;
if (nu >= 2) mode = nu - 2.0D;
return mode;
} |
3bfe2f2b-60ce-454b-8d44-87e4420e1abb | 5 | private static void add_Iron_Dome(War war) {
IronDome dome;
Queue<IronDome> IronDomes = war.getIronDomes();
while (true) {
dome = null;
System.out.println("Enter Iron Dome ID: ");
String id = scanner.next();
for (IronDome idome : IronDomes) {
if (idome.getDomeId().equalsIgnoreCase(id)) {
dome = idome;
break;
}
}
if (dome == null) {
try {
war.Create_Iron_Dome(id);
} catch (Exception e) {
e.printStackTrace();
}
break;
} else {
System.out.println("This ID already exists! ");
}
}
} |
3282e561-b7a2-450a-878e-a2f976083e3f | 7 | public static List<Integer> MergeTwoSortedLists(List<Integer> one, List<Integer> two) {
List<Integer> mergedList = new ArrayList<Integer>();
int i1 = 0, i2 = 0, s1 = one.size(), s2 = two.size();
while (i1 < s1 || i2 < s2) {
if (i1 < s1 && i2 < s2) {
if (one.get(i1) < two.get(i2)) {
mergedList.add(one.get(i1++));
}
else {
mergedList.add(two.get(i2++));
}
}
else if (i1 < s1) {
mergedList.add(one.get(i1++));
}
else if (i2 < s2) {
mergedList.add(two.get(i2++));
}
}
return mergedList;
} |
ac5b3375-7866-4ea1-8967-7b878d69f28b | 8 | private String formatTime(long millis){
String formattedTime;
String hourFormat = "";
int hours = (int)(millis / 3600000);
if(hours >= 1){
millis -= hours * 3600000;
if(hours < 10){
hourFormat = "0" + hours;
}
else{
hourFormat = "" + hours;
}
hourFormat += ":";
}
String minuteFormat;
int minutes = (int)(millis / 60000);
if(minutes >= 1){
millis -= minutes * 60000;
if(minutes < 10){
minuteFormat = "0" + minutes;
}
else{
minuteFormat = "" + minutes;
}
}
else{
minuteFormat = "00";
}
String secondFormat;
int seconds = (int)(millis / 1000);
if(seconds >= 1){
millis -= seconds * 1000;
if(seconds < 10){
secondFormat = "0" + seconds;
}
else{
secondFormat = "" + seconds;
}
}
else{
secondFormat = "00";
}
String milliFormat;
if(millis > 99){
milliFormat = "" + millis;
}
else if(millis > 9){
milliFormat = "0" + millis;
}
else{
milliFormat = "00" + millis;
}
formattedTime = hourFormat + minuteFormat + ":" + secondFormat + ":" + milliFormat;
return formattedTime;
} |
58fe5a56-8eaf-48e4-8281-5f9f0da066d5 | 0 | public String toString(String input) {
return name + calc(input);
} |
ccc28c76-399b-434a-a42d-9be2f0b35bd4 | 5 | public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> rst = new ArrayList<String>();
Map<String, List<String>> classSet = new HashMap<String, List<String>>();
for (int i = 0; i < strs.length; i++) {
String standard = getStandard(strs[i]);
List<String> ele = classSet.get(standard);
if (ele == null){
ele = new LinkedList<String>();
ele.add(strs[i]);
classSet.put(standard, ele);
}else ele.add(strs[i]);
}
for (List<String> list : classSet.values()) {
if (list.size() > 1) {
for (String str : list)
rst.add(str);
}
}
return rst;
} |
1b7dee65-06b3-46cf-a580-11d3db87ba1d | 8 | public void addToManager(int workerId, int managerId) {
boolean workerExists = false;
boolean managerExists = false;
Employee manager = null;
for (Employee employee : staff) {
if (employee.getId() == workerId) {
workerExists = true;
}
if (employee.getId() == managerId && employee.getPost() instanceof Manager) {
managerExists = true;
manager = employee;
}
}
if (workerExists && managerExists) {
((Manager)manager.getPost()).addWorker(workerId);
logger.info("Employee id: " + workerId + " was added to manager id: " + managerId);
prepareToWrite();
} else {
if (!workerExists) {
logger.error("Worker with id: " + workerId + "not found");
}
if (!managerExists) {
logger.error("Manager with id: " + managerId + "not found");
}
return;
}
} |
067ccae8-f7a3-48a8-8f82-d797050d9199 | 7 | public VolumeID setDriveType(int n) throws ShellLinkException {
if (n == DRIVE_UNKNOWN || n == DRIVE_NO_ROOT_DIR || n == DRIVE_REMOVABLE || n == DRIVE_FIXED
|| n == DRIVE_REMOTE || n == DRIVE_CDROM || n == DRIVE_RAMDISK) {
dt = n;
return this;
} else
throw new ShellLinkException("incorrect drive type");
} |
083ee688-4ba7-4469-9eca-c84fcc547709 | 2 | @RequestMapping(value = {"/CuentaBancaria/id/{idCuentaBancaria}"}, method = RequestMethod.GET)
public void read(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idCuentaBancaria") int idCuentaBancaria) {
try {
ObjectMapper jackson = new ObjectMapper();
String json = jackson.writeValueAsString(cuentaBancariaDAO.read(idCuentaBancaria));
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType("application/json; charset=UTF-8");
noCache(httpServletResponse);
httpServletResponse.getWriter().println(json);
} catch (Exception ex) {
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("text/plain; charset=UTF-8");
try {
noCache(httpServletResponse);
ex.printStackTrace(httpServletResponse.getWriter());
} catch (Exception ex1) {
noCache(httpServletResponse);
}
}
} |
87478750-f38d-40a9-ba8c-9c2a6db1accf | 5 | @Override
public void add(T element) { // sorted insert
LLNode<T> newNode = new LLNode<T>(element);
current = head;
while (current!=null){
if (current.compareTo(newNode)>0){
if (current==head){ //add to front
newNode.setLink(head);
head=newNode;
break;
} else { //add in middle
previous.setLink(newNode);
newNode.setLink(current);
break;
}
} else if (current.getLink()==null) { //add to end
current.setLink(newNode);
current=current.getLink();
}
previous=current;
current=current.getLink();
}
if (head==null){ //list is empty
head = newNode;
}
length+=1;
} |
b055ac12-19a1-4332-8091-0cfe3e12dcbc | 7 | public double getCurrentActivityFracComplete() {
switch (this.currentStatus) {
case NOT_STARTED:
return 0.0;
case RUNNING:
case PAUSED:
case CANCELLING:
return this.taskMonitor.getCurrentActivityFractionComplete();
case CANCELLED:
case COMPLETED:
case FAILED:
return 1.0;
}
return 0.0;
} |
58da038d-cc5b-41c3-9ad2-8af2653a8e31 | 9 | public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Aplicacao aplicacao;
try {
aplicacao = em.getReference(Aplicacao.class, id);
aplicacao.getCodigoAplicacao();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The aplicacao with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
Collection<QualificadorAplicacao> qualificadorAplicacaoCollectionOrphanCheck = aplicacao.getQualificadorAplicacaoCollection();
for (QualificadorAplicacao qualificadorAplicacaoCollectionOrphanCheckQualificadorAplicacao : qualificadorAplicacaoCollectionOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Aplicacao (" + aplicacao + ") cannot be destroyed since the QualificadorAplicacao " + qualificadorAplicacaoCollectionOrphanCheckQualificadorAplicacao + " in its qualificadorAplicacaoCollection field has a non-nullable codigoAplicacao field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
Veiculo codigoVeiculo = aplicacao.getCodigoVeiculo();
if (codigoVeiculo != null) {
codigoVeiculo.getAplicacaoCollection().remove(aplicacao);
codigoVeiculo = em.merge(codigoVeiculo);
}
Produto codigoProduto = aplicacao.getCodigoProduto();
if (codigoProduto != null) {
codigoProduto.getAplicacaoCollection().remove(aplicacao);
codigoProduto = em.merge(codigoProduto);
}
Posicao codigoPosicao = aplicacao.getCodigoPosicao();
if (codigoPosicao != null) {
codigoPosicao.getAplicacaoCollection().remove(aplicacao);
codigoPosicao = em.merge(codigoPosicao);
}
Pais codigoPais = aplicacao.getCodigoPais();
if (codigoPais != null) {
codigoPais.getAplicacaoCollection().remove(aplicacao);
codigoPais = em.merge(codigoPais);
}
em.remove(aplicacao);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} |
508dd28b-5e27-4c99-990a-b9150f67da9a | 2 | public void countOut() {
if (this.type != NodeType.INPUT) {
double out = 0.0;
for (int i = 0; i < getIncomingLinks().size(); i++) {
out += getIncomingLinks().get(i).getWeight() * getIncomingLinks().get(i).getIn_node().getPotential();
}
double newPower = activationFfermi(out); // activation function
this.setPotential(newPower);
}
} |
bc846031-9f95-4946-8b8a-e8a7542a71a8 | 8 | public void msgChannel (IRCMessage m)
{
// System.out.println("APP: chan");
if (m.getPrefixNick().startsWith("s-")) // server msg
{
int tableID = 0;
String msg = m.params[1];
Scanner s = new Scanner(msg);
if (s.hasNext(tablePattern))
{
tableID = s.nextInt();
if ((tableID < 0) || (tableID >= numberOfTables))
{
Dbg.println(Dbg.DBG1, "invalid table ID " + tableID);
return;
}
}
if (s.hasNext(datePattern))
{
if (acceptPublicUpdates)
{
processUpdate(tableID, s, null, null);
}
else
{
publicUpdates[tableID].putMessage(m);
}
}
else
{
if (msg.startsWith("IRCDDB "))
{
channelTimeout = 0;
}
else if (extApp != null)
{
extApp.msgChannel( m );
}
}
}
} |
e283c931-b837-4f98-b4af-49be8fbaa2b3 | 5 | @Override
public boolean equals(Object o) {
if (!(o instanceof TextureRegion)) return false;
TextureRegion t = (TextureRegion) o;
return file.equals(t.file) && x == t.x && y == t.y && width == t.width && height == t.height;
} |
94f22428-3bbd-4f2b-a75a-da4a5098f54e | 3 | boolean isValid() {
return !(Double.isInfinite(x) || Double.isNaN(x) ||
Double.isInfinite(y) || Double.isNaN(y) );
} |
16888e37-1088-42b3-bb73-4d48b55a97e7 | 1 | public void downdload(String rep, String file){
System.out.println("Downloading file");
try{
ftp.downloadFile(rep, fileRep+file);
System.out.println("File downloaded");
}
catch(Exception e){
e.printStackTrace();
}
} |
5a1a790a-f8d8-43c2-a1ad-7e97733940d6 | 4 | public boolean findAtSW(int piece, int x, int y){
if(x==7 || y==0 || b.get(x+1,y-1)==EMPTY_PIECE) return false;
else if(b.get(x+1,y-1)==piece) return true;
else return findAtSW(piece,x+1,y-1); // there is an opponent
} // end findAtSW |
abe5e32e-0b05-4ba9-bf02-e92792e19a73 | 0 | @Override
public void setAddress(Address address) {
super.setAddress(address);
} |
ba67297a-5bf0-42c3-8153-81ad72da2404 | 8 | private void consolidate() {
// Initialize array by making each entry NIL.
int arraySize = ((int) Math.floor(Math.log(n) * oneOverLogPhi)) + 1;
Entry array[] = new Entry[arraySize];
if (min != null) {
for (Entry w : min.nodelist()) {
// Find two roots x and y in the root list with the same degree,
// where key[x]<=key[y].
Entry x = w;
int d = w.degree;
while (array[d] != null) {
Entry y = array[d];
// Whichever of x and y has he smaller key becomes the parent of
// the other.
if (x.key > y.key) {
Entry tmp = x;
x = y;
y = tmp;
}
// Remove y from the root list, and make y a child of x.
link(y, x);
// Because node y is no longer a root, the pointer to it in the
// array is removed.
array[d] = null;
// Restore the invariant.
d++;
}
array[d] = x;
}
}
// Empty the root list.
min = null;
// Reconstruct the root list from the array.
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
min = concatenateNode(min, array[i]);
if (min == null || array[i].key < min.key) {
min = array[i];
}
}
}
} |
714f491d-1960-47b7-b0ca-6ca0c663c487 | 5 | public MyriadSocketReader(SocketReaderParameters parameters) {
// read input parameters from job config
this.nodePath = parameters.getDGenNodePath().getAbsolutePath();
this.outputBase = parameters.getOutputBase().getAbsolutePath();
this.datasetID = parameters.getDatasetID();
this.stage = parameters.getStage();
this.scalingFactor = parameters.getScalingFactor();
this.nodeCount = parameters.getNodeCount();
this.nodeID = parameters.getNodeID();
// open SocketReader server at input socket number
try {
this.serverSocket = new ServerSocket(0);
this.serverSocketPort = this.serverSocket.getLocalPort();
} catch (IOException e) {
cleanup();
throw new RuntimeException("Could not open reader server socket.");
}
// open heartbeat HTTP server
try {
org.mortbay.log.Log.setLog(null); // disable the jetty log
this.heartBeatServer = new Server(0);
this.heartBeatServer.setHandler(new HeartBeatHandler());
this.heartBeatServer.start();
this.heartBeatServerPort = this.heartBeatServer.getConnectors()[0].getLocalPort();
} catch (Exception e) {
cleanup();
throw new RuntimeException("Could not open heart beat server socket.");
}
// start data generator process
try {
this.dgenProcess = Runtime.getRuntime().exec(getDGenCommand());
} catch (IOException e) {
cleanup();
throw new RuntimeException("Failed to start data generator process.");
}
// create client socket from socket server
try {
this.clientSocket = this.serverSocket.accept();
} catch (IOException e) {
cleanup();
throw new RuntimeException("Failed to open receiver socket.");
}
// create input reader for client socket
try {
this.inputReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()),
MyriadSocketReader.BUFFER_SIZE);
} catch (IOException e) {
cleanup();
throw new RuntimeException("Failed to open input stream.");
}
// create reader thread for the process (ignores the stdout)
this.dgenReaderThread = new Thread(new MyriadDGenRunner());
this.dgenReaderThread.start();
} |
70dd0353-193e-4f16-994a-1bbe15498b4c | 9 | protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (ziel != null && player != null) {
Rectangle zielRec = new Rectangle((int) ziel.getX() - 10,
(int) ziel.getY() + 25, 20, 20);
Rectangle playerRec = new Rectangle(spieler.playerx + 25,
spieler.playery + 100, 25, 20);
g.drawRect(zielRec.x, zielRec.y, zielRec.width, zielRec.height);
g.drawRect(playerRec.x, playerRec.y, playerRec.width,
playerRec.height);
if (collisionList != null) {
for (int i = 0; i < collisionList.size(); i++) {
g.drawRect(collisionList.get(i).x, collisionList.get(i).y,
collisionList.get(i).getSize().width, collisionList
.get(i).getSize().height);
}
}
g.drawLine(zielRec.x, zielRec.y, playerRec.x, playerRec.y);
if (playerRec.intersects(zielRec)) {
run = false;
}
if (run) {
calculate(3);
}
}
if (textureList.size() != 0) {
for (int i = 0; i < textureList.size(); i++) {
g.drawImage(textureList.get(i).getImage(), textureList.get(i)
.getLocation().x, textureList.get(i).getLocation().y,
textureList.get(i).getWidth(), textureList.get(i)
.getHeight(), this);
}
}
if (spieler != null) {
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(spieler.winkel - 90),
spieler.playerx + 40, spieler.playery + 110);
g2d.drawImage(spieler.getImage(), spieler.playerx - 10,
spieler.playery + 60, 100, 100, this);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
} |
ad79ea57-5c3c-4b1e-a2c0-897a2ab85dda | 8 | private void aceptSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptSelectActionPerformed
boolean error = false;
String errorString = "";
Object[] what = new Object[7];
what[0] = conectionBoolean.isSelected();
if (!userSelectData.getText().equalsIgnoreCase(""))
what[1] = userSelectData.getText();
else {
error = true;
errorString += "No user specified.\n";
}
if (!passSelectData.getText().equalsIgnoreCase(""))
what[2] = passSelectData.getText();
else {
error = true;
errorString += "No password specified.\n";
}
what[3] = conectionEnabledSelectData.getText();
ArrayList resultadoSelect = new ArrayList();
ArrayList tablaSelect = new ArrayList();
int filas = tablaSelectResult.getRowCount();
for (int i = 0; i < filas; i++) {
resultadoSelect.add((String)tablaSelectResult.getValueAt(i, 0));
}
if (filas == 0) {
error = true;
errorString += "Result field is missing.\n";
}
what[4] = resultadoSelect;
filas = tablaSelectTable.getRowCount();
for (int i = 0; i < filas; i++) {
tablaSelect.add((String)tablaSelectTable.getValueAt(i, 0));
}
if (filas == 0) {
error = true;
errorString += "Table field is missing.\n";
}
what[5] = tablaSelect;
what[6] = conditionSelectConditionText.getText();
if (conditionSelectConditionText.getText().equalsIgnoreCase("")) {
error = true;
errorString += "Condition field is missing.\n";
}
if (!error) {
Controller.controller(Controller.SELECTBD, what);
this.dispose();
} else {
JOptionPane op = new JOptionPane();
int messagetype = JOptionPane.ERROR_MESSAGE; //JOptionPane.INFORMATION_MESSAGE
op.showMessageDialog(this, errorString, "[ERROR] Some fields are missing", messagetype);
}
}//GEN-LAST:event_aceptSelectActionPerformed |
813416a1-793a-49fe-ad93-3350cf53fda4 | 5 | public void miseAJourEtatsBateaux() {
this.etatBateaux.setVisible(manuel || this._partie.isAutomatique());
this.etatBateaux.removeAll();
this.bateaux.setVisible(manuel || this._partie.isAutomatique());
this.bateaux.removeAll();
Iterator ite = this._partie.getCasesBateaux().keySet().iterator();
while(ite.hasNext()){
Case c = this._partie.getCasesBateaux().get((String)ite.next());
int nbCasesTouche = c.getBateau().getLongueur()-c.getBateau().getNbCasesNonTouchees();
int nbCasesNonTouche = c.getBateau().getNbCasesNonTouchees();
JPanel panelEtat = new JPanel();
panelEtat.setOpaque(false);
panelEtat.setLayout(new BoxLayout(panelEtat, BoxLayout.X_AXIS));
// Ajout des nom des bateaux
JLabel nomBateau = new JLabel(c.getBateau().getNom());
nomBateau.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
nomBateau.setFont(new java.awt.Font("Helvetica Neue", 0, 20));
nomBateau.setForeground(Color.WHITE);
nomBateau.setOpaque(false);
this.bateaux.add(nomBateau);
// Image pour une caseBateau non touchee
for(int i = 0; i < nbCasesNonTouche;i++) {
JLabel nonTouche = new JLabel();
nonTouche.setIcon(new ImageIcon(new ImageIcon(getClass().getResource("/stockage/images/Rond_plein.png")).getImage().getScaledInstance(24, 24, Image.SCALE_DEFAULT)));
panelEtat.add(nonTouche);
}
// Image pour une caseBateau touchee
for(int i = 0; i < nbCasesTouche;i++) {
JLabel touche = new JLabel();
touche.setIcon(new ImageIcon(new ImageIcon(getClass().getResource("/stockage/images/Rond_vide.png")).getImage().getScaledInstance(24, 24, Image.SCALE_DEFAULT)));
panelEtat.add(touche);
}
this.etatBateaux.add(panelEtat);
}
} // miseAJourEtatsBateaux() |
91df9132-c004-4344-9307-f9a7658adec4 | 8 | static String getModifiersText(int modifiers) {
StringBuffer buf = new StringBuffer();
if ((modifiers & InputEvent.SHIFT_DOWN_MASK) != 0) {
buf.append("Shift ");
}
if ((modifiers & InputEvent.CTRL_DOWN_MASK) != 0) {
buf.append("Ctrl ");
}
if ((modifiers & InputEvent.META_DOWN_MASK) != 0) {
buf.append("Meta ");
}
if ((modifiers & InputEvent.ALT_DOWN_MASK) != 0) {
buf.append("Alt ");
}
if ((modifiers & InputEvent.ALT_GRAPH_DOWN_MASK) != 0) {
buf.append("AltGraph ");
}
if ((modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) {
buf.append("Button1 ");
}
if ((modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) {
buf.append("Button2 ");
}
if ((modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) {
buf.append("Button3 ");
}
return buf.toString();
} |
8c2bb55a-5153-4506-9b4d-1e5d1104fbb2 | 7 | static String d(String s, String t) {
int[][] b = new int[s.length()+1][t.length()+1];
for (int i = s.length() - 1; i >= 0; i--) {
for (int j = t.length() - 1; j >= 0; j--) {
if (s.charAt(i) == t.charAt(j)) {
b[i][j] = b[i+1][j+1] + 1;
} else {
b[i][j] = Math.max(b[i+1][j], b[i][j+1]);
}
}
}
int i = 0, j = 0;
StringBuffer u = new StringBuffer();
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) {
u.append(s.charAt(i));
i++;
j++;
} else if (b[i+1][j] >= b[i][j+1]) {
i++;
} else {
j++;
}
}
return u.toString();
} |
145e1425-ebb1-483f-a466-30ef50d1704a | 9 | static private String getTypeFromUnit(String s){
for (int i = 0; i < weightUnits.length; i++) {
if (weightUnits[i].unit.equalsIgnoreCase(s) ||
weightUnits[i].abrv.equalsIgnoreCase(s)) {
return "weight";
}
}
for (int i = 0; i < volUnits.length; i++) {
if (volUnits[i].unit.equalsIgnoreCase(s) ||
volUnits[i].abrv.equalsIgnoreCase(s)) {
return "vol";
}
}
for (int i = 0; i < pressureUnits.length; i++) {
if (pressureUnits[i].unit.equalsIgnoreCase(s) ||
pressureUnits[i].abrv.equalsIgnoreCase(s)) {
return "pressure";
}
}
return "undefined";
} |
ccdaaeb1-4752-4bce-a9bf-3b681b56e84f | 7 | public boolean addUserToTopic(final String topicKey,
final String userKey,
final String userName,
final String channelToken) throws TopicAccessException {
assert topicKey != null && topicKey.trim().length() > 0;
assert userKey != null && userKey.trim().length() > 0;
assert userName != null && userName.trim().length() > 0;
assert channelToken != null && channelToken.trim().length() > 0;
try {
return new TransactionRunner<Boolean>(getDatastore()) {
protected Boolean txnBlock() {
try {
Entity subscriberEntity = datastore.get(subscriberEntityKey(topicKey, userKey));
if ((Boolean)subscriberEntity.getProperty(IS_DELETED_PROP)) {
//if deleted then treat it like it wasn't found in the first place
throw new EntityNotFoundException(subscriberEntity.getKey());
}
return false; //subscriber already existed
} catch (EntityNotFoundException enfe) {
//then need to create subscriber
Entity subscriberEntity = new Entity(SUBSCRIBER_KIND, userKey, topicEntityKey(topicKey));
subscriberEntity.setProperty(IS_DELETED_PROP, false);
subscriberEntity.setProperty(USER_NAME_PROP, userName);
subscriberEntity.setUnindexedProperty(CHANNEL_TOKEN_PROP, channelToken);
subscriberEntity.setUnindexedProperty(MESSAGE_NUM_PROP, 0);
datastore.put(subscriberEntity);
return true;
}
}
}.run();
} catch (Exception e) {
throw new TopicAccessException("Error adding user " + userKey + " to topic " + topicKey, e);
}
} |
c6d26344-8f04-47ee-8b55-86e0f9e05a22 | 2 | public void setOption(String option, Collection values) {
if (option.equals("or")) {
isOr = true;
matchers = (IdentifierMatcher[]) values
.toArray(new IdentifierMatcher[values.size()]);
} else if (option.equals("and")) {
isOr = false;
matchers = (IdentifierMatcher[]) values
.toArray(new IdentifierMatcher[values.size()]);
} else
throw new IllegalArgumentException("Invalid option `" + option
+ "'.");
} |
8064f5ee-29a6-42ac-9de3-4059b68a301b | 1 | public FileConfiguration get() {
if (config == null) {
reload();
}
return config;
} |
b0c86940-7a31-4e73-b55e-44ef7ef09e1a | 7 | public int read(int width) throws IOException {
if (width == 0) {
return 0;
}
if (width < 0 || width > 32) {
throw new IOException("Bad read width.");
}
int result = 0;
while (width > 0) {
if (this.available == 0) {
this.unread = this.in.read();
if (this.unread < 0) {
throw new IOException("Attempt to read past end.");
}
this.available = 8;
}
int take = width;
if (take > this.available) {
take = this.available;
}
result |= ((this.unread >>> (this.available - take)) & mask[take])
<< (width - take);
this.nrBits += take;
this.available -= take;
width -= take;
}
return result;
} |
5b321e38-77cf-41c5-a3b2-e1384cbfb28a | 8 | public RemoteServer(final int port) {
// check annotated functions
LOG.info("Loading declared functions...");
Set<Method> methods = Classes.listAllAnnotatedMethods(Server.class, Function.class);
methods.addAll(Classes.listAnnotatedMethods(getClass(), Function.class)); //add this one so that it is available outside this project
for (Method m : methods) {
if (Modifier.isStatic(m.getModifiers())){
FUNCTIONS.add(m);
for (Class<?> parameterType : m.getParameterTypes()) {
if (parameterType.isPrimitive()) {
LOG.warning(String.format("%s has a primitive parameter type, whilst not a problem, the client may autobox that parameter into the wrong non-primitive class and therefor trying to call a method with the wrong signature.", m));
}
}
} else {
LOG.warning(String.format("Not adding method [%s]. Currently we only support static methods.", m));
}
}
LOG.info(String.format("Found the following defined functions (class annotated with '@Server', static method annotated with '@Function'): %s%n", FUNCTIONS));
// open server socket
new Thread(new Runnable() {
public void run() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
throw new RuntimeException(e);
}
while (!Thread.currentThread().isInterrupted()) {
try {
Socket socket = serverSocket.accept();
submit(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
LOG.info(String.format("started server on port: %s", port));
} |
09a54038-3b14-485c-931d-97731649edf2 | 3 | @Override
public boolean onKeyUp(int key) {
Iterator<IGameScreen> it = screens.iterator();
while(it.hasNext()) {
IGameScreen screen = it.next();
if(screen.onKeyUp(key)) {
return true;
}
}
if(camera.onKeyUp(key)) {
return true;
}
Application.get().getEventManager().queueEvent(new KeyUpEvent(key));
return false;
} |
a9ac4087-5e07-4283-b4ff-15569915c11c | 2 | public List<Message> DisplayAllMessagesSent (String S){
List<Message> listemsg = new ArrayList<>();
String requete = "select * from message where Sender ='"+S+"'";
try {
Statement statement = MyConnection.getInstance()
.createStatement();
ResultSet resultat = statement.executeQuery(requete);
while(resultat.next()){
Message msg =new Message();
msg.setId_message(resultat.getInt(1));
msg.setFrom(resultat.getString(2));
msg.setTo(resultat.getString(3));
msg.setObject(resultat.getString(4));
msg.setContent(resultat.getString(5));
msg.setRead(resultat.getBoolean(6));
listemsg.add(msg);
}
return listemsg;
} catch (SQLException ex) {
//Logger.getLogger(PersonneDao.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("erreur lors du chargement des depots "+ex.getMessage());
return null;
}
} |
1b5e2618-7b77-4574-9c48-cf57ddd94349 | 9 | public static void startShell() {
Listener listen = new Listener();
System.out.print(" >>");
Scanner in = new Scanner(System.in);
String line = null;
String response = null;
Client client = null;
while ((line = in.nextLine()).length() > 0) {
try{
client = null; // for garbage collection if previous have been
// allocated
if ("quit".equalsIgnoreCase(line)) {
break;
}
String[] params = line.split(" ");
if (INFO.equalsIgnoreCase(line)) {
response = info();
} else if (line.startsWith(SENDTO)) {
response = sendTo(params);
} else if (line.startsWith(SEND)) {
response = send(params);
} else if (line.startsWith(CONNECT)) {
response = connect(params);
} else if (line.startsWith(DISCONNECT)) {
response = disconnect(params);
} else if (SHOW.equalsIgnoreCase(line)) {
response = show();
} else {
response = listen.doWork(line);
}
System.out.println("" + response);
// take in next input
System.out.print(" >>");
in = new Scanner(System.in);
}catch(Exception ex){
System.out.println("Some Exception!!");
}
}
System.exit(1);
} |
9b1ab2ac-c23d-49b4-9f8d-d1afbbf55dc7 | 3 | private boolean isDrawed(List<Point> points, Point p) {
for (Point point : points) {
if (p.x == point.x && p.y == point.y) {
return true;
}
}
return false;
} |
a98a6a15-b4a4-4b2f-909f-4f9bff8aaff7 | 1 | public final void setStoreNo(String storeNo) {
if(storeNo.length() != 5){
throw new IllegalArgumentException();
}
this.storeNo = storeNo;
} |
e08befc8-32ad-4787-97d2-ae22798a9565 | 1 | @Override
public void testStarted(Description description) {
resetCurrentFailure();
final Xpp3Dom testCase = new Xpp3Dom("testcase");
setCurrentTestCase(testCase);
testCase.addChild(createTester(testerName));
testCase.addChild(createTimeStamp(new Date()));
// This is the only place where we access results, so we should be fine to just synchronize here.
synchronized (results) {
results.addChild(testCase);
}
final TestLinkId<?> id = TestLinkId.fromDescription(description);
testCase.setAttribute(id.getType(), String.valueOf(id.getId()));
} |
e669e179-777d-41b8-8e06-212608f78d03 | 3 | private void loadBackups() {
new Thread() {
@Override
public void run() {
DefaultListModel model = new DefaultListModel();
File backupDir = new File(System.getProperty("user.home") + "/.androidtoolkit/backups");
if (debug)
logger.log(Level.DEBUG, "Loading backups from: " + backupDir.getAbsolutePath() + " for device: " + device.toString());
if (!backupDir.exists()) {
backupDir.mkdirs();
interrupt();
}
// List backups
for (File f : backupDir.listFiles(new ABFilter())) {
model.addElement(f.getName());
}
jList1.setModel(model);
interrupt();
}
}.start();
} |
128d3403-f0fe-4c26-ac15-8f44b51f97b0 | 0 | public void setShopUrl(String shopUrl) {
this.shopUrl = shopUrl;
} |
cd3f0f87-b323-4bee-ae8a-6e03ce39cb42 | 7 | public static boolean createSocket(String host, int port) {
// Open socket on given host and port number
try {
clientSocket = new Socket(host, port);
input = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
//System.err.println("Don't know about host " + host);
return false;
} catch (IOException e) {
//System.err.println("Couldn't get I/O for the connection to the host "
// + host);
return false;
}
// Create PlayerClient thread to read from Server
if (clientSocket != null && os != null && is != null) {
try {
new Thread(new PlayerClient()).start();
while (!closed) {
os.println(input.readLine().trim());
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
return false;
}
return true;
}
return true;
} |
675da0d7-4ebf-4f7b-a462-4d6dc362dc34 | 7 | protected void cellsResized(Object[] cells)
{
if (cells != null)
{
mxIGraphModel model = this.getGraph().getModel();
model.beginUpdate();
try
{
// Finds the top-level swimlanes and adds offsets
for (int i = 0; i < cells.length; i++)
{
if (!this.isSwimlaneIgnored(cells[i]))
{
mxGeometry geo = model.getGeometry(cells[i]);
if (geo != null)
{
mxRectangle size = new mxRectangle(0, 0, geo.getWidth(), geo.getHeight());
Object top = cells[i];
Object current = top;
while (current != null)
{
top = current;
current = model.getParent(current);
mxRectangle tmp = (graph.isSwimlane(current)) ?
graph.getStartSize(current) :
new mxRectangle();
size.setWidth(size.getWidth() + tmp.getWidth());
size.setHeight(size.getHeight() + tmp.getHeight());
}
boolean parentHorizontal = (current != null) ? isCellHorizontal(current) : horizontal;
resizeSwimlane(top, size.getWidth(), size.getHeight(), parentHorizontal);
}
}
}
}
finally
{
model.endUpdate();
}
}
} |
c42ea165-489f-43c1-b4d8-9a35893ffb64 | 4 | @Test
public void removeTest() {
final int n = 1_000;
Array<Integer> seq = emptyArray();
for(int k = 0; k < n; k++) {
assertEquals(k, seq.size());
for(int i = 0; i < k; i++) {
final Array<Integer> seq2 = seq.remove(i);
assertEquals(k - 1, seq2.size());
final Iterator<Integer> iter = seq2.iterator();
for(int j = 0; j < k - 1; j++) {
assertTrue(iter.hasNext());
assertEquals(j < i ? j : j + 1, iter.next().intValue());
}
assertFalse(iter.hasNext());
}
seq = seq.snoc(k);
}
} |
27747178-2373-44fd-b5fe-fe05b341cffa | 4 | boolean isTaskStillValid(Task t)
{
if (t.px < px || t.px >= px + sx)
return false;
if (t.pz < pz || t.pz >= pz + sz)
return false;
return getChunk(t.px, t.pz) == beingPaintedChunk;
} |
8814ae4d-38a1-4e3f-9af2-e81d25c7f800 | 9 | private static void printBinaryFeature(Tagger tagger, HarvardInquirer harvardInquirer, String s) {
List<TaggedToken> tagged = tagger.tokenizeAndTag(s);
boolean containsHostileWord = false;
boolean containsNegativeWord = false;
boolean containsFailWord = false;
// System.out.println(s);
for (TaggedToken taggedToken : tagged) {
for (Map<String, String> entry : harvardInquirer.getEntriesForWord(taggedToken.token.toLowerCase())) {
// System.out.println(taggedToken.token + " " + taggedToken.tag + " " + entry);
if (hasTag(taggedToken.tag, entry)) {
// http://www.wjh.harvard.edu/~inquirer/homecat.htm
if (entry.containsKey("Hostile")) containsHostileWord = true;
if (entry.containsKey("Negativ")) containsNegativeWord = true;
if (entry.containsKey("Fail")) containsFailWord = true;
}
}
}
// System.out.println(containsHostileWord + " " + containsNegativeWord + " " + containsFailWord);
if(containsFailWord || containsHostileWord || containsNegativeWord) {
System.out.println(s);
}
} |
2fad7594-9a3b-4a5f-be8e-b190602ec53d | 2 | public Timestamp getOrdertimeByOrdernumber(Statement statement,String ordernumber)//根据订单号获取预定进入时间
{
Timestamp result = null;
sql = "select ordertime from ParkRelation where ordernumber = '" + ordernumber +"'";
try
{
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
result = rs.getTimestamp("ordertime");
}
}
catch (SQLException e)
{
System.out.println("Error! (from src/Fetch/ParkRelation.getOrdertimeByOrdernumber())");
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} |
08c74ade-2ab0-419e-afd6-99cfcbb23746 | 7 | public static boolean isContinuous(List<Location> l){
List<Location> copy = new ArrayList<Location>(l);
sortLocation(copy);
int dir = getDirection(copy);
if(dir == INVALID_DIR)
return false;
Location prevLoc = null;
for(int i=0;i<copy.size();i++){
Location curr = copy.get(i);
if(prevLoc!=null){
if(dir == HORIZONTAL && ((curr.getX()-prevLoc.getX()) != 1) ){
return false;
}
else if(dir == VERTICAL && ((curr.getY() - prevLoc.getY())!=1)){
return false;
}
}
prevLoc = curr;
}
return true;
} |
2b9ac58c-de85-411d-a5c6-7e2210f36e5a | 0 | @Column(name = "CUE_NATURALEZA")
@Id
public String getCueNaturaleza() {
return cueNaturaleza;
} |
9ac9838c-3f3c-49ee-aae4-5c6e11e95981 | 8 | public static boolean isScramble(String s1, String s2) {
//if exactly the same
if (s1 == s2) {return true;}
int size = s1.length();
int value1 = 0;
int value2 = 0;
//compare if s1 and s2 contains the same chars
for (int i = 0; i < size; i++) {
value1 += (s1.charAt(i)) - 'a';
value2 += (s1.charAt(i) - 'a');
}
if (value1 != value2) {
return false;
}
//check scrambles
/*
* s1[0,i], s2[0,i]; s1[i, size], s2[i, size]
s1[0,i], s2[size-i, size]; s1[i, size], s2[0, size-i]
*/
for (int i = 1; i < size; i++) {
if (isScramble(s1.substring(0, i), s2.substring(0, i)) &&
isScramble(s1.substring(i, size), s2.substring(i, size))) {
return true;
}
//here
if (isScramble(s1.substring(0, i), s2.substring(size - i, size)) &&
isScramble(s1.substring(i, size), s2.substring(0, size - i))) {
return true;
}
}
return false;
} |
e648da30-00a6-4fb9-8815-bb7abe550171 | 0 | public void add(String name, String ip, int port) {
System.out.println(name + ":" + ip + ":" + port);
ClientInfo a = new ClientInfo(name, ip, port);
client_list.add(a);
} |
146b47d4-3040-43a3-8541-f7bf6aaff834 | 0 | @Override
public Message toMessage(Session session) throws JMSException {
Message message = session.createMessage();
setMessageProperties(message);
message.setJMSType(TYPE);
return message;
} |
4d0d0b60-1f04-4b58-92d7-d7bafa01e88e | 7 | private Set<Trace> getTracesFromNode(ProcessNode node, int steps) {
Set<Trace> traces = new HashSet<Trace>();
if (node instanceof EndNode || steps == 0) {
Trace newTrace = new Trace();
traces.add(newTrace);
return traces;
}
if (node instanceof ActivityNode) {
return getTracesFromActivityNode((ActivityNode) node, steps);
}
if (node instanceof AndSplit) {
AndJoin andJoin = this.getMatchingAndJoin((AndSplit) node, steps-1);
Set<Trace> partTraces = this.getTracesInAndBlock((AndSplit) node, andJoin, steps);
Set<Trace> nextTraces = getTracesFromNode(andJoin, steps-1);
for (Trace t1 : partTraces) {
for (Trace t2 : nextTraces) {
Trace t = new Trace(t1.getActivities());
t.addAllActivities(t2.getActivities());
traces.add(t);
}
}
}
for (ProcessEdge edge : this.outgoingEdgesOf(node)) {
Set<Trace> outTraces = getTracesFromNode(this.getEdgeTarget(edge), steps-1);
traces.addAll(outTraces);
}
return traces;
} |
d4b57fec-3013-4f15-8473-6f2b65973517 | 1 | public static void enumCompareTo(opConstant constant)
{
System.out.println(constant);
for(opConstant c : opConstant.values())
{
System.out.println(constant.compareTo(c));
}
} |
f9892205-5915-4607-9133-1bdab26e3519 | 1 | private boolean isEquals(String str1, String str2, boolean ignoreCase) {
if (ignoreCase) {
return str1.equalsIgnoreCase(str2);
} else {
return str1.equals(str2);
}
} |
42504e0a-41a3-495a-9c90-d2c7e2886617 | 8 | private void download(final String id, final String title, final int lastRow) throws IOException, InterruptedException{
Runnable dl = new Runnable() {
@Override
public void run() {
Result songURL = null;
try {
songURL = JGroovex.getSongURL(id).result;
} catch (IOException e1) {
modelDl.setValueAt(("Error"), lastRow-1, 1);
e1.printStackTrace();
}
System.out.println("Serverid:"+songURL.streamServerID);
System.out.println("Serverid:"+songURL.streamKey);
System.out.println("Serverid:"+songURL.ip);
modelDl.setValueAt(("Downloading"), lastRow-1, 1);
SongStream params = null;
InputStream is = null;
int downloaded=0;
try {
params = JGroovex.getSongStream(songURL.ip, songURL.streamKey);
JGroovex.markSongAsDownloaded(songURL.streamServerID, songURL.streamKey, id);
initTimer(songURL.streamServerID, songURL.streamKey, id);
} catch (IOException e1) {
modelDl.setValueAt(("Error"), lastRow-1, 1);
e1.printStackTrace();
}
is = params.getStream();
int lenght = params.getSize();
File f=new File(downloadPath+File.separator+clearTitle(title)+".mp3");
OutputStream out = null;
try {
out = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte buf[]=new byte[3000];
int len;
try {
while((len=is.read(buf))>0){
downloaded+=len;
out.write(buf,0,len);
modelDl.setValueAt(downloaded*100/lenght+"%", lastRow-1, 2);
}
} catch (IOException e) {
modelDl.setValueAt(("Error"), lastRow-1, 1);
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("\nFile Downloaded...................................");
modelDl.setValueAt(("Finished"), lastRow-1, 1);
try {
JGroovex.markSongComplete(songURL.streamServerID, songURL.streamKey, id);
timer.cancel();
} catch (IOException e) {
e.printStackTrace();
}
}
};
exec.execute(dl);
} |
c6cb3163-d1fc-4574-8c28-ac4c5024232b | 4 | public void processPacket(OggPacket packet) {
SkeletonPacket skel = SkeletonPacketFactory.create(packet);
// First packet must be the head
if (packet.isBeginningOfStream()) {
fishead = (SkeletonFishead)skel;
} else if (skel instanceof SkeletonFisbone) {
SkeletonFisbone bone = (SkeletonFisbone)skel;
fisbones.add(bone);
bonesByStream.put(bone.getSerialNumber(), bone);
} else if (skel instanceof SkeletonKeyFramePacket) {
keyFrames.add((SkeletonKeyFramePacket)skel);
} else {
throw new IllegalStateException("Unexpected Skeleton " + skel);
}
if (packet.isEndOfStream()) {
hasWholeStream = true;
}
} |
6238d7e6-332d-4e62-8150-fbc27c82a614 | 4 | public Server getServer(int port) {
logMessage(LOGLEVEL_TRIVIAL, "Getting server at port " + port + ".");
if (servers == null || servers.isEmpty())
return null;
ListIterator<Server> it = servers.listIterator();
Server desiredServer;
while (it.hasNext()) {
desiredServer = it.next();
if (desiredServer.port == port)
return desiredServer;
}
return null;
} |
61551aea-6bf6-4dd8-9dba-9c1312eb913d | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/* We will loop, possibly for all of the remaining characters. */
for (;;) {
j = offset;
b = true;
/* Compare the circle buffer with the to string. */
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/* If we exit the loop with b intact, then victory is ours. */
if (b) {
return true;
}
/* Get the next character. If there isn't one, then defeat is ours. */
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
ab4e2fb1-36af-41f2-81f7-94e2ad01a30d | 5 | private void loadItemTypes(String fn) {
String line;
String parts[];
try {
InputStream in = getClass().getResourceAsStream(GameController.CONFIG_DIR + fn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String name = "";
int createQty = 0;
int maxStack = 0;
String category = "";
String type = "";
int techLevel = 0;
String item1 = "";
int item1Qty = 0;
String item2 = "";
int item2Qty = 0;
String item3 = "";
int item3Qty = 0;
String item4 = "";
int item4Qty = 0;
String skill1 = "";
String skill2 = "";
String workBench = "";
float xpModifier = 1f;
String description = "";
ItemType it;
while ((line = br.readLine()) != null) {
if (line.length() == 0) {
continue;
}
if (line.startsWith("//")) {
continue;
}
parts = line.split(" ", 19);
if (parts.length != 19) {
System.out.println("Error in " + fn);
}
name = parts[0];
createQty = Integer.parseInt(parts[1]);
maxStack = Integer.parseInt(parts[2]);
category = parts[3];
type = parts[4];
techLevel = Integer.parseInt(parts[5]);
item1 = parts[6];
item1Qty = Integer.parseInt(parts[7]);
item2 = parts[8];
item2Qty = Integer.parseInt(parts[9]);
item3 = parts[10];
item3Qty = Integer.parseInt(parts[11]);
item4 = parts[12];
item4Qty = Integer.parseInt(parts[13]);
skill1 = parts[14];
skill2 = parts[15];
workBench = parts[16];
xpModifier = Float.parseFloat(parts[17]);
description = parts[18];
it = new ItemType(this, registry, name, createQty, maxStack, category, type, techLevel,
item1, item1Qty, item2, item2Qty, item3, item3Qty, item4, item4Qty,
skill1, skill2, workBench, xpModifier, description);
itemTypes.put(name, it);
itemTypesList.add(it);
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
} |
51956fa0-0c99-4096-bc46-d8c7a05432d2 | 2 | public static void deleteCarte(Carte carte) {
Statement stat;
try {
stat = ConnexionDB.getConnection().createStatement();
stat.executeUpdate("delete from carte where id_carte="+ carte.getId_carte());
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
} |
efedf9eb-383a-4f0c-b356-14b8de0ed4c7 | 3 | @Override
public WriteMsg write(FileContent data) throws RemoteException,
IOException, NotBoundException {
masterLogger.logMessage("===>> Write '" + data.fileName + "' request");
if (!files.contains(data.fileName)) {
// create new file and set meta data
files.add(data.fileName);
filePrimReplica.put(data.fileName, rand.nextInt(numReplicas));
for (Iterator<Entry<Integer, ReplicaLoc>> iterator = replicaPaths
.entrySet().iterator(); iterator.hasNext();) {
Entry<Integer, ReplicaLoc> entry = iterator.next();
ReplicaLoc repl = entry.getValue();
String replLoc = repl.location;
int replPort = repl.replicaPort;
// Reading from replica
Registry registryReplica1 = LocateRegistry.getRegistry(replLoc,
replPort);
ReplicaServerClientInterface replHandler = (ReplicaServerClientInterface) registryReplica1
.lookup(Global.REPLICA_LOOKUP);
replHandler.createFile(data.fileName);
}
// edit in filesDirectory.in
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(Global.FILES_DIRECTORY, true)));
out.print(data.fileName + "\n");
out.close();
} catch (Exception e) {
System.err.println("Error in broadcast method: "
+ e.getMessage());
}
// done
masterLogger
.logMessage("===>> Creating empty file in all replicas ....");
}
ReplicaLoc primLoc = replicaPaths.get(filePrimReplica
.get(data.fileName));
WriteMsg wMsg = new WriteMsg(txID++, 1, primLoc);
return wMsg;
} |
4e8d1dde-9c19-4ab3-996d-ec15cdcdd360 | 0 | public void setCell(int x, int y, boolean isAlive) {
setCellAt(x, y, isAlive);
} |
3f3d5687-fa33-4c3f-bfe2-c6d5a3ce4b22 | 0 | public static void main(String[] args) {
int i = 1234567890;
float f = i;
System.out.println(i - (int) f); // -46
} |
12441ddc-510a-4d6c-a38c-04b40d2cedea | 7 | private static void spawn() {
if(numOfMonsters > 0) {
switch (monsterIndex) {
case 0: @SuppressWarnings("unused")
WaterBalloon waterballoon = new WaterBalloon(spawnLocation.getXVector() + random.nextInt(10),
spawnLocation.getYVector() + random.nextInt(10));
break;
case 1: @SuppressWarnings("unused")
WaterBottlePack waterBottlePack = new WaterBottlePack(spawnLocation.getXVector() + random.nextInt(10),
spawnLocation.getYVector() + random.nextInt(10));
break;
case 2: @SuppressWarnings("unused")
WaterGunMech waterGunMech = new WaterGunMech(spawnLocation.getXVector() + random.nextInt(10),
spawnLocation.getYVector() + random.nextInt(10));
}
numOfMonsters--;
} else if(levelTimer > 0) {
if(deltaTimer > 60) {
deltaTimer = 0;
levelTimer--;
} else {
deltaTimer++;
}
} else if(levelArrayIndex > 0) {
levelTimer = currentLevel.get(currentLevel.size() - levelArrayIndex).getTimer();
monsterIndex = currentLevel.get(currentLevel.size() - levelArrayIndex).getMob2Spawn();
numOfMonsters = currentLevel.get(currentLevel.size() - levelArrayIndex).getNumOfMobs();
setSpawnLocation();
levelArrayIndex--;
}
} |
14de6123-fa6f-4762-bf1c-c32b73ac2951 | 3 | public void subsetsWithDupRec(int [] num, int start, Stack<Integer> stk){
for(int i = start; i < num.length; ++i){
// if(i > start && num[i] == num[i-1]) continue;
stk.push(num[i]);
res.add(new ArrayList<Integer>(stk));
// start from i+1 instead of "start+1", in certain level, start won't change
// subsetsWithDupRec(num, start+1, stk);
subsetsWithDupRec(num, i+1, stk);
stk.pop();
while (i < num.length - 1 && num[i] == num[i+1]) ++i;
}
} |
2213149c-744e-43ed-b0f6-88222fcc7827 | 0 | public Builder(String tilte, String auther) {
this.title = tilte;
this.auther = auther;
} |
414e12ca-dddd-4ea6-814b-c798a919226f | 2 | void deleteSuccess(String s) {
System.out.println("deleteSuccess");
if (this.selFile.exists()) {
this.result.setText("<HTML><font color='red'>Error In Deleting \" " + this.selFile.getName() + " \" " + s + "</font></html>");
} else if (!this.selFile.exists()) {
this.result.setText("<HTML><font color='green'>\"" + this.selFile.getName() + "\"</font> " + s + " Has Been Deleted Successfully !!!!</html>");
}
} |
35c7ee2a-9918-44fd-a46a-98c43096dbdd | 0 | public static String getNumOS() {
return numOS;
} |
73c14faf-0b84-4e20-8d88-6e75f92d4106 | 5 | public static void main(final String[] args) throws Exception {
String[] colNames = null;
OrderBy orderby = null;
// delimited by a comma
// text qualified by double quotes
// ignore first record
final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(new File("PEOPLE-CommaDelimitedWithQualifier.txt"), ',', '"');
final DataSet ds = pzparser.parse();
// re order the data set by last name
orderby = new OrderBy();
orderby.addOrderColumn(new OrderColumn("CITY", false));
orderby.addOrderColumn(new OrderColumn("LASTNAME", true));
ds.orderRows(orderby);
colNames = ds.getColumns();
while (ds.next()) {
for (final String colName : colNames) {
System.out.println("COLUMN NAME: " + colName + " VALUE: " + ds.getString(colName));
}
System.out.println("===========================================================================");
}
if (ds.getErrors() != null && !ds.getErrors().isEmpty()) {
System.out.println("FOUND ERRORS IN FILE....");
for (int i = 0; i < ds.getErrors().size(); i++) {
final DataError de = (DataError) ds.getErrors().get(i);
System.out.println("Error: " + de.getErrorDesc() + " Line: " + de.getLineNo());
}
}
} |
bb47ccd5-bd9f-4bd8-841a-f9714149187b | 3 | public static ArrayList<Method> getSetters(Class theClass){
Method[] methods=theClass.getMethods();
ArrayList<Method> setters = new ArrayList<Method>();
if(methods==null)
return setters;
for(int i=0;i<methods.length;i++){
if(isSetter(methods[i].getName()))
setters.add(methods[i]);
}
return setters;
} |
0bbd6e84-9b9b-4ab3-ae01-4963df94549b | 4 | protected Dimension getLargestCellSize(Container parent,
boolean isPreferred) {
int ncomponents = parent.getComponentCount();
Dimension maxCellSize = new Dimension(0,0);
for ( int i = 0; i < ncomponents; i++ ) {
Component c = parent.getComponent(i);
Rectangle rect = compTable.get(c);
if ( c != null && rect != null ) {
Dimension componentSize;
if ( isPreferred ) {
componentSize = c.getPreferredSize();
} else {
componentSize = c.getMinimumSize();
}
// Note: rect dimensions are already asserted to be > 0 when the
// component is added with constraints
maxCellSize.width = Math.max(maxCellSize.width,
componentSize.width / rect.width);
maxCellSize.height = Math.max(maxCellSize.height,
componentSize.height / rect.height);
}
}
return maxCellSize;
} |
ec2c43f8-8a26-46ef-b6fc-1a7bd5fef1c3 | 1 | public void setName( String name ) {
if( name == null )
throw new IllegalArgumentException( "name must not be null" );
this.name = name;
} |
0a32a9ac-de5d-4ac5-95f3-728762cf6e3f | 6 | public static List<TerritoireCase> createTerritoires(int nbPlayer) {
List<TerritoireCase> terris = new LinkedList<TerritoireCase>();
try {
// Creation des territoires
PreparedStatement ps = conn.prepareStatement("SELECT * FROM territoire WHERE plateau = ?");
ps.setInt(1, nbPlayer);
ResultSet rs = ps.executeQuery();
HashMap<Integer, Territoire> territoires = new HashMap<Integer, Territoire>();
while (rs.next()) {
Rectangle r = new Rectangle(rs.getInt("x"), rs.getInt("y"), rs.getInt("w"), rs.getInt("h"));
TerritoireCase tc = new TerritoireCase(r);
Territoire t = new Territoire();
t.setEnBordure(rs.getBoolean("enbordure"));
t.setNbUnite(rs.getInt("tribuoubliee"));
//t.setNom(rs.getString("name")); TODO : Virer l'attribut dans la DB / ajouter l'attribut dans le classe
tc.setTerritoire(t);
territoires.put(rs.getInt("uid"), t);
terris.add(tc);
}
rs.close();
ps.close();
// Creation des adjacences
ps = conn.prepareStatement("SELECT * FROM adjacence WHERE plateau = ?");
ps.setInt(1, nbPlayer);
rs = ps.executeQuery();
while (rs.next()) {
Territoire t1 = territoires.get(rs.getInt("uid_t1"));
Territoire t2 = territoires.get(rs.getInt("uid_t2"));
t1.addTerritoireAdjacent(t2);
t2.addTerritoireAdjacent(t1);
}
rs.close();
ps.close();
// TODO éléments
ps = conn.prepareStatement("SELECT * FROM elements WHERE plateau = ?");
ps.setInt(1, nbPlayer);
rs = ps.executeQuery();
while (rs.next()) {
Territoire t = territoires.get(rs.getInt("territoire"));
String elm = rs.getString("nom");
Class<?> elmClass = Element.ELEMENTS.get(elm);
if (elmClass != null) {
t.addElement((Element) elmClass.getConstructor(Territoire.class).newInstance(t)); // TODO : Simplifier en supprimant l'argument du constructeur ?
}
}
rs.close();
ps.close();
}
catch (Exception e) {
e.printStackTrace();
}
return terris;
} |
3f44140a-16e0-4150-bed7-7b8642e07caf | 9 | public void reproduction() {
Stack<Case> casePossible = new Stack<>();
for (int x = Math.max(0, conteneur.getX() - famille.getSpecs().getPorteSpore()); x < Math.min(conteneur.getX() + famille.getSpecs().getPorteSpore(), conteneur.getContainer().getPlateau().length); x++) {
for (int y = Math.max(0, conteneur.getY() - (famille.getSpecs().getPorteSpore() - Math.abs(conteneur.getX() - x))); y < Math.min(conteneur.getY() + (famille.getSpecs().getPorteSpore() - Math.abs(conteneur.getX() - x)), conteneur.getContainer().getPlateau()[0].length); y++) {
if (conteneur.getContainer().getPlateau()[x][y].isTraversable() && conteneur.getContainer().getPlateau()[x][y] != conteneur && conteneur.getContainer().getPlateau()[x][y].getPlante() == null) {
casePossible.add(conteneur.getContainer().getPlateau()[x][y]);
}
}
}
for (Case c : casePossible) {
if ((int) (Math.random() * 101) <= famille.getSpecs().getProliferation()) {
if ((int) (Math.random() * 10001) <= famille.getSpecs().getTauxMutationPlante()) {
if (this instanceof Herbe) {
FamillePlante fp = new FamillePlante(0, c);
conteneur.getContainer().getPartie().getFamillesPlante().add(fp);
} else {
FamillePlante fp = new FamillePlante(1, c);
conteneur.getContainer().getPartie().getFamillesPlante().add(fp);
}
} else {
c.getGraines().add(new Graine(famille));
famille.setCompteurGraines(famille.getCompteurGraines() + 1);
}
}
}
casePossible.clear();
} |
d90b3ea4-a428-4281-bf33-5c67bc67c17e | 7 | public void setEditBrush(int b){
brushtype = b;
switch(brushtype){
// 1x1
case 1: sigmund = new onebrush(); break;
//2x2
case 2: sigmund = new twobrush(); break;
//3x3
case 3: sigmund = new threebrush(); break;
//Glider
case 4: sigmund = new gliderbrush(); sigmund.setOrientation(0); break;
//R-pentomino
case 5: sigmund = new rpentbrush(); sigmund.setOrientation(0); break;
//Extended vonNeumann
case 6: sigmund = new evbrush(); break;
//vonNeumann Brush
case 7: sigmund = new vonNeumannbrush(); break;
default : sigmund = new onebrush(); break;}
} |
402e4b9f-6243-4e88-b741-2d538ba068af | 3 | @Override
public Processo updateProcesso(Processo newProc,Processo oldProc) throws Exception{
if(oldProc.getSituacao() == 0){
ColTramite colTramite = new ColTramite();
TramiteProcesso tramite = new TramiteProcesso();
tramite = colTramite.retrieveTramiteProcesso(oldProc.getDtAbertura());
if(tramite.getTipo().getTipo().equals("Abertura")){
if(newProc.getSituacao() != oldProc.getSituacao()){
sdf = new SimpleDateFormat("dd/MM/yyyy");
UCManterTramiteManager manager = new UCManterTramiteManager();
tramite = new TramiteProcesso();
tramite.setDtTramite(sdf.format( new Date( System.currentTimeMillis() ) ));
tramite.setObservacoes("Lan�amento da situa��o");
TipoTramite tipo = new TipoTramite();
tipo.setTipo(getSituacao(newProc.getSituacao()));
tramite.setTipo(tipo);
tramite.setProc(oldProc);
tramite = manager.insertTramiteProcesso(tramite);
}
return colProc.updateProcesso(newProc, oldProc);
}
else
throw new NoUpdateProcess("Processo n�o pode ser atualizado",
"O Tr�mite do processo n�o � Abertura");
}
else
throw new NoUpdateProcess("Processo n�o pode ser atualizado",
"Situa��o do Processo n�o � de Aberto");
} |
72a4ae17-57ff-4791-8549-0b2b69f41ac6 | 5 | @Override
public int hashCode() {
int result = (int) (driverId ^ (driverId >>> 32));
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (autoPlate != null ? autoPlate.hashCode() : 0);
result = 31 * result + (brand != null ? brand.hashCode() : 0);
result = 31 * result + (model != null ? model.hashCode() : 0);
return result;
} |
9efbbd4c-f5b3-4cfb-8367-b94e9f1f452b | 7 | public EDTView(SingleFrameApplication app) {
super(app);
initComponents();
init();
this.donner1.setVisible(false);
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
} |
b8871954-ac32-4a7a-98ae-a67d6fa10f51 | 8 | public AbstractBeanTreeNode generateNewDefaultArrayElementNode() {
if (null == this.children) {
this.children = new Vector<AbstractBeanTreeNode>();
}
AbstractBeanTreeNode arrayChildNode = null;
Class<?> componentType = this.getObjType().getComponentType();
Object arrayElement = null;
String nodeName = componentType.getSimpleName();
String methodName = null;
if(false == isTypeNumberOrString(componentType)) {
Object parentObj = this.userObject;
Method method = findGetMethodInParentByName(parentObj, nodeName);
if(method != null) {
try {
arrayElement = method.invoke(parentObj, new Object[]{});
methodName = method.getName();
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
if(arrayElement == null) {
arrayElement = this.getObjectDefaultValueInstance(componentType);
}
Object arrayElementDefaultValue = this.getObjectDefaultValueInstance(componentType);
arrayChildNode = new BeanObjectTreeNode(this, componentType.getSimpleName(), arrayElement.getClass(), arrayElement, arrayElementDefaultValue, methodName);
if(false == componentType.isPrimitive()) {
arrayChildNode.initChildren();
}
return arrayChildNode;
} |
b42bc665-de71-4326-a296-4d31555d5711 | 0 | public ProtocolKeepAlive(String username, String status) {
mUserName = username;
mStatus = status;
} |
87c0cc6e-c5a8-4e5d-97eb-aea3e2484442 | 4 | public static void deleteRecursive(File dir) {
if(dir.exists() && dir.isDirectory()) {
for(File f : dir.listFiles()) {
if(f.isDirectory()) {
deleteRecursive(f);
}
else {
f.delete();
}
}
}
} |
2089c248-4542-49dd-b7b7-2ce166e1a1eb | 8 | private int arg_list(String funcdef){
tokenActual = analizadorLexico.consumirToken();
Simbolo simb = analizadorSemantico.tablaDeSimbolos.obtenerSimbolo(funcdef, GLOBAL_SCOPE);
int numParams;
if(simb!=null){
if(simb.existePropiedad("numparams")){
numParams = Integer.parseInt(simb.obtenerValor("numparams"));
}else{
numParams = 0;
}
}else{
numParams = 0;
}
if(!tokenActual.obtenerLexema().equals(")")){
if(tokenActual.obtenerLexema().equals(",")){
tokenActual = analizadorLexico.consumirToken();
simple_expresion();
String tipo = analizadorSemantico.ultipoTipo;
int count = 1 + arg_list(funcdef);
if((count-1) < (numParams)){
if(!simb.paramsTypes[(numParams - count)].equals(tipo)){
String info = "Parametro "+ (numParams - count + 1) +" se esperaba de tipo "+simb.paramsTypes[count-1];
error(23, info,tokenActual.obtenerLinea());
}
//System.out.println(count);
}
return count;
}else{
analizadorLexico.retroceso();
tokenActual = analizadorLexico.consumirToken();
simple_expresion();
String tipo = analizadorSemantico.ultipoTipo;
int count = 1 + arg_list(funcdef);
if((count-1)<numParams){
if(!simb.paramsTypes[(numParams - count)].equals(tipo)){
String info = "Parametro "+ (numParams - count + 1) +" se esperaba de tipo "+simb.paramsTypes[count-1];
error(23, info,tokenActual.obtenerLinea());
}
//System.out.println(count);
}
//System.out.println(count);
return count;
}
}
return 0;
} |
f3f9d97f-ec4d-4e40-8886-5a0accb3f696 | 9 | public boolean evaluateInput(MachineInput machineInput) {
if(inputAdapter==null) {
throw new IllegalStateException("No InputAdapter specified prior to calling evaluateInput()");
}
boolean inputIgnored = false;
inputAdapter.queueInput(machineInput);
while(inputAdapter.hasNext()) {
TransitionInput transitionInput = inputAdapter.next();
for(StateMachineEventListener<TransitionInput> listener : eventListeners) {
listener.beforeEvaluatingInput(transitionInput, this);
}
boolean evaluateInput = true;
if(currentState instanceof SubmachineState) {
// Delegate the evaluation of the input
submachine.evaluateInput(transitionInput);
// If the submachine transitioned to (or was left in) a final state, extract its result value to evaluate on this machine
if(submachine.getState() instanceof FinalState) {
FinalState<TransitionInput> finalState = (FinalState<TransitionInput>)submachine.getState();
transitionInput = finalState.getResult();
} else {
evaluateInput = false;
}
}
if(evaluateInput) {
Transition<TransitionInput> validTransition = findFirstValidTransitionFromCurrentState(transitionInput);
if(validTransition == null) {
inputIgnored = true;
for(StateMachineEventListener<TransitionInput> listener : eventListeners) {
listener.noValidTransition(transitionInput, this);
}
} else {
transition(validTransition,transitionInput);
}
}
for(StateMachineEventListener<TransitionInput> listener : eventListeners) {
listener.afterEvaluatingInput(transitionInput, this);
}
}
return inputIgnored;
} |
b5643041-aee4-4719-85df-0f6cfe88b171 | 6 | @Override
public void validate() {
if (uname == null) {
addActionError("Please Enter User Name");
}
if (email == null) {
addActionError("Please Enter Email Address");
}
if (pwd == null) {
addActionError("Please Enter Password");
}
if (confirmpwd == null) {
addActionError("Please Enter Confirm Password");
}
if (!confirmpwd.equals(pwd)) {
addActionError("Confirm Password and Password Not Match Please Enter Again");
}
User user = (User) myDao.getDbsession().get(User.class, email);
if (user != null) // addFieldError("email","sorry Email id Already Taken");
{
addActionError("Sorry Email id Already Taken");
}
} |
4ff7901a-8160-4494-829a-fbe377493f06 | 9 | public void update() {
time++;
if(time % (random.nextInt(50) + 30) == 0) {
xa = random.nextInt(3) - 1;
ya = random.nextInt(3) - 1;
if(random.nextInt(4) == 0){
xa = 0;
ya = 0;
}
}
if(walking) animSprite.update();
else animSprite.setFrame(0);
if (ya < 0) {
animSprite = up;
dir = Direction.UP;
}
if (ya > 0) {
animSprite = down;
dir = Direction.DOWN;
}
if (xa < 0) {
animSprite = left;
dir = Direction.LEFT;
}
if (xa > 0) {
animSprite = right;
dir = Direction.RIGHT;
}
if (xa != 0 || ya != 0) {
move(xa, ya);
walking = true;
} else {
walking = false;
}
} |
6114fef4-dfd6-47d6-94af-81c70d5d9906 | 0 | public void setServiceDate(String serviceDate) {
this.serviceDate = serviceDate;
setDirty();
} |
dfcab7ed-fed9-48e4-bde8-18d2bac2995e | 8 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
// In this case, we use the instance of an event to trigger
// the initial filling of the deck with cards, since, once
// this object is capable of handling events, it must already
// be "in the world" and ready to receive cards.
if((!alreadyFilled)&&(owner()!=null))
fillInTheDeck();
// This handler also checks to see if anyone is saying "shuffle"
// directly to the deck item. If so, we cancel the message by
// returning false (since it would make them look silly to be
// talking to a deck of cards), and instead
// display a message showing the owner of this deck shuffling it.
if((msg.amITarget(this))
&&(msg.targetMinor()==CMMsg.TYP_SPEAK)
&&(msg.targetMessage()!=null)
&&(msg.targetMessage().toUpperCase().indexOf("SHUFFLE")>0))
{
if(!shuffleDeck())
msg.source().tell(L("There are no cards left in the deck"));
else
{
final Room R=CMLib.map().roomLocation(this);
if(R!=null)
R.show(msg.source(),null,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_QUIETMOVEMENT,
L("<S-NAME> <S-HAS-HAVE> thoroughly shuffled <O-NAMESELF>."));
}
return false;
}
return super.okMessage(myHost,msg);
} |
21d3be23-314e-4e6c-91ca-58e96699b551 | 4 | public void validate(Secao secao){
if (secao == null || secao.equals("")){
throw new SaveException("Seção não pode ser vazia.");
} else {
if(secao.getNome() == null || secao.getNome().equals("")){
throw new SaveException("Nome da seção não pode ser vazio.");
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.