method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
cfd0fcec-127c-41d4-a040-60373bc344bb | 0 | public void setjCheckBoxQuit(JCheckBox jCheckBoxQuit) {
this.jCheckBoxQuit = jCheckBoxQuit;
} |
52a3be46-35d6-4e0f-a4fc-b9852e8d688b | 1 | @Override
public byte[] getPayload() throws IOException {
byte[] payload=null;
try {
payload = reload();
} catch (FileNotFoundException ex) {
this.log(Level.WARNING,"file not found retrieving payload "+ex.toString());
}
return payload;
} |
a049444f-813c-4171-8d87-e513d7b0014f | 3 | public void setFullScreen(DisplayMode dm, JFrame window){ //Display mode: 4 param 2 resolution (X Y), bit depth, refresh rate
window.setUndecorated(true); //titlebars scrollbars
window.setResizable(false);
vc.setFullScreenWindow(window);
//check
if(dm != null && vc.isDisplayChangeSupported()) { //vc is able to change the display
try {
vc.setDisplayMode(dm);
} catch (Exception ex) {}
}
} |
e1b27c5e-7b74-431c-a66b-5f0fbed0faec | 0 | @Override
public int filterRGB(int x, int y, int rgb) {
return (rgb & 0xff000000) | amount;
} |
d962d850-2ad0-4f99-8840-f41b274e80cf | 9 | private void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header)
throws InterruptedException
{
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) return;
StringTokenizer st = new StringTokenizer( inLine );
if ( !st.hasMoreTokens())
sendError( HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" );
String method = st.nextToken();
pre.put("method", method);
if ( !st.hasMoreTokens())
sendError( HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" );
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf( '?' );
if ( qmi >= 0 )
{
decodeParms( uri.substring( qmi+1 ), parms );
uri = decodePercent( uri.substring( 0, qmi ));
}
else uri = decodePercent(uri);
// If there's another token, it's protocol version,
// followed by HTTP headers. Ignore version but parse headers.
// NOTE: this now forces header names lowercase since they are
// case insensitive and vary by client.
if ( st.hasMoreTokens())
{
String line = in.readLine();
while ( line != null && line.trim().length() > 0 )
{
int p = line.indexOf( ':' );
if ( p >= 0 )
header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim());
line = in.readLine();
}
}
pre.put("uri", uri);
}
catch ( IOException ioe )
{
sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
}
} |
8e5925d5-3555-491e-989b-dbcb36cb3a24 | 1 | public static void SQLencrypted (String host, String port, String db, String user, char [] pw) {
try {
String newPW = String.valueOf(pw);
// See also Encrypting with DES Using a Pass Phrase.
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpec = new DESKeySpec(secretSalt.getBytes());
SecretKey key = keyFactory.generateSecret(keySpec);
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt(newPW);
LoginData.writeSQL (host,port,db,user,encrypted);
} catch (Exception e) {
Error_Frame.Error(e.toString());
}
} |
9e1739a9-39b7-47bb-a877-33b7c90d093d | 5 | private int handleCC(String value,
DoubleMetaphoneResult result,
int index) {
if (contains(value, index + 2, 1, "I", "E", "H") &&
!contains(value, index + 2, 2, "HU")) {
//-- "bellocchio" but not "bacchus" --//
if ((index == 1 && charAt(value, index - 1) == 'A') ||
contains(value, index - 1, 5, "UCCEE", "UCCES")) {
//-- "accident", "accede", "succeed" --//
result.append("KS");
} else {
//-- "bacci", "bertucci", other Italian --//
result.append('X');
}
index += 3;
} else { // Pierce's rule
result.append('K');
index += 2;
}
return index;
} |
1ab9a9fe-794c-408f-9e71-abf88956fdf1 | 0 | public Neuron getOutputNeuron() {
return outputNeuron;
} |
8a31e921-8ba4-430d-b179-1c7b2166482a | 7 | public void mouseClicked(MouseEvent me) {
Point cell = me.getPoint();
if (me.getClickCount() == 1) {
int col = tabel.columnAtPoint(cell);
int row = tabel.rowAtPoint(cell);
if (col == 4) {
CounterParty counterParty = (CounterParty) tabel.getValueAt(row, col);
if (counterParty == null) {
CounterPartySelector sel = new CounterPartySelector((Statement)statements.getBusinessObjects().get(row), statements, counterParties);
sel.setVisible(true);
counterParty = sel.getSelection();
}
if (counterParty != null) {
Statement statement = (Statement)statements.getBusinessObjects().get(row);
statement.setCounterParty(counterParty);
refresh();
System.out.println(counterParty.getName());
for(BankAccount account : counterParty.getBankAccounts().values()) {
System.out.println(account.getAccountNumber());
System.out.println(account.getBic());
System.out.println(account.getCurrency());
}
SearchOptions searchOptions = new SearchOptions();
searchOptions.searchForCounterParty(counterParty);
new GenericStatementTableFrame(searchOptions, statements).setVisible(true);
// parent.addChildFrame(refreshableTable);
}
} else if (col == 5) {
String transactionCode = (String) tabel.getValueAt(row, 6);
SearchOptions searchOptions = new SearchOptions();
searchOptions.searchForTransactionCode(transactionCode);
new GenericStatementTableFrame(searchOptions, statements).setVisible(true);
// parent.addChildFrame(refreshableTable);
} else if (col == 6){
String communication = (String) tabel.getValueAt(row, 7);
SearchOptions searchOptions = new SearchOptions();
searchOptions.searchForCommunication(communication);
new GenericStatementTableFrame(searchOptions, statements).setVisible(true);
// parent.addChildFrame(refreshableTable);
}
}
} |
0b80fa89-92ff-45a2-ade3-9501bdc7459a | 2 | @Override
public Object invoke(Context context,List<Object> arguments) {
context = context.subContext();
int nArgs = Math.min(arguments.size(), variables.size());
for (int i=0;i<nArgs;i++){
context.setVariable(variables.get(i), arguments.get(i));
}
for (Statement statement: statements){
statement.execute(context);
}
return null;
} |
9f73517d-affa-46ee-82a0-8eca579a6bc7 | 9 | @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
String destino = null;
ArrayList order = new ArrayList();
String ordenacion= "id";
String ordenVerCurriculums = request.getParameter("ordenacionCurr");
String pagCurrO = request.getParameter("pagina");
String orden = request.getParameter("campo");
String tipo = request.getParameter("orden");
if (ordenVerCurriculums == null){
if(orden != null && tipo != null){
switch(orden){
case "Nombre":
ordenacion = "Nombre";
}
switch(tipo){
case"↑":
ordenacion += " asc";
break;
case"↓":
ordenacion += " desc";
}
}
}else{
ordenacion = ordenVerCurriculums;
}
order.add(ordenacion);
ArrayList where = new ArrayList();
// String pagOrden = request.getParameter("pagina");
String pagCurr = request.getParameter("pagCurr");
int rpp = 2;
int pa = 1;
if(pagCurr != null){
pa = Integer.parseInt(pagCurr);
}
if(pagCurrO != null){
pa = Integer.parseInt(pagCurrO);
}
try {
String titulo = request.getParameter("titulo");
String id = request.getParameter("ofer");
where.add("id in (SELECT id_usuario FROM DOCUMENTOS WHERE id in "
+ "(SELECT ID_CURRICULUM FROM BOLSA WHERE ID_OFERTA ="+id+"))");
POJOCurriculums pojoC = new POJOCurriculums();
pojoC.setIdOferta(id);
LinkedList<POJOUsuario> lista = DAOCurriculums.sacaDocu(pojoC, pa, rpp, order, where);
request.setAttribute("curr", lista);
session.setAttribute("numPagCurr", pa);
request.setAttribute("idOfer",id);
request.setAttribute("titulo",titulo);
request.setAttribute("pagina",pa);
request.setAttribute("ordenacionCurr", ordenacion);
destino = "/curriculums.jsp";
ServletContext cont = getServletConfig().getServletContext();
RequestDispatcher reqDispatcher = cont.getRequestDispatcher(destino);
reqDispatcher.forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
} |
bb38d27c-3db6-4718-a418-97080f150db4 | 7 | public void testNodeRemoval2b() {
setTree(new TreeNode("dummy"));
TreeNode root = new TreeNode("root", 1);
TreeNode leaf = new TreeNode("leaf");
root.setBranch(new TreeNode[]{ leaf });
Map tree = Collections.synchronizedMap(new HashMap());
tree.put(root, new TreeNode[]{ leaf });
tree.put(leaf, new TreeNode[]{});
Map refCounts = Collections.synchronizedMap(new HashMap());
refCounts.put(root, new Integer(0));
refCounts.put(leaf, new Integer(1));
TreeNode node = root;
int count = 0;
//setTree(root);
try {
((Question3)answer).deleteNode(tree, refCounts, node);
assertTrue(null, "Your code doesn't update the reference counts for nodes!", tree != null && tree.size() == 1 && tree.containsKey(leaf) && refCounts != null && refCounts.size() == 1 && refCounts.containsKey(leaf) && ((Integer)(refCounts.get(leaf))).intValue() == 0);
} catch(Throwable exn) {
fail(exn, "No exception's should be generated, but your code threw: " + exn.getClass().getName());
} // end of try-catch
} // end of method testNodeRemoval2b |
8853cb40-be73-4c94-a5fa-750eb84da9ea | 8 | private void appendSource(int position) {
final int limit = 4;
int start;
final int skip = position - limit + 1;
if (skip <= 0) {
start = 0;
} else {
if (skip == 1) {
htmlStrings.add("... (skipping 1 line) ...");
plainStrings.add("... (skipping 1 line) ...");
} else {
htmlStrings.add("... (skipping " + skip + " lines) ...");
plainStrings.add("... (skipping " + skip + " lines) ...");
}
start = position - limit + 1;
}
for (int i = start; i < position; i++) {
htmlStrings.add(StringUtils.hideComparatorCharacters(getSource().getLine(i)));
plainStrings.add(getSource().getLine(i));
}
final String errorLine = getSource().getLine(position);
htmlStrings.add("<w:red>" + StringUtils.hideComparatorCharacters(errorLine) + "</w>");
plainStrings.add(StringUtils.hideComparatorCharacters(errorLine));
final StringBuilder underscore = new StringBuilder();
for (int i = 0; i < errorLine.length(); i++) {
underscore.append("^");
}
plainStrings.add(underscore.toString());
final Collection<String> textErrors = new LinkedHashSet<String>();
for (ErrorUml er : printedErrors) {
textErrors.add(er.getError());
}
for (String er : textErrors) {
htmlStrings.add(" <color:red>" + er);
plainStrings.add(" " + er);
}
boolean first = true;
for (String s : getSuggest()) {
if (first) {
htmlStrings.add(" <color:white><i>" + s);
} else {
htmlStrings.add("<color:white>" + StringUtils.hideComparatorCharacters(s));
}
first = false;
}
} |
0e894910-efb2-41b9-82ec-bdd2e71632e9 | 7 | public void updateLoggers() {
log.trace("Syncing up JDK logger levels from Log4j");
final Map<Logger, java.util.logging.Logger> loggerMap = this.loggerMap;
final LevelMapper levelMapper = this.levelMapper;
loggerMap.clear();
final Logger rootLogger = Logger.getRootLogger();
final LoggerRepository repository = rootLogger.getLoggerRepository();
final Enumeration loggers = repository.getCurrentLoggers();
final Enumeration<String> jdkLoggerNames = LogManager.getLogManager().getLoggerNames();
final Set<String> removeLoggers = new HashSet<String>();
while (jdkLoggerNames.hasMoreElements()) {
removeLoggers.add(jdkLoggerNames.nextElement());
}
while (loggers.hasMoreElements()) {
final Logger logger = (Logger) loggers.nextElement();
final String name = logger.getName();
final java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger(name);
removeLoggers.remove(name);
final org.apache.log4j.Level targetLevel = logger.getLevel();
if (targetLevel == null) {
if (log.isTraceEnabled()) {
log.trace("Remapping logger \"" + name + "\" with null level");
}
jdkLogger.setLevel(null);
} else {
final Level sourceLevel = levelMapper.getSourceLevelForTargetLevel(targetLevel);
if (log.isTraceEnabled()) {
log.trace("Remapping logger \"" + name + "\" to JDK level \"" + sourceLevel + "\"");
}
loggerMap.put(logger, jdkLogger);
jdkLogger.setLevel(sourceLevel);
}
}
removeLoggers.remove("");
final Level sourceLevel = levelMapper.getSourceLevelForTargetLevel(rootLogger.getLevel());
if (log.isTraceEnabled()) {
log.trace("Remapping root logger to JDK level \"" + sourceLevel + "\"");
}
this.rootLogger.setLevel(sourceLevel);
// clear levels for loggers which are no longer referenced in the configuration
for (String loggerName : removeLoggers) {
java.util.logging.Logger.getLogger(loggerName).setLevel(null);
}
} |
0a63e9b7-d78a-4280-aa71-d1d7bebd98d3 | 4 | @SuppressWarnings("static-access")
public static CommandLine createOptions(String[] args)
{
CommandLine cmd=null;
//create the options
Options options = new Options();
options.addOption("h", "help", false, "prints the help content");
options.addOption(OptionBuilder.withArgName("json-file").hasArg().withDescription("input file with the JSON").withLongOpt("input").create("i"));
options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("output directory (Default: ./)").withLongOpt("output").create("o"));
options.addOption(OptionBuilder.withArgName("name").hasArg().withDescription("output file name (witout extension)").withLongOpt("name").create("n"));
options.addOption(OptionBuilder.withArgName("file").hasArg().isRequired().withDescription("template file").withLongOpt("template").create("t"));
options.addOption(new Option( "pdf", "generate output in pdf format" ));
options.addOption(new Option( "doc", "generate output in doc format (.odt or .docx, depend of the template format)" ));
options.addOption(new Option( "html", "generate output in html format" ));
options.addOption(new Option( "a", "all" , false, "generate output in all format (default)" ));
//parse it
try{
CommandLineParser parser = new GnuParser();
cmd = parser.parse(options, args);
}
catch(MissingOptionException e){
displayHelp(options);
System.exit(1);
} catch(MissingArgumentException e){
displayHelp(options);
System.exit(1);
} catch(ParseException e){
System.err.println("Error while parsing the command line: "+e.getMessage());
System.exit(1);
} catch(Exception e){
e.printStackTrace();
}
return cmd;
} |
8c5b7729-9cc3-4349-b312-b947df670f63 | 8 | public static void mult( RowD1Matrix64F a, D1Matrix64F b, D1Matrix64F c)
{
if( c.numCols != 1 ) {
throw new MatrixDimensionException("C is not a column vector");
} else if( c.numRows != a.numRows ) {
throw new MatrixDimensionException("C is not the expected length");
}
if( b.numRows == 1 ) {
if( a.numCols != b.numCols ) {
throw new MatrixDimensionException("A and B are not compatible");
}
} else if( b.numCols == 1 ) {
if( a.numCols != b.numRows ) {
throw new MatrixDimensionException("A and B are not compatible");
}
} else {
throw new MatrixDimensionException("B is not a vector");
}
int indexA = 0;
int cIndex = 0;
double b0 = b.get(0);
for( int i = 0; i < a.numRows; i++ ) {
double total = a.get(indexA++) * b0;
for( int j = 1; j < a.numCols; j++ ) {
total += a.get(indexA++) * b.get(j);
}
c.set(cIndex++ , total);
}
} |
efbd1ea9-716d-4c0d-9a52-c465397002c4 | 2 | public static boolean isDinheiro(String valor) {
final String NUMEROS = "0123456789.";
for (int i = 0; i < valor.length(); i++) {
char caracter = valor.charAt(i);
if (NUMEROS.indexOf(caracter) == -1) {
return false;
}
}
return true;
} |
052055c0-390a-45d0-ab57-3abfbfed6cfe | 1 | @Override
public boolean execute() {
Boolean val = true;
try {
this.document.loadFromFile(filePath);
} catch (Exception ex) {
ex.printStackTrace();
val = false;
}
return val;
} |
0ab30740-92fc-4e94-8c61-8d7742108bdd | 1 | public final void setDefaultAction(Action a) {
if(a == null)
defaultAction = unknownCommandAction;
else
defaultAction = a;
} |
f7c7662b-4275-4efa-bef4-55b315166d64 | 5 | public void run(Graphics g){
if(!closed){
g.drawImage(img, x,y,x+(3*8), y+(3*8), 0, 0, 3, 3, null);
g.drawImage(img, x,y+(3*8), x+(3*8), y+h-(3*8), 0, 3, 3, 6, null);
g.drawImage(img, x,y+h-(3*8), x+(3*8), y+h, 0, 6, 3, 9, null);
g.drawImage(img, x+3*8,y,x+w-(3*8), y+(3*8), 3, 0, 6, 3, null);
g.drawImage(img, x+3*8,y+(3*8),x+w-(3*8), y+h-(3*8), 3, 3, 6, 6, null);
g.drawImage(img, x+(3*8),y+h-(3*8), x+w-(3*8), y+h, 3, 6, 6, 9, null);
g.drawImage(img, x+w-(3*8),y,x+w, y+(3*8), 6, 0, 9, 3, null);
g.drawImage(img, x+w-(3*8),y+(3*8), x+w, y+h-(3*8), 6, 3, 9, 6, null);
g.drawImage(img, x+w-(3*8),y+h-(3*8), x+w, y+h, 6, 6, 9, 9, null);
g.setFont(FontFileHandler.Tahooey);
if(text.equals("CREDITS")){
g.drawString("Lead Developer: Tahooey",x+(4*8),y+(4*8));
g.drawString("Music By: Tahooey",x+(4*8),y+(5*8)+2);
g.drawString("Textures By: Tahooey",x+(4*8),y+(6*8)+4);
g.drawString("Help with Coding: DeathJockey",x+(4*8),y+(7*8)+6);
g.drawString("(c) TheOnlyTahooey Games",x+(4*8),y+(32*8)+32);
}else if(text.equals("HELP")){
g.drawString("Controls: Up : w",x+(4*8),y+(4*8));
g.drawString(" Down : s",x+(4*8),y+(5*8)+2);
g.drawString(" Left : a",x+(4*8),y+(6*8)+4);
g.drawString(" Right : d",x+(4*8),y+(7*8)+6);
g.drawString(" Turn Music Off : o",x+(4*8),y+(8*8)+8);
g.drawString(" EDIT MODE",x+(4*8),y+(9*8)+10);
g.drawString(" Toggle Blocks : Left",x+(4*8),y+(10*8)+12);
g.drawString(" and Right Arrows",x+(4*8),y+(11*8)+14);
g.drawString(" Toggle Maps: 1 & 2",x+(4*8),y+(12*8)+16);
//g.drawString(" Change Map Block",x+(4*8),y+(13*8)+18);
//g.drawString(" Destination: 3 & 4",x+(4*8),y+(14*8)+20);
g.drawString("Goal: Defeat the Enemies (Soon)",x+(4*8),y+(19*8)+30);
g.drawString("and Don't die (Soon)",x+(4*8),y+(20*8)+32);
}else if(text.equals("CONTACT")){
g.drawString("Please report Bugs to me on",x+(4*8),y+(4*8)+2);
g.drawString("Twitter @Tahooey",x+(4*8),y+(5*8)+4);
}else{
g.drawString(text, x+(4*8),y+(4*8));
}
b.run(g);
if(b.isClicked){
closed=true;
}
}
} |
d6cebe6c-2984-473d-8db8-f69b2389db8c | 7 | private JSONArray readArray(boolean stringy) throws JSONException {
JSONArray jsonarray = new JSONArray();
jsonarray.put(stringy ? readString() : readValue());
while (true) {
if (probe) {
log("\n");
}
if (!bit()) {
if (!bit()) {
return jsonarray;
}
jsonarray.put(stringy ? readValue() : readString());
} else {
jsonarray.put(stringy ? readString() : readValue());
}
}
} |
dc1f02c3-4d60-41aa-8228-08763702db01 | 6 | synchronized public void start(int number_of_threads){
// start the number of threads concurrently that have been given to the initial start
if(_recordings.size() > 0){
// check that the recordings to download is larger than the number of threads to initial start with
// if it is smaller then there is no reason to use more threads than there are downloads :)
if(_recordings.size() < number_of_threads){
number_of_threads = _recordings.size();
}
for(int i = 0; i < number_of_threads; i++){
Recording recording = _recordings.get(i);
GetRecording video = new GetRecording(_client, this, recording);
// Give the download thread a name and generate a random number so all download thread are unique
video.setName(THREADNAME + _rnd.nextInt(RANDOMBOUNDARY));
LOG.debug("Created new thread for download with name: " + video.getName());
// start the thread with the newly generated name for the download
video.start();
numberOfRunningThreads++;
LOG.debug("New Thread Started successfully");
// loop over all recordings in the _trackkeeper to find the recording for which we just started a download thread
// and remove it from the list so the list will eventually be empty.
Iterator<Recording> it = _trackkeeper.iterator();
LOG.debug("Trying to find the recording we started a thread for in the internal ist of recordings");
while(it.hasNext()){
Recording rec = it.next();
if(rec.getId().equals(recording.getId()) && rec.getType() == recording.getType()){
it.remove();
LOG.debug("Found the recording and successfully deleted it from the list");
break;
}
}
}
}
} |
8b76ab38-1f1f-4627-8c32-8366353e1e15 | 1 | public long read2bytes() throws IOException {
long b0 = read();
long b1 = read();
if (le)
return b0 | (b1 << 8);
else
return b1 | (b0 << 8);
} |
0dbcd05f-c935-4083-a30d-f9349e305720 | 4 | public ScoreBoardCon() {
scores = new ArrayList<Score>();
// Sets the path to the users current working directory/save/highscores.save
fs = System.getProperty("file.separator");
path = Paths.get(System.getProperty("user.dir") + fs + "save" + fs + "highscores.save");
File file = new File(path.toString());
// If the file already exists, load it.
if(file.exists()) {
try {
load();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
84020fb5-cabd-40a3-a516-057d6638efdf | 5 | @Override
public Exam create(Exam toCreate) {
try (Connection con = getConnection();
PreparedStatement insertExam = con.prepareStatement(queryInsertExam, new String[]{columnExamId});
PreparedStatement insertQuestion = con.prepareStatement(queryInsertQuestion, new String[]{columnQuestionId});
PreparedStatement insertAnswer = con.prepareStatement(queryInsertAnswer, new String[]{columnAnswerId})) {
con.setAutoCommit(false);
insertExam.setNString(1, toCreate.getSubject().getId());
insertExam.setNString(2, toCreate.getName());
insertExam.execute();
String examId;
try (ResultSet generatedKeysExam = insertExam.getGeneratedKeys();) {
generatedKeysExam.next();
examId = generatedKeysExam.getString(1);
}
for (Question question : toCreate.getQuestions()) {
insertQuestion.setNString(1, examId);
insertQuestion.setNString(2, question.getText());
insertQuestion.execute();
String questionId;
try (ResultSet questionRS = insertQuestion.getGeneratedKeys()) {
questionRS.next();
questionId = questionRS.getString(1);
}
for (Answer answer : question.getAnswers()) {
insertAnswer.setNString(1, questionId);
insertAnswer.setNString(2, answer.getText());
insertAnswer.setInt(3, answer.getIsCorrect() ? 1 : 0);
insertAnswer.execute();
}
}
con.commit();
con.setAutoCommit(true);
} catch (SQLIntegrityConstraintViolationException integrityConstraintException) {
/*
Exam name is only unique value for exam except id. So in case of
such exception exam name is appended by time in millis and creation is retried.
Looks like hack, but no need for more complex solution now.
*/
logger.error("Exam with name '{}' already exists.", toCreate.getName());
logger.error("Retry with datetime appended to exam name.");
String datetime = com.yakovchuk.sphinx.util.DateUtil.getCurrentDateTime();
return create(new Exam.Builder(toCreate)
.name(toCreate.getName() + " " + datetime)
.build());
} catch (SQLException e) {
logger.error("Failed to create exam {}", toCreate);
throw new SphinxSQLException(e);
}
return toCreate;
} |
96e7392e-1c67-44ad-848d-8fffcdbd7b58 | 0 | public BodyPart getBodypart(){
return bodypart;
} |
9b61a004-ce5f-4ccb-83ec-c82bf37cd298 | 5 | public static Field parseField(String raw) {
if (Strings.isEmpty(raw) || !raw.contains(": ")) {
return null;
}
Builder fieldBuilder = new Builder();
String[] partArray = raw.split(":");
// I originally used a For Each, but that requires hacky access to the internal field in the Builder which is a bit hacky.
for (int i = 0; i <= partArray.length - 1; i++) {
if (i == 0) {
fieldBuilder.name(partArray[i].trim());
} else {
// If we are dealing with a value that had colons in it, replace them.
fieldBuilder.value((i > 1 ? ":" : "") + partArray[i].trim());
}
}
return fieldBuilder.build();
} |
3afb92d9-3c4b-42b8-86f1-e6ef61db85bf | 8 | public void intersection(SFormsFastMapDirect map) {
for (int i = 2; i >= 0; i--) {
FastSparseSet<Integer>[] lstOwn = elements[i];
if (lstOwn.length == 0) {
continue;
}
FastSparseSet<Integer>[] lstExtern = map.elements[i];
int[] arrnext = next[i];
int pointer = 0;
do {
FastSparseSet<Integer> first = lstOwn[pointer];
if (first != null) {
FastSparseSet<Integer> second = null;
if (pointer < lstExtern.length) {
second = lstExtern[pointer];
}
if (second != null) {
first.intersection(second);
}
if (second == null || first.isEmpty()) {
lstOwn[pointer] = null;
size--;
changeNext(arrnext, pointer, pointer, arrnext[pointer]);
}
}
pointer = arrnext[pointer];
}
while (pointer != 0);
}
} |
ac00477a-de24-49d0-bf6f-8bd2a3b86cc6 | 4 | private void preciomedicamentosFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_preciomedicamentosFieldKeyTyped
// TODO add your handling code here:
if (!Character.isDigit(evt.getKeyChar()) && evt.getKeyChar() !='.' && !Character.isISOControl(evt.getKeyChar()))
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
}
if(preciomedicamentosField.getText().length() == 5)
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
JOptionPane.showMessageDialog(this, "Precio de medicamento demadiado grande.", "ADVERTENCIA", WIDTH);
}
}//GEN-LAST:event_preciomedicamentosFieldKeyTyped |
831050cc-bc4f-436a-b4de-716e5382f40b | 7 | public InfoNode Add(int key, String value, Node node){
if(node instanceof LeafNode){
if(((LeafNode) node).size < BPlusTreeIntToString60.maxDegree + 1){
node.add(key, value);
return null;
}
else{
return SplitLeaf(key,value,node);
}
}
if(node instanceof InternalNode){
for(int i = 1; i <= node.getSize();i++ ){
if(key < ((InternalNode)node).keys[i]){
InfoNode tempInfo = Add(key, value, ((InternalNode)node).children[i-1]);
if(tempInfo == null){
return null;
}
else{
return dealWithPromote(tempInfo,node);
}
}
}
InfoNode tempInfo = Add(key, value, ((InternalNode)node).children[node.getSize()]);
if(tempInfo == null){
return null;
}
else{
return dealWithPromote(tempInfo,node);
}
}
return null;
} |
5b48ff39-8c9f-4d84-92a0-a08a9bd13d56 | 6 | private String DELETE_Request(String url, String url_params) {
StringBuffer response;
String json_data = "";
HttpsURLConnection con = null;
try {
// url = "https://selfsolve.apple.com/wcResults.do";
// url_params = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// URL obj = new URL(url);
// con = (HttpsURLConnection) obj.openConnection();
con = (HttpsURLConnection) set_headers(url);
con.setDoOutput(true);
con.setRequestMethod("DELETE");
con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
// con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(url_params);
wr.flush();
wr.close();
System.out.println(url_params);
System.out.println(con.getResponseCode());
if (con.getResponseCode() == 500)
System.out.println(con.getErrorStream());
if (con.getResponseCode() == 201) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
json_data = response.toString();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
} catch (Exception e) {
con.getErrorStream();
}
return json_data;
} |
1e8cd83d-bf7d-446f-a9a7-2649e4b8dab9 | 7 | public void keyReleased(KeyEvent e)
{
int code = e.getKeyCode();
if(code == P)
{
keyP = false;
}
if(code == R1 || code == R2)
{
rightKey = false;
}
if (code == L1 || code == L2)
{
leftKey = false;
}
if (code == U1 || code == U2)
{
upKey = false;
}
} |
12f48ef4-2f9d-40b6-870c-a715569a58e7 | 9 | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
String PlayerName;
if(args.length != 2){
sender.sendMessage("/addowner <ChannelName> <PlayerName>");
return true;
}
String ChanName = args[0].toLowerCase();
if (player != null) {
PlayerName = player.getName().toLowerCase();
} else {
PlayerName = "Console";
}
List<String> ChowList = plugin.getStorageConfig().getStringList(ChanName+".owner");
if (player == null || ChowList.contains(PlayerName) && player.hasPermission("scc.admin")) {
String AddPlayName = plugin.myGetPlayerName(args[1]).toLowerCase();
boolean ChanTemp = plugin.getStorageConfig().contains(ChanName);
if(ChanTemp == false) {
plugin.NotExist(sender, ChanName);
return true;
} else {
if (ChowList.contains(AddPlayName)) {
sender.sendMessage(plugin.DARK_RED+"[SCC] "+plugin.GOLD + AddPlayName + plugin.DARK_RED + " already has owner access to " + plugin.GOLD + ChanName);
return true;
} else {
ChowList.add(AddPlayName); // add the player to the list
plugin.getStorageConfig().set(ChanName+".owner", ChowList); // set the new list
sender.sendMessage(plugin.DARK_GREEN+"[SCC] "+plugin.GOLD+ AddPlayName + plugin.DARK_GREEN + " added to " + plugin.GOLD + ChanName + "'s" + plugin.DARK_GREEN + " owner list");
Player target = plugin.getServer().getPlayer(AddPlayName);
if(target != null) { target.sendMessage(plugin.DARK_GREEN+"[SCC] "+"You have been added to " + plugin.GOLD + ChanName + "'s" + plugin.DARK_GREEN + " owner list"); }
plugin.saveStorageConfig();
return true;
}
}
} else {
plugin.NotOwner(sender, ChanName);
return true;
}
} |
aec129aa-db2b-4782-8e28-63ab4101584a | 5 | public static Pair<String> minmax(String[] a)
{
if (a == null || a.length == 0) return null;
String min = a[0];
String max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<String>(min, max);
} |
aff9ca1e-62e2-4521-a309-935cdd34bfff | 0 | public String getChargeTermid() {
return ChargeTermid;
} |
85553488-ad74-40a1-b1df-b4b669516a45 | 7 | protected boolean renewPoints() {
int points = ctx.summoning.points();
for (GameObject obelisk : ctx.objects.select().id(OBELISK).within(20).first()) {
if (ctx.camera.prepare(obelisk) && obelisk.interact("Renew")) {
Timer t = new Timer(10000);
while (t.running()) {
if (ctx.players.local().inMotion()) {
t.reset();
}
if (ctx.camera.pitch() < 80) {
ctx.camera.pitch(Random.nextInt(80, 101));
}
if (ctx.summoning.points() > points) {
options.status = "Recharged at obelisk";
script.log.info(options.status);
script.summoningTask.nextPoints = Random.nextInt((int) (options.beastOfBurden.requiredPoints() * 1.5), (int) (options.beastOfBurden.requiredPoints() * 2.33));
Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return ctx.players.local().idle();
}
}, 250, 10);
ctx.sleep(500);
return true;
}
ctx.sleep(500);
}
}
}
return false;
} |
6467490e-f853-4fb8-9c01-66dc71028ede | 0 | public void setEmailType(String emailType) {
this.emailType = emailType;
} |
23a6ac86-05b6-4d5b-9beb-2f1283957997 | 7 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking, tickID))
return false;
if(ticking instanceof MOB)
{
final MOB mob=(MOB)ticking;
if((mob.amFollowing()==null)||(mob.amFollowing().isMonster())||(!CMLib.flags().isInTheGame(mob.amFollowing(), true)))
{
if(mob.getStartRoom()==null)
mob.destroy();
else
if(mob.getStartRoom() != mob.location())
CMLib.tracking().wanderAway(mob, false, true);
return false;
}
}
return true;
} |
84ab744d-fafa-4a6c-94af-198c7f0e2ab1 | 4 | public static Hashtable<Integer, Double> GrowthContains(int start, int range, int averageCount)
{
Random rnd = new Random();
Hashtable<Integer, Double> NTable = new Hashtable<Integer, Double>();
//Go through the range
for (int n = start; n < range+1; n+=500)
{
int warm = 0;
while (warm < 10000)
{ warm++; /*Let the thread warm up.*/ System.nanoTime(); }
//Take the average algorithm time at range r
long algorithmTime = 0;
for (int a = 0; a < averageCount; a++)
{
//Timing
ArrayBasedCollection<Integer> arr = new ArrayBasedCollection<Integer>();
arr.addAll(ascendingInts(n));
int elemLoc = rnd.nextInt(arr.size-1);
Integer element = arr.get(elemLoc);
long warmUptime = System.nanoTime();
//Run the algorithm
arr.contains(element);
long containsTime = System.nanoTime();
//OVERHEAD
for(int i = 1; i<elemLoc; i++){
}
long overHead = System.nanoTime();
//Calculate time
algorithmTime += (containsTime - warmUptime) - (overHead - containsTime);
}
System.out.println(n + "\t" + (double) algorithmTime/averageCount);
NTable.put(n ,(double) (algorithmTime/averageCount));
}
return NTable;
} |
8e8a899b-ecbf-4950-aa7b-d90a8b22d811 | 6 | public boolean moveActorIfPossible(Actor actor, GridPoint destination) {
int x = destination.getColumn();
int y = destination.getRow();
if (y < 0 || y >= this.height || x < 0 || x >= this.width) {
return false;
}
Tile currentTile = this.tiles[y][x];
if (currentTile.isImpassable()) {
return false;
}
if (currentTile.getOccupant() == null) {
GridPoint oldLocation = actor.getLocation();
Tile oldTile = this.tiles[oldLocation.getRow()][oldLocation.getColumn()];
oldTile.setOccupant(null);
currentTile.setOccupant(actor);
actor.updateLocation(x, y);
return true;
}
return false;
} |
50b824ef-d660-4b65-9e9d-29b8efedc047 | 5 | public Component getTableCellRendererComponent
(JTable table, Object value, boolean selected, boolean focused, int row, int column)
{
setEnabled(table == null || table.isEnabled());
if(column==0) {
setHorizontalAlignment(SwingConstants.CENTER);
setForeground(null);
setBackground(null);
}
else {
setHorizontalAlignment(SwingConstants.RIGHT);
for (int i=0;i<highlightIndex.size(); i++) {
if(row == ((Integer)highlightIndex.elementAt(i)).intValue()) {
setForeground(Color.blue);
break;
}
else
setForeground(null);
}
if (row == flashIndex) {
setBackground(Color.orange);
}
else
setBackground(null);
}
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
return this;
} |
f2c359c5-632a-4824-9d45-8800cc2a668e | 3 | public Map<String,String> parseArguments(String[] argv) {
Map<String, String> optionsValueMap = new HashMap<String, String>();
fileNameArguments = new ArrayList<String>();
for (int i = 0; i < argv.length; i++) { // Cannot use foreach, need i
Debug.println("getopt", "parseArg: i=" + i + ": arg " + argv[i]);
char c = getopt(argv); // sets global "optarg"
if (c == DONE) {
fileNameArguments.add(argv[i]);
} else {
optionsValueMap.put(Character.toString(c), optarg);
// If this arg takes an option, must arrange here to skip it.
if (optarg != null) {
i++;
}
}
}
return optionsValueMap;
} |
25bd5900-ce45-4195-b987-45d37751b788 | 3 | @Override
public void KeybindTouched(KeybindEvent e) {
if(e.getKeybind().equals(Keybind.CONFIRM) && e.getKeybind().clicked()) {
if(textFill < getLength()) {
textFill = getLength();
setSize(getWidth((int) textFill + 1), getHeight((int) textFill + 1));
removeTimeListener(timeListener);
}
}
} |
fd094901-863a-4fd4-8844-51609757f369 | 9 | public int[] oneTrainIn(){
/*if(eventIndex>numF1){
//System.out.println("!!!Error @ an unexperienced event RECORDED BY SEQUENCE LEARNER!!!");
return null;
}
curSeqWeight.add(new Double(tho));
curSeq.add(new Integer(eventIndex));
tho-=v;*/
/*if(curSeq.size()<startIndex){
return null;
}*/
int winner=findWinnerPartial();
if(winner==-2){
return new int[]{-1};
}
if(winner==-1){
this.emptyAccumulated();
return null;
}
double[][] winnerCode=new double[numF1][maxIdEvents];
for(int i=0;i<numF1;i++){
System.arraycopy(weight[winner][i],0, winnerCode[i], 0, maxIdEvents);
}
/* System.out.println("Print won weights---"+winner);
for(int i=0;i<weight[winner].length;i++){
for(int j=0;j<weight[winner][i].length;j++){
System.out.print(weight[winner][i][j]+"\t");
}
System.out.println("");
}
System.out.println("");*/
Vector<Integer> winnerSeq=new Vector<Integer>(0);
double maxWeight=0;
int maxEvent_1=-1;
int maxEvent_2=-1;
do{
for(int i=0;i<numF1;i++){
for(int j=0;j<this.maxIdEvents;j++){
if(maxWeight<winnerCode[i][j]){
maxWeight=winnerCode[i][j];
maxEvent_1=i;
maxEvent_2=j;
}
}
}
if(maxWeight>0){
winnerSeq.add(new Integer(maxEvent_1));
winnerCode[maxEvent_1][maxEvent_2]=0;
maxWeight=0;
maxEvent_1=-1;
maxEvent_2=-1;
}
else{
break;
}
}while(true);
int[] learnSeq=new int[winnerSeq.size()];
for(int i=0;i<learnSeq.length;i++){
learnSeq[i]=winnerSeq.get(i).intValue();
}
emptyAccumulated();
return learnSeq;
} |
013688ce-25f4-4e48-a948-6d8c5a5e3972 | 7 | public String getTargetTypeName(int targetType)
{
Integer targetTypeKey = getTargetTypeKey(targetType);
if (null == targetTypeKey)
{
return "UNKNOWN TYPE 0x" + Integer.toHexString(targetType);
}
switch(targetTypeKey.intValue())
{
case TARGET_TYPE__SKILL_REGENERATION: return "SKILL_REGENERATION";
case TARGET_TYPE__SKILL_DISARM_TRAP: return "SKILL_DISARM_TRAP";
case TARGET_TYPE__SKILL_DARKELF_ABILITY: return "SKILL_DARKELF_ABILITY";
case TARGET_TYPE__SKILL_VAMPIRE_ABILITY: return "SKILL_VAMPIRE_ABILITY";
case TARGET_TYPE__SKILL_DRAGON_ABILITY: return "SKILL_DRAGON_ABILITY";
case TARGET_TYPE__ROSTER_CHARACTER: return "ROSTER_CHARACTER";
default:
return super.getTargetTypeName(targetType);
}
} |
4e19f189-ad6f-4f38-b2ae-ab166572d6df | 1 | public AnimationData(int frameCount, long frameDelay, float initialX, float initialY, float frameW, float frameH) {
this.frames = new ArrayList<FrameData>();
for(int i = 0; i < frameCount; i++) {
frames.add(new FrameData(initialX+i*frameW, initialY, frameW, frameH));
}
this.currentFrame = 0;
this.frameDelay = frameDelay;
this.onCurrentFrame = 0;
} |
9eb1543a-2ca7-45fc-ae17-0da9fbf60731 | 3 | private void setModDownloads() {
String downloadModList = util.getModDownloads();
dlModList = downloadModList.split(";");
con.log("Log","Downloadable mods found... " + dlModList.length);
lblModDlCounter.setText("Downloadable mod Count: " + dlModList.length);
if(tglbtnNewModsFirst.isSelected()){
for(int i=dlModList.length-1; i>-1; i--){
addModDownloadToModel(i);
}
}
else {
for(int i=0; i<dlModList.length; i++){
addModDownloadToModel(i);
}
}
} |
17c58557-eb91-43b4-a0b6-ad5e2dd84978 | 0 | @Id
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator")
@Column(name = "person_id")
public int getPersonId() {
return personId;
} |
1940efe6-f457-4224-8f5e-0c2efbb473d6 | 2 | public int turn(Turn.direction dir) {
switch (dir) {
case LEFT:
return (this.direction + 5) % 6;
case RIGHT:
return (this.direction + 1) % 6;
default:
return -1;
}
} |
66f1faa7-f989-490f-bdaf-1052e6430235 | 7 | public void setPoints() {
if (x2 - x > sizeX * cspc2 && this == sim.getDragElm()) {
setSize(2);
}
int hs = cspc;
int x0 = x + cspc2;
int y0 = y;
int xr = x0 - cspc;
int yr = y0 - cspc;
int xs = sizeX * cspc2;
int ys = sizeY * cspc2;
rectPointsX = new int[]{xr, xr + xs, xr + xs, xr};
rectPointsY = new int[]{yr, yr, yr + ys, yr + ys};
setBbox(xr, yr, rectPointsX[2], rectPointsY[2]);
int i;
for (i = 0; i != getPostCount(); i++) {
Pin p = pins[i];
switch (p.side) {
case SIDE_N:
p.setPoint(x0, y0, 1, 0, 0, -1, 0, 0);
break;
case SIDE_S:
p.setPoint(x0, y0, 1, 0, 0, 1, 0, ys - cspc2);
break;
case SIDE_W:
p.setPoint(x0, y0, 0, 1, -1, 0, 0, 0);
break;
case SIDE_E:
p.setPoint(x0, y0, 0, 1, 1, 0, xs - cspc2, 0);
break;
}
}
} |
4bd5e4cb-2e77-42b8-a45b-eb642d36c6c6 | 3 | public void generatePif(List<pif> p, String filename) {
FileWriter outputStream = null;
try {
outputStream = new FileWriter(filename);
for (pif f : p) {
outputStream.write(f.code + " " + f.positionST + " ("
+ f.token + ")\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
c623d23a-1399-4a2f-8195-88f694207015 | 7 | boolean isSystemObjectTypeObjectSetUsesDifferent(SystemObjectTypeProperties property, SystemObjectType systemObjectType) {
final NonMutableSet nonMutableSet = systemObjectType.getNonMutableSet("Mengen");
final List<SystemObject> directObjectSetUses = nonMutableSet.getElementsInVersion(systemObjectType.getConfigurationArea().getModifiableVersion());
// Mengenverwendungen ermitteln
final List<ConfigurationSet> objectSetUses = new ArrayList<ConfigurationSet>();
for(Object object : property.getAtgAndSet()) {
if(object instanceof ConfigurationSet) {
objectSetUses.add((ConfigurationSet)object);
}
}
// Anzahl überprüfen
if(objectSetUses.size() != directObjectSetUses.size()) return true;
// Elemente überprüfen
for(ConfigurationSet configurationSet : objectSetUses) {
final String objectSetName = configurationSet.getObjectSetName();
ObjectSetUse checkObjectSetUse = null;
for(SystemObject systemObject : directObjectSetUses) {
ObjectSetUse objectSetUse = (ObjectSetUse)systemObject;
if(objectSetName.equals(objectSetUse.getObjectSetName())) {
checkObjectSetUse = objectSetUse;
break;
}
}
if(isObjectSetUseDifferent(configurationSet, checkObjectSetUse)) return true;
}
return false;
} |
9025a2df-b485-45fe-8219-aa5b37f8c7e2 | 4 | public static List<Integer> maxProfitPoint(int[] prices, int a, int b) {
List<Integer> res = new ArrayList<Integer>();
if (a == b) {res.add(a); res.add(a); res.add(0);return res;}
int profit = 0;
int min = a;
int minp = a, maxp = a;
for(int i = a; i < b; i++) {
if (profit < prices[i] - prices[min]) {profit = prices[i] - prices[min]; maxp = i; minp = min;}
if (prices[min] > prices[i]) {min = i;}
}
res.add(minp); res.add(maxp); res.add(profit);
return res;
} |
964ee620-45b9-489a-91ee-23691dd5d7b0 | 3 | private void addListeners()
{
newItem.setMnemonic(KeyEvent.VK_N);
newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
newItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
createFrame();
}
});
closeItem.setMnemonic(KeyEvent.VK_W);
closeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
closeItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
desktop.getSelectedFrame().setClosed(true);
}
catch(java.beans.PropertyVetoException v) {}
offsetMultiplier -= 1;
}
});
closeAllItem.setMnemonic(KeyEvent.VK_W);
closeAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK+ActionEvent.SHIFT_MASK));
closeAllItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JInternalFrame[] frame;
frame = desktop.getAllFrames();
for(int i=0;i<frame.length;i++)
{
try
{
frame[i].setClosed(true);
}
catch(java.beans.PropertyVetoException v) {}
}
offsetMultiplier = 0;
}
});
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
helpItem.setMnemonic(KeyEvent.VK_F1);
helpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1,0));
helpItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFrame help = new JFrame("Help");
JPanel panel = new JPanel();
JLabel help_text = new JLabel();
help_text.setFont(font);
help_text.setText("... --- ...");
help.setLayout(new BorderLayout());
panel.add(help_text);
help_text.setAlignmentX(JComponent.CENTER_ALIGNMENT);
help.add(panel);
help.setPreferredSize(new Dimension(600,600));
help.pack();
help.setVisible(true);
}
});
authorItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
MyAvatar avatar = new MyAvatar();
JFrame author = new JFrame("Author");
JPanel panel = new JPanel();
JLabel author_text = new JLabel("Application Programming Class");
author.setLayout(new BorderLayout());
panel.add(author_text);
author_text.setAlignmentX(JComponent.CENTER_ALIGNMENT);
author.add(panel,BorderLayout.NORTH);
author.add(avatar,BorderLayout.CENTER);
author.setPreferredSize(new Dimension(600,600));
author.pack();
author.setVisible(true);
}
}
);
} |
6211580a-4c6e-43c4-9272-773daad6009b | 8 | private void doExecuteScript(final Resource scriptResource) {
if (scriptResource == null || !scriptResource.exists())
return;
TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
transactionTemplate.execute(new TransactionCallback() {
@SuppressWarnings("unchecked")
public Object doInTransaction(TransactionStatus status) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String[] scripts;
try {
scripts = StringUtils.delimitedListToStringArray(stripComments(IOUtils.readLines(scriptResource
.getInputStream())), ";");
}
catch (IOException e) {
throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
}
for (int i = 0; i < scripts.length; i++) {
String script = scripts[i].trim();
if (StringUtils.hasText(script)) {
try {
jdbcTemplate.execute(script);
}
catch (DataAccessException e) {
if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
logger.debug("DROP script failed (ignoring): " + script);
}
else {
throw e;
}
}
}
}
return null;
}
});
} |
96801eff-33cf-4542-9ba0-c87d5cb03b72 | 5 | private void processDeleteMaster(Sim_event ev)
{
if (ev == null) {
return;
}
Object[] obj = (Object[]) ev.get_data();
if (obj == null)
{
System.out.println(super.get_name() +
".processDeleteMaster(): master file name is null");
return;
}
String name = (String) obj[0]; // get file name
Integer resID = (Integer) obj[1]; // get resource id
int msg = DataGridTags.CTLG_DELETE_MASTER_SUCCESSFUL;
try
{
ArrayList list = (ArrayList) catalogueHash_.get(name);
if (list.size() == 1)
{
int event = DataGridTags.CTLG_DELETE_MASTER;
sendMessageToHighLevelRC(name, event);
if (waitingMasterDeletes_ == null) {
waitingMasterDeletes_ = new ArrayList();
}
waitingMasterDeletes_.add(obj);
}
else
{
msg = DataGridTags.CTLG_DELETE_MASTER_REPLICAS_EXIST;
sendMessage(name, DataGridTags.CTLG_DELETE_MASTER_RESULT, msg,
resID.intValue() );
}
}
catch (Exception e)
{
System.out.println(super.get_name() +
".processDeleteMaster(): exception error");
}
} |
5200071c-f891-4450-9611-1226ee1502e4 | 5 | @Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("bungeeutils.admin")) {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + plugin.messages.get(EnumMessage.NOPERM)).create());
return;
}
if (args.length == 0) {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.AQUA + "Usage: " + ChatColor.YELLOW + "/maintenance toggle").create());
return;
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("toggle")) {
boolean status = this.handleMaintenance();
if (status) {
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.GREEN + "Maintenance has been enabled on all servers!").create());
return;
}
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.RED + "Maintenance has been disabled on all servers!").create());
return;
}
sender.sendMessage(new ComponentBuilder("").append(plugin.prefix + ChatColor.AQUA + "Usage: " + ChatColor.YELLOW + "/maintenance toggle").create());
}
} |
b4bab3c7-79d2-4409-a861-33c0f0ed3755 | 0 | public String[] getArgs(String[] args)
{
String[] a = new String[args.length - 1];
System.arraycopy(args, 1, a, 0, a.length);
return a;
} |
f423235c-7101-4a37-a4f5-b17c8b7e2942 | 3 | public UInt64 readUInt64() {
byte[] bytes = new byte[8];
for(int i = 0; i < 8; i++) {
try {
bytes[i] = this.readByte();
} catch (IOException e) {
Client.logger.Log(e);
}
}
UInt64 value = new UInt64((byte)0);
try {
value = new UInt64(bytes);
} catch (InvalidUIntException e) {
Client.logger.Log(e);
}
return value;
} |
99ea5a2f-8f70-4ccf-9cdd-8625abc01a42 | 1 | public void testWithFieldAdded2() {
Partial test = createHourMinPartial();
try {
test.withFieldAdded(null, 0);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20);
} |
b931d34a-13b9-47a6-bfa9-e82ed3fb8e3a | 2 | private boolean isNotReady()
{
return closed || !initialized || listener == null;
} |
8c2d6ec2-8a51-44cd-b250-51edcc40c46e | 2 | public ArrayList<Rod> getMaximumRevenueRods(int totalLength, ArrayList<Rod> rodList) {
rods = new ArrayList<Rod>(rodList);
// sort rods by price length ratio
rods = RodCuttingCommon.getInstance().sortByPriceLengthRatio(rods);
// greedy add rods until sum of selected rods length not > total length
int currentLength = 0;
int index = 0;
ArrayList<Rod> selectedRods = new ArrayList<Rod>();
while (index < rods.size()) {
Rod rod = rods.get(index);
if (rod.getLength() + currentLength <= totalLength) {
selectedRods.add(new Rod(rod.getIndex(), rod.getLength(), rod.getPrice()));
currentLength += rod.getLength();
}
else {
index++;
}
}
return selectedRods;
} |
bd2a8c64-04a8-47b2-9f5d-3a8af89d3967 | 2 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(this.jTextField1.getText().isEmpty()){
Error np = new Error(this,true);
np.ready("Debe ingresar su nombre de usuario");
np.setVisible(true);
}
else{
if(this.jPasswordField1.getText().isEmpty()){
Error np = new Error(this,true);
np.ready("Debe ingresar su contraseña");
np.setVisible(true);
}
else{
Operador.Menu mn = new Operador.Menu();
mn.setVisible(true);
}
}
}//GEN-LAST:event_jButton1ActionPerformed |
37425920-b30e-46ef-b2ec-73cfa2ea10ff | 2 | public static void handleEpgQueryReply(HTSMsg msg, HTSPClient client) {
Collection<String> requiredFields = Arrays.asList(new String[]{"query"});
if (msg.keySet().containsAll(requiredFields)){
//TODO
} else if (msg.get("error") != null){
//TODO
} else{
System.out.println("Faulty reply");
}
} |
e5f8bb3c-affb-4239-a1b1-d1a5b56155e6 | 2 | public static String secondsToMinutes(int time) {
if (time < 0)
return null;
int minutes = (time / 60) % 60;
String minutesStr = (minutes < 10 ? "0" : "") + minutes;
return new String(minutesStr);
} |
0b77409e-33b9-4361-b8ea-2b24e49b8866 | 7 | @EventHandler
public void WitherJump(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.Jump.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.Jump.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, plugin.getWitherConfig().getInt("Wither.Jump.Time"), plugin.getWitherConfig().getInt("Wither.Jump.Power")));
}
}
} |
31ec00be-6fc3-4edc-a8dd-91c937d4b0a1 | 3 | public static MyUnits unmarshal(String filepath)
{
MyUnits lengthUnits = null;
try
{
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(Launcher.SCHEMA_LOC+Launcher.SCHEMA1_NAME));
lengthUnits = (MyUnits)Factory.loadInstance(new FileInputStream(filepath), schema, MyUnits.class);
}
catch (FileNotFoundException e)
{
System.out.println("! File not found ! "+e.getMessage());
}
catch (JAXBException e)
{
System.out.println(e.getCause());
System.out.println("! JAXB Exception ! "+e.getMessage());
}
catch (SAXException e)
{
System.out.println("! SAX Exception ! "+e.getMessage());
}
return lengthUnits;
} |
ff93cde2-bba8-404b-9c5c-9f8ca445a7b6 | 8 | @SuppressWarnings("incomplete-switch")
@Override
public void fkActionEvent(FkActionEvent event) {
//System.out.println( "Event data:"+ event.data );
MessageBox dialog;
Boolean closeSelf=false;
switch(event.type)
{
case ACTION_ABORTED:
txtBUSYMSG.setText(Messages.NewAccountDialog_55);
dialog = new MessageBox(shlNewAccount, SWT.ICON_WARNING);
dialog.setText(Messages.NewAccountDialog_56);
dialog.setMessage(Messages.NewAccountDialog_57);
dialog.open();
updatePage(FkNewAccStep.REVIEW);
break;
case ACTION_ERROR:
txtBUSYMSG.setText(Messages.NewAccountDialog_58);
dialog = new MessageBox(shlNewAccount, SWT.ICON_ERROR);
dialog.setText(Messages.NewAccountDialog_59);
dialog.setMessage(Messages.NewAccountDialog_60);
dialog.open();
closeSelf=true;
break;
case ACTION_OKAY:
txtBUSYMSG.setText(Messages.NewAccountDialog_61);
dialog = new MessageBox(shlNewAccount, SWT.ICON_INFORMATION);
dialog.setText(Messages.NewAccountDialog_62);
dialog.setMessage(Messages.NewAccountDialog_63);
dialog.open();
closeSelf=true;
break;
case ACTION_WAITING:
txtBUSYMSG.setText(Messages.NewAccountDialog_64);
break;
case ACTION_WORKING:
txtBUSYMSG.setText(Messages.NewAccountDialog_65);
animation.setVisible(false);
break;
case STATE_ERROR:
txtBUSYMSG.setText(Messages.NewAccountDialog_0);
dialog = new MessageBox(shlNewAccount, SWT.ICON_ERROR);
dialog.setText(Messages.NewAccountDialog_1);
dialog.setMessage(Messages.NewAccountDialog_2);
dialog.open();
closeSelf=true;
break;
}
if( !shlNewAccount.isDisposed() && closeSelf )
{
shlNewAccount.close();
}
} |
f6134d27-48d0-4adb-aebf-48dc986b0d88 | 6 | @Override
protected void toXMLImpl(XMLStreamWriter out, Player player,
boolean showAll, boolean toSavedGame)
throws XMLStreamException {
// Start element:
out.writeStartElement(getXMLElementTagName());
// Add attributes:
out.writeAttribute(ID_ATTRIBUTE, getId());
out.writeAttribute("tile", getTile().getId());
if (type != null && (showAll || toSavedGame)) {
out.writeAttribute("type", getType().toString());
}
if (name != null && (showAll || toSavedGame)) {
out.writeAttribute("name", name);
}
// End element:
out.writeEndElement();
} |
12ebb4bf-d4a1-4fbf-b130-3f626245b03f | 8 | protected EToolsSearchResponse handleResponse(HttpResponse response, EToolsSearchResponse value, Context context) throws IOException {
if (response.getStatusLine().getStatusCode() != 200)
throw new IOException("status is not OK");
Document doc;
{
InputStream in = response.getEntity().getContent();
doc = Jsoup.parse(response.getEntity().getContent(), null, "");
in.close();
}
if (doc.title().equalsIgnoreCase("Access Banned"))
throw new IOException("access banned");
if (doc.title().equalsIgnoreCase("Access Denied"))
throw new IOException("access denied");
if (value == null) {
value = new EToolsSearchResponse();
value.requestedQuery = this.query;
value.requestedResultCount = this.resultCount;
try {
context.setParamAsString("jsessionid", MultiRequest.extractCookies(response.getFirstHeader("Set-Cookie").getValue()).get("JSESSIONID"));
} catch (Exception e) {}
}
for (Element element : doc.getElementsByClass("record")) {
try {
Result result = new Result();
result.title = element.children().get(0).text();
result.link = element.children().get(0).attr("href");
result.snippet = element.children().get(1).text();
value.results.add(result);
} catch (Exception e) {}
if (value.results.size() >= this.resultCount) {
context.complete();
break;
}
}
return value;
} |
739a44d9-b84f-4ae8-98b6-d8543bc7e160 | 5 | public String listarSeriales() {
String Recorrer_seriales = "";
try {
ResultSet list_SER = ele.consultarSeriales(datos_elemento);
String colorEstado = "";
String iconoEstado = "";
String nomFuncion = "";
while (list_SER.next()) {
Recorrer_seriales += "<tr>";
Recorrer_seriales += "<td><center>" + list_SER.getString("Seriales").toString().trim() + "</center></td>";
if (list_SER.getString("Estado").toString().trim().equals("Disponible")) {
colorEstado = "success";
iconoEstado = "ok-circle";
nomFuncion = "Estado_disponible(" + '"' + list_SER.getString("Seriales").toString().trim() + '"' + ")";
} else if (list_SER.getString("Estado").toString().trim().equals("No disponible")) {
colorEstado = "danger";
iconoEstado = "remove-circle";
nomFuncion = "Estado_noDisponible(" + '"' + list_SER.getString("Seriales").toString().trim() + '"' + ")";
} else if (list_SER.getString("Estado").toString().trim().equals("Prestamo")) {
colorEstado = "info";
iconoEstado = "ban-circle";
nomFuncion = "Estado_noDisponible(" + '"' + list_SER.getString("Seriales").toString().trim() + '"' + ")";
}
Recorrer_seriales += " <td><div id='cambio_est'><button class='btn btn-" + colorEstado + " glyphicon glyphicon-" + iconoEstado + "' onclick ='" + nomFuncion + "'></button></center></div></td>";
Recorrer_seriales += "</tr>";
}
} catch (Exception e) {
Recorrer_seriales = "error" + e.getMessage();
}
return Recorrer_seriales;
} |
a327e1cc-4d89-4d63-961f-13f15bcc54ef | 4 | public static Document getDocumentByQuery(String query){
String youdao = "fanyi.youdao.com";
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false);
HttpHost targetHost = new HttpHost(youdao);
query = query.replace(" ", "%20");
HttpGet httpget = new HttpGet("/openapi.do?keyfrom=Sam-Su&key=1825873072&type=data&doctype=xml&version=1.1&q=" + query);
httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");
httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
HttpResponse response = null;
InputStream content = null;
HttpEntity entity = null;
Document doc = null;
try {
response = httpclient.execute(targetHost, httpget);
if(response != null){
entity = response.getEntity();
}
if(entity != null){
content = entity.getContent();
}
if(content != null){
doc = DocumentHelper.getDocument(content);
}
} catch (Exception e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
return doc;
} |
ee50af5d-d942-4991-aaa0-2a63f5993a03 | 6 | public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} |
e1690e1a-6e94-4672-8fd4-2ca4d76bd66b | 2 | public ResultSet validate(String email, String password) {
ResultSet res = null;
try {
// hash password with SHA1 algorithm
String hashPass = makeSHA1Hash(password);
String query = "SELECT * FROM customer where email=? and password=?";
stmnt = CONN.prepareStatement(query);
// Bind Parameters
stmnt.setString(1, email);
stmnt.setString(2, hashPass);
res = stmnt.executeQuery();
} catch (SQLException ex) {
handleSqlExceptions(ex);
} catch (NoSuchAlgorithmException nsae){}
return res;
} |
4ac01413-ccbf-48c5-98b6-98c6a7de5584 | 4 | public synchronized int baseNumberPreMRna(int pos) {
int count = 0;
for (Exon eint : sortedStrand()) {
if (eint.intersects(pos)) {
// Intersect this exon? Calculate the number of bases from the beginning
int dist = 0;
if (isStrandPlus()) dist = pos - eint.getStart();
else dist = eint.getEnd() - pos;
// Sanity check
if (dist < 0) throw new RuntimeException("Negative distance for position " + pos + ". This should never happen!\n" + this);
return count + dist;
}
count += eint.size();
}
return -1;
} |
1e2b7fe7-599d-4d2e-9c9b-8c3f463f557b | 1 | public void test_getValue_long() {
assertEquals(0, iField.getValue(0L));
assertEquals(12345678 / 90, iField.getValue(12345678L));
assertEquals(-1234 / 90, iField.getValue(-1234L));
assertEquals(INTEGER_MAX / 90, iField.getValue(LONG_INTEGER_MAX));
try {
iField.getValue(LONG_INTEGER_MAX + 1L);
fail();
} catch (ArithmeticException ex) {}
} |
80120418-c9dd-4164-95e3-3cbf655f332a | 6 | public static String replace(String in, String match, String replacement) {
// check for null refs
if (in == null || match == null || replacement == null) {
return in;
}
StringBuffer out = new StringBuffer();
int matchLength = match.length();
int inLength = in.length();
for (int i = 0; i < inLength; i++) {
int upperSearhLimit = i + matchLength;
if ((upperSearhLimit <= inLength) && (in.substring(i,upperSearhLimit).equals(match))) {
out.append(replacement);
i = upperSearhLimit - 1;
} else {
out.append(in.charAt(i));
}
}
return out.toString();
} |
00a182ff-33ff-43ef-ae52-9adef77da807 | 1 | private void updateHC() {
if (this.hoveredClassroom != null) {
this.name.setText(this.hoveredClassroom.getName());
this.type.setText(this.hoveredClassroom.getType().getShortName() + " (" + this.hoveredClassroom.getType().getName() + ")");
this.eff.setText(((Integer)(this.hoveredClassroom.getEffectif())).toString());
}
else {
this.name.setText("");
this.type.setText("");
this.eff.setText("");
}
} |
ed263c76-b1cd-46de-8010-16ac5e53cb9c | 2 | public TLValue resolve(String var) {
TLValue value = variables.get(var);
if(value != null) {
// The variable resides in this scope
return value;
}
else if(!isGlobalScope()) {
// Let the parent scope look for the variable
return parent.resolve(var);
}
else {
// Unknown variable
return null;
}
} |
173642cd-e439-49d2-907b-694add763fcb | 8 | public void doit( String finp, String sheetnm )
{
WorkBookHandle book = new WorkBookHandle( finp );
WorkSheetHandle sheet = null;
try
{
sheet = book.getWorkSheet( sheetnm );
WorkSheetHandle[] handles = book.getWorkSheets();
ChartHandle[] charts = book.getCharts();
for( int i = 0; i < charts.length; i++ )
{
System.out.println( "Found Chart: " + charts[i] );
}
sheet.add( Integer.valueOf( 4 ), "A4" );
sheet.add( Integer.valueOf( 5 ), "A5" );
sheet.add( Integer.valueOf( 14 ), "B4" );
sheet.add( Integer.valueOf( 15 ), "B5" );
sheet.add( Integer.valueOf( 24 ), "C4" );
sheet.add( Integer.valueOf( 25 ), "C5" );
try
{
ct = book.getChart( "Test Chart" );
}
catch( ChartNotFoundException e )
{
System.out.println( e );
}
sheet.add( new Float( 103.256 ), "F23" );
sheet.add( Integer.valueOf( 125 ), "G23" );
if( ct.changeSeriesRange( "Sheet1!C23:E23", "Sheet1!C23:G23" ) )
{
;
}
System.out.println( "Successfully Changed Series Range!" );
sheet.add( "D", "F24" );
sheet.add( "E", "G24" );
if( ct.changeCategoryRange( "Sheet1!C24:E24", "Sheet1!C24:G24" ) )
{
;
}
System.out.println( "Successfully Changed Categories Range!" );
if( ct.changeTextValue( "Category X", "Widget Class" ) )
{
;
}
System.out.println( "Successfully Changed Categories Label!" );
if( ct.changeTextValue( "Value Y", "Sales Totals" ) )
{
;
}
System.out.println( "Successfully Changed Values Label!" );
ct.setTitle( "New Chart Title!" );
System.out.println( "Chart Name: " + ct );
foutpath = finp + "output.xls";
// Copy the worksheet
book.copyWorkSheet( "Sheet2", "SheetNEW" );
// Copy the Chart
try
{
book.copyChartToSheet( "New Chart Title!", "SheetNEW" );
}
catch( Exception e )
{
System.out.println( e );
}
testWrite( book, foutpath );
WorkBookHandle b2 = new WorkBookHandle( foutpath );
}
catch( WorkSheetNotFoundException e )
{
System.out.println( e );
}
} |
05f50c80-3733-44aa-9f9b-ed5960b3fe51 | 2 | public static void main(String[] args) throws IOException, ClassNotFoundException {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),vlcLibraryPath);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
player = new EmbeddedAudioPlayer(vlcLibraryPath);
frame.add(player.getPanel());
frame.setTitle("twat frame");
frame.setVisible(true);
panel.add(label);
frame.add(panel);
player.prepareMediaWithDuration("src/XMLBits/RunWithUs.mp3", 30, 5, false);
play = new JButton("PLAY");
stop = new JButton("STOP");
pause = new JButton("PAUSE");
loop = new JButton("NO LOOPING");
volume = new JSlider();
/**
* setup play button listener
*/
play.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
player.playMedia();
}
});
/**
* setup stop button listener
*/
stop.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
player.stopMedia();
}
});
/**
* setup pause button listener
*/
pause.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
player.pauseMedia();
}
});
/**
* setup loop button listener
*/
loop.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(!player.getLooping()) {
player.setLooping(true);
loop.setText("LOOPING");
}
else if(player.getLooping()) {
player.setLooping(false);
loop.setText("NOT LOOPING");
}
}
});
/**
* setup volume slider listener
*/
volume.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
player.setVolumePercentage(volume.getValue());
}
});
panel.add(play);
panel.add(pause);
panel.add(stop);
panel.add(loop);
volume.setBounds(0, 100, 100, 10);
panel.add(volume);
musicThread.start();
} |
e291428d-526e-4d09-9c1e-0d214b9a7097 | 4 | @RequestMapping("queryDeptById")
@ResponseBody
public SystemResponse<Department> queryDeptById(HttpServletRequest request, HttpServletResponse response)
{
SystemResponse<Department> result = new SystemResponse<Department>();
String deptId = request.getParameter("deptId");
String isCacheString = request.getParameter("isCache");
boolean isCache = false;
if (null == deptId || "".equals(deptId))
{
System.out.println("Department ID is NULL!");
result.setRetrunCode("99");
return result;
}
if (null != isCacheString && "true".equals(isCacheString))
{
isCache = true;
}
Department dept = new Department();
dept.setDeptId(Integer.valueOf(deptId));
dept = DepartmentDao.queryDept(dept, isCache);
List<Department> depts = new ArrayList<Department>(1);
depts.add(dept);
result.setList(depts);
result.setRetrunCode("00");
return result;
} |
4af37c73-339c-4ee5-9bee-919af1372ddf | 6 | public void reload() {
if (this.maxAmmo > 0) {
if (this.currentAmmo < this.maxCurrentAmmo) {
if (this.maxCurrentAmmo - this.currentAmmo > this.maxAmmo) {
this.currentAmmo += this.maxAmmo;
this.decreaseAmmo(this.maxAmmo);
SoundEffect.GUNRELOAD.play();
if (this.currentAmmo > 0) this.canShot = true;
}
else if (this.maxCurrentAmmo - this.currentAmmo <= this.maxAmmo) {
this.decreaseAmmo(this.maxCurrentAmmo - this.currentAmmo);
this.currentAmmo += this.maxCurrentAmmo - this.currentAmmo;
SoundEffect.GUNRELOAD.play();
if (this.currentAmmo > 0) this.canShot = true;
}
}
}
else SoundEffect.CANTSHOOT.play();
} |
f0c42755-4498-42c3-8b82-208a49c93bdf | 9 | public void store() {
// needed to create a store() method different from the one in
// Properties class to store configurations, in order to not lose
// commented out lines from config file
BufferedReader br = null;
StringBuilder confString = new StringBuilder();
try {
br = new BufferedReader(new FileReader(configFile));
String line;
for (; (line = br.readLine()) != null;) {
confString.append(line + "\n");
}
} catch (FileNotFoundException e) {
// remote.cfg doesn't exist yet: create this file using template
// from resources.files package
try {
configFile.createNewFile();
} catch (IOException e1) {
System.err
.println(RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.RemoteResourcesConfiguration_Error_ConfigFileError));
return;
}
confString = ResourcesLoader
.getFileResourceContent("template_remote.cfg");
} catch (IOException e) {
System.err
.println(RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.RemoteResourcesConfiguration_Error_StoreGenericError));
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err
.println(RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.RemoteResourcesConfiguration_Error_StoreGenericError));
}
}
}
for (String configuration : configurations.stringPropertyNames()) {
String newConfigLine = configuration + " = "
+ configurations.getProperty(configuration);
Matcher m = Pattern.compile(
"(#?)" + configuration + "\\s*=\\s*(\\w*)").matcher(
confString);
if (m.find()) {
confString.replace(0, confString.length(),
m.replaceAll(newConfigLine));
} else { // if configuration was not present in config file
confString.append("\n" + newConfigLine);
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(configFile));
bw.write(confString.toString());
bw.close();
} catch (IOException e) {
System.err
.println(RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.RemoteResourcesConfiguration_Error_UnableToStore));
}
} |
c71819ea-fd4f-4397-8b20-c1d46569419d | 2 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
String date = request.getParameter("date"); // format must be yyyy-mm-dd
String state = request.getParameter("state");
String minormax = request.getParameter("minormax"); //must be 'min' or 'max'
String temperature = "";
if (minormax.equalsIgnoreCase("min")) {
temperature = MongoDBAPI.getMinTemperature(date, state);
} else if (minormax.equalsIgnoreCase("max")) {
temperature = MongoDBAPI.getMaxTemperature(date, state);
}
out.print(temperature);
} |
927ebdef-9b0c-4c07-9318-fd65e702b0a9 | 1 | private void initialize() {
this.setBounds(100, 100, 800, 600);
sourceImagePanel = new JPanel();
sourceImagePanel.setBounds(10, 30, 293, 447);
getContentPane().add(sourceImagePanel);
imageSourceLabel = new JLabel("");
sourceImagePanel.add(imageSourceLabel);
imageSourceLabel.setIcon(new ImageIcon(imageResource));
resultImagePanel = new JPanel();
resultImagePanel.setBounds(481, 30, 293, 447);
getContentPane().add(resultImagePanel);
imageResultLable = new JLabel("");
resultImagePanel.add(imageResultLable);
JButton btnProcess = new JButton("Process");
btnProcess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
BufferedImage bufferedImage = ImageUtil
.getBufferedImage(imageResource);
BufferedImage bufferedResult = converter
.process(bufferedImage);
ImageUtil.convertToImage(IMAGE_RESULT, bufferedResult);
imageResultLable.setIcon(new ImageIcon(IMAGE_RESULT));
update();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
btnProcess.setBounds(346, 79, 89, 23);
getContentPane().add(btnProcess);
update();
} |
738b0e53-4675-4c82-8d72-5a82c6cbd518 | 9 | public static boolean comienza(String baseDeDatos, String entrada) {
/* ENTRADA DE DATOS */
String[] cadena;
StringTokenizer tokenizerBD = new StringTokenizer(baseDeDatos, " ");
int cantTokensBD = tokenizerBD.countTokens();
StringTokenizer tokenizerEntrada = new StringTokenizer(entrada, " ");
int cantTokensEntrada = tokenizerEntrada.countTokens();
if (cantTokensEntrada == 0) {
return true;
} else if (cantTokensEntrada == 1) {
boolean encontrado = false;
for (int j=0; j<cantTokensBD && !encontrado; j++) {
if (tokenizerBD.nextToken().toUpperCase().startsWith(entrada.trim().toUpperCase()) ) {
encontrado = true;
}
}
return encontrado;
} else {
boolean encontrado = false;
cadena = new String[cantTokensBD];
for (int i=0; i<cantTokensBD; i++) {
cadena[i] = new String(tokenizerBD.nextToken());
}
for (int j=0; j<(cadena.length-1) && !encontrado; j++) {
String aux = "";
for (int k=j; k<cadena.length; k++) {
aux += cadena[k]+" ";
}
encontrado = aux.toUpperCase().startsWith(entrada.trim().toUpperCase());
}
return encontrado;
}
} |
fcfec858-e4c8-4429-8dcd-f4f73e70edb3 | 5 | public void initialise(World world) throws PatternFormatException
{
String[] cellParts = cells.split(" ");
for (int i=0;i<cellParts.length;i++)
{
char[] currCells = cellParts[i].toCharArray();
for (int j=0;j<currCells.length;j++)
{
if (currCells[j] != '1' && currCells[j] != '0') throw new PatternFormatException("Error: incorrect format of cell description");
if (currCells[j] == '1') world.setCell(j+startCol,i+startRow,true);
}
}
} |
99cfa4f7-b6b0-45c5-88cd-353a036b31aa | 4 | public static byte[] TripleDES_Decrypt(byte[] data,byte[][] keys)
{
int i;
byte[] tmp = new byte[data.length];
byte[] bloc = new byte[8];
K = generateSubKeys(keys[0]);
K1 = generateSubKeys(keys[1]);
K2 = generateSubKeys(keys[2]);
for (i = 0; i < data.length; i++) {
if (i > 0 && i % 8 == 0) {
bloc = encrypt64Bloc(bloc,K2, true);
bloc = encrypt64Bloc(bloc,K1, false);
bloc = encrypt64Bloc(bloc,K, true);
System.arraycopy(bloc, 0, tmp, i - 8, bloc.length);
}
if (i < data.length)
bloc[i % 8] = data[i];
}
bloc = encrypt64Bloc(bloc,K2, true);
bloc = encrypt64Bloc(bloc,K1, false);
bloc = encrypt64Bloc(bloc,K, true);
System.arraycopy(bloc, 0, tmp, i - 8, bloc.length);
tmp = deletePadding(tmp);
return tmp;
} |
333d0059-9248-44d9-ad42-cd151eb3936b | 6 | @Override
public void deserialize(Buffer buf) {
memberId = buf.readInt();
if (memberId < 0)
throw new RuntimeException("Forbidden value on memberId = " + memberId + ", it doesn't respect the following condition : memberId < 0");
rank = buf.readShort();
if (rank < 0)
throw new RuntimeException("Forbidden value on rank = " + rank + ", it doesn't respect the following condition : rank < 0");
experienceGivenPercent = buf.readByte();
if (experienceGivenPercent < 0 || experienceGivenPercent > 100)
throw new RuntimeException("Forbidden value on experienceGivenPercent = " + experienceGivenPercent + ", it doesn't respect the following condition : experienceGivenPercent < 0 || experienceGivenPercent > 100");
rights = buf.readUInt();
if (rights < 0 || rights > 4294967295L)
throw new RuntimeException("Forbidden value on rights = " + rights + ", it doesn't respect the following condition : rights < 0 || rights > 4294967295L");
} |
f06c0c55-443f-4d6a-854e-981ecab62c3d | 3 | public void visitClassType(final String name) {
if (type != TYPE_SIGNATURE || state != EMPTY) {
throw new IllegalStateException();
}
CheckMethodAdapter.checkInternalName(name, "class name");
state = CLASS_TYPE;
if (sv != null) {
sv.visitClassType(name);
}
} |
0f65b484-11be-44f0-9151-2dec13fee1aa | 0 | public static IBomber buildBomber(int number, int bombs, Match match, String projectFolder) throws IOException {
ProcessBuilder pb = new ProcessBuilder(projectFolder + "/run.sh", Integer.toString(number), Integer.toString(Game.PORT_NO));
Map<String, String> env = pb.environment();
env.put("PATH", System.getenv("PATH"));
pb.directory(new File(projectFolder));
pb.redirectErrorStream(true);
Process process = pb.start();
IBomber bomb = new Bomber(number, bombs, match, projectFolder);
bomb.setMyProcess(process);
return bomb;
} |
8691f4a3-5790-4dd4-9bb4-162f242a0e6d | 1 | public void runJob() {
try {
JobOperator jo = BatchRuntime.getJobOperator();
long jobId = jo.start("eod-sales", new Properties());
System.out.println("Started job: with id: " + jobId);
} catch (JobStartException ex) {
ex.printStackTrace();
}
} |
ddc7d49e-872f-4075-950b-0582ffdf4b81 | 0 | public String getDescription() {
return description;
} |
30211420-2deb-4bca-bb75-98da68627852 | 5 | public usb.core.Device getDevice (String portId)
throws IOException
{
// hack to work with hotplugging and $DEVICE
// /proc/bus/usb/BBB/DDD names are unstable, evil !!
if (portId.startsWith("usb-@0x")) {
String wanted_busnumstr = portId.substring(7);
int wanted_busnum = Integer.parseInt(wanted_busnumstr,16);
if(trace) {
System.out.println("getDevice() looking up port: " + portId);
}
synchronized (busses) {
Enumeration e = busses.keys ();
while (e.hasMoreElements ()) {
USB bus = (USB) busses.get (e.nextElement ());
if (wanted_busnum == bus.getBusNum ())
return bus.getDevice (1);
else if (trace) {
System.out.println("Host.getDevice(" + Integer.toHexString(wanted_busnum)
+ ") skipping: " +
Integer.toHexString(bus.getBusNum ()));
}
}
}
}
return null;
} |
3828e729-a6c4-431f-80b8-45c18d6365cc | 8 | static double dijsktra(int d,int h,double[][] mAdy){
int n=mAdy.length;double[] sol=new double[n];
boolean[] visitados=new boolean[n];
PriorityQueue<double[]> cola=new PriorityQueue<double[]>(n,new Comparator<double[]>(){
public int compare(double[] o1,double[] o2){
if(o1[0]<o2[0])return -1;
if(o1[0]>o2[0])return 1;
if(o1[1]<o2[1])return -1;
if(o1[1]>o2[1])return 1;
return 0;
}
});
Arrays.fill(sol,Double.POSITIVE_INFINITY);sol[d]=0;
visitados[d]=true;cola.add(new double[]{0,d});
for(;!cola.isEmpty();) {
double[] u=cola.poll();
int p=(int)u[1];
visitados[p]=true;
for(int v=0;v<n;v++)
if(!visitados[v]&&sol[v]>sol[p]+mAdy[p][v])
cola.add(new double[]{sol[v]=sol[p]+mAdy[p][v],v});
}
return sol[h];
} |
e39f5c11-c477-46bc-b102-849db05b12f5 | 9 | public void do_interrupt(int ID) {
System.out.println("Interrupt");
if (is_bit_set(7, 0xb)) {
switch (ID) {
// RB0 Interrupt
case 1:
if (is_bit_set(4, 0xb)) {
STACK.add(getProgrammCounter());
setProgramCounter(4);
set_Bit(1, 0xb);
}
System.out.println("RB0 Interrupt");
break;
// Timer Interrupt
case 2:
if (is_bit_set(5, 0xb)) {
STACK.add(getProgrammCounter());
setProgramCounter(4);
set_Bit(2, 0xb);
}
break;
// Port B Interrupt
case 3:
if (is_bit_set(3, 0xb)) {
STACK.add(getProgrammCounter());
setProgramCounter(4);
set_Bit(0, 0xb);
}
System.out.println("RB4-7 Interrupt");
break;
// EEPROM Interrupt
case 4:
if (is_bit_set(6, 0xb)) {
STACK.add(getProgrammCounter());
setProgramCounter(4);
}
break;
}
}
} |
310926d7-04c9-4eaa-b0b3-a847623f8ee2 | 1 | @Test
public void testBadRange() throws Exception {
final Properties config = new Properties();
final String min_uptime = "2000";
final String max_uptime = "200";
config.setProperty("min_uptime", min_uptime);
config.setProperty("max_uptime", max_uptime);
final ConnectionProcessor proc = new MockConnectionProcessor();
try {
final Filter f = new DisconnectFilter(proc, config);
} catch (RuntimeException e) {
Assert.assertTrue(e.getMessage().indexOf(min_uptime) != -1);
Assert.assertTrue(e.getMessage().indexOf(max_uptime) != -1);
}
} |
6d11b6e7-aa83-4a4c-843b-c2957a3354a6 | 3 | @Override
public boolean acceptsDraggableObject(DraggableObject object)
{
if(object instanceof DraggableObjectEntity)
{
DraggableObjectEntity fileobj = ((DraggableObjectEntity)object);
if(fileobj.uuid != null)
{
if(!fileobj.uuid.trim().equals(""))
return true;
}
}
return false;
} |
c15078a7-18e2-46db-a0fe-275ad3a02f9c | 5 | public void setSubtotalRow(String countType, int rid, double[] subtotal, HSSFWorkbook workbook, HSSFSheet sheet) {
HSSFRow row = sheet.createRow(rid);
for (int k = 0; k < 10; k++) {
try {
switch (k) {
case 3:
excelUtils.setCellValue(subtotal[0], workbook, k, row, cellStyle.cellFontBoldBorderStyle);// 原币
break;
case 4:
excelUtils.setCellValue(subtotal[1], workbook, k, row, cellStyle.cellFontBoldBorderStyle);// 原币
break;
case 5:
excelUtils.setCellValue(subtotal[2], workbook, k, row, cellStyle.cellFontBoldBorderStyle);// 原币
break;
default:
excelUtils.setCellValue(null, workbook, k, row, cellStyle.cellFontBoldBorderStyle);// 其它赋空
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
sheet.addMergedRegion(new CellRangeAddress(rid, rid, 0, 2));// 合并单元格
HSSFCell cell = row.getCell(0);
cell.setCellValue(countType);
cell.setCellStyle(cellStyle.cellFontBoldCenterBorderStyle);// 样式赋给单元格
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.