text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Description getFunctional()
{
Description tRequirements = new Description();
for(Property tProp : this) {
if(tProp != null) {
if(!(tProp instanceof NonFunctionalRequirementsProperty)) {
tRequirements.set(tProp);
}
}
}
return tRequirements;
} | 3 |
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(button.getText().equals("Stop Play Record")){
player.stopThread();
interf.deleteMyWindowListener();
button.setText("Start Play Record");
if(Optiums.DISABLES_BUTTONS)
buttonRecorder.setEnabled(true);
}else{
if(Optiums.DISABLES_BUTTONS)
buttonRecorder.setEnabled(false);
File fileDir = new File(edit.getText() +"." + Optiums.FILE_TYPE.toString().toLowerCase());
if(fileDir.exists()){
try {
player = new Player(fileDir, button, buttonRecorder);
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
edit.setText("Something go wrong.");
if(Optiums.DISABLES_BUTTONS)
buttonRecorder.setEnabled(true);
}
player.start(interf.DataSourthForDiagram(player));
button.setText("Stop Play Record");
}else{
edit.setText("Wrong directory.");
if(Optiums.DISABLES_BUTTONS)
buttonRecorder.setEnabled(true);
}
}
} | 7 |
public Object[] compileToClassFiles(String source,
String sourceLocation,
int lineno,
String mainClassName)
{
Parser p = new Parser(compilerEnv, compilerEnv.getErrorReporter());
ScriptOrFnNode tree = p.parse(source, sourceLocation, lineno);
String encodedSource = p.getEncodedSource();
Class<?> superClass = getTargetExtends();
Class<?>[] interfaces = getTargetImplements();
String scriptClassName;
boolean isPrimary = (interfaces == null && superClass == null);
if (isPrimary) {
scriptClassName = mainClassName;
} else {
scriptClassName = makeAuxiliaryClassName(mainClassName, "1");
}
Codegen codegen = new Codegen();
codegen.setMainMethodClass(mainMethodClassName);
byte[] scriptClassBytes
= codegen.compileToClassFile(compilerEnv, scriptClassName,
tree, encodedSource,
false);
if (isPrimary) {
return new Object[] { scriptClassName, scriptClassBytes };
}
int functionCount = tree.getFunctionCount();
ObjToIntMap functionNames = new ObjToIntMap(functionCount);
for (int i = 0; i != functionCount; ++i) {
FunctionNode ofn = tree.getFunctionNode(i);
String name = ofn.getFunctionName();
if (name != null && name.length() != 0) {
functionNames.put(name, ofn.getParamCount());
}
}
if (superClass == null) {
superClass = ScriptRuntime.ObjectClass;
}
byte[] mainClassBytes
= JavaAdapter.createAdapterCode(
functionNames, mainClassName,
superClass, interfaces, scriptClassName);
return new Object[] { mainClassName, mainClassBytes,
scriptClassName, scriptClassBytes };
} | 9 |
public DataTag load()
{
DataTag tag = null;
try
{
final ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
tag = (DataTag) in.readObject();
in.close();
}
catch (final Exception i)
{
if (!i.getClass().equals(EOFException.class))
{
System.err.println("Exception: " + i.getClass().getName());
i.printStackTrace();
}
}
return tag == null ? new DataTag() : tag;
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MerchantsFollowed other = (MerchantsFollowed) obj;
if (merId != other.merId)
return false;
if (mfId != other.mfId)
return false;
if (uId != other.uId)
return false;
return true;
} | 6 |
public LinkedList<Video> searchVideos(LinkedList<Pair<String, String>> whereClauses,
LinkedList<String> whereConjunctions, char order) throws SQLException {
LinkedList<String> select = new LinkedList<String>();
select.add("*");
LinkedList<String> from = new LinkedList<String>();
from.add("Videos");
Pair<String, LinkedList<String>> orderBy;
if (order == 'a') {
orderBy = new Pair<String, LinkedList<String>>("Year", new LinkedList<String>());
} else if (order == 'b') {
orderBy = new Pair<String, LinkedList<String>>(
"(SELECT AVG(Score) FROM Reviews WHERE Reviews.ISBN = Videos.ISBN)", new LinkedList<String>());
} else {
orderBy = new Pair<String, LinkedList<String>>(
"(SELECT AVG(Score) FROM Reviews, Trusts WHERE IsTrusted = 1 AND Trustee = Reviewer AND " +
"Reviews.ISBN = Videos.ISBN AND Truster = ?)", new LinkedList<String>());
orderBy.getValue().add(username);
}
String orderDirection = "DESC";
int limit = 0;
ResultSet resultSet = executeDynamicQuery(select, from, whereClauses, whereConjunctions, orderBy,
orderDirection, limit);
return videoListFromResultSet(resultSet);
} | 2 |
@Test
public void test_mult_skalar() {
int a = 2;
int b = 3;
int skalar = -4;
Matrix m1 = new MatrixArray(a,b);
Matrix m2 = new MatrixArray(a,b);
for(int i = 1; i <= a; i++){
for(int j = 1; j <= b; j++)
m1.insert(i, j, (double)(2*i-j));
}
for(int i = 1; i <= a; i++){
for(int j = 1; j <= b; j++)
m2.insert(i, j, (double)((2*i-j) * skalar));
}
//System.out.println(m2);
assertEquals(m2,m1.mul(skalar));
} | 4 |
private JPanel custtab() {
JPanel cust = new JPanel();
cust.setLayout(null);
JButton newcust, edcust, delcust, viewcust;
newcust = new JButton("New Customer");
edcust = new JButton("Edit Customer");
delcust = new JButton("Delete Customer");
viewcust = new JButton("View all Customers");
newcust.setBounds(100, 45, 200, 30);
edcust.setBounds(100, 85, 200, 30);
delcust.setBounds(100, 125, 200, 30);
viewcust.setBounds(100, 165, 200, 30);
newcust.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
new NewCustomer();
}
});
edcust.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
String accno = getaccno();
if (accno == null || accno.trim().length() == 0)
setVisible(true);
else {
ResultSet rs = query("select * from customer where accno = "
+ accno);
try {
if (!rs.next()) {
JOptionPane.showMessageDialog(null,
"Account does not exist with this No.", "",
JOptionPane.ERROR_MESSAGE);
setVisible(true);
} else
new EditCustomer(Integer.parseInt(accno), 0);
} catch (HeadlessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
delcust.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
String accno = getaccno();
if (accno == null || accno.trim().length() == 0)
setVisible(true);
else {
try {
ResultSet rs = query("select * from customer where accno = "
+ accno);
if (!rs.next()) {
JOptionPane.showMessageDialog(null,
"Account does not exist with this No.", "",
JOptionPane.ERROR_MESSAGE);
} else {
query("delete from customer where accno = " + accno);
JOptionPane.showMessageDialog(null, "Account : "
+ accno + " deleted");
}
setVisible(true);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
viewcust.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
new ViewFrame().viewFrame(0, 0, 1,username);
}
});
cust.add(newcust);
cust.add(edcust);
cust.add(delcust);
cust.add(viewcust);
return cust;
} | 9 |
@Override
public boolean getIsUniqueAttribute() {
return false;
} | 0 |
private void parseModuleConfig(String index, Element el)
{
NodeList nl = el.getElementsByTagName("Config");
Map<String,String> map = new HashMap<String,String>();
if(nl != null && nl.getLength() > 0)
{
for(int i = 0; i < nl.getLength(); i++)
{
Element el2 = (Element)nl.item(i);
if(el2.getAttribute("name") != null)
map.put(el2.getAttribute("name"),
el2.getFirstChild().getNodeValue());
}
}
cmp.put(index, map);
} | 4 |
public void methode1()
{
} | 0 |
@Override
protected void setPanelPerson(User u, boolean newUser) {
super.setPanelPerson(u, newUser);
btnSave.setEnabled(false);
if (newUser || u == null) {
// we don't want any rows selected
ListSelectionModel m = table.getSelectionModel();
m.clearSelection();
return;
}
tableModel.setRowSelect(u);
} | 2 |
@Override
public void addProperRoom(Room R)
{
if(R==null)
return;
if(!CMLib.flags().isSavable(this))
CMLib.flags().setSavable(R,false);
if(R.getArea()!=this)
{
R.setArea(this);
return;
}
synchronized(myRooms)
{
if(!myRooms.contains(R))
{
addProperRoomnumber(R.roomID());
Room R2=null;
for(int i=0;i<myRooms.size();i++)
{
R2=myRooms.elementAt(i);
if(R2.roomID().compareToIgnoreCase(R.roomID())>=0)
{
if(R2.ID().compareToIgnoreCase(R.roomID())==0)
myRooms.setElementAt(R,i);
else
myRooms.insertElementAt(R,i);
return;
}
}
myRooms.addElement(R);
}
}
} | 7 |
private static ParameterCode getParameterCode(String s) {
ParameterCode[] codes = ParameterCode.values();
for (ParameterCode c : codes) {
if (s.compareTo(c.toString()) == 0)
return c;
}
return ParameterCode.NO_CODE;
} | 2 |
public static void main(String[] args) {
int i = 0;
while( i <= 100 ) {
System.out.println("i = " + i);
i+=2; //i=i+2;
}
///////////////////////////////////////////////
i = 0;
while( i <= 100 ) {
if( i%2 == 0 )
System.out.println("i = " + i);
i++;
}
/////////////////////////////////////////
i = 0;
while( i <= 100 ) {
if( i%2 != 0 )
System.out.println("i = " + i);
i++;
}
i = 1;
while( i <= 100 ) {
System.out.println("i = " + i);
i+=2;
}
} | 6 |
private static boolean checkSignature(byte[] buffer) {
for(int i=0 ; i<SIGNATURE.length ; i++) {
if(buffer[i] != SIGNATURE[i]) {
return false;
}
}
return true;
} | 2 |
private HashMap<String,String> readQueryFromTable(HashMap<String,String> propertiesMap) {
List<HashMap<String,String>> propertiesMapList = transactionQueryHistoryDao.getTableProperties();
for(HashMap<String,String> map : propertiesMapList) {
QueryType queryType = QueryType.valueOf(map.get("queryType"));
String fromTime = map.get("timestamp").substring(0,10);
switch (queryType) {
case IDEA:
propertiesMap.put("query.idea.from_time", fromTime);
break;
case COMMENT:
propertiesMap.put("query.comment.from_time", fromTime);
break;
case REPLY:
propertiesMap.put("query.reply.from_time", fromTime);
break;
case TELL_A_FRIEND:
propertiesMap.put("query.tellafriend.from_time", fromTime);
break;
case REVIEW:
propertiesMap.put("query.review.from_time", fromTime);
break;
case EMAIL_HISTORY:
propertiesMap.put("query.emailhistory.from_time", fromTime);
break;
case TESTIMONIAL:
propertiesMap.put("query.testimonial.from_time", fromTime);
break;
}
}
return propertiesMap;
} | 8 |
protected void enableGUI() {
buildFieldRef();
for (JComponent elem : editableElements) {
if (elem != null) {
elem.setEnabled(true);
}
}
for (JTextComponent elem : editableTextFields) {
if (elem != null) {
elem.setEditable(true);
}
}
} | 4 |
private boolean edgeAndScheduleSelection(EvolvingGraph graph, Vector<Integer> tLBD){
Vector<Integer> arrivalTime = new Vector<Integer>();
boolean improved = false;
eMin = new Vector<Edge>(graph.getNumOfNodes());
tMin = new Vector<Integer>(graph.getNumOfNodes());
for (int i = 0; i < graph.getNumOfNodes(); i++){
eMin.add(i, null);
tMin.add(i, Integer.MAX_VALUE);
arrivalTime.add(i, tLBD.get(i));
}
for (Node node : graph.getNodes()){
if (tLBD.get(node.getId()) != Integer.MAX_VALUE){
for (Edge edge : node.getAdj()){
Integer newTime = edge.getNextDeparture(tLBD.get(node.getId()));
if (newTime != null) {
Node v = edge.getV();
if ( newTime + edge.getCost() < arrivalTime.get(v.getId())){
eMin.set(v.getId(), edge);
tMin.set(v.getId(), newTime);
arrivalTime.set(v.getId(), newTime + edge.getCost());
improved = true;
}
}
}
}
}
return improved;
} | 6 |
public static double countAdjacents(Board b)
{
int counter = 0;
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
if ( j < 3 && Board.canCombine(b.boardState[i][j], b.boardState[i][j+1])) {
counter++;
}
if ( i < 3 && Board.canCombine(b.boardState[i][j], b.boardState[i+1][j])) {
counter++;
}
}
}
return adjToScore(counter);
} | 6 |
public boolean Apagar(T obj) {
try {
manager.remove(manager.merge(obj));
return true;
} catch (Exception ex) {
return false;
}
} | 1 |
public String readUntil(String pattern) throws InterruptedException, IOException {
cnt=0;
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer buffer = new StringBuffer();
char ch = (char) dataIn.read();
String msg;
String broken[];
while (runner==1) {
buffer.append(ch);
msg=buffer.toString();
String chk=msg.trim();
String rtn=msgchk(chk,msg);
if (rtn != null){return rtn;}
if (ch == lastChar) {
if (buffer.toString().endsWith(pattern)) {
broken=msg.split(" ");
for (int i=0;i<broken.length;i++ ) {
if (broken[i].equals("gossips:")){
player=broken[i-1];
}
}
return player+"<4;2>0:"+buffer.toString();
}
if (buffer.toString().endsWith("telepaths:")) {
broken=msg.split(" ");
for (int i=0;i<broken.length;i++ ) {
if (broken[i].equals("telepaths:")){
player=broken[i-1];
}
}
GosLink2.gb.tele(player.trim().toLowerCase(),mynum);
}
}
ch = (char) dataIn.read();
}
return null;
} | 9 |
public RayIntersect fireRay(double x, double z, double angle){
double tan = math.tan(angle);
int MAX_LOOPS = (int)(Math.ceil(raycaster.getCamera().getViewDistance()) + 1);
RayIntersect vert = fireVerticleRay(x, z, angle, tan, MAX_LOOPS);
RayIntersect horiz = fireHorizontalRay(x, z, angle, tan, MAX_LOOPS);
boolean vertValid = validRay(vert);
boolean horizValid = validRay(horiz);
if(vertValid == false){
if(horizValid == true) {
return horiz;
}else{
return null;
}
}
if(horizValid == false){
return vert;
}
if(vert.getDistance() < horiz.getDistance()){
return vert;
}
return horiz;
} | 4 |
private static Node merge(Node odd, Node even) {
// Sentinel Node
Node list = new Node(0, null);
Node start = list;
while (odd != null || even != null) {
if (odd != null && even != null) {
if ((int)odd.getData() < (int)even.getData()) {
list.setNext(odd);
odd = odd.getNext();
list = list.getNext();
} else if ((int)odd.getData() > (int)even.getData()) {
list.setNext(even);
even = even.getNext();
list = list.getNext();
} else {
list.setNext(odd);
odd = odd.getNext();
list = list.getNext();
list.setNext(even);
even = even.getNext();
list = list.getNext();
}
} else if (odd != null) {
list.setNext(odd);
odd = odd.getNext();
list = list.getNext();
} else if (even != null) {
list.setNext(even);
even = even.getNext();
list = list.getNext();
}
}
return start;
} | 8 |
private void setupChoosableFontProperties() {
// Load fonts and add them to the combobox 'cbFonts'
String[] fontNames = parent.getParentView().getAvailableFonts();
for (String font : fontNames) {
this.cbFonts.addItem(font);
}
this.cbFonts.setSelectedItem(this.dss.getCurrentFont());
this.cbFonts.setEditable(false);
// Add Font styles
this.cbFontStyle.addItem("Plain");
this.cbFontStyle.addItem("Bold");
this.cbFontStyle.addItem("Italic");
if (this.dss.getCurrentFontStyle() == 0) {
this.cbFontStyle.setSelectedItem("Plain");
} else if (this.dss.getCurrentFontStyle() == 1) {
this.cbFontStyle.setSelectedItem("Bold");
} else if (this.dss.getCurrentFontStyle() == 2) {
this.cbFontStyle.setSelectedItem("Italic");
}
this.cbFontStyle.setEditable(false);
// Add Font sizes
for (int size = 8; size <= 72; size++) {
this.cbFontSize.addItem(size);
}
this.cbFontSize.setSelectedItem(this.dss.getCurrentFontSize());
this.cbFontSize.setEditable(false);
} | 5 |
void processAnnotations(Annotation[] annotations)
{
int sourceLoaderCount = 0;
int sourceCount = 0;
int prefixCount = 0;
int postfixCount = 0;
try
{
for (final Annotation annotation : annotations)
{
if (annotation instanceof AutoConfigLoader)
{
AutoConfigLoader annotation2 = (AutoConfigLoader)annotation;
pushSourceLoaderStack(annotation2.value());
++ sourceLoaderCount;
}
else if (annotation instanceof AutoConfigSource)
{
AutoConfigSource annotation2 = (AutoConfigSource)annotation;
pushSourceStack(annotation2.value());
++ sourceCount;
}
else if (annotation instanceof AutoConfigPrefix)
{
AutoConfigPrefix annotation2 = (AutoConfigPrefix)annotation;
pushPrefixStack(annotation2.value());
++ prefixCount;
}
else if (annotation instanceof AutoConfigPostfix)
{
AutoConfigPostfix annotation2 = (AutoConfigPostfix)annotation;
pushPostfixStack(annotation2.value());
++ postfixCount;
}
}
}
finally
{
_stackCountInfos.addLast(new StackCountInfo(sourceLoaderCount, sourceCount, prefixCount, postfixCount));
}
} | 5 |
public void setDisplayMode(int displaymode) {
this.pconnect.setDisplayMode(displaymode);
} | 0 |
public void run(String[] args) {
//---------------------------------------------------------------
// Parse arguments.
//---------------------------------------------------------------
CommandArgs cmd = new CommandArgs
(args, // arguments to parse
"CDR", // options without argument
"G", // options with argument
0,0); // no positional arguments
if (cmd.nErrors()>0) return;
String gramName = cmd.optArg('G');
if (gramName==null)
{
System.err.println("Specify -G grammar file.");
return;
}
SourceFile src = new SourceFile(gramName);
if (!src.created()) return;
//---------------------------------------------------------------
// Create PEG object from source file.
//---------------------------------------------------------------
PEG peg = new PEG(src);
if (peg.errors>0) return;
// System.out.println(peg.iterAt + " iterations for attributes.");
// System.out.println(peg.iterWF + " iterations for well-formed.");
if (peg.notWF==0)
System.out.println("The grammar is well-formed.");
//---------------------------------------------------------------
// Display as requested.
//---------------------------------------------------------------
if (cmd.opt('C'))
{
peg.compact();
peg.showAll();
}
else if (cmd.opt('D')) peg.showAll();
else if (cmd.opt('R')) peg.showRules();
} | 8 |
private String spaceString(int n) {
StringBuffer sbuf = new StringBuffer(n);
for (int i = 0; i < n; i++) {
sbuf.append(' ');
}
return sbuf.toString();
} | 1 |
public SimulatorView getSimulatorView()
{
return view;
} | 0 |
@Override
public void onMouseClicked(int x, int y, int button)
{
if(button == 0 && this.x <= x && x <= this.x+this.width && this.y <= y && y <= this.y+this.height)
this.clicks++;
super.onMouseClicked(x, y, button);
} | 5 |
public boolean findBid(Object objet, User seller){
Bid b = new Bid(new Date(), objet, seller, 0, 0);
if(bidList.indexOf(b) == -1)
return false;
else
return true;
} | 1 |
@Override
public int check(DiceSet diceSet) {
int points = 0;
Map<Integer, Integer> vals = new HashMap<Integer, Integer>();
for (int i = 0; i < diceSet.SIZE; ++i) {
int key = diceSet.getValue(i);
if (!vals.containsKey(key)) {
vals.put(key, 1);
}
else {
vals.put(key, vals.get(key) + 1);
}
}
if (vals.keySet().size() == 2) {
points = 25;
for (Integer key: vals.keySet()) {
if (vals.get(key) < 2) {
points = 0;
}
}
}
return points;
} | 5 |
@Test
public void test() {
byte[] data = new ProtoBuilder().array("foo", new String[]{"a", "b", "c"}, "bar").build();
Object result = new ProtoParser().parse(data).result();
if (result instanceof Object[]) {
for (Object obj :(Object[]) result) {
if (obj instanceof Object[]) {
for (Object d :(Object[]) obj) {
System.out.println("\t" + d);
}
} else {
System.out.println(obj);
}
}
}
} | 4 |
static public void writeLinesToFile(String filename, ArrayList<String> lines) {
File file = null;
try {
file = new File(filename);
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileWriter writer = new FileWriter(file);
for (String line : lines)
writer.write(line + "\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
public static String readLine() {
Scanner input = new Scanner(System.in);
String line = "";
if(input.hasNextLine()) {
line = input.nextLine();
} return line;
} | 1 |
public String toString() {
return "Person[name=" + ((name == null) ? "null" : name.toString()) +
", birth=" + ((birth == null) ? "null" : birth.toString()) + "]";
} | 2 |
private void validateBudgetChoice(String budget_choice) throws InvalidBudgetTypeException {
if(budget_choice != ANNUAL_BUDGET && budget_choice != MONTHLY_BUDGET) {
throw new InvalidBudgetTypeException("Invalid Budget Type.");
}
} | 2 |
public void addToLines(PathItem l) {
lines.add(l);
} | 0 |
public void specialAttack2() {
skill2.attack(this.getAgility(), this.getLuck());
} | 0 |
public void formTourList(SessionRequestContent request) throws ServletLogicException {
Criteria criteria = new Criteria();
criteria.addParam(DAO_ID_DIRECTION, request.getAttribute(JSP_ID_DIRECTION));
User user = (User) request.getSessionAttribute(JSP_USER);
if (user != null) {
criteria.addParam(DAO_USER_LOGIN, user.getLogin());
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
criteria.addParam(DAO_ROLE_NAME, type);
} else {
criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE));
}
Short tourStatus = getTourStatus(request);
if (tourStatus != null) {
criteria.addParam(DAO_TOUR_STATUS, tourStatus);
}
Short tourDateStatus = getTourDateStatus(request);
if (tourDateStatus != null) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
if (tourDateStatus == 1) {
criteria.addParam(DAO_TOUR_DATE_FROM, date);
} else if (tourDateStatus == 0) {
criteria.addParam(DAO_TOUR_DATE_TO, date);
}
}
try {
AbstractLogic tourLogic = LogicFactory.getInctance(LogicType.TOURLOGIC);
List<Tour> tours = tourLogic.doGetEntity(criteria);
request.setSessionAttribute(JSP_TOUR_LIST, tours);
} catch (TechnicalException ex) {
throw new ServletLogicException(ex.getMessage(), ex);
}
} | 6 |
private boolean jj_3_69() {
if (jj_scan_token(SMALLER)) return true;
return false;
} | 1 |
private void updateStateTellNumOfSteps(List<Keyword> keywords, List<String> terms) {
//We should have come here by a keyword jump and the recipe shouldve been passed or set
if (keywords != null && !keywords.isEmpty()) {
for (Keyword kw : keywords) {
if (kw.getKeywordData().getType() == KeywordType.RECIPE) {
currRecipe = new Recipe((RecipeData)kw.getKeywordData().getDataReference().get(0));
return;
}
}
}
//If not, the recipe should've already been set, if not, we need a recipe Name.
if (currRecipe == null || currRecipe.getRecipeData() == null) {
getCurrentDialogState().setCurrentState(RecipeAssistance.RA_WAITING_FOR_RECIPE_NAME);
return;
}
if (keywords == null || keywords.isEmpty() && currRecipe != null) {
DialogManager.giveDialogManager().setInErrorState(true);
}
} | 9 |
public String toString(String format, NumberFormat nf) throws IllegalArgumentException {
if(nf == null || format == null || format.isEmpty()){
throw new IllegalArgumentException("NumberFormat and String arguments"
+ "must not be null or empty.");
}
return String.format(format, description, qty, nf.format(price), nf.format(discount), nf.format(price - discount));
// return description + " " + qty + " " + price + " " + discount + " " + (price - discount);
} | 3 |
private void setArgPosition() {
int xPos;
for (xPos=pos; xPos<fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos>pos && xPos<fmt.length()) {
if (fmt.charAt(xPos)=='$') {
positionalSpecification = true;
argumentPosition=
Integer.parseInt(fmt.substring(pos,xPos));
pos=xPos+1;
}
}
} | 5 |
public void delete(Key key) {
if(key == null) {
throw new NullPointerException("Key may not be null");
}
if(!membershipTest(key)) {
throw new IllegalArgumentException("Key is not a member");
}
int[] h = hash.hash(key);
hash.clear();
for(int i = 0; i < nbHash; i++) {
// find the bucket
int wordNum = h[i] >> 4; // div 16
int bucketShift = (h[i] & 0x0f) << 2; // (mod 16) * 4
long bucketMask = 15L << bucketShift;
boolean hasUpdatedSuccess = false; // 是否更新成功
int retriedTimes = 0; // 已重试次数
while(!hasUpdatedSuccess && retriedTimes < MAX_UPDATE_RETRY_TIMES) {
long oldVal = buckets[wordNum].get();
long bucketValue = (oldVal & bucketMask) >>> bucketShift;
// only decrement if the count in the bucket is between 0 and BUCKET_MAX_VALUE
if(bucketValue >= 1 && bucketValue < BUCKET_MAX_VALUE) {
// decrement by 1
hasUpdatedSuccess = buckets[wordNum]
.compareAndSet(oldVal,
(oldVal & ~bucketMask) | ((bucketValue - 1) << bucketShift));
}
retriedTimes++;
} // while ends
// do log
if(!hasUpdatedSuccess && retriedTimes == MAX_UPDATE_RETRY_TIMES) {
LOG.error("collision occurn: delete");
}
}
} | 9 |
public void setNewTheme(String newTheme)
{
themeName = newTheme;
} | 0 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Venda other = (Venda) obj;
if (this.codigo != other.codigo) {
return false;
}
if (!Objects.equals(this.cliente, other.cliente)) {
return false;
}
if (!Objects.equals(this.valorTotal, other.valorTotal)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
if (!Objects.equals(this.itens, other.itens)) {
return false;
}
return true;
} | 7 |
public static void parseToMe (LinkedList<String[]> programArray, Hashtable<String, Integer> labelsHash, String name) throws IOException{
BufferedReader file = new BufferedReader(new FileReader(name));
String line;
int pc = 0;
Pattern comline = Pattern.compile("(\\b[a-zA-Z]*\\b:\\s*)?(\\b[a-zA-Z]{2,4}\\b)[^:]?((-?\\d+\\.?\\d*|[^#]*|\\s*))\\s*[\n\f#]*");
Pattern labeline = Pattern.compile("(\\b[a-zA-Z]*\\b:\\s*)[\n\f#]*$");
Pattern other = Pattern.compile("^#.*[\n\f]*|^[ \t\n]*$");
while((line = file.readLine()) != null){
Matcher matchLabel = labeline.matcher(line);
Matcher matchComLine = comline.matcher(line);
Matcher matchOther = other.matcher(line);
String label;
if(matchOther.find()){
System.out.print("");
}
else if(matchLabel.find()){
label = matchLabel.group(1).substring(0, matchLabel.group(1).length()-1);
labelsHash.put(label, pc);
pc++;
//System.out.println(label);
}
else if(matchComLine.find()){
String opcode = "", arg="";
if(matchComLine.group(1) != null){
label = matchComLine.group(1).substring(0, matchComLine.group(1).length()-1);
labelsHash.put(label, pc);
}
if(matchComLine.group(2) != null){
opcode = matchComLine.group(2);
//System.out.println(opcode);
}
if(matchComLine.group(3) != null && !matchComLine.group(3).equals("")){
arg = matchComLine.group(3);
}
pc++;
String [] comando = {opcode,arg};
programArray.add(comando);
}
else{System.out.print(line+": ");System.out.println("Syntax Error.") ;}
}
} | 8 |
private void sieve(int[] p){
for (int i=2;i<1e6;i++){
if (p[i] == 1){
for (int j=i+i;j<1e6;j+=i){
p[j]=0;
}
}
}
} | 3 |
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((affected!=null)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected)
||msg.amISource(((MOB)affected).amFollowing())
||(msg.source()==invoker()))
&&(msg.sourceMinor()==CMMsg.TYP_QUIT))
{
unInvoke();
if(msg.source().playerStats()!=null)
msg.source().playerStats().setLastUpdated(0);
}
} | 7 |
@Override
public void onEnable() {
config = getConfig();
config.options().copyDefaults(true);
saveConfig();
cfile = new File(getDataFolder(), "config.yml");
instance = this;
getServer().getPluginManager().registerEvents(this, this);
this.saveDefaultConfig();
if (setupEconomy()) {
FreeForAll.instance = this;
FreeForAll.ffaconfig = new FFAConfig(this);
ffaconfig.load();
loadArenas();
new Queue().runTaskTimer(this, 20, 20);
System.out.println("[FreeForAll] arenas loaded.");
try {
DB = new MySQLc(this);
usingDataBaseLeaderBoards = true;
try {
engineManager.registerEngine(new LeaderboardEngine(DB));
} catch (EngineException ex) {
System.out.println(ex.getMessage());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("Can't load database");
}
System.out.println("[FreeForAll] Starting base engines...");
try {
engineManager.registerEngine(new InventoryEngine());
} catch (EngineException ex) {
System.out.println(ex.getMessage());
}
try {
engineManager.registerEngine(new OfflineStorageEngine());
} catch (EngineException ex) {
System.out.println(ex.getMessage());
}
try {
engineManager.registerEngine(new StorageEngine());
} catch (EngineException ex) {
System.out.println(ex.getMessage());
}
try {
engineManager.registerEngine(new KillStreakEngine());
} catch (EngineException ex) {
System.out.println(ex.getMessage());
}
try {
engineManager.registerEngine(new DebugEngine());
} catch (EngineException ex) {
System.out.println(ex.getMessage());
}
System.out.println("[FreeForAll] Done starting base engines.");
ffapl = new FFAPlayerListener(this);
System.out.println("[FreeForAll] has been enabled.");
if (this.getDescription().getVersion().contains("EB")) {
Bukkit.getConsoleSender().sendMessage(ChatColor.BLUE + "[FreeForAll] YOU ARE USING AN EXPERIMENTAL BUILD. USE AT YOUR OWN RISK.");
}
} else {
System.out.println("[FreeForAll] unable to load vault.");
getServer().getPluginManager().disablePlugin(this);
}
} | 9 |
private static void displayMostUsefulReviews(BufferedReader reader, VideoStore videoStore) {
try {
System.out.println("Please enter the title of the video you want to get reviews for:");
String isbn = getISBNFromTitle(reader, videoStore, reader.readLine());
System.out.println("Up to how many reviews?");
int amount = Integer.parseInt(reader.readLine());
displayReviews(videoStore.getUsefulReviews(isbn, amount), false);
} catch (Exception e) {
System.out.println("There was an error while getting the most useful reviews.");
}
} | 1 |
private void startAnnouncer() {
if(announcerId != -1) {
// Stop previous announcer
plugin.getServer().getScheduler().cancelTask(announcerId);
}
if(!announcerUse || announcements.isEmpty()) {
return;
}
final int delay = announcerInterval * minutesToTicks;
announcerId = plugin
.getServer()
.getScheduler()
.scheduleSyncRepeatingTask(plugin,
new WorldAnnouncerTask(worldName, announcements),
delay, delay);
if(plugin.getModuleForClass(ConfigHandler.class).debugAnnouncer) {
plugin.getLogger().info("Started announcer for " + worldName + ", " + announcerId);
}
} | 4 |
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} | 7 |
public static void main(String[] args) {
//9 different table sizes are considered, and there are 169 equivalence classes of paired cards
double[][][] suited = new double[9][13][13];
double[][][] unSuited = new double[9][13][13];
for(int playerCount = 2; playerCount <= 10; playerCount++){
System.out.println("Starting on table size " + playerCount);
for(int cardIValue = 2; cardIValue <= 14; cardIValue++){
for(int cardJValue = 2; cardJValue <= 14;cardJValue++){
Card cardI = new Card(Suit.DIAMONDS,cardIValue);
Card cardJSuited = new Card(Suit.DIAMONDS,cardJValue);
Card cardJUnsuited = new Card(Suit.CLUBS,cardJValue);
RolloutDealer suitedDealer = new RolloutDealer(cardI,cardJSuited);
RolloutDealer unsuitedDealer = new RolloutDealer(cardI,cardJUnsuited);
Player suitedPlayer = new RolloutPlayer("0");
Player unsuitedPlayer = new RolloutPlayer("0");
suitedDealer.addPlayer(suitedPlayer);
unsuitedDealer.addPlayer(unsuitedPlayer);
for (int i = 1; i < playerCount; i++) {
suitedDealer.addPlayer(new RolloutPlayer(Integer.toString(i)));
unsuitedDealer.addPlayer(new RolloutPlayer(Integer.toString(i)));
}
long suitedWins = 0;
long unsuitedWins = 0;
for(int i = 0; i < NUM_TESTS;i++){
GameResult result = suitedDealer.runGame(i);
if(result.getWinners().contains(suitedPlayer)){
suitedWins++;
}
result = unsuitedDealer.runGame(i);
if(result.getWinners().contains(unsuitedPlayer)){
unsuitedWins++;
}
}
suited[playerCount-2][cardIValue-2][cardJValue-2] = ((double)(suitedWins) / (double) (NUM_TESTS));
unSuited[playerCount-2][cardIValue-2][cardJValue-2] = ((double)(unsuitedWins) / (double) (NUM_TESTS));
// System.out.println("Player count is " + playerCount);
// System.out.println("Card values are " + cardIValue + " " + cardJValue);
// System.out.println("Suited wins " + suitedWins + " " + suited[playerCount-2][cardIValue-2][cardJValue-2] );
// System.out.println("Unsuited wins " + unsuitedWins + " " + unSuited[playerCount-2][cardIValue-2][cardJValue-2]);
}
}
}
RolloutResult result = new RolloutResult(suited, unSuited);
FileOutputStream file;
try {
file = new FileOutputStream("Output.rollout");
ObjectOutputStream stream = new ObjectOutputStream(file);
stream.writeObject(result);
stream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 9 |
public String parseExprContent(String rawContent) {
StringBuilder sb = new StringBuilder();
String s = "";
for (int i = 0; i < rawContent.length(); i++) {
char c = rawContent.charAt(i);
if(Character.isLetter(c)){ // When we find a letter, do a while till you cant find more digits
s += c;
i++;
c = rawContent.charAt(i);
while(Character.isDigit(c)){
s += c;
i++;
if(!(i < rawContent.length())){ // Avoids index out of bounds
break;
}
c = rawContent.charAt(i);
}
i--; // So the next forloop doesnt skip an index
s = s.toUpperCase();
if(validCellRef(s)){
String cellContent = getCellContent(s); // Tries to get expr from hashMap
if (!cellContent.equals("")) {
sb.append(cellContent);
s = "";
}else{
System.out.println("Sheet -> parseExpr() cant find cellRef in hashMap");
}
}
}else{
sb.append(c);
}
}
return sb.toString();
} | 6 |
@Override
public void getTokenEmissionWeights(SequenceInput input, int idxTknTrain,
double[] weights) {
// Clear weights array.
Arrays.fill(weights, 0d);
/*
* Index of the given sequence within the training dataset, if it is
* part of one.
*/
int idxSeqTrain = input.getTrainingIndex();
if (!distillationOnGoing) {
if (idxTknTrain == 0)
kernelCacheCurrentExample = new double[input.size()][][];
kernelCacheCurrentExample[idxTknTrain] = new double[dualEmissionVariables
.size()][];
}
int _idxSeqSV = 0;
// For each sequence.
for (Entry<Integer, TreeMap<Integer, TreeMap<Integer, AveragedParameter>>> entrySequence : dualEmissionVariables
.entrySet()) {
// Current sequence index.
int idxSeqSV = entrySequence.getKey();
TreeMap<Integer, TreeMap<Integer, AveragedParameter>> sequence = entrySequence
.getValue();
int _idxTknSV = 0;
if (!distillationOnGoing)
kernelCacheCurrentExample[idxTknTrain][_idxSeqSV] = new double[sequence
.size()];
// For each token within the current sequence.
for (Entry<Integer, TreeMap<Integer, AveragedParameter>> entryToken : sequence
.entrySet()) {
// Currect token index.
int idxTknSV = entryToken.getKey();
// Calculate the kernel function value.
double k;
if (distillationOnGoing) {
if (idxSeqTrain == idxSeqSV && idxTknTrain == idxTknSV) {
/*
* Do not use the kernel function value between a
* support vector and itself, in order to calculate the
* prediction when removing this support vector.
*/
++_idxTknSV;
continue;
} else {
/*
* Kernel function values between two support vectors
* are cached.
*/
k = kernelCache.get(new DualEmissionKeyPair(idxSeqSV,
idxTknSV, idxSeqTrain, idxTknTrain));
}
} else {
/*
* Evaluate the kernel function between the training example
* token and the current support vector.
*/
k = kernel(inputs[idxSeqSV], idxTknSV, input, idxTknTrain);
/*
* Store the kernel function value in the current example
* temporary cache.
*/
kernelCacheCurrentExample[idxTknTrain][_idxSeqSV][_idxTknSV] = k;
}
/*
* Sum the kernel function values weighted by the alpha
* counters.
*/
for (Entry<Integer, AveragedParameter> entryAlpha : entryToken
.getValue().entrySet()) {
int state = entryAlpha.getKey();
double alpha = entryAlpha.getValue().get();
weights[state] += alpha * k;
}
++_idxTknSV;
}
++_idxSeqSV;
}
} | 9 |
public void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//Render Here
map.render(g);
gui.render(g);
paths.render(g);
gui.render2(g);
for(int i = 0; i < unitList.size(); i++) {
unitList.get(i).render(g);
}
gui.render3(g);
g.dispose(); //Clean
bs.show(); //Shows render
} | 2 |
@Override
public String describeValue(final boolean[] data, final int requestedNameLength)
{
long val = 0;
for(int i = 0; i < data.length; i++)
{
if(true == data[i])
{
val = val + (1 <<((numBits-1) -i));
}
// else 0 * something = nothing
}
if(true == signed)
{
// TODO
}
final StringBuffer sb = createNameDescription();
final int spaces = requestedNameLength - sb.length();
for(int i = 0; i < spaces; i++)
{
sb.append(" ");
}
return sb.toString() + ": " +String.format(valuePresenation, val);
// return sb.toString() + ": " + val;
} | 4 |
private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
int tempX, tempY, tempMines;
try {
tempX = Integer.parseInt(numX.getText());
tempY = Integer.parseInt(numY.getText());
tempMines = Integer.parseInt(numMines.getText());
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "The boxes must be filled with numbers only.");
return;
}
if (validate(tempX, tempY, tempMines)
&& (Minesweeper.myWidth != tempX
|| Minesweeper.myHeight != tempY
|| Minesweeper.Mines != tempMines)) {
Minesweeper.myWidth = tempX;
Minesweeper.myHeight = tempY;
Minesweeper.Mines = tempMines;
parent.newGame();
parent.setCustom();
} else if (!validate(tempX, tempY, tempMines)) {
javax.swing.JOptionPane.showMessageDialog(null, "There must be between 9 and 30 horizontal spaces,\r\nbetween 9 and 24 vertical spaces,\r\nand between 10 and (x-1)(y-1) mines.");
return;
}
this.dispose();
}//GEN-LAST:event_OKButtonActionPerformed | 6 |
private void reduce() {
int[] primes = getPrimeNumbers();
for (int divisor : primes) {
if(numerator < divisor) break;
if(denominator < divisor) break;
divide(divisor);
}
} | 3 |
public void setHmac(Key key){
Mac hmac = null;
try {
hmac = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
System.err.println("NoSuchAlgorithmException (HmacSHA256 not valid): " + e.getMessage());
}
try {
hmac.init(key);
} catch (InvalidKeyException e) {
System.err.println("InvalidKeyException: " + e.getMessage());
}
byte[] message = this.toString().getBytes();
if(hmac!=null){
hmac.update(message);
byte[] hash = hmac.doFinal();
base64hash = Base64.encode(hash);
}
} | 3 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(((msg.sourceMinor()==CMMsg.TYP_TELL)
||(msg.othersMajor(CMMsg.MASK_CHANNEL)))
&&((msg.source()==affected)
||((msg.source().location()==CMLib.map().roomLocation(affected))
&&(msg.source().isMonster())
&&(msg.source().willFollowOrdersOf((MOB)affected)))))
{
msg.source().tell(L("Your message drifts into oblivion."));
return false;
}
return true;
} | 7 |
String fetch_m3u(String m3u) {
InputStream pstream = null;
if (m3u.startsWith("http://")) {
try {
URL url;
if (running_as_applet) {
url = new URL(getCodeBase(), m3u);
} else {
url = new URL(m3u);
}
URLConnection urlc = url.openConnection();
pstream = urlc.getInputStream();
} catch (Exception ee) {
System.err.println(ee);
return null;
}
}
if (pstream == null && !running_as_applet) {
try {
pstream = new FileInputStream(System.getProperty("user.dir")
+ System.getProperty("file.separator") + m3u);
} catch (Exception ee) {
System.err.println(ee);
return null;
}
}
String line = null;
while (true) {
try {
line = readline(pstream);
} catch (Exception e) {
}
if (line == null) {
break;
}
return line;
}
return null;
} | 9 |
@Override
public int getFirstSlotLocationX() {
return isNotPlayerInventory() ? centerX-54 :centerX - 44;
} | 1 |
public void affichageTableur(String pretexte, ArrayList<ArrayList<Character>> al)
{
System.out.println(pretexte);
System.out.println("[");
for(ArrayList<Character> mot : al)
System.out.println("\tPosition : " + al.indexOf(mot) +"(" + tableurNonTrie.indexOf(mot) + ")\t" + mot);
System.out.println("]");
} | 1 |
public static List<CharacterObject> GetConnectedPlayers(short x_centr_cell, short y_centr_cell, short dist_radius)
{
List<CharacterObject> list = new ArrayList<CharacterObject>();
for(int ix = x_centr_cell - dist_radius; ix < x_centr_cell + dist_radius; ix++)
for(int iy = y_centr_cell - dist_radius; iy < y_centr_cell + dist_radius; iy++)
{
List<BaseObject> lbase = World.Inst().GetLandCell((short)ix, (short)iy).GetConteiner();
for(BaseObject ob : lbase)
if((ob instanceof CharacterObject) && ((CharacterObject)ob).IsConnect())
list.add((CharacterObject)ob);
}
return list;
} | 5 |
protected void genWeapon(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
final StringBuffer parts=new StringBuffer("");
Item I=CMClass.getItem(E.getStat("WEAPONCLASS"));
if(I!=null)
{
I.setMiscText(E.getStat("WEAPONXML"));
I.recoverPhyStats();
parts.append(I.name());
}
mob.tell(L("@x1. Natural Weapon: @x2.",""+showNumber,parts.toString()));
if((showFlag!=showNumber)&&(showFlag>-999))
return;
final String newName=mob.session().prompt(L("Enter a weapon name from your inventory to change, or 'null' for human\n\r:"),"");
if(newName.equalsIgnoreCase("null"))
{
E.setStat("WEAPONCLASS","");
mob.tell(L("Human weapons set."));
}
else
if(newName.length()>0)
{
I=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,newName);
if(I==null)
{
mob.tell(L("'@x1' is not in your inventory.",newName));
mob.tell(L("(no change)"));
return;
}
I=(Item)I.copyOf();
E.setStat("WEAPONCLASS",I.ID());
E.setStat("WEAPONXML",I.text());
I.destroy();
}
else
{
mob.tell(L("(no change)"));
return;
}
} | 8 |
private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnLoginActionPerformed
// TODO add your handling code here:
String username = this.jTxtFldUsername.getText();
String password = this.jTxtFldPassword.getText();
Connection conn = Conexion.GetConnection();
try {
if (username != null && password!=null){
String sql = ("SELECT Puesto_idPuesto FROM empleados WHERE idEmpleados='" + username + "' AND telefono='" + password + "'");
st = conn.createStatement();
rs = st.executeQuery(sql);
if( rs.next()){
//in this case enter when at least one result comes it means user is valid
JOptionPane.showMessageDialog(this,"Usuario Encontrado");
String [] val = {rs.getString(1)};
if("2".equals(val[0])){
JOptionPane.showMessageDialog(this, "Bienvenido Vendedor!");
Ventas vent = new Ventas();
vent.setVisible(true);
this.dispose();
}else{
JOptionPane.showMessageDialog(this, "Bienvenido Administrador");
Administrador admin = new Administrador();
admin.setVisible(true);
this.dispose();
}
} else {
//in this case enter when result size is zero it means user is invalid
JOptionPane.showMessageDialog(this,"Usuario No Encontrado");
}
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getErrorCode()+": "+e.getMessage());
}
}//GEN-LAST:event_jBtnLoginActionPerformed | 5 |
public static void main(String[] args) {
ParamsParse params = null;
/**
* Тут в зависимости от параметров мы либо делаем xml файл со структурой базы,
* либо сравниваем существующий xml файл с тем что есть в базе
*/
// Проверим число параметров. В качестве параметра должен быть задан файл.
if (args.length != 1) {
System.out.println("Неверный формат вызова.");
System.out.println("В качетве параметра необходимо указать файл с параметрами.");
return;
}
// Прочитаем параметры из файла
try {
params = new ParamsParse(args[0]);
} catch (Exception e) {
System.out.println("ObjectComparer: В процессе разбора параметров возникла ошибка");
e.printStackTrace();
}
if (params.getMode().equalsIgnoreCase("generate")) {
// Если мы тут то надо генерить файл //
System.out.println("generate");
try {
// Сгенерим текст и сложим его в файл
PosibleActions action = new PosibleActions();
action.generate((String)params.getTarget(), (DBParams)params.getSource());
} catch (Exception e) {
System.out.println("ObjectComparer.generate: Ошибка при вызове генератора нового файла с информацией о схеме");
e.printStackTrace();
}
}
else if (params.getMode().equalsIgnoreCase("compare")) {
// Если мы тут то надо сравнить существующий файл //
System.out.println("compare");
try {
// Сгенерим текст и сложим его в файл
PosibleActions action = new PosibleActions();
action.compare((DBParams)params.getTarget(), (String)params.getSource());
} catch (Exception e) {
System.out.println("ObjectComparer.compare: Ошибка при вызове режима сравнениея файла со схемой");
e.printStackTrace();
}
}
} | 6 |
public Prime(int n) {
max = n;
bitSet = new BitSet(max + 1);
if (max > 1){
bitSet.set(0, 2, false);
bitSet.set(2, max + 1, true);
for (long i = 2; i * i <= max; ++i) {
if (isPrime((int) i)) {
for (long j = i * i; j <= max; j += i) {
bitSet.set((int) j, false);
}
}
}
}
primeCount = bitSet.cardinality();
} | 4 |
public static void main(String[] args)
{
Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE);
int i;
for (i = 0; i < NACCOUNTS; i++)
{
TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE);
Thread t = new Thread(r);
t.start();
}
} | 1 |
int checkID(String id) {
int errorNumber = 0;
char[] idCharArray = id.toCharArray();
if (id.length() == 18) {
char lastChar = idCharArray[17];
for (int i = 0; i < idCharArray.length - 1; i++) {
if ((int) idCharArray[i] >= (int) '0' && (int) idCharArray[i] <= (int) '9') {
if ((int) lastChar == (int) 'X' || ((int) lastChar >= (int) '0' && (int) lastChar <= (int) '9')) {
errorNumber = 0;
} else errorNumber = 5; //5 is id format error
} else errorNumber = 5;
}
} else errorNumber = 6; //6 is id length is wrong
return errorNumber;
} | 7 |
public Inventory(int size)
{
this.size = size;
itemList = new Item[size];
x = 50;
y = 470;
w = 176;
h = 40;
int n = 100001 + (int)(Math.floor(Math.random() * 8));
addItem(n);
n = 110001 + (int)(Math.floor(Math.random() * 7));
addItem(n);
n = 120001 + (int)(Math.floor(Math.random() * 7));
addItem(n);
} | 0 |
private static String getKeepAliveMsg(Neighbor from) {
StringBuilder result = new StringBuilder();
result.append("From:");
result.append(Setup.ROUTER_NAME);
result.append("\n");
result.append("Type:KeepAlive\n");
return result.toString();
} | 0 |
void makeOLSAveragesTable( double[][] D, double[][] A )
{
edge e,f,g,h;
edge exclude;
e = f = null;
e = depthFirstTraverse(e);
while ( null != e )
{
f = e;
exclude = e.tail.parentEdge;
/* we want to calculate A[e.head][f.head] for all edges
except those edges which are ancestral to e. For those
edges, we will calculate A[e.head][f.head] to have a
different meaning, later*/
if ( e.head.leaf() )
{
while ( null != f )
{
if ( exclude != f )
{
if ( f.head.leaf() )
A[e.head.index][f.head.index] =
A[f.head.index][e.head.index] =
D[e.head.index2][f.head.index2];
else
{
g = f.head.leftEdge;
h = f.head.rightEdge;
A[e.head.index][f.head.index] =
A[f.head.index][e.head.index] =
(g.bottomsize*A[e.head.index][g.head.index]
+ h.bottomsize*A[e.head.index][h.head.index])
/f.bottomsize;
}
}
else //exclude == f
exclude = exclude.tail.parentEdge;
f = depthFirstTraverse(f);
}
}
else
//e.head is not a leaf, so we go recursively to
//values calculated for the nodes below e
while ( null !=f )
{
if ( exclude != f )
{
g = e.head.leftEdge;
h = e.head.rightEdge;
A[e.head.index][f.head.index] =
A[f.head.index][e.head.index] =
(g.bottomsize*A[f.head.index][g.head.index]
+ h.bottomsize*A[f.head.index][h.head.index])
/e.bottomsize;
}
else
exclude = exclude.tail.parentEdge;
f = depthFirstTraverse(f);
}
/*now we move to fill up the rest of the table: we want
A[e.head.index][f.head.index] for those cases where e is an
ancestor of f, or vice versa. We'll do this by choosing e via a
depth first-search, and the recursing for f up the path to the
root*/
f = e.tail.parentEdge;
if (null != f)
fillTableUp(e,f,A,D);
e = depthFirstTraverse(e);
}
/*we are indexing this table by vertex indices, but really the
underlying object is the edge set. Thus, the array is one element
too big in each direction, but we'll ignore the entries involving the root,
and instead refer to each edge by the head of that edge. The head of
the root points to the edge ancestral to the rest of the tree, so
we'll keep track of up distances by pointing to that head*/
/*10/13/2001: collapsed three depth-first searches into 1*/
} | 8 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HistorialPrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HistorialPrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HistorialPrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HistorialPrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HistorialPrestamosUsuario().setVisible(true);
}
});
} | 6 |
private boolean saveGame(File fout){
DataOutputStream file;
try{
file = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fout)));
}catch(FileNotFoundException ex){
return false;
}
try{
//write status
file.writeInt(score1);
file.writeInt(score2);
file.writeInt(level);
//write options
file.writeBoolean(gravExists);
file.writeBoolean(gravVisible);
file.writeBoolean(unlimitedLives);
file.writeInt(numAsteroids);
file.writeInt(startingLevel);
file.writeBoolean(isSinglePlayer);
//write players
file.writeInt(player1.getX());
file.writeInt(player1.getY());
file.writeDouble(player1.getAngle());
file.writeDouble(player1.getVX());
file.writeDouble(player1.getVY());
file.writeDouble(player1.getVAngle());
file.writeInt(player1.getLives());
if (player2 == null){
file.writeInt(0);
}else{
file.writeInt(1);
file.writeInt(player2.getX());
file.writeInt(player2.getY());
file.writeDouble(player2.getAngle());
file.writeDouble(player2.getVX());
file.writeDouble(player2.getVY());
file.writeDouble(player2.getVAngle());
file.writeInt(player2.getLives());
}
file.writeInt(bullets.size());
for (Bullet bullet:bullets){
file.writeInt(bullet.getX());
file.writeInt(bullet.getY());
file.writeDouble(bullet.getAngle());
file.writeDouble(bullet.getVX());
file.writeDouble(bullet.getVY());
file.writeDouble(bullet.getVAngle());
file.writeInt(bullet.getColor().getRGB());
file.writeInt(bullet.getShooter());
file.writeDouble(bullet.getDist());
}
file.writeInt(asteroids.size());
for (Asteroid asteroid:asteroids){
file.writeInt(asteroid.getX());
file.writeInt(asteroid.getY());
file.writeDouble(asteroid.getAngle());
file.writeDouble(asteroid.getVX());
file.writeDouble(asteroid.getVY());
file.writeDouble(asteroid.getVAngle());
file.writeInt(asteroid.getType());
}
if (rogueSpaceship == null){
file.writeInt(0);
}else{
file.writeInt(1);
file.writeInt(rogueSpaceship.getX());
file.writeInt(rogueSpaceship.getY());
file.writeDouble(rogueSpaceship.getAngle());
file.writeDouble(rogueSpaceship.getVX());
file.writeDouble(rogueSpaceship.getVY());
file.writeDouble(rogueSpaceship.getVAngle());
}
if (alienShip == null){
file.writeInt(0);
}else{
file.writeInt(1);
file.writeInt(alienShip.getX());
file.writeInt(alienShip.getY());
file.writeDouble(alienShip.getAngle());
file.writeDouble(alienShip.getVX());
file.writeDouble(alienShip.getVY());
file.writeDouble(alienShip.getVAngle());
file.writeInt(alienShip.getLives());
}
file.close();
}catch (IOException ex){
return false;
}
return true;
} | 7 |
public Exception getException() {
return exception;
} | 0 |
private String writeDropForeignKeys() {
StringBuilder sb = new StringBuilder();
Table fromTable;
ForeignNode node;
for ( int keyNum = 0; keyNum < foreignNodeList.size(); keyNum++ ) {
node = foreignNodeList.get( keyNum );
fromTable = tableMap.get( node.getFromTable() );
sb.append( "ALTER TABLE " + fromTable.getTableName() );
sb.append( " DROP CONSTRAINT FK_" + fromTable.getTableName() + "_" + keyNum + ";\n" );
}
return sb.toString();
} | 1 |
public static void main(String[] args){
Deck d;
decks = new DeckList();
try {
FileInputStream fileStream = new FileInputStream("Deck.ser");
ObjectInputStream os = new ObjectInputStream(fileStream);
Object deckList = os.readObject();
decks = (DeckList) deckList ;
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if(decks.size() !=0){
d = decks.get(0);
}
else{
d = new Deck("First Deck");
decks.add(d);
}
final NameGame game = new NameGame(decks);
if(d.size() > 0) {
if(d.get(0).isPic()) {
game.setPic(d.get(0));
}
else {
game.setPrint(d.get(0),1);
}
}
game.updateSize(d.size());
game.setCardNum();
game.setTitle("FlashCard App");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setSize(800, 600);
game.setLocationRelativeTo(null);
game.getContentPane().setBackground(Color.BLUE);
game.setVisible(true);
game.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
try {
FileOutputStream fs = new FileOutputStream("Deck.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(game.getDeckList());
os.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
} | 5 |
@SuppressWarnings("unchecked") // FIXME in Java7
private void filterDestinations() {
DefaultListModel model = (DefaultListModel) destinationList.getModel();
Object selected = destinationList.getSelectedValue();
model.clear();
for (Destination d : destinations) {
if (showOnlyMyColonies) {
if (d.location instanceof Europe
|| d.location instanceof Map
|| (d.location instanceof Colony
&& ((Colony) d.location).getOwner() == getMyPlayer())) {
model.addElement(d);
}
} else {
model.addElement(d);
}
}
destinationList.setSelectedValue(selected, true);
if (destinationList.getSelectedIndex() == -1) {
destinationList.setSelectedIndex(0);
}
} | 7 |
public void addBomber(IBomber b){
bombers.add(b);
} | 0 |
public static Graph FechoTransitivo(Graph grafo) {
Graph resultado = new Graph(grafo.getNlc());
resultado.setMatriz(grafo.getMatriz());
for (int i = 0; i < resultado.getNlc(); i++)
for (int j = 0; j < resultado.getNlc(); j++) {
for (int k = 0; k < resultado.getNlc(); k++) {
//Se existe caminho de j para i e de i para k, logo existe caminho de j para k
if ((resultado.getElement(j, i) > 0) && (resultado.getElement(i, k) > 0)) {
resultado.setElement(j, k, 2);
}
}
}
return resultado;
} | 5 |
public void rimuovi(T x) {
AlberoBin<T> curr = cercaNodo(x);
if (curr == null || !curr.val().equals(x)) return;
AlberoBin<T> padre; int pos;
if (curr.sin() == null || curr.des() == null) {
pos = curr.pos();
padre = curr.padreBin();
rimuoviNodo(curr);
} else {
AlberoBin<T> curr2 = max(curr.sin());
curr.setVal(curr2.val());
pos = curr2.pos();
padre = curr2.padreBin();
rimuoviNodo(curr2);
}
aggiustaRimozione((AlberoBinLFB<T>)padre, pos);
} | 4 |
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
} | 5 |
private ConfigurationArea handleObject(ConfigurationArea configurationArea, final Set<SystemObject> objects, final SystemObject systemObject, final SystemObject dynamicObject) {
// alle SystemObjekte werden hier betrachtet (Konfigurations-Objekte und dynamische Objekte)
// Attribute, ObjectSet, AttributeGroupUsage etc. müssen herausgefiltert werden
if(systemObject instanceof Attribute) return configurationArea;
if(systemObject instanceof AttributeGroupUsage) return configurationArea;
if(systemObject instanceof ObjectSet) return configurationArea;
if(systemObject instanceof ObjectSetUse) return configurationArea;
if(systemObject instanceof IntegerValueRange) return configurationArea;
if(systemObject instanceof IntegerValueState) return configurationArea;
// Konfigurationsbereich-Objekt bei Bedarf neu setzen
if(systemObject instanceof ConfigurationArea) {
configurationArea = (ConfigurationArea)systemObject;
}
else {
// Im Normalfall einfach Objekt merken (ggf. überschreiben)
objects.add(dynamicObject);
}
return configurationArea;
} | 7 |
private static String parseEscapedSequence(StringCharacterIterator iterator) throws UnsupportedEncodingException {
char c = iterator.next();
if (c == '\\') {
return new String(new byte[]{0, '\\'}, "UTF-8");
} else if (c == '"') {
return new String(new byte[]{0, '\"'}, "UTF-8");
} else if (c == 'b') {
return new String(new byte[]{0, '\b'}, "UTF-8");
} else if (c == 'n') {
return new String(new byte[]{0, '\n'}, "UTF-8");
} else if (c == 'r') {
return new String(new byte[]{0, '\r'}, "UTF-8");
} else if (c == 't') {
return new String(new byte[]{0, '\t'}, "UTF-8");
} else if (c == 'U' || c == 'u') {
//4 digit hex Unicode value
String byte1 = "";
byte1 += iterator.next();
byte1 += iterator.next();
String byte2 = "";
byte2 += iterator.next();
byte2 += iterator.next();
byte[] stringBytes = {(byte) Integer.parseInt(byte1, 16), (byte) Integer.parseInt(byte2, 16)};
return new String(stringBytes, "UTF-8");
} else {
//3 digit octal ASCII value
String num = "";
num += c;
num += iterator.next();
num += iterator.next();
int asciiCode = Integer.parseInt(num, 8);
byte[] stringBytes = {0, (byte) asciiCode};
return new String(stringBytes, "UTF-8");
}
} | 8 |
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + (this.mapID != null ? this.mapID.hashCode() : 0);
hash = 97 * hash + (this.map != null ? this.map.hashCode() : 0);
hash = 97 * hash + (this.cell != null ? this.cell.hashCode() : 0);
return hash;
} | 3 |
@Override
public void keyPressed(KeyEvent e) {
// Synchronise the registeredListeningObjects
synchronized (registeredListeningObjects) {
for (IKeyboardEventable keyListener : registeredListeningObjects) {
synchronized (waitingEventLists) {
waitingEventLists.get(KeyEventType.KEY_PRESSED).add(new EventHolder(e, keyListener));
}
}
}
if (!currentlyDownKeys.contains(e.getKeyCode())) {
currentlyDownKeys.add(e.getKeyCode());
}
} | 2 |
public List getTags() {
clearResultMetaInformation();
List tags = new ArrayList();
StringBuffer result = new StringBuffer();
GetMethod get = new GetMethod(apiEndpoint + DeliciousConstants.TAGS_GET);
get.setDoAuthentication(true);
try {
httpResult = httpClient.executeMethod(get);
checkNotAuthorized(httpResult);
logger.debug("Result: " + httpResult);
if (get.getResponseBodyAsStream() != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), DeliciousUtils.UTF_8));
String input;
while ((input = bufferedReader.readLine()) != null) {
result.append(input).append(DeliciousUtils.LINE_SEPARATOR);
}
get.releaseConnection();
Document document = documentBuilder.parse(new InputSource(new StringReader(result.toString())));
NodeList tagItems = document.getElementsByTagName(DeliciousConstants.TAG_TAG);
if (tagItems != null && tagItems.getLength() > 0) {
for (int i = 0; i < tagItems.getLength(); i++) {
Node tagItem = tagItems.item(i);
Tag tag;
String count = tagItem.getAttributes().getNamedItem(DeliciousConstants.COUNT_ATTRIBUTE).getNodeValue();
String tagAttribute = tagItem.getAttributes().getNamedItem(DeliciousConstants.TAG_ATTRIBUTE).getNodeValue();
tag = new Tag(Integer.parseInt(count), tagAttribute);
tags.add(tag);
}
}
}
} catch (IOException e) {
logger.error(e);
} catch (SAXException e) {
logger.error(e);
throw new DeliciousException("Response parsing error", e);
}
return tags;
} | 7 |
public int getEffectTextWidth(String text) {
if (text == null)
return 0;
int width = 0;
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) == '@' && index + 4 < text.length() && text.charAt(index + 4) == '@') {
index += 4;
} else {
width += characterScreenWidth[text.charAt(index)];
}
}
return width;
} | 5 |
public boolean isDirected() {
return directed;
} | 0 |
@Override
protected final void onButtonClick(Button button) {
if (!frozen) {
if (button.active) {
if (loaded && button.id < 5) {
this.openLevel(button.id);
}
// if (finished || loaded && var1.id == 5) {
// frozen = true;
// LevelDialog var2;
// (var2 = new LevelDialog(this)).setDaemon(true);
// SwingUtilities.invokeLater(var2);
// }
if (finished || loaded && button.id == 6) {
minecraft.setCurrentScreen(parent);
}
}
}
} | 7 |
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
titleTextField = new javax.swing.JTextField();
searchTextField = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
replaceTextField = new javax.swing.JTextField();
applyButton = new javax.swing.JButton();
icon = new JButton()
{
@Override
public void setIcon(Icon defaultIcon)
{
super.setIcon(defaultIcon);
if (defaultIcon != button.getIcon())
DatabaseSaver.save();
}
};
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
customSearchTextField = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
directUrlTextField = new javax.swing.JTextField();
removeButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Edit Album");
setAlwaysOnTop(true);
setBackground(new java.awt.Color(39, 39, 39));
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt)
{
closeDialog(evt);
}
});
okButton.setBackground(removeButton.getBackground());
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
okButtonActionPerformed(evt);
}
});
cancelButton.setBackground(removeButton.getBackground());
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cancelButtonActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Title:");
titleTextField.setBackground(new java.awt.Color(204, 204, 204));
titleTextField.setText("jTextField1");
titleTextField.setBorder(javax.swing.BorderFactory.createCompoundBorder(null, javax.swing.BorderFactory.createEmptyBorder(4, 5, 4, 5)));
titleTextField.addCaretListener(new javax.swing.event.CaretListener()
{
public void caretUpdate(javax.swing.event.CaretEvent evt)
{
titleTextFieldCaretUpdate(evt);
}
});
searchTextField.setBackground(new java.awt.Color(204, 204, 204));
searchTextField.setBorder(titleTextField.getBorder());
jLabel3.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Replace in files:");
jLabel4.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel4.setForeground(new java.awt.Color(216, 216, 216));
jLabel4.setText("with");
replaceTextField.setBackground(new java.awt.Color(204, 204, 204));
replaceTextField.setBorder(titleTextField.getBorder());
applyButton.setBackground(removeButton.getBackground());
applyButton.setText("Apply");
applyButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
applyButtonActionPerformed(evt);
}
});
icon.setBackground(new java.awt.Color(89, 89, 89));
icon.setForeground(new java.awt.Color(255, 255, 255));
icon.setBorder(null);
icon.setBorderPainted(false);
icon.setContentAreaFilled(false);
icon.setHideActionText(true);
icon.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
icon.setMaximumSize(Utils.ICON_DIMENSION);
icon.setMinimumSize(Utils.ICON_DIMENSION);
icon.setPreferredSize(Utils.ICON_DIMENSION);
icon.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jLabel5.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Picture:");
jLabel6.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel6.setForeground(new java.awt.Color(216, 216, 216));
jLabel6.setText("Custom search:");
customSearchTextField.setBackground(new java.awt.Color(204, 204, 204));
customSearchTextField.setBorder(titleTextField.getBorder());
customSearchTextField.setText("");
jLabel7.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel7.setForeground(new java.awt.Color(216, 216, 216));
jLabel7.setText("Direct URL:");
directUrlTextField.setBackground(new java.awt.Color(204, 204, 204));
directUrlTextField.setBorder(titleTextField.getBorder());
removeButton.setBackground((System.getProperty("os.name").equals("Linux")) ? new Color(150, 150, 150) : null);
removeButton.setText("Remove");
removeButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
removeButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(layout.createSequentialGroup()
.addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(replaceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(titleTextField))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(removeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(applyButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(directUrlTextField, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(customSearchTextField))
.addGap(25, 25, 25))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(217, 217, 217)))
.addComponent(icon, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(titleTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(replaceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(customSearchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(directUrlTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(icon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(okButton)
.addComponent(applyButton)
.addComponent(removeButton))
.addContainerGap())
);
getRootPane().setDefaultButton(okButton);
titleTextField.getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>//GEN-END:initComponents | 2 |
public static void main(String[] args) {
//Fail
ResourceBundle res = ResourceBundle.getBundle("GlobalRes");
String msg;
if(args.length > 0){
msg = res.getString(GlobalRes.GOODBYE);
}
else{
msg = res.getString(GlobalRes.HELLO);
}
System.out.println(msg);
//Fail
ResourceBundle res1 = ResourceBundle.getBundle("GlobalRes_en");
String msg1;
if(args.length > 0){
msg1 = res1.getString(GlobalRes.GOODBYE);
}
else{
msg1 = res1.getString(GlobalRes.HELLO);
}
System.out.println(msg1);
//Fail. The class "GlobalRes_en_AU" does not exist, so GlobalRes_en_AU.properties will be read.
ResourceBundle res2 = ResourceBundle.getBundle("GlobalRes_en_AU");
String msg2;
if(args.length > 0){
msg2 = res2.getString(GlobalRes.GOODBYE);
}
else{
msg2 = res2.getString(GlobalRes.HELLO);
}
System.out.println(msg2);
} | 3 |
private static void sendRefuseOfferPackages(String buyer, String service,
List<String> usersToRefuse) {
SerializableRefuseOffer refuseOffer;
SelectionKey key;
for (String refusedSeller : usersToRefuse) {
refuseOffer = new SerializableRefuseOffer();
refuseOffer.userName = buyer;
refuseOffer.serviceName = service;
key = Server.registeredUsersChannels.get(refusedSeller);
if (null == key) {
Server.loggerServer.error("The user is no longer logged in");
} else {
Server.sendData(key, refuseOffer);
}
}
} | 2 |
public void setFesEstado(String fesEstado) {
this.fesEstado = fesEstado;
} | 0 |
@Override
public String getTitle() {
return "Java Blocks Game";
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.