method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
164559ac-1928-4484-8a48-304f24d9949e | 0 | public double getMarkerLatitude()
{
return markerRect.getLatitude();
} |
2f5b1381-df06-4a94-bdb0-b2f9eaac5127 | 7 | public static void commandMode(final EnvironmentInterface env) {
final int maxBuf = 200;
byte[] buf = new byte[maxBuf];
int length;
try {
System.out.print("\nTAallocation: query using predicates, assert using \"!\" prefixing predicates;\n !exit() to quit; !help() for help.\n\n> ");
while ((length=System.in.read(buf))!=-1) {
String s = new String(buf,0,length);
s = s.trim();
if (s.equals("exit")) break;
if (s.equals("?")||s.equals("help")) {
s = "!help()";
System.out.println("> !help()");
}
if (s.length()>0) {
if (s.charAt(0)=='!')
env.assert_(s.substring(1));
else
System.out.print(" --> "+env.eval(s));
}
System.out.print("\n> ");
}
} catch (Exception e) {
System.err.println("exiting: "+e.toString());
}
} |
ec020bfc-0831-47a4-a496-531b84bdb1b0 | 0 | public MeasureKit(DataStructures inData, int numberOfPoints){
this.inData = inData;
this.numberOfPoints = numberOfPoints;
} |
279caffe-73c5-4ca3-8258-100147915630 | 9 | private void fillNumbers() {
int dx[] = { 0, 1, 1, 1, 0, -1, -1, -1 };
int dy[] = { -1, -1, 0, 1, 1, 1, 0, -1 };
int width = board.length;
int height = board[0].length;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (board[x][y] != MINE) {
board[x][y] = 0;
for (int d = 0; d < dx.length; d++) {
int px = x + dx[d];
int py = y + dy[d];
if (px >= 0 && px < width && py >= 0 && py < height && board[px][py] == MINE) {
board[x][y]++;
}
}
}
}
}
} |
5bf5f26e-777e-4759-8c58-9d4f9d85d1fd | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserBean other = (UserBean) obj;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
} |
07b8dc50-4fd9-476f-92a2-627dbd7c039f | 9 | public void encode(char c, BitOutputStream bos) throws IOException {
int nodeNumber = currentNumber;
for (int i = 512; i >= currentNumber; --i) {
// found leaf with symbol
if (c == nodes[i].symbol && nodes[i].left == null) {
nodeNumber = i;
break;
}
}
BitSet reverseEncoding = new BitSet();
int length = 0;
// found nyt node, append reverse encoding of c
if (nodeNumber == currentNumber) {
for (int i = 0; i < 8; ++i) {
reverseEncoding.set(7 - i, (c & (1 << i)) != 0);
}
length = 8;
}
Node currentNode = nodes[nodeNumber];
// ascend the tree unitl the root node is found and add encoding
while (currentNode.parent != null) {
if (currentNode.parent.right == currentNode) {
reverseEncoding.set(length);
}
currentNode = currentNode.parent;
length = length + 1;
}
// reverse the encoding
BitSet encoding = new BitSet(length);
for (int i = 0; i < length; ++i) {
if (reverseEncoding.get(length - i - 1)) {
encoding.set(i);
}
}
update(nodeNumber, c);
bos.write(encoding, length);
} |
6a27be01-5dce-48fc-ae6a-9eb2cab0108a | 5 | void nachRechts() {
if (dx < 0) {
dx = 0;
try {
texture = TextureLoader.getTexture("PNG", new FileInputStream(new File(uT.locationMid)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
dx = 3;
try {
texture = TextureLoader.getTexture("PNG", new FileInputStream(new File(uT.locationRight)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
705133cd-f94e-4278-bee6-74e42d26edf4 | 5 | private void parse(Node groupNode) throws UnisensParseException{
NamedNodeMap attr = groupNode.getAttributes();
Node attrNode = attr.getNamedItem(GROUP_ID);
id = (attrNode != null) ? attrNode.getNodeValue():"" ;
attrNode = attr.getNamedItem(GROUP_COMMENT);
comment = (attrNode != null) ? attrNode.getNodeValue() : "";
NodeList groupEntryNodes = groupNode.getChildNodes();
Node groupEntryNode;
int length = groupEntryNodes.getLength();
for(int i = 0 ; i < length ; i++){
groupEntryNode = groupEntryNodes.item(i);
if(groupEntryNode.getNodeType() == Node.ELEMENT_NODE){
String entryId = groupEntryNode.getAttributes().getNamedItem(GROUPENTRY_REF).getNodeValue();
Entry entry = unisens.getEntry(entryId);
if(entry != null)
entries.add(entry);
else
throw new UnisensParseException(String.format("Unvalid unisens.xml : the entry with id %s in group with id %s not exist!", entryId, getId()), UnisensParseExceptionTypeEnum.UNISENS_GROUP_ENTRY_NOT_EXIST);
}
}
} |
bd492600-a060-41dc-8afe-11c34230d4a5 | 5 | public boolean place(int x, int y) { //if all squares are free, place ship and placed == true. if not, return false
if (randomAlignment() == true) {
x = randomWithRange(0,7);
for (int i = x; i < x + 3; i++) {
if (!Grid.isSquareEmpty(i, y)) {
Grid.addToSquare(i, y, this);
position[i][y] = 1;
} else {
return false;
}
}
} else {
y = randomWithRange(0,7);
for (int i = y; i < y + 3; i++) {
if (!Grid.isSquareEmpty(x, i)) {
Grid.addToSquare(x, i, this);
position[x][i] = 1;
} else {
return false;
}
}
}
Grid.addShipToGrid();
placed = true;
return true;
} |
ec8fe500-b87b-4c68-a099-9d71b2019eed | 8 | @Override
public Set<String> composeSample(Distribution base, int maxSize) {
// if all samples fit into the maxSize just return them all.
if (this.getSampleSizeSum() <= maxSize) {
return this.getSampleReferences();
}
TreeSet<String> result = new TreeSet<String>();
Distribution approximateDistribution = new LaplaceDistribution(
GreedySampleComposition.LAPLACE_LAMBDA);
DistributionCompare distCompare = new DistributionCompare();
int currentSize = 0;
TreeSet<String> remaining = new TreeSet<String>();
remaining.addAll(this.getSampleReferences());
// remove all samples which are anyway too big
System.out.println("Cleaning too big distribs");
this.cleanTooBig(remaining, maxSize);
// iteratively select one atomic sample until the maxsize is reached or
// no more (suitable) atomic samples are available
while ((remaining.size() > 0) && (currentSize <= maxSize)) {
String selectedSample = null;
Distribution bestApprox = null;
double minCrossEntropy = Double.POSITIVE_INFINITY;
System.out.println("Searching "+remaining.size()+" options");
int cnt = 0;
for (String sample : remaining) {
cnt++;
if ( (cnt % 100) ==0) {
System.out.print(".");
if ( (cnt % 2000) ==0) {
System.out.println(" "+cnt);
}
}
Distribution sDist = this.getSampleDistribution(sample);
LaplaceDistribution composedDist = new LaplaceDistribution(
GreedySampleComposition.LAPLACE_LAMBDA);
composedDist.mergeFromDistributions(approximateDistribution,
sDist);
double crossEntropy = distCompare.crossEntropy(composedDist,
base);
if ((bestApprox == null) || (crossEntropy < minCrossEntropy)) {
bestApprox = composedDist;
minCrossEntropy = crossEntropy;
selectedSample = sample;
}
}
// update the approximation by taking the best approximation from
// the previous attempt
approximateDistribution = bestApprox;
int size = this.getSampleSize(selectedSample);
result.add(selectedSample);
remaining.remove(selectedSample);
currentSize += size;
System.out.println(size+"\t"+currentSize+" / "+maxSize+"\t"+minCrossEntropy+"\t"+selectedSample);
// Remove samples which are too big
this.cleanTooBig(remaining, maxSize - currentSize);
}
return result;
} |
1ef8d01d-7246-45c9-b1e6-1adff5ce4b89 | 8 | public int largestRectangleArea(int[] height) {
Stack<Integer> stack = new Stack<Integer>();
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
if (stack.isEmpty() || height[stack.peek()] <= height[i]) {
stack.push(i);
} else {
while (!stack.isEmpty() && height[stack.peek()] > height[i]) {
int current = stack.pop();
int area = height[current] * (stack.isEmpty() ? i : (i - stack.peek() - 1));
maxArea = Math.max(area, maxArea);
}
stack.push(i);
}
}
while (!stack.isEmpty()) {
int current = stack.pop();
int area = height[current] * (stack.isEmpty() ? height.length : height.length - stack.peek() - 1);
maxArea = Math.max(area, maxArea);
}
return maxArea;
} |
446ca5b3-bc58-4ee0-a31f-8e31ee164603 | 6 | public List<Edge> incidentEdges(Vertex vertex) {
ArrayList<Edge> edgeList = null;
if (graphType == Type.UNDIRECTED) {
for (EdgeListObject elo : vertex.getIncidenceList()) {
if (edgeList == null)
edgeList = new ArrayList<Edge>();
edgeList.add(elo.getEdge());
}
} else {
List<EdgeListObject> outEdges = vertex.getOutEdges();
if (outEdges != null) {
for (EdgeListObject elo : outEdges) {
if (edgeList == null)
edgeList = new ArrayList<Edge>();
edgeList.add(elo.getEdge());
}
}
}
return edgeList;
} |
88e20fce-af8e-4e4e-a6df-f13e01cc704f | 4 | public mxPoint getParentOffset(Object parent)
{
mxPoint result = new mxPoint();
if (parent != null && parent != this.parent)
{
mxIGraphModel model = graph.getModel();
if (model.isAncestor(this.parent, parent))
{
mxGeometry parentGeo = model.getGeometry(parent);
while (parent != this.parent)
{
result.setX(result.getX() + parentGeo.getX());
result.setY(result.getY() + parentGeo.getY());
parent = model.getParent(parent);;
parentGeo = model.getGeometry(parent);
}
}
}
return result;
} |
324cf5f1-cf0f-41f7-b39e-ca09416a436d | 9 | public void updateDirection(SnakePart s){
if(s.x >= wa || s.y >= ha || s.x < 0 || s.y < 0){
gameEnd();
return;
}
int dir = board[(int) s.x][(int) s.y];
if(dir==1){
s.xD = 0;
s.yD = 1;
}
if(dir==2){
s.xD = -1;
s.yD = 0;
}
if(dir==3){
s.xD = 0;
s.yD = -1;
}
if(dir==4){
s.xD = 1;
s.yD = 0;
}
if(snake.get(snake.size() - 1) == s){
board[(int) s.x][(int) s.y] = 0;
}
} |
b6258568-bba7-41ec-b714-ac8a3f04892d | 8 | public Usage(){
addForm(_defaultprop);
StringBuffer defprop = new StringBuffer();
FileInputStream fin = null;
InputStreamReader ir = null;
BufferedReader br = null;
try {
fin = new FileInputStream(AppUtil.getAppPath() + AppUtil.DEFAULT_PROP_FILE);
ir = new InputStreamReader(fin,"UTF-8");
br = new BufferedReader(ir);
String line;
while ((line = br.readLine()) != null) {
defprop.append(line + "\n");
}
_defaultprop.setModel(new Model(new String( defprop.toString())));
}
catch (Exception e) {
_defaultprop.setModel(new Model("デフォルトプロパティファイルが読み込めませんでした"));
if(br != null){
try {
br.close();
} catch (IOException e1) {
// TODO 自動生成された catch ブロック
e1.printStackTrace();
}
}
if(ir != null){
try {
ir.close();
} catch (IOException e1) {
// TODO 自動生成された catch ブロック
e1.printStackTrace();
}
}
if(fin != null){
try {
fin.close();
} catch (IOException e1) {
// TODO 自動生成された catch ブロック
e1.printStackTrace();
}
}
}
} |
2ab10d4f-2564-4ce5-8abd-ce10e5bee1e5 | 4 | @EventHandler(priority = EventPriority.LOWEST)
public void onLoginServer(ServerConnectEvent e) {
ProxiedPlayer p = e.getPlayer();
if (plugin.maintenanceEnabled && !p.hasPermission("bungeeutils.bypassmaintenance")) {
p.disconnect(new ComponentBuilder("").append(plugin.messages.get(EnumMessage.KICKMAINTENANCE)).create());
return;
}
String name = p.getName();
if (p.hasPermission("bungeeutils.staffcolor")) {
name = plugin.tabStaffColor + name;
} else {
name = plugin.tabDefaultColor + name;
}
if (name.length() > 16) {
p.setDisplayName(name.substring(0, 16));
} else {
p.setDisplayName(name);
}
} |
f5a1c124-e058-47e0-8591-f3d12960abe6 | 0 | public void removePlotter(final Plotter plotter) {
plotters.remove(plotter);
} |
55deab98-5bb2-4eec-9809-cd52319471e0 | 9 | @Override
public void populate(World world, Random random, Chunk chunk) {
if (!isGraveyardSet(chunk) && random.nextInt(4) < 1) {
Vector<GraveyardStructure> structures = new Vector<>();
for (Class<? extends GraveyardStructure> clazz : structureClasses) {
try {
GraveyardStructure newGS = clazz.newInstance();
Location l = null;
if (!newGS.canBeOverlapped()) for (GraveyardStructure gs : structures) {
if (!gs.canBeOverlapped() && newGS.getBlockArea().intersectWith(gs.getBlockArea())) {
l = new Location(world, 1, 1, 1); // TODO
}
}
structures.add(newGS);
newGS.create(world, random, l);
}
catch (InstantiationException | IllegalAccessException e) {
logger.log(Level.SEVERE, "Error", e);
}
}
}
} |
77bd5030-bdb7-48bc-be03-7f54a3065d2b | 2 | @Command(name = "language", usage = "[language]")
@RequiresPermission
private void languageCommand(CommandSender sender, CommandArgs args)
{
if (args.size() > 0)
{
String language = args.getString(0);
Translation tranlation = Translation.get(this.plugin.getClass(), language);
if (tranlation != null)
{
plugin.setTranslation(tranlation);
plugin.getConfig().set("language", language);
plugin.saveConfig();
sender.sendMessage(_("language_changed", _("language_" + tranlation.getLanguage())));
}
else
{
sender.sendMessage(_("language_failed", language));
}
}
else
{
sender.sendMessage(_("language_current", _("language_" + this.plugin.getTranslation().getLanguage())));
}
} |
bb037cfd-bbaa-4c34-a6e7-12b2b6eb9ca3 | 8 | private String testCount() {
String tCount = "";
// report test totals
if (this.numberOfTests == 1) {
tCount = "\nRan 1 test.\n";
} else if (this.numberOfTests > 1) {
tCount = "\nRan " + this.numberOfTests + " tests.\n";
}
// report error totals
if (this.errors == 0) {
tCount = tCount + "All tests passed.\n";
}
if (this.errors == 1) {
tCount = tCount + "1 test failed.\n";
} else if (this.errors > 1) {
tCount = tCount + this.errors + " tests failed.\n";
}
// report warnings totals
if (this.warnings == 0) {
tCount = tCount + "\n";
}
if (this.warnings == 1) {
tCount = tCount + "Issued 1 warning of inexact comparison.\n\n";
} else if (this.warnings > 1) {
tCount = tCount + "Issued " + this.warnings +
" warnings of inexact comparison.\n\n";
}
return tCount;
} |
87064088-e8e9-40d8-8b23-e34000008f83 | 2 | private static ArrayList<String> toStringArrayList(String str) {
ArrayList<String> array = new ArrayList<String>();
String[] Str = str.split("");
for(String s : Str) {
if(s != "") {
array.add(s);
}
}
return array;
} |
16ba7bc6-6488-4fa5-9da3-bbc984c546a4 | 1 | public PropertyTree getNode(int result) {
if(nodes.size()>result) {
return nodes.get(result);
}
return null;
} |
a8b84716-2260-4284-b56c-8b1996634b45 | 3 | public static void main(String[] args) {
Logger logger = null;
try {
logger = new Logger("log.txt");
logger.log("Test 1");
logger.log("Test 2");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (logger != null) {
try {
logger.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
33faa07e-788b-40a0-b53c-40b66db75ece | 9 | void run(){
Scanner sc = new Scanner(System.in);
for(;;){
int n = sc.nextInt();
int m = sc.nextInt();
if((n|m)==0)break;
Map<String, Integer> ref = new HashMap<String, Integer>();
int id = 0;
int s = id; ref.put(sc.next(), id++);
int p = id; ref.put(sc.next(), id++);
int g = id; ref.put(sc.next(), id++);
int[][] e = new int[n][n];
for(int[]a:e)Arrays.fill(a, 1<<29);
while(m--!=0){
String A = sc.next();
String B = sc.next();
int a = -1, b = -1;
if(ref.containsKey(A))a = ref.get(A);
else {
a = id; ref.put(A, id++);
}
if(ref.containsKey(B))b = ref.get(B);
else{
b = id; ref.put(B, id++);
}
int d = sc.nextInt(), t = sc.nextInt();
e[a][b] = e[b][a] = d/40+t;
}
for(int k=0;k<n;k++)for(int i=0;i<n;i++)for(int j=0;j<n;j++)e[i][j] = Math.min(e[i][j], e[i][k]+e[k][j]);
System.out.println(e[s][p]+e[p][g]);
}
} |
8696b6a5-38a6-458a-a9f4-46cf70d6b177 | 0 | protected void initialize() {
_nextDistance();
super.initialize();
} |
b503a5cb-e719-4282-b2f0-a9eab1fffe0a | 6 | public static void main(String[] args) throws IOException {
String host = args[0];
int port = Integer.parseInt(args[1]);
String serviceName = args[2];
BufferedReader in = new BufferedReader(new FileReader(args[3]));
// locate the registry and get ror.
RMIRegistryClient registry = RMIRegistryClient.getRegistry(host, port);
ZipCodeServer zcs;
try {
zcs = (ZipCodeServer) registry.lookup(serviceName, "ZipCodeServerImpl");
// reads the data and make a "local" zip code list.
// later this is sent to the server.
// again no error check!
ZipCodeList l = null;
boolean flag = true;
while (flag) {
String city = in.readLine();
String code = in.readLine();
if (city == null)
flag = false;
else
l = new ZipCodeList(city.trim(), code.trim(), l);
}
// the final value of l should be the initial head of
// the list.
// we print out the local zipcodelist.
System.out.println("This is the original list.");
ZipCodeList temp = l;
while (temp != null) {
System.out.println("city: " + temp.city + ", " + "code: "
+ temp.ZipCode);
temp = temp.next;
}
// test the initialise.
zcs.initialise(l);
System.out.println("\n Server initalised.");
// test the find.
System.out.println("\n This is the remote list given by find.");
temp = l;
while (temp != null) {
// here is a test.
String res = zcs.find(temp.city);
System.out.println("city: " + temp.city + ", " + "code: " + res);
temp = temp.next;
}
// test the findall.
System.out.println("\n This is the remote list given by findall.");
// here is a test.
temp = zcs.findAll();
while (temp != null) {
System.out.println("city: " + temp.city + ", " + "code: "
+ temp.ZipCode);
temp = temp.next;
}
// test the printall.
System.out.println("\n We test the remote site printing.");
// here is a test.
zcs.printAll();
} catch (Remote440Exception e) {
e.printStackTrace();
}
} |
6a6fe739-c4ae-4eb9-bef6-bd5308f79fe7 | 8 | public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand().toLowerCase();
try {
if(cmd != null) {
if (cmd.equals("open interface")) {
selectInterface(ActionHandler.openInterface());
}
if (cmd.equals("show grid")) {
Settings.displayGrid = displayGrid.isSelected();
Settings.write();
}
if (cmd.equals("show data")) {
Settings.displayData = displayData.isSelected();
Settings.write();
}
if (cmd.equals("hover highlight")) {
Settings.displayHover = displayHover.isSelected();
Settings.write();
}
if (cmd.equals("force enabled")) {
Settings.forceEnabled = forceEnabled.isSelected();
Settings.write();
}
if (cmd.equals("save")) {
Main.getInstance().updateArchive(Main.interfaces);
}
}
} catch (Exception e) {
}
} |
efd7da78-32fd-482a-8431-070bf4e441bc | 6 | private static List<BeanMappingObject> parseMappingObject(InputStream in) {
Document doc = XmlHelper.createDocument(
in,
Thread.currentThread().getContextClassLoader().getResourceAsStream(
MAPPING_SCHEMA));
Element root = doc.getDocumentElement();
NodeList globalNodeList = root.getElementsByTagName("global-configurations");
if (globalNodeList.getLength() > 1) {
throw new BeanMappingException("global-configurations is exceed one node!");
}
BeanMappingBehavior globalBehavior = BeanMappingConfigHelper.getInstance().getGlobalBehavior();
if (globalNodeList.getLength() == 1) {
globalBehavior = BeanMappingBehaviorParse.parse(globalNodeList.item(0), globalBehavior);
BeanMappingConfigHelper.getInstance().setGlobalBehavior(globalBehavior);
}
NodeList classAliasNodeList = root.getElementsByTagName("class-alias-configurations");
for (int i = 0; i < classAliasNodeList.getLength(); i++) {
ClassAliasParse.parseAndRegister(classAliasNodeList.item(i));
}
NodeList convertorNodeList = root.getElementsByTagName("convertors-configurations");
for (int i = 0; i < convertorNodeList.getLength(); i++) {
ConvertorParse.parseAndRegister(convertorNodeList.item(i));
}
NodeList functionClassNodeList = root.getElementsByTagName("function-class-configurations");
for (int i = 0; i < functionClassNodeList.getLength(); i++) {
FunctionClassParse.parseAndRegister(functionClassNodeList.item(i));
}
NodeList nodeList = root.getElementsByTagName("bean-mapping");
List<BeanMappingObject> mappings = new ArrayList<BeanMappingObject>();
// 解析BeanMappingObject属性
for (int i = 0; i < nodeList.getLength(); i++) {
BeanMappingObject config = BeanMappingParse.parse(nodeList.item(i), globalBehavior);
// 添加到返回结果
mappings.add(config);
}
return mappings;
} |
9a9512e0-e4cb-4f43-863c-2cd8753dcb27 | 6 | @Override
public Predictors<MultiClassLabel> process(Predictors<Collection<MultiClassLabel>> input) throws Exception {
Predictors<MultiClassLabel> res = new Predictors<MultiClassLabel>(input.size());
for(int i = 0; i<input.size(); i++) {
Collection<MultiClassLabel> sets = input.get(i);
TIntIntMap counters = new TIntIntHashMap();
for(MultiClassLabel set : sets){
for(int v : set.getClasses()) {
counters.adjustOrPutValue(v, 1, 1);
}
}
int[] values = counters.values();
Arrays.sort(values);
final int threshold = values.length > N ? values[values.length - N] : 0;
if (threshold <= 1){
getContext().getProgressReporter().reportWarning("Top three threshold is too low, not enough data? ");
}
final TIntSet r = new TIntHashSet();
counters.forEachEntry(new TIntIntProcedure() {
@Override
public boolean execute(int a, int b) {
if (b >= threshold){
r.add(a);
}
return true;
}
});
res.set(i, new MultiClassLabel(r.toArray()));
}
return res;
} |
dd0b8513-1ee5-466d-977a-26baeb354292 | 6 | public double[] getRandLetterNoise(double ordM, double invM) throws IOException {
char letter;
Random r = new Random();
letter = (char) (r.nextInt(5) + 'J');
BufferedImage letterImage = ImageIO.read(getClass().getResource("/images/" + letter + ".png"));
double[] result = new double[400];
int rand;
for (int i = 0 ; i< 20; i++)
for (int k = 0 ; k< 20; k++){
if (Math.random() > (1 - ordM))
{
rand = r.nextInt(255);
letterImage.setRGB(i, k, new Color(rand,rand, rand ).getRGB() );
}
if (Math.random() > (1 - invM))
letterImage.setRGB(i, k, 0xFFFFFF - letterImage.getRGB(i, k) );
}
int m;
int rgb ;
int red ;
int green ;
int blue ;
for (int i = 0 ; i< 20; i++)
for (int k = 0 ; k< 20; k++){
rgb = letterImage.getRGB(i, k);
red = (rgb >> 16) & 0xFF;
green = (rgb >> 8) & 0xFF;
blue = (rgb & 0xFF);
result[20*i + k] = ((red + green + blue) / 3) - 128;
m = letterImage.getRGB(i, k);
}
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
ImageIcon icon = new ImageIcon( letterImage );
lastImage = icon;
double d = 0;
lastLetter = letter;
lastArrayImage = result;
return result;
} |
5cf14334-9bdc-46a3-8d07-2352db7981af | 4 | public static boolean isImprimivel(Tipo tipo)
{
switch(tipo){
case INTEIRO:
case REAL:
case CARACTERE:
case CADEIA:
return true;
default:
return false;
}
} |
9c108b46-08b7-45b2-8c39-9506345718a8 | 1 | public void map_move_step(int x, int y) {
Gob pgob;
int btn = 1;
int modflags = 0;
synchronized (glob.oc) {
pgob = glob.oc.getgob(playergob);
}
if (pgob == null)
return;
Coord mc = tilify(pgob.position());
Coord offset = new Coord(x, y).mul(tileSize);
mc = mc.add(offset);
wdgmsg("click", JSBotUtils.getCenterScreenCoord(), mc, btn, modflags);
} |
6f879d88-41b2-4e54-ba13-3b5c66048e29 | 7 | @Override
public NameData[] getNameData() {
int length = crawledData.length;
updateStatus(length, 0, 0, 0);
if(length == 0) return null;
for(int i = 0; i < length; i++) {
cd = crawledData[i];
// Für jedes crawledData wird neu angefangen nach Künstlern zu suchen.
foundNameIDs.clear();
cachedOneNameIDs.clear();
String[] textBlocks = cd.getTextBlocks();
for(int t = 0; t < textBlocks.length; t++) {
String text = textBlocks[t];
if(text.length() == 0) continue;
tokens.clear();
tokens.add("");
tokens.add("");
perPos.clear();
String taggedText = classifier.classifyWithInlineXML(text);
// Alle Satzzeichen, auf denen das folgende Wort großgeschrieben sein könnte abrücken.
taggedText = rPuncts.matcher(taggedText).replaceAll(" $0 ");
Matcher m = rSplit.matcher(taggedText);
while(m.find()) {
// Anführungszeichen am Anfang oder Ende entfernen.
String token = rQuotes.matcher(m.group()).replaceAll("");
if(rTags.matcher(token).matches()) {
if(token.contains("<I-PER>")) {
token = token.replace("<I-PER>", "");
token = token.replace("</I-PER>", "");
token = rPuncts2.matcher(token).replaceAll("");
token = rTwoNames.matcher(token).replaceAll("$1 $2");
perPos.add(tokens.size());
}
else {
token = "";
}
}
tokens.add(token);
}
// Namen mit DB vergleichen.
findNamesInDB();
// Vor Namen nach Künstler-Bezeichnung suchen.
findNamesByTitle();
// Restlichen getaggten Namen entfernen.
removeRemainingTokens();
// Restlichen Wörter nach Namen durchsuchen.
searchRemainingWords();
updateStatus(length, i+1, textBlocks.length, t+1);
}
}
return foundNames.toArray(new NameData[foundNames.size()]);
} |
75d29e0a-acab-4086-a44d-21506714edd4 | 8 | public void loop(){
int counter = 0;
printOptions();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true){
int i = 5;
try {
i = Integer.valueOf(br.readLine());
if (i<0 || i>2){
System.out.println("Please enter a number between 0 and 2");
printOptions();
}
} catch (NumberFormatException e) {
System.out.println("Please enter a number between 0 and 2");
} catch (IOException e) {
System.out.println("Please enter a number between 0 and 2");
}
if (i==0){
exportMostCorrelated();
printOptions();
}
else if (i==1){
printToScreen();
printOptions();
}
else if (i==2){
System.exit(0);
}
}
} |
49ca64c9-9968-46ba-9e85-a0559c44dcb2 | 6 | 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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
} |
e8ba2bdb-b623-4ddd-9fc0-a0e023300122 | 5 | public Tile(int x, int y, int typeInt) {
tileX = x * 40;
tileY = y * 40;
type = typeInt;
r = new Rectangle();
if (type == 5) {
tileImage = StartingClass.tiledirt;
} else if (type == 8) {
tileImage = StartingClass.tilegrassTop;
} else if (type == 4) {
tileImage = StartingClass.tilegrassLeft;
} else if (type == 6) {
tileImage = StartingClass.tilegrassRight;
} else if (type == 2) {
tileImage = StartingClass.tilegrassBot;
} else {
type = 0;
}
} |
2506f634-d78a-4b1e-a6ce-25c3908da43b | 8 | public int compare(Object o1, Object o2)
{
final EdgeCrossing a = (EdgeCrossing)o1;
final EdgeCrossing b = (EdgeCrossing)o2;
if(a.getAngle() < b.getAngle())
{
return -1;
}
if(a.getAngle() > b.getAngle())
{
return 1;
}
// Angles are equal.
if(a.getAngle() == 0)
{
return (a.getY() < b.getY()) ? -1 : (a.getY() > b.getY()) ? 1 : 0;
}
if(a.getAngle() == 2)
{
return (a.getY() > b.getY()) ? -1 : (a.getY() < b.getY()) ? 1 : 0;
}
throw new RuntimeException("No result");
} |
2b20581f-c48d-455e-ae5f-1cd7f41fca6a | 6 | public static void analyseResults(File resultFile)
{
try
{
int correctHams = 0;
int correctSpams = 0;
int incorrectHams = 0;
int incorrectSpams = 0;
int lineCounter = 0;
Scanner sc = new Scanner(resultFile);
File analysisFile = new File("analysis3.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(analysisFile));
while (sc.hasNextLine())
{
String tempLine = sc.nextLine();
String[] splitLine = tempLine.split(" ");
lineCounter = Integer.parseInt(splitLine[0]);
if (lineCounter < 401)
{
bw.write(lineCounter + " " + splitLine[1] + " " + splitLine[2] + " spam ");
if (splitLine[2].compareTo("spam") == 0)
{
bw.write("correct");
correctSpams++;
}
else
{
bw.write("incorrect");
incorrectSpams++;
}
}
else
{
bw.write(lineCounter + " " + splitLine[1] + " " + splitLine[2] + " ham ");
if (splitLine[2].compareTo("ham") == 0)
{
bw.write("correct");
correctHams++;
}
else
{
bw.write("incorrect");
incorrectHams++;
}
}
bw.newLine();
}
bw.write("Correct Hams = " + correctHams + " IncorrectHams = " + incorrectHams + " Correct Spams = " + correctSpams + " IncorrectSpams = " + incorrectSpams);
bw.newLine();
int totalCorrect = correctHams + correctSpams;
bw.write(String.valueOf(totalCorrect));
bw.close();
}
catch (FileNotFoundException f)
{
System.out.println(f.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
} |
719d5b43-dd96-4dbf-806a-a9ccb0de185e | 1 | public DataPoint(double one, int to, double two, int tt, double three, int tth, double four, int tf, double five, int tfi )
{
p1 = one;
p2 = two;
p3 = three;
p4 = four;
p5 = five;
t1 = to;
t2 = tt;
t3 = tth;
t4 = tf;
t5 = tfi;
//Fill the array with values to feed to perceptrons
fVals[0] = p1;
fVals[1] = p2;
fVals[2] = p3;
fVals[3] = p4;
fVals[4] = p5;
//Fill the array with times to feed to perceptrons
tVals[0] = t1;
tVals[1] = t2;
tVals[2] = t3;
tVals[3] = t4;
tVals[4] = t5;
if(p1/t1/p2/t2/p3/t3/p4/t4/p5/t5>0)
{
isValid = true;
}
//Generate boolean values from the date of the first point
genFeatures();
} |
10ec8dd5-f57c-404b-ac3c-245bcff5f9ac | 9 | public static void main(String[] args) throws Exception {
String host = null;
int port = -1;
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "] = " + args[i]);
}
if (args.length < 2) {
System.out.println("USAGE: java client host port");
System.exit(-1);
}
try { /* get input parameters */
host = args[0];
port = Integer.parseInt(args[1]);
} catch (IllegalArgumentException e) {
System.out.println("USAGE: java client host port");
System.exit(-1);
}
try { /* set up a key manager for client authentication */
SSLSocketFactory factory = null;
try {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
KeyManagerFactory kmf = KeyManagerFactory
.getInstance("SunX509");
TrustManagerFactory tmf = TrustManagerFactory
.getInstance("SunX509");
SSLContext ctx = SSLContext.getInstance("TLS");
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String inputKeystore = System.console().readLine("Keystore: ");
char[] inputPass = System.console().readPassword("Password: ");
ks.load(new FileInputStream("stores/"+inputKeystore+"keystore"), inputPass); // keystore
// password
// (storepass)
ts.load(new FileInputStream("stores/"+inputKeystore+"truststore"),
inputPass); // truststore password (storepass);
kmf.init(ks, inputPass); // user password (keypass)
tmf.init(ts); // keystore can be used as truststore here
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
factory = ctx.getSocketFactory();
} catch (IOException e) {
System.out.println(e.getMessage());
throw new IOException(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception(e.getMessage());
}
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
System.out.println("\nsocket before handshake:\n" + socket + "\n");
/*
* send http request
*
* See SSLSocketClient.java for more information about why there is
* a forced handshake here when using PrintWriters.
*/
socket.startHandshake();
SSLSession session = socket.getSession();
X509Certificate cert = (X509Certificate) session
.getPeerCertificateChain()[0];
String subject = cert.getSubjectDN().getName();
System.out
.println("certificate name (subject DN field) on certificate received from server:\n"
+ subject + "\n");
System.out.println("socket after handshake:\n" + socket + "\n");
System.out.println("secure connection established\n\n");
BufferedReader read = new BufferedReader(new InputStreamReader(
System.in));
ObjectInputStream inStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String msg;
for (;;) {
msg = read.readLine();
if (msg.equalsIgnoreCase("quit")) {
break;
}
Request req = generateRequest(msg);
if (req!=null) {
outStream.writeObject(req);
outStream.flush();
AckResponse resp = (AckResponse) inStream.readObject();
System.out.println("Recieved response with message:\n" + resp.getMessage());
}
}
in.close();
outStream.close();
read.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
5949625b-def1-4345-ae16-2e1f4c5e1a75 | 8 | @Override
public QueryResult execQuery(Query q) {
Statement st = null;
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
if(!q.isParsed()) {
q.parse();
}
try {
st = con.createStatement();
ResultSet res = st.executeQuery(q.getParsedQuery());
while(res.next()) {
HashMap<String, String> row = new HashMap<String, String>();
ResultSetMetaData rsmd = res.getMetaData();
int columns = rsmd.getColumnCount();
for(int i = 1; i < columns + 1; i++) {
row.put(rsmd.getColumnName(i).toLowerCase(), res.getString(i));
}
data.add(row);
}
}catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, " Could not execute query!");
if(this.dbg) {
plugin.getLogger().log(Level.INFO, e.getMessage(), e);
}
} finally {
try {
if(st != null) {
st.close();
}
}catch (Exception e) {
plugin.getLogger().log(Level.SEVERE, " Could not close database connection");
if(this.dbg) {
plugin.getLogger().log(Level.INFO, e.getMessage(), e);
}
}
}
return QueryResult.QR(data);
} |
fd1948dd-e554-421d-b99c-8230858e0638 | 3 | private boolean noTeleporterOnWall(Grid grid) {
List<Teleporter> teleports = getTeleportersOfGrid(grid);
for (Teleporter teleport : teleports) {
final Position tpPos = grid.getElementPosition(teleport);
for (Element e : grid.getElementsOnPosition(tpPos))
if (e instanceof Wall)
return false;
}
return true;
} |
6b3f4c79-0342-459a-b837-e39555d2c383 | 8 | private void algo() {
// Step 1 -
// initialize the zero flow (if none is given)
// mark Quelle
init();
// Step 2
// save the current to be inspected Vertice into vi.
// end loop, if there are no more.
for (Long vi = popFromQueue(); vi != -1L; vi = popFromQueue()) {
// filter all edges by O(vi) and I(vi).
List<Set<Long>> partition = makeInOutPartitionOf(vi);
Set<Long> incoming = partition.get(0);
Set<Long> outgoing = partition.get(1);
// Forward-edges
for (Long eID : outgoing) {
increaseAccess(); // Zugriff auf ein Edge
long vj = graph.getTarget(eID);
// make the forward-mark of for every edge that goes from vi to
// an yet unmarked
if (!verticeIsMarked(vj) && f(eID) < c(eID)) {
saveForwardEdge(eID, vj, vi);
}
}
// Backward-edges
for (Long eID : incoming) {
increaseAccess(); // Zugriff auf ein Edge
long vj = graph.getSource(eID);
// make the backward-mark of for every edge that goes from vi to
// an yet unmarked vj
if (!marked.containsKey(vj) && f(eID) > 0) {
saveBackwardEdge(eID, vj, vi);
}
}
// an dieser Stelle im Code wurde frueher der Vertice als inspected
// gesetzt. In EdmondsKarp passiert dies schon beim Entnehmen aus der Queue.
// Step 3
// if the senke/destination was reached(marked) then augment the flow
if (verticeIsMarked(destId)) {
// step three. calculate the augmenting path and update the flow
updateByAugmentingPath();
}
}
// Step 4
// we're finished now!
} |
0b538c36-f293-40b1-95c7-53c610350027 | 4 | @Override
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
super.startElement(uri, localName, name, atts);
if (numLayers > 0
&& startRecordingElementName.equalsIgnoreCase(localName)
&& "class".equalsIgnoreCase(atts.getLocalName(0))
&& startRecordingElementAttrName.equalsIgnoreCase(atts
.getValue("class"))) {
startRecording = true;
}
} |
5422ac0b-351f-40e8-9c7a-1874d633ff65 | 3 | @Override
public int loginUser(UserRequest request) {
int result = -1;
User unvalidatedUser = new User(request.getUsername(), request.getPassword());
int index = users.indexOf(unvalidatedUser);
if(index > -1) {
IUser validUser = users.get(index);
result = (validUser.getPassword().equals(unvalidatedUser.getPassword()) && validUser.getUserame().equals(unvalidatedUser.getUserame())) ? index : -1;
}
System.out.println("User login return code: " + result);
return result;
} |
aa22935b-5eee-40be-bbfa-00baf30a2f16 | 6 | 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(LetterEditFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LetterEditFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LetterEditFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LetterEditFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LetterEditFormViewController().setVisible(true);
}
});
} |
10b2ed59-df5c-46ff-b4b6-7d7672b6fefc | 1 | public final void enqueue() {
if (nextOnQueue == null) {
this.nextOnQueue = notifyQueue.first;
notifyQueue.first = this;
}
} |
03e2bc08-870b-43c9-9c60-c34387e997a3 | 7 | public BigInteger[][] getEncryptionKeys(BigInteger[] keyArray) {
// String keyString
BigInteger[] outputArray = new BigInteger[52];
// BigInteger[] keyArray = Helper.stringToBigIntegerArray(keyString);
BigInteger key = Helper.bigIntegerArraySum(keyArray, 8);
BigInteger[] shortKeyArray = Helper.extractValues(key, 16, 8);
// get keys
int i = 0;
while (i != 52) {
for (int j = 0; j < shortKeyArray.length; j++) {
BigInteger tmp = shortKeyArray[j];
outputArray[i++] = tmp;
if (i == 52) {
break;
}
}
if (i != 52) {
key = Helper.shift(key, 16, 25);
shortKeyArray = Helper.extractValues(key, 16, 8);
}
}
// get as 2d array
BigInteger[][] nicerArray = new BigInteger[9][6];
int counter = 0;
for (int zeile = 0; zeile < nicerArray.length; zeile++) {
for (int spalte = 0; spalte < nicerArray[zeile].length; spalte++) {
nicerArray[zeile][spalte] = outputArray[counter++];
if (counter == 52) {
return nicerArray;
}
}
}
return nicerArray;
} |
7b980ead-aaa5-426f-8f41-9c03042be4e5 | 0 | public int getStatus() {
return this.Status;
} |
144afce5-832f-4c77-a6f9-56daf4f28dee | 7 | public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// @Override
// public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse response)throws Exception {
String code = req.getParameter("code");
if (code == null || code.equals("")) {
// an error occurred, handle this
}
System.out.println("SignInFB -- ok 1 - ");
String token = null;
try {
String g = "https://graph.facebook.com/oauth/access_token?client_id=293207454144373&redirect_uri=" + URLEncoder.encode("http://localhost:8080/ProWayHub/signin_fb.htm", "UTF-8") + "&client_secret=533dd055d3280917d59b42ee1c008c63&code=" + code;
URL u = new URL(g);
URLConnection c = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer b = new StringBuffer();
while ((inputLine = in.readLine()) != null)
b.append(inputLine + "\n");
in.close();
token = b.toString();
if (token.startsWith("{"))
throw new Exception("error on requesting token: " + token + " with code: " + code);
} catch (Exception e) {
// an error occurred, handle this
}
System.out.println("SignInFB -- ok 2 - ");
String graph = null;
try {
String g = "https://graph.facebook.com/me?" + token;
URL u = new URL(g);
URLConnection c = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer b = new StringBuffer();
while ((inputLine = in.readLine()) != null)
b.append(inputLine + "\n");
in.close();
graph = b.toString();
System.out.println("SignInFB -- ok 3 - ");
} catch (Exception e) {
// an error occurred, handle this
}
String facebookId = "";
String firstName = "";
String middleNames = "";
String lastName = "";
String email = "";
// Gender gender;
// try {
// JSONObject json = new JSONObject(graph);
/* facebookId = json.getString("id");
firstName = json.getString("first_name");
if (json.has("middle_name"))
middleNames = json.getString("middle_name");
else
middleNames = null;
if (middleNames != null && middleNames.equals(""))
middleNames = null;
lastName = json.getString("last_name");
email = json.getString("email");*/
/* if (json.has("gender")) {
String g = json.getString("gender");
if (g.equalsIgnoreCase("female"))
gender = Gender.FEMALE;
else if (g.equalsIgnoreCase("male"))
gender = Gender.MALE;
else
gender = Gender.UNKNOWN;
} else {
gender = Gender.UNKNOWN;
}*/
System.out.println("SignInFB -- block try - "+graph);
// } catch (JSONException e) {
// an error occurred, handle this
System.out.println("SignInFB -- block catch - ");
//}
// return mapping.findForward(SUCCESS);
} |
21ec61b0-c352-40ee-81f2-d4178fd386d5 | 3 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
Transferable clipboardContent = getToolkit().getSystemClipboard().getContents(this);
if ((clipboardContent != null)
&& (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) {
try {
String tempString;
tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
jTextArea1.setText(tempString);
} catch (Exception e) {
e.printStackTrace();
}
}
}//GEN-LAST:event_jButton2ActionPerformed |
479be841-2867-4cff-bd42-528e6a3aaafb | 3 | public boolean load(String audiofile) {
try {
setFilename(audiofile);
sample = AudioSystem.getAudioInputStream(getURL(filename));
clip.open(sample);
return true;
} catch (IOException e) {
return false;
} catch (UnsupportedAudioFileException e) {
return false;
} catch (LineUnavailableException e) {
return false;
}
} |
e3c43998-a3a0-4456-b869-2cdf8d8585d0 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Atendimento)) {
return false;
}
Atendimento other = (Atendimento) object;
if ((this.codatendimento == null && other.codatendimento != null) || (this.codatendimento != null && !this.codatendimento.equals(other.codatendimento))) {
return false;
}
return true;
} |
32ab5123-dfd0-458f-bc03-bffc045bb48c | 0 | public void addSubCategory(SubCategory scat)
{
this.subcategories.add(scat);
} |
cb57497e-a528-4b8e-a674-222c5819d307 | 9 | @Override
public boolean equals(Object o) {
if (null == o || !(o instanceof BytesKey)) {
return false;
}
BytesKey k = (BytesKey) o;
if (null == k.getData() && null == this.getData()) {
return true;
}
if (null == k.getData() || null == this.getData()) {
return false;
}
if (k.getData().length != this.getData().length) {
return false;
}
for (int i = 0; i < this.data.length; ++i) {
if (this.data[i] != k.getData()[i]) {
return false;
}
}
return true;
} |
9c06e962-8e63-4f58-916b-f16160ba3718 | 1 | public boolean isDownloadList() {
MediaUrlDao mediaUrlDao = new MediaUrlDao();
mediaUrlModelList = mediaUrlDao.getUrlList();
if (mediaUrlModelList.size() > 0 ) {
return true;
}
return false;
} |
8a5b7aa9-a8dc-4786-8258-e2d65a23c76b | 8 | public String weekday_name( int weekday )
{
String result = "";
if ( weekday == 1 )
{
result = "Sunday";
}
else if ( weekday == 2 )
{
result = "Monday";
}
else if ( weekday == 3 )
{
result = "Tuesday";
}
else if ( weekday == 4 )
{
result = "Wednesday";
}
else if ( weekday == 5 )
{
result = "Thursday";
}
else if ( weekday == 6 )
{
result = "Friday";
}
else if ( weekday == 7 )
{
result = "Saturday";
}
else if ( weekday == 0 )
{
result = "Saturday";
}
else
{
result = "error";
}
return result;
} |
3e20ec73-ab68-44d5-be8c-90caee45a6d0 | 9 | private String getSFieldEntries(){
String output = "";
Integer counter = 0;
for (int i = 0; i < this.sObjects().length; i++) {
if(!this.objects.equals("all") && !this.objectList().contains(sObjects()[i].getName().toLowerCase() )){
continue;
}
if(this.limit != -1 && counter++ > this.limit){ break;}
String object_name = "ALL_" + this.getFormattedObjectName(this.sObjects()[i]) + "_FIELDS";
String sfieldTemplate = this.ROW_TEMPLATE;
sfieldTemplate = sfieldTemplate.replace("{{object_name}}", object_name);
String field_list = "";
DescribeSObjectResult describeSObjectResult = null;
try {
describeSObjectResult = this.salesforceConnection().getPartnerConnection().describeSObject(this.sObjects()[i].getName());
} catch (ConnectionException e) {
e.printStackTrace();
}
Field[] fields = describeSObjectResult.getFields();
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];
if(this.ignoreFieldList().size() > 0 && this.ignoreFieldList().contains(field.getName().toLowerCase() )){
continue;
}
field_list += field.getName() + ",";
}
field_list = field_list.substring(0, field_list.length() - 1);
sfieldTemplate = sfieldTemplate.replace("{{field_list}}", field_list);
output += "\t" + sfieldTemplate + "\n";
}
return output;
} |
1ae5809c-cfad-42d8-b637-0a3acb0be177 | 6 | public void testInferenceProblemStoreReuse() {
System.out.println("\n**** testInferenceProblemStoreReuse ****");
CycAccess cycAccess = null;
try {
try {
if (connectionMode == LOCAL_CYC_CONNECTION) {
cycAccess = new CycAccess(testHostName, testBasePort);
} else if (connectionMode == SOAP_CYC_CONNECTION) {
cycAccess = new CycAccess(endpointURL, testHostName, testBasePort);
} else {
fail("Invalid connection mode " + connectionMode);
}
} catch (Throwable e) {
fail(StringUtils.getStringForException(e));
}
try {
if (!cycAccess.isOpenCyc()) {
final String inferenceProblemStoreName = "my-problem-store";
cycAccess.initializeNamedInferenceProblemStore(inferenceProblemStoreName, null);
CycFormulaSentence query = cycAccess.makeCycSentence("(#$objectFoundInLocation ?WHAT ?WHERE)");
CycList variables = new CycList();
variables.add(makeCycVariable("?WHAT"));
variables.add(makeCycVariable("?WHERE"));
InferenceParameters queryProperties = new DefaultInferenceParameters(cycAccess);
CycConstant universeDataMt = cycAccess.getKnownConstantByGuid(UNIVERSE_DATA_MT_GUID_STRING);
CycList response = cycAccess.queryVariables(variables, query, universeDataMt, queryProperties, inferenceProblemStoreName);
assertNotNull(response);
response = cycAccess.queryVariables(variables, query, universeDataMt, queryProperties, inferenceProblemStoreName);
assertNotNull(response);
response = cycAccess.queryVariables(variables, query, universeDataMt, queryProperties, inferenceProblemStoreName);
assertNotNull(response);
cycAccess.destroyInferenceProblemStoreByName(inferenceProblemStoreName);
}
} catch (Throwable e) {
e.printStackTrace();
fail(e.toString());
}
} finally {
if (cycAccess != null) {
cycAccess.close();
cycAccess = null;
}
}
System.out.println("**** testInferenceProblemStoreReuse OK ****");
} |
b48960b0-b78b-40f5-acff-be37c22758b4 | 9 | protected void genGender(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
mob.tell(L("@x1. Gender: '@x2'.",""+showNumber,""+Character.toUpperCase((char)E.baseCharStats().getStat(CharStats.STAT_GENDER))));
if((showFlag!=showNumber)&&(showFlag>-999))
return;
final String newType=mob.session().choose(L("Enter a new gender (M/F/N)\n\r:"),L("MFN"),"");
int newValue=-1;
if(newType.length()>0)
newValue=("MFN").indexOf(newType.trim().toUpperCase());
if(newValue>=0)
{
switch(newValue)
{
case 0:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'M');
break;
case 1:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'F');
break;
case 2:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'N');
break;
}
}
else
mob.tell(L("(no change)"));
} |
79c2cf24-a643-4005-9c11-71c2924bb5d0 | 1 | public void collideVertical() {
// check if collided with ground
if (getVelocityY() > 0) {
onGround = true;
}
setVelocityY(0);
} |
43245c1c-cbc1-40bb-8071-e3cd52cc6820 | 3 | public void setColor(int r, int g, int b){
double dR = mapIntColToDoubleCol(r), dG = mapIntColToDoubleCol(g), dB = mapIntColToDoubleCol(b);
if((colorR != dR)||(colorG != dG)||(colorB != dB)){
//only print the statement, if the color changed
colorR = dR;
colorG = dG;
colorB = dB;
println(colorR+" "+colorG+" "+colorB+" setrgbcolor");
}
} |
47947f8b-34cc-4a38-91a2-a0368145aba3 | 1 | public AudioThread(int port) {
try{
serverSocket = new ServerSocket(port);
} catch (Exception e){ e.printStackTrace(); }
} |
83bcbb48-07ba-439b-926a-ff70914c93f0 | 1 | private HTMLPanel createFeedbackPanel(List<String> history) {
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<div id = 'feedbackHistoryPanel'>"
+ "<div class='panelTitle'>"+constants.Feedback()+"</div>");
for (String h : history) {
htmlBuilder.append("<div class='FeedbackEntry'>"+h+"</div>");
}
htmlBuilder.append("</div>");
String html = htmlBuilder.toString();
HTMLPanel panel = new HTMLPanel(html);
return panel;
} |
72f92c11-e5ac-44d0-8d6a-e8c4ec5ba968 | 0 | public void scrub() {
append(" Detergent.scrub()");
super.scrub(); // Call base-class version
} |
8df311e2-9725-4d9d-bd4b-8031e8c3d1d7 | 6 | @Override
public void mutate() {
Population offspring = new Population();
for (int i = 0; i < population.getSize(); ++i){
double r;
synchronized (rng){
r = rng.nextDouble();
}
if (r < PROBABILITY){
HiffIndividual mutant = new HiffIndividual(population.getIndividual(i));
int possition;
synchronized (rng){
possition = Math.abs(rng.nextInt()) % mutant.getSize();
}
for (int k = possition; k < mutant.getSize(); ++k){
mutant.inverse(k);
}
offspring.addIndividual(mutant);
} else {
offspring.addIndividual(new HiffIndividual(population.getIndividual(i)));
}
}
double bestOld = population.getFittest();
double bestNew = offspring.getFittest();
if (bestNew > bestOld){
reward = 1;
for (int i = 0; i < population.getSize(); ++i){
population.setIndividual(i, offspring.getIndividual(i));
}
} else if (bestNew == bestOld){
// reward = 0.5;
reward = 0;
} else {
reward = 0;
}
} |
566dda85-392c-45ca-9e02-934dd22ac385 | 9 | @SuppressWarnings("unchecked")
private StringBuilder traverse(Object object, String path) throws IllegalAccessException, InvocationTargetException {
StringBuilder ret = new StringBuilder();
if (isSkipObject(object)) {
return ret;
}
Method[] methods = object.getClass().getMethods();
if (object instanceof List) {
List list = (List) object;
int size = list.size();
if (size > 0 || includeEmptyLists) {
ret.append(buildEquals(String.valueOf(size), path + ".size()"));
}
for (int i = 0; i < list.size(); i++) {
Object listElement = list.get(i);
ret.append(processResult(null, listElement, buildPathListEntry(path, i, listElement), false));
}
} else {
for (Method currMethod : methods) {
if (isRelevantGetter(currMethod)) {
Object result = null;
try {
result = currMethod.invoke(object, (Object[]) null);
} catch (Exception e) {
//getter exceptions ignorieren
}
try {
// ret.append(processResult(result, buildPath(curr,
// result,
// path)));
ret.append(processResult(currMethod, result, path, false));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
return ret;
} |
7aed50bb-e904-4aba-8f66-ff99b3d139d8 | 9 | protected int findLastUnion() {
int split = -1;
int depth = 0;
int end = start + length;
for (int i = end - 1; i != start; i--) {
switch (expr[i]) {
case '}':
case ']':
depth++;
break;
case '{':
case '[':
if (--depth == 0) {
split = i;
collection = true;
}
break;
case '.':
if (depth == 0) {
split = i;
}
break;
}
if (split != -1) break;
}
return split;
} |
02fccbb7-77d8-49c9-9062-6dd2448294f4 | 8 | @Test
public void testToStringSockClosedSocketThread() {
LOGGER.log(Level.INFO, "----- STARTING TEST testToStringSockClosedSocketThread -----");
try {
server1.startThread();
} catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) {
exception = true;
}
waitListenThreadStart(server1);
Sock sock = null;
try {
sock = new Sock("127.0.0.1", port);
} catch (IOException e) {
exception = true;
}
SocketThread new_socket_thread = new SocketThread(sock, server2, "TEST");
try {
new_socket_thread.getSocket().close();
} catch (IOException e) {
exception = true;
}
boolean loop = false;
Timing new_timer = new Timing();
while (loop) {
if ((new_socket_thread.getSocket().getSocket() == null && new_socket_thread.getSocket().getIn() == null && new_socket_thread.getSocket().getOut() == null) || new_timer.getTime() > timeout) {
loop = false;
}
}
String to_string = null;
to_string = new_socket_thread.toString();
Assert.assertFalse(exception, "Exception found");
Assert.assertNotEquals(to_string, null, "SocketThread data not generated into a readable String with added character");
LOGGER.log(Level.INFO, "SocketThread String details: \n{0}", to_string);
LOGGER.log(Level.INFO, "----- TEST testToStringSockClosedSocketThread COMPLETED -----");
} |
1572b413-0550-43dd-8bd9-e6ea7239e02a | 1 | private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
if(DescField51.getText() != null)
{
readsettings.write((String)jComboBox1.getSelectedItem(), DescField51.getText() );
JOptionPane.showMessageDialog(null, "Settings changed!", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE);
login_area.open1 = 0;
this.setVisible(false);
}
}//GEN-LAST:event_jButton3MouseClicked |
6b5292c3-fdd8-4fb1-b582-8807571ef32b | 0 | public Timestamp getCreateDateGmt() {
return this.createDateGmt;
} |
5d09e821-62bc-448e-aa9f-31c954860ab5 | 8 | private boolean connected(Country a, Country b) {
if (a == null || b == null) {
return false;
}
if (a.getUnit().getArmy() != b.getUnit().getArmy()) {
return false;
}
boolean[] visited = new boolean[42];
Queue<Country> searchQ = new ArrayDeque<Country>();
searchQ.add(a);
while (!searchQ.isEmpty()) {
Country top = searchQ.remove();
if (top == b) {
return true;
}
for (Country c : top.getConnections()) {
if (c.getUnit().getArmy() == top.getUnit().getArmy()
&& !visited[c.getId() - 1]) {
searchQ.add(c);
visited[c.getId() - 1] = true;
}
}
}
return false;
} |
69f7253b-6140-4b95-8d3a-70f5e3f58e45 | 0 | public int getManaRegen()
{
return manaRegen;
} |
1c3aed89-8b7d-4c40-86eb-dd9be8bb6f9d | 4 | public static char nextLetter(char letter) {
if (letter == 'Z') {
return 'A';
}
else if (letter == 'z') {
return 'a';
}
for (int i = 0; i < 51; i++) {
if (getAlphabet(true).charAt(i) == letter) {
return getAlphabet(true).charAt(i + 1);
}
}
//keeps compiler happy
return ' ';
} |
eae71764-f4e0-4a57-8ec4-0e0397c3a5de | 7 | protected Option[] discoverOptionsViaReflection() {
Class<? extends AbstractOptionHandler> c = this.getClass();
Field[] fields = c.getFields();
List<Option> optList = new LinkedList<Option>();
for (Field field : fields) {
String fName = field.getName();
Class<?> fType = field.getType();
if (fName.endsWith("Option")) {
if (Option.class.isAssignableFrom(fType)) {
Option oVal = null;
try {
field.setAccessible(true);
oVal = (Option) field.get(this);
} catch (IllegalAccessException ignored) {
// cannot access this field
}
if (oVal != null) {
optList.add(oVal);
}
}
}
}
return optList.toArray(new Option[optList.size()]);
} |
e58f9264-4568-49db-b54d-15cf85035cf9 | 6 | private static void printClass(ClassDoc cd) {
String type;
if (cd.isInterface()) {
type = "interface";
} else if (cd.isEnum()) {
type = "enum";
} else {
type = "class";
}
os.println("\\begin{texdocclass}{" + type + "}{"
+ HTMLToTex.convert(cd.name()) + "}");
os.println("\\label{texdoclet:" + cd.containingPackage().name() + "." + cd.name() + "}");
os.println("\\begin{texdocclassintro}");
printComment(cd);
os.println("\\end{texdocclassintro}");
printSees(cd);
FieldDoc[] fields = cd.fields();
if (fields.length > 0) {
os.println("\\begin{texdocclassfields}");
printFields(cd, fields);
os.println("\\end{texdocclassfields}");
}
ConstructorDoc[] constructors = cd.constructors();
if (constructors.length > 0) {
os.println("\\begin{texdocclassconstructors}");
printExecutableMembers(cd, constructors, "constructor");
os.println("\\end{texdocclassconstructors}");
}
FieldDoc[] enums = cd.enumConstants();
if (enums.length > 0) {
os.println("\\begin{texdocenums}");
printEnums(cd, enums);
os.println("\\end{texdocenums}");
}
MethodDoc[] methods = cd.methods();
if (methods.length > 0) {
os.println("\\begin{texdocclassmethods}");
printExecutableMembers(cd, methods, "method");
os.println("\\end{texdocclassmethods}");
}
os.println("\\end{texdocclass}");
os.println("");
os.println("");
} |
5fb1431c-0555-4f24-801c-4fd786edc170 | 9 | private void traverseMutualGraph(KB_Node child, KB_Node knownParent) {
ArrayList<KB_Node> argPath = new ArrayList<KB_Node>();
ArrayList<ArrayList<KB_Node>> hold;
ArgInfo.mutationCheck[] mutationCheck = ArgInfo.mutationCheck.values();
int findMutationParent = 0, findMutationChild = 1;
ChildLoop:
for (int i = 0; i < mutationCheck.length; i++) {
for (int j = 0; j < mutationCheck.length; j++) {
if (argInfo.checkMutation(knownParent).equalsIgnoreCase(mutationCheck[i].getMath()))
findMutationParent = i;
if (argInfo.checkMutation(child).equalsIgnoreCase(mutationCheck[j].getMath()))
findMutationChild = j;
if (findMutationChild == findMutationParent) {
argPath.add(knownParent);
argPath.add(child);
hold = checkE2C(child);
ArrayList<KB_Node> pathHolder = new ArrayList<KB_Node>(argPath);
/**
* Find E2C relation from the leaf node.
* If no arg found, skip this step.
*/
if (!hold.isEmpty()) {
for (ArrayList<KB_Node> n : hold) {
for (KB_Node k : n) {
if (k != argPath.get(argPath.size() - 1))
argPath.add(k);
}
setJE2C(argPath);
argPath = new ArrayList<KB_Node>(pathHolder);
}
break ChildLoop;
} else {
//setJE2C(argPath);
}
hold.clear();
}
}
}
} |
7c217413-fd56-4d9a-904c-35a0d4ed3c04 | 6 | public void resetMap() throws SlickException {
GameGrid.mapArray = new Tile[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
GameGrid.mapArray[i][j] = new Tile(i, j);
if (i == 0 || i == rows - 1 || j == 0 || j == columns - 1) {
GameGrid.mapArray[i][j].walkable = false;
}
}
}
startTile = GameGrid.mapArray[rows - 2][1];
startTile.start = true;
startTile.walkable = true;
endTile = GameGrid.mapArray[1][columns - 2];
endTile.end = true;
endTile.walkable = true;
openList = new ArrayList<Tile>();
closedList = new ArrayList<Tile>();
} |
e611d6ee-c009-42bf-9fea-1c2a21160779 | 5 | @Override
public void moveComponent(final Integer diffX, final Integer diffY) {
if (diffX == null && diffY == null)
return;
super.moveComponent(diffX, diffY);
for (final Edge edge : this.task.getInputEdges()) {
edge.getEdgeComponent().updateComponent(null, this);
}
for (final Edge edge : this.task.getOutputEdges()) {
edge.getEdgeComponent().updateComponent(this, null);
}
for (final ActivityEvent event : this.task.getActivityEvents()) {
event.getEventComponent().moveComponent(diffX, diffY);
}
} |
d8986981-7837-4d67-930a-066728c4119b | 6 | public boolean setNodeParam(String region, String agent, String plugin, String paramKey, String paramValue)
{
boolean isUpdated = false;
int count = 0;
try
{
while((!isUpdated) && (count != retryCount))
{
if(count > 0)
{
//System.out.println("iNODEUPDATE RETRY : region=" + region + " agent=" + agent + " plugin" + plugin);
Thread.sleep((long)(Math.random() * 1000)); //random wait to prevent sync error
}
isUpdated = IsetNodeParam(region, agent, plugin, paramKey, paramValue);
count++;
}
if((!isUpdated) && (count == retryCount))
{
System.out.println("GraphDBEngine : setINodeParam : Failed to add node in " + count + " retrys");
}
}
catch(Exception ex)
{
System.out.println("GraphDBEngine : setINodeParam : Error " + ex.toString());
}
return isUpdated;
} |
f81f8192-749c-486d-aea9-d8ee53340ff1 | 6 | 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(RezerwacjeWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RezerwacjeWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RezerwacjeWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RezerwacjeWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RezerwacjeWindow().setVisible(true);
}
});
} |
62a6e5cc-7915-4ed4-92a2-e2ab01d80a90 | 0 | public void setDepartment(int department) {
this.department = department;
} |
6edeefb8-6f35-44d2-b4d9-c3b173173f8e | 3 | public int checkbannedips()
{
try
{
BufferedReader in = new BufferedReader(new FileReader("./data/bannedips.txt"));
String data = null;
while ((data = in.readLine()) != null)
{
if (connectedFrom.equalsIgnoreCase(data))
{
return 5;
}
}
}
catch (IOException e)
{
System.out.println("Critical error while checking banned ips!");
e.printStackTrace();
}
return 0;
} |
571659bd-cde9-4a92-8386-94ddd7b04eb3 | 7 | @Override public void draw(
HDR64Buffer dest, int x, int y,
int clipLeft, int clipTop, int clipRight, int clipBottom
) {
assert clipLeft >= 0;
assert clipTop >= 0;
assert clipRight <= dest.width;
assert clipBottom <= dest.height;
// TODO: more efficiently!
int skipY = clipTop > y ? clipTop - y : 0;
int skipX = clipLeft > x ? clipLeft - x : 0;
for( int sy=skipY, dy=y+skipY; sy<height && dy<clipBottom; ++sy, ++dy ) {
for(
int sx=skipX, dx=x+skipX, si=width*sy+sx, di=dest.width*dy+dx;
sx<width && dx<clipRight;
++sx, ++dx, ++si, ++di
) {
long v = data[si];
// TODO: Handle alpha better!
if( (v & 0x8000000000000000l) == 0x8000000000000000l ) {
dest.data[di] = v;
}
}
}
} |
09db3ff9-d39a-4c2b-beb6-ad5f7b938a4d | 7 | private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
} |
51a6f4e2-62e4-4005-a44d-59e011b1a394 | 7 | public Map<String, String> getPropertiesFromServer() {
if (this.connector == null) {
return Collections.emptyMap();
}
Map<String, String> properties = Collections.emptyMap();
try {
properties = this.connector.get();
if (this.backupMode && properties != null && !properties.isEmpty()) {
this.storeBackUp(properties);
}
this.getLogger().info("Properties From Server:\n" + properties);
} catch (Exception e) {
if (!this.continueWithConnectionErrors) {
throw new RuntimeException("Cannot get values from " + this.getServerUrl(), e);
} else {
this.getLogger().warn("Cannot get values from with " + this.getServerUrl(), e);
}
if (this.backupMode) {
properties = this.loadBackUp();
}
}
return properties;
} |
2f8607c3-dd4f-4438-b4b7-d9e7fb8d5a41 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof AbstractPassengerCarriage))
return false;
AbstractPassengerCarriage other = (AbstractPassengerCarriage) obj;
if (baggageCurWeight != other.baggageCurWeight)
return false;
if (baggageMaxWeight != other.baggageMaxWeight)
return false;
if (comfortType != other.comfortType)
return false;
if (passengerCurCount != other.passengerCurCount)
return false;
if (passengerMaxCount != other.passengerMaxCount)
return false;
return true;
} |
f88e5818-019c-46ae-adca-6c9e73def7c2 | 3 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == view.getLoginView().getLoginButton()){
try{
String username = view.getLoginView().getUsername().getText();
String password = view.getLoginView().getPassword().getText();
DAOFactoryLogin daoFactoryLogin = (DAOFactoryLogin) view.getLoginView().getLoginMethodJComboBox().getSelectedItem();
if(model.login(username, password, daoFactoryLogin)){
view.getFormsWindow().setVisible(false);
view.getMainWindow().setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "Username/Password incorrect");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(null, "Unimplemented function");
}
} |
bcdcae61-7546-48f1-a28a-75820df0d800 | 3 | public List<LoginEntry> readLoginInfo(String playerName) {
List<LoginEntry> retList = new ArrayList<LoginEntry>();
try {
ResultSet rs = _sqLite.query("SELECT login.* FROM player, login "
+ "WHERE player.playername = '" + playerName + "' "
+ "AND player.id = login.id_player "
+ "AND login.time_logout NOT NULL "
+ "ORDER BY login.time_login DESC;");
while (rs.next()) {
try {
LoginEntry le = new LoginEntry(playerName,
rs.getString("time_login"),
rs.getInt("time_online"),
rs.getString("world"),
rs.getInt("x"),
rs.getInt("y"),
rs.getInt("z"),
rs.getInt("blocks_placed"),
rs.getInt("blocks_broken"));
retList.add(le);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return retList;
} |
3597ca58-ac61-4a0b-a7fe-6d6730836c4e | 1 | public static float speed() {
if (Level.state == 0) {
return 1;
} else {
return (float) (2 / Math.pow(2, Level.state));
}
} |
856a4187-d6f2-48a0-8aa9-b798105f5986 | 0 | public Plant(Field field, Location location)
{
alive = true;
this.field = field;
setLocation(location);
} |
fc57d892-45ce-4f1f-94cb-6e75712e077d | 1 | public boolean checkAccusation(Solution accusation) {
if (accusation.equals(solution))
return true;
else return false;
} |
aaa4b6bf-b44e-40e0-bdb3-6d6b5ca6ea48 | 0 | public void setSecond(T newValue) { second = newValue; } |
b9f8c7e6-4700-4f41-8c1b-bdfcc3fd5d92 | 6 | protected boolean executeInternal(RuleContext ruleContext)
{
Rule rule = ruleContext.getActiveRule();
if (null == rule)
{
throw new RuntimeException("RulesEngine.execute: Active Rule object has not been loaded on the RuleContext");
}
// a_Load dependencies
String ruleName = rule.getName();
rule.loadDependencies(ruleContext.getLoader());
// a_Execute rule
if (ruleContext.getEvents().isInfoEnabled())
{
ruleContext.getTimer().set("Execute: " + ruleName + ": execute");
}
boolean result = true;
try
{
// a_Execute the rule
ruleContext.getEvents().event("RulesEngine.execute: Executing rule START: " + rule.getName());
if (rule.execute(ruleContext) && ruleContext.isStopOnFirstTrue())
{
ruleContext.getEvents().event("RulesEngine.execute: First true detected and request to stop was requested: " + rule.getName());
result = false;
}
ruleContext.getEvents().event("RulesEngine.execute: Executing rule END: " + rule.getName());
}
catch (Throwable e)
{
ruleContext.getEvents().error(e);
result = false;
}
if (ruleContext.getEvents().isInfoEnabled())
{
ruleContext.getTimer().reset();
}
return result;
} |
c5ad5fab-8f9d-4c3f-b664-a90387101cb5 | 8 | private void XspeedTFKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_XspeedTFKeyTyped
boolean OK = false;
if((evt.getKeyChar()=='-')&&(XspeedTF.getText().equals("")))OK = true;
if((evt.getKeyChar()=='.')&&(!XspeedTF.getText().equals("")&&!XspeedTF.getText().equals("-")))OK = true;
if((evt.getKeyChar()>='0')&&(evt.getKeyChar()<='9'))OK = true;
if(!OK){
evt.setKeyChar('\0');
}
}//GEN-LAST:event_XspeedTFKeyTyped |
2cfda134-000c-494b-8f49-c22467310376 | 5 | public void identifier() {
//le nom du joueur
nom = JOptionPane.showInputDialog(null, "entrer votre nom svp :",
"Entrer le nom", JOptionPane.PLAIN_MESSAGE);
if (nom == null || nom.equals("")) {
nom = "Anonyme";
}
//le type du jeu
if (m3.isSelected()) {
type = m3.getText();
JOptionPane.showMessageDialog(this, "Vous avez 5 min", "Information", JOptionPane.INFORMATION_MESSAGE);
} else if (m4.isSelected()) {
type = m4.getText();
JOptionPane.showMessageDialog(this, "Vous avez 7 min", "Information", JOptionPane.INFORMATION_MESSAGE);
} else if (m5.isSelected()) {
type = m5.getText();
JOptionPane.showMessageDialog(this, "Vous avez 10 min", "Information", JOptionPane.INFORMATION_MESSAGE);
} else {
type = mAutreType.getText();
JOptionPane.showMessageDialog(this, "Vous avez 15 min", "Information", JOptionPane.INFORMATION_MESSAGE);
}
//la date
String format = "dd/MM/yy HH:mm:ss";
SimpleDateFormat formater = new SimpleDateFormat(format);
Date date = new Date();
dateJour = formater.format(date);
}// |
4a1e1709-4972-4fff-aa6b-e1da43428454 | 5 | public void remove() {
AccountRemoveEvent Event = new AccountRemoveEvent(this.name);
iConomy.getBukkitServer().getPluginManager().callEvent(Event);
if (!Event.isCancelled()) {
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = iConomy.getiCoDatabase().getConnection();
ps = conn.prepareStatement("DELETE FROM " + Constants.SQLTable + " WHERE username = ?");
ps.setString(1, this.name);
ps.executeUpdate();
} catch (Exception ex) {
System.out.println("[iConomy] Failed to remove account: " + ex);
} finally {
if (ps != null) try {
ps.close();
} catch (SQLException ex) {
} if (conn != null)
iConomy.getiCoDatabase().close(conn);
}
}
} |
00060675-2f3e-4d1f-8463-d00d4fd0ab5b | 7 | public String get(final String uuid, final String... extra)
throws BadRequestException, DocumentNotFoundException, ServerErrorException
{
final String xslt = extra[0];
if (extra.length == 0 || xslt == null)
return super.get(uuid, extra);
final XMLDocument document;
final XSLTDocument transformer;
final XSDDocument schema;
try {
if (!dao.exists(uuid)) {
document = getRemote(uuid);
dao.create(document);
} else
document = dao.get(uuid);
if (!xsltDAO.exists(xslt)) {
transformer = getRemoteXSLT(xslt);
xsltDAO.create(transformer);
} else
transformer = xsltDAO.get(xslt);
try {
final String xsd = transformer.getXSD();
if (!xsdDAO.exists(xsd)) {
schema = getRemoteXSD(xsd);
xsdDAO.create(schema);
} else
schema = xsdDAO.get(xsd);
} catch (final DocumentNotFoundException dnfe) {
throw new BadRequestException("XSD not found", dnfe);
}
} catch (final SQLException sqe) {
throw new ServerErrorException("Database Error", sqe);
}
validate(document, schema);
return transform(document, transformer);
} |
9c55dba8-c162-40f1-a0f3-b5ba86016b90 | 6 | private static void removeShit() {
for (StringBuilder s : outStrings) {
for (int i = 0; i < s.length(); i++) {
boolean deleted = false;
char c = s.charAt(i);
if (c == '[') {
int startNote = i;
int endNote = i + 1;
while (s.charAt(endNote) != ']') {
endNote++;
}
s.delete(startNote, endNote+1);
deleted = true;
}
int ch = (int) c;
if (!checkChar(ch)) {
s.deleteCharAt(i);
deleted = true;
}
if (deleted) i--;
}
}
} |
bb0eba38-fbd7-45ad-971e-7163e6cbdfc8 | 1 | @Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
getStageManager().setStatge(StageManager.STAGE_MENUE, null);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.