package modifiedlines;
import edu.nyu.cs.javagit.api.DotGit;
import edu.nyu.cs.javagit.api.JavaGitConfiguration;
import edu.nyu.cs.javagit.api.JavaGitException;
import edu.nyu.cs.javagit.api.WorkingTree;
import edu.nyu.cs.javagit.api.commands.GitLogResponse;
import edu.nyu.cs.javagit.api.commands.GitStatus;
import edu.nyu.cs.javagit.api.commands.GitStatusOptions;
import edu.nyu.cs.javagit.api.commands.GitStatusResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
*
* #
author aryan000
*/
public class UseGit {
private static File repositoryDirectory;
private static DotGit dotGit;
public static void main(String s[]) throws JavaGitException, IOException
{
File f = new File("C:\\Program Files\\Git\\bin\\git.exe");
if(!f.exists())
{
System.out.println("does not exist");
}
else
System.out.println("exists at " + f.getPath());
JavaGitConfiguration.setGitPath("C:\\Program Files\\Git\\bin");
System.out.println("Git version : " + JavaGitConfiguration.getGitVersion());
// repositoryDirectory = new File("/home/aryan000/Desktop/retrofit");
repositoryDirectory = new File("/home/aryan000/Desktop/changeprone/changeprone");
System.out.println("Git Repository Location : " + repositoryDirectory.getAbsolutePath());
//get the instance of the dotGit Object
dotGit = DotGit.getInstance(repositoryDirectory);
// System.out.println("checking what i have got ");
// GitLogResponse.CommitFile com ;
// com = (GitLogResponse.CommitFile) dotGit.getLog();
//
// System.out.println(com);
WorkingTree wt = dotGit.getWorkingTree();
File workingTreePath = wt.getPath();
GitStatus gitStatus = new GitStatus();
GitStatusResponse status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
File anotherFileDir = new File("/home/aryan000/Desktop/retrofit/test.txt");
GitStatusOptions options = new GitStatusOptions();
options.setOptOnly(true);
status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
System.out.println("----- Print log to see our commit -----");
for (GitLogResponse.Commit c : dotGit.getLog()) {
System.out.println("commit id is : " + c.getSha());
System.out.println(" commit message is : " + c.getMessage());
System.out.println(" author of the commit is : " + c.getAuthor());
System.out.println(" date modified is : " + c.getDateString());
System.out.println(" number of files changed is : " + c.getFiles());
List<GitLogResponse.CommitFile> store = c.getFiles();
if(store!=null)
System.out.println("the number of files changed is : " + store.size());
System.out.println("list of files changed is : " + c.getFilesChanged());
System.out.println("total number of additions : " + c.getLinesDeleted());
System.out.println("total number of merger : " + c.getMergeDetails());
}
// for(GitLogResponse.CommitFile c : dotGit.getLog())
}
}
Output is shown as :
Exception in thread "main" edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified. { path=[C:\Program Files\Git\bin] }
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:220)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:247)
at modifiedlines.UseGit.main(UseGit.java:40)
Caused by: edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified.
at edu.nyu.cs.javagit.api.JavaGitConfiguration.determineGitVersion(JavaGitConfiguration.java:81)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:217)
... 2 more
Java Result: 1
My query is how to find git logs and the files changed due to a particular commit using a Java Program.
Can any 1 help me in this.
Please See : This code is working fine in Ubuntu i.e. no Path problem still I am unable to get the files changed during a commit. It is give me a List as a null.
This bug was opened a long time ago and just fixed it. Please give it a try , use master branch please, and let me know if it works for you.
Related
I've been trying to add a reaction roles command to my discord bot. But strangely it isn't working properly.
But the problem is that it worked six months ago. I haven't changed anything in my code.
The code stops here: Emote emote = emotes.get(0);
My class:
package de.nameddaniel.bot.commands;
import java.util.List;
import de.nameddaniel.bot.main.LiteSQL;
import de.nameddaniel.bot.main.Utils;
import de.nameddaniel.bot.types.ServerCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Emote;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
public class ReactionRolesCommand implements ServerCommand {
#Override
public void performCommand(Member m, TextChannel channel, Message msg) {
//!rr channel messageid :ok: ...
String[] args = msg.getContentDisplay().split(" ");
if(m.hasPermission(Permission.MANAGE_ROLES)) {
if(args.length >= 5) {
List<TextChannel> channels = msg.getMentionedChannels();
List<Role> roles = msg.getMentionedRoles();
List<Emote> emotes = msg.getEmotes();
System.out.println("3");
TextChannel tc = msg.getMentionedChannels().get(0);
String messageIDString = args[1];
Role role = roles.get(0);
System.out.println("1");
try {
long messageID = Long.parseLong(messageIDString);
Emote emote = emotes.get(0);
tc.addReactionById(messageID, emote).queue();
System.out.println("2");
LiteSQL.onUpdate("INSERT INTO reactroles(guildid, channelid, messageid, emote, roleid) "
+ "VALUES(" + channel.getGuild().getIdLong() + ", " + tc.getIdLong() + ", "
+ messageID + ", '" + emote.getId() + "', " + role.getIdLong() + ")");
Utils.Embed("Deiner Nachricht in " + msg.getMentionedChannels() + " wurde die Reaktion " + msg.getEmotes()
+ " hinzugefĆ¼gt.", channel, "Erfolgreich!");
}
catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("ReactionCommand");
}
}
else
Utils.Embed("Bitte benutze: !rr [MessageID] #channel [Emote] #Rolle", channel, "Falscher Syntax");
System.out.println(args.length);
}
else
msg.delete().queue();
}
}
The error Code:
3
1
[JDA [0 / 1] MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at java.util.Collections$UnmodifiableList.get(Unknown Source)
at de.nameddaniel.bot.commands.ReactionRolesCommand.performCommand(ReactionRolesCommand.java:40)
at de.nameddaniel.bot.main.CommandManager.perform(CommandManager.java:43)
at de.nameddaniel.bot.listener.CommandListener.onMessageReceived(CommandListener.java:25)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:430)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:82)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:69)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:147)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:122)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:948)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:835)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:813)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:986)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
What I could figure out is, that my List emotes is empty. But I have no idea why..
Most of the code is in German. So ask me if you need a translation.
If there is anything missing also please tell me.
Hope you can help me, Daniel :D
The mistake was, that I confounded Emote with Emoji. So it has to be an Emoji instead of an emote.
I read JPype documentation from this link: http://jpype.readthedocs.io/en/latest/, but i am not sure that i can use JPype or it is better that i choose another way to run java class from python3. Also i have to point that i get a little confused for doing with JPype.
i did this:
import urllib.request
import os
import tempfile
import sys
import fileinput
import logging
import JPype as jp
# here i have python code and do something else
"""
my python code
"""
#from this point till end of the code i did for my question
logging.basicConfig(filename="ERROR.txt", level= logging.ERROR)
try:
logging.debug('we are in the main try loop')
jp.startJVM("C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest.java", "-ea")
test_class = jp.JClass("ClassWithTest")
a = testAll()
file_java_class = open("OUTPUT.txt", "w")
file_java_class.write(a)
except Exception as e1:
logging.error(str(e1))
jp.shutdownJVM()
But it has problem and shows me this error: 7, in import
jpype as jp ModuleNotFoundError: No module named 'jpype'
========================================================================
I have to point that my java class is in my python path and my java
class is:
public class ClassWithTest{
public ClassWithTest(){
/* Va invocato */
System.out.println(insertLength("Tests ready to run"));
}
public void testAbs(){
/* Va invocato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.println(insertLength("abs(-2) = 2: " + testResult(Math.abs(-2), 2)));
System.out.println(insertLength("abs(-3) = -2: " + testResult(Math.abs(-3), -2)));
}
public void testRound(){
/* Va invocato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.println(insertLength("round(0.7) = 1: " + testResult(Math.round(0.7), 1)));
System.out.println(insertLength("round(0.2) = 1: " + testResult(Math.round(0.2), 1)));
}
public void testMin(){
/* Va invocato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.println(insertLength("min(7,3) = 3: " + testResult(Math.min(7,3), 3)));
System.out.println(insertLength("min(5,7) = 7: " + testResult(Math.min(5,7), 7)));
}
public void testMax(){
/* Va invocato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.println(insertLength("max(7,14) = 14: " + testResult(Math.max(7,14), 14)));
System.out.println(insertLength("max(5,7) = 5: " + testResult(Math.max(5,7), 5)));
}
public void TestDiv(){
/* Non andreabbe chiamato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.println(insertLength("14 / 2 = 7: " + testResult(14 / 7, 3)));
// assert(14 / 0 == 10));
}
public void testMult(int x){
/* Non andreabbe chiamato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.printf("2 * %d = %s:", x, testResult(2 * x, 2 * x)));
// assert(false));
}
public void otherTest(){
/* Non andreabbe chiamato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
System.out.printf("1 = 1:", testResult(1, 1)));
// assert(false));
}
private void testAll(){
/* Non dovrebbe essere chiamato */
System.out.println(insertLength("Invocation of " + Thread.currentThread().getStackTrace()[1].getMethodName()));
testAbs());
testRound());
testMin());
testMax());
}
private static String testResult(double result, double expected){
return (result == expected ? "ok" : "no"));
}
public static String insertLength(Object obj){
String line = obj.toString());
return String.format("[%d]> %s", line.length(), line));
}
public static void main(String[] args){
(new ClassWithTest()).testAll());
}
}
i do not know why this not work?!! i read jython, but i can not use
jython, because i did not understand well. could you help me:
1- how can i run java class from python 2- save the out put of
execution in text file 3- save the possible error messages in
another text file and then terminate. thank you
I normally use JYthon. Making use of Java from within Jython applications is about as seamless as using external Jython modules within a Jython script.
Here is a simple example:
from java.lang import Math
Math.max(4, 7)
Math.pow(10,5)
from java.lang import System as javasystem
javasystem.out.println("Hello")
Hello
I've used the Weka GUI for training and testing a file (making predictions), but can't do the same with the API. The error I'm getting says there's a different number of attributes in the train and test files. In the GUI, this can be solved by checking "Output predictions".
How to do something similar using the API? do you know of any samples out there?
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.meta.FilteredClassifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
import weka.filters.unsupervised.attribute.Remove;
public class WekaTutorial
{
public static void main(String[] args) throws Exception
{
DataSource trainSource = new DataSource("/tmp/classes - edited.arff"); // training
Instances trainData = trainSource.getDataSet();
DataSource testSource = new DataSource("/tmp/classes_testing.arff");
Instances testData = testSource.getDataSet();
if (trainData.classIndex() == -1)
{
trainData.setClassIndex(trainData.numAttributes() - 1);
}
if (testData.classIndex() == -1)
{
testData.setClassIndex(testData.numAttributes() - 1);
}
String[] options = weka.core.Utils.splitOptions("weka.filters.unsupervised.attribute.StringToWordVector -R first-last -W 1000 -prune-rate -1.0 -N 0 -stemmer weka.core.stemmers.NullStemmer -M 1 "
+ "-tokenizer \"weka.core.tokenizers.WordTokenizer -delimiters \" \\r\\n\\t.,;:\\\'\\\"()?!\"");
Remove remove = new Remove();
remove.setOptions(options);
remove.setInputFormat(trainData);
NominalToBinary filter = new NominalToBinary();
NaiveBayes nb = new NaiveBayes();
FilteredClassifier fc = new FilteredClassifier();
fc.setFilter(filter);
fc.setClassifier(nb);
// train and make predictions
fc.buildClassifier(trainData);
for (int i = 0; i < testData.numInstances(); i++)
{
double pred = fc.classifyInstance(testData.instance(i));
System.out.print("ID: " + testData.instance(i).value(0));
System.out.print(", actual: " + testData.classAttribute().value((int) testData.instance(i).classValue()));
System.out.println(", predicted: " + testData.classAttribute().value((int) pred));
}
}
}
Error:
Exception in thread "main" java.lang.IllegalArgumentException: Src and Dest differ in # of attributes: 2 != 17152
This was not an issue for the GUI.
You need to ensure that categories in train and test sets are compatible, try to
combine train and test sets
List item
preprocess them
save them as arff
open two empty files
copy the header from the top to line "#data"
copy in training set into first file and test set into second file
In this case I am creating a plugin to learn, I need to know the following things.
What I want to do is to establish points on the map and at these points when another command will fall lightning.
1- For example: /thor setpoint 1, 2, 3, 4...
And in config created...
Lightning:
1:
x:
y:
z:
2:
x:
y:
z:
3... 6, 14..
The next three commands.
/thor delpoint 1, 2, 3... = Deleted point ID
/launch all = Launch all points
/launch ID = Only launch id
For now I managed to fall into a coordinate, single configuration file.
Thanks in advance
Main:
package me.alexbanper.thorproject.plugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
//import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public class ThorProject extends JavaPlugin implements Listener {
public void onEnable(){
saveDefaultConfig();
}
public void onDisable(){
}
public boolean onCommand(CommandSender enviar, Command comando, String commandLabel, String[] args){
Player player = (Player) enviar;
if(enviar instanceof Player){
if(commandLabel.equalsIgnoreCase("trueno")){
if(player.hasPermission("trueno.comando")){
if(args.length == 0){
player.sendMessage(col("&aUtiliza:"));
player.sendMessage(col("&6/trueno iniciarahora &5Inicia los truenos"));
player.sendMessage(col("&6/trueno iniciartiempo SEGUNDOS &5Inicia con segundos"));
player.sendMessage(col("&6/trueno setpoint &5establece un punto"));
}else if(args.length == 1){
if(args[0].equalsIgnoreCase("setpoint")){
this.getConfig().set("Config" + ".Thor" + ".X", player.getLocation().getBlockX());
this.getConfig().set("Config" + ".Thor" + ".Y", player.getLocation().getBlockY());
this.getConfig().set("Config" + ".Thor" + My".Z", player.getLocation().getBlockZ());
//this.getConfig().set("Config" + ".World", player.getLocation().getWorld());
saveConfig();
player.sendMessage(col("&aSpawnPoint 1 set!"));
player.sendMessage("X: " + getConfig().getInt("Config.Thor.X"));
player.sendMessage("Y: " + getConfig().getInt("Config.Thor.Y"));
player.sendMessage("Z: " + getConfig().getInt("Config.Thor.Z"));
player.sendMessage("World: " + getConfig().getString("Config.World"));
}else if(args[0].equalsIgnoreCase("setpoint2")){
this.getConfig().set("Config" + ".Thor2" + ".X", player.getLocation().getBlockX());
this.getConfig().set("Config" + ".Thor2" + ".Y", player.getLocation().getBlockY());
this.getConfig().set("Config" + ".Thor2" + ".Z", player.getLocation().getBlockZ());
//this.getConfig().set("Config" + ".World", player.getLocation().getWorld());
saveConfig();
player.sendMessage(col("&aSpawnPoint 2 Set!"));
player.sendMessage("X: " + getConfig().getInt("Config.Thor2.X"));
player.sendMessage("Y: " + getConfig().getInt("Config.Thor2.Y"));
player.sendMessage("Z: " + getConfig().getInt("Config.Thor2.Z"));
player.sendMessage("World: " + getConfig().getString("Config.World"));
}
}
}else{enviar.sendMessage(col("&cAcceso Denegado!"));}
}else if(commandLabel.equalsIgnoreCase("it")){
int x = getConfig().getInt("Config.Thor.X");
int y = getConfig().getInt("Config.Thor.Y");
int z = getConfig().getInt("Config.Thor.Z");
int x2 = getConfig().getInt("Config.Thor2.X");
int y2 = getConfig().getInt("Config.Thor2.Y");
int z2 = getConfig().getInt("Config.Thor2.Z");
//Object world = getConfig().get("Config" + ".World");
Location light = new Location(null, x, y, z);
Location light2 = new Location(null, x2, y2, z2);
Bukkit.getServer().getWorld("world").strikeLightningEffect(light);
Bukkit.getServer().getWorld("world").strikeLightningEffect(light2);
player.sendMessage("All correct!");
}
}else{enviar.sendMessage("Only Players!");}
return false;
}
public static String col(String msg){
return ChatColor.translateAlternateColorCodes('&', msg);
}
}
/trueno = /thor (I speak Spanish)
First of all, you need to save the world name too or you cannot get the location at all later. For all, make a call to get the keyset and iterate through all of the locations. (Be careful how you do this, make sure you are using the correct keys)
Delete the map of the key when you need to delete a location. Lastly, get the corresponding key when selecting a specific ID.
There are plenty of videos you can google to understand the behavior of Bukkit's YAMLConfigiration class, but most of them are absolutely horrible. I found one that isn't AS bad for you. It is for config files, but the YAMLConfig class behaves very similarly. (I plan on doing some of my own tutorials this summer, but I am going to be VERY careful with following java conventions and correct practice unlike most of these youtubers)
Bukkit Coding ~ Episode 5: Configuration: https://youtu.be/SBvrpmNDr74
As a side note, the bukkit forums are a better place for bukkit development than stack overflow.
http://bukkit.org/forums/
I want to use netapp manageability api using java.
By using that api I want to access remote systems storage.
How do I connect to remote system to and access storage details using api?
Any sample code to connect to remote system and access it??
Here is a answer.
But it gives only version and isclustered or not.
It do not gives details about volumelist.
import java.util.Iterator;
import java.util.List;
import com.netapp.nmsdk.client.ApiRunner;
import com.netapp.nmsdk.client.ApiTarget;
import com.netapp.nmsdk.client.ApiTarget.TargetType;
import com.netapp.nmsdk.client.ApiTarget.Protocol;
import com.netapp.nmsdk.dfm.api.event.*;
import com.netapp.nmsdk.dfm.api.event.EventListIterStartRequest;
import com.netapp.nmsdk.dfm.api.volume.VolumeInfo;
import com.netapp.nmsdk.dfm.api.volume.VolumeListInfoIterStartRequest;
import com.netapp.nmsdk.ontap.api.system.SystemGetVersionRequest;
import com.netapp.nmsdk.ontap.api.system.SystemGetVersionResponse;
public class RunStorage {
public void startStorage(){
System.out.println("in start storage class");
}
public static void main (String [] args){
//Attempt to connect to host and get basic info.
String myip= "192.168.x.xx";
String url = "https://"+myip;
Protocol protocol = Protocol.INSECURE_HTTPS;
try {
System.out.println("url is .." + url);
ApiRunner apirunner = new ApiRunner(ApiTarget.builder()
.withHost(myip)
.withUserName("username")
.withPassword("password")
.withTargetType(TargetType.FILER)
.useProtocol(protocol)
.build()
);
// to get version of device
SystemGetVersionRequest vq = new SystemGetVersionRequest();
SystemGetVersionResponse vr = apirunner.run(vq);
System.out.println("System version is .. " + vr.getVersion());
// ****************** end of version *****************
// To check wheather systems is clustered or not
if (vr.isClustered() != null && vr.isClustered()){
System.out.println("storage is clustered");
}
else {
System.out.println("Storage is in 7 Mode");
}
//********************** end of cluster **********************
// To get List of volumes
VolumeListInfoIterStartRequest volumeListReq = new VolumeListInfoIterStartRequest();
System.out.println(volumeListReq);
Iterator<VolumeInfo> volumeIter = apirunner.iterate(volumeListReq,10);
System.out.println(volumeIter);
VolumeInfo volume ;
System.out.println("outside while .. " + volumeIter.toString());
while (volumeIter.hasNext()){
volume = volumeIter.next();
if(volume == null){
System.out.println("in if");
}
else {
System.out.println("in else");
}
System.out.println("Volume object is .. " + volume);
System.out.println("volume name is.. " + volume.getVolumeName());
System.out.println("extra .. " + volume.getAggregateName());
System.out.println("Type.. " + volume.getBlockType());
System.out.println("State .. " + volume.getVolumeState());
System.out.println("Total size .. " + volume.getVolumeSize());
System.out.println("Total used size .. " + volume.getVolumeFullThreshold());
}
// ********************* end of volume list ************
}
catch (Exception e){
e.printStackTrace();
System.out.println("Error in getting info");
}
}
}