How to get peer list? - discovery

I have a problem with jxta.
I dont get peer list.
#Override public void discoveryEvent(DiscoveryEvent event) {
DiscoveryResponseMsg res = event.getResponse();
Enumeration en = res.getAdvertisements();
if (en != null) {
while (en.hasMoreElements()) {
PeerAdvertisement a = (PeerAdvertisement)en.nextElement();
Console.append(a.name()+"\n");
}
}
and
discovery.getRemoteAdvertisements(null, DiscoveryService.PEER, null, null, 1, null);
Console.append - is append to JTextArea. In this console print only one peer, but jxtanetwork have 3 peers. Where is error?
P.S. I get code from How do I discover peers and send messages in JXTA-JXSE 2.6?
P.P.S Sorry for my bad english.. I'm hope for your help... Thanks

1 is the issue, it is the maximum number of answers your will get back (1 is less than 3).

Related

Slowmode command always sends the same thing

I'm trying to get my slowmode command working. Basically when I type >sm 2s it replies with "Please follow this example: ;sm 5" <-- this reply should just send if args are null.
if(args[1] == null) {
return message.channel.send("Please follow this example: ;sm 5")
}if (args[1] !== null) {
message.channel.setRateLimitPerUser(args[0])
message.channel.send(`Slowmode is now ${args[0]}s`)
}}
module.exports.config = {
name: "sm",
aliases: []
}```
In JavaScript and most other languages, you could refer to ! in functions as not.
For example, let's take message.member.hasPermission(). If we add ! at the start, giving us:
if (!message.member.hasPermission('ADMINISTRATOR') return
We're basically telling the client, if the message member does **not** have the administrator permission, return the command.
Now, let's take your if statement, saying if (!args[1] == null) {, you're basically telling the client if not args[1] equals to null do this:, which let's face it makes totally no sense.
When we want to compare a variable with a certain value, we would want to tell the client if args[1] is **not** equal to null, do this. Hence why you should fix you if statement into saying:
if (args[1] !== null) {
Sorry for the pretty long answer, felt like giving a little lesson to someone :p

Make //repeat command correct length node & discord.js

Currently for my discord bot I am trying to make a repeat command for me and my friends but the issue is since I'm new to discord.js and node I don't know any good alternatives to "startswith", what this means is while the "//repeat #user" command works, "//repeattesttext #user" also does the same thing. Is there any way to prevent this? Here is my code:
if (!msg.guild) return;
if (msg.content.startsWith('//repeat')) {
if (msg.member.roles.cache.has("744347114255155201")) {
if (!active4) {
const user = msg.mentions.users.first();
if (user) {
const memb = msg.guild.member(user);
if (memb) {
if (active4) {
active4 = false;
msg.channel.send("Repeat Deactivated.")
} else {
id2 = memb.id
active4 = true
msg.channel.send("Repeat Activated")
}
}
}
} else {
active4 = false
msg.channel.send("Repeat Deacivated.")
}
return
} else {
msg.channel.send("You don't have RBLX permissions.")
return
}
}
Any help would be appreciated and since I'm new if you can please explain how your code works. Even if you can't I'll still be grateful for an answer of any kind!
Instead of checking if the string starts with //repeat, you should check if the first word is equal to that.
This can be achieving by separating the msg.content in an array containing its words.
msg.content.split(' ') gives that array.
msg.content.split(' ')[0] === '//repeat' is the if statement you are looking for.

Unban command JDA 4.1.1_101, can't make it work and I don't know why

i'm coding a Discord bot with JDA 4.1.1_101. I created the "ban" command, but i can't make the unban command work. I can't really understand why... Thank you for your help.
if (args[0].equalsIgnoreCase(Main.prefix + "unban")) {
if(event.getGuild().getSelfMember().hasPermission(Permission.BAN_MEMBERS)) {
if (args.length > 0 && args.length < 3) {
try {
event.getMessage().delete().queue();
User member = event.getMessage().getMentionedMembers().get(0).getUser();
String id = member.getId();
event.getGuild().unban(id).queue();
EmbedBuilder ban = new EmbedBuilder();
ban.setColor(Color.GREEN);
ban.setTitle("UnBan");
ban.setDescription("UnBan Report");
ban.addField("Staffer: ", event.getMessage().getAuthor().getName(), true);
ban.addField("Unban: ", member.getName(), true);
logs.sendMessage(ban.build()).queue();
} catch (IndexOutOfBoundsException exx) {
EmbedBuilder error = new EmbedBuilder();
error.setColor(0xff3923);
error.setTitle("Error: User");
error.setDescription("Invalid user.");
event.getChannel().sendMessage(error.build()).queue(message -> {
message.delete().queueAfter(5, TimeUnit.SECONDS);
});
}
} else {
EmbedBuilder error = new EmbedBuilder();
error.setColor(0xff3923);
error.setTitle("Error: Wrong usage.");
error.setDescription("Use: .unban [#user].");
event.getChannel().sendMessage(error.build()).queue(message -> {
message.delete().queueAfter(5, TimeUnit.SECONDS);
});
}
}
}
The problem is, that you are trying to retrieve the user from the mention in the message.
Since the user isn't part of the guild anymore, it seems like this doesn't work.
In order to work around this issue, you have to retrieve the ID manually.
A mention is always in the format <#userid> or <!#userid>.
To get the ID you could just split the message and replace the unnecessary parts, e.g. String id = event.getMessage().getContentRaw().split("<")[1].split(">")[0].replace("!", "").replace("#", "");
I'm sure there are better and smoother ways for doing this. ;)
A better way of retrieving the ID would be using a regex such as <#!?(\d+)> as mentioned by Minn.
In order to get the name of the user, you just need the ID via event.getJDA().getUserById(id).getName().
It's important to mention that you can't properly mention a user who isn't on the server (which is the case when they are banned).
(Addition: I tried using .getMentionedUsers() with the same result as OP.)

How to write mango query in chaincode correctly?

Problem:
I have developed a chaincode. And there I have created a function to retrieve all the lands belongs to a particular person. The code looks like this.
async nthUsersLands(stub, args) {
if (args.length != 1) {
throw new Error(
"Incorrect number of arguments. Expecting NIC ex: 944999014V"
);
}
let nic = args[0];
let landsAsBytes = await stub.getQueryResult({
selector: {
docType: "land",
owner: nic
}
});
console.log(landsAsBytes.toString());
return landsAsBytes;
}
};
But when I invoking this transaction it leaves me to error like this.
Error: Illegal value for queryvalue element of type string: object
(not a string)
Can someone help me to solve this issue? I look for a solution to this problem on the Internet. But I was unable to find out any good solution to this problem. Thank you!
let landsAsBytes = await stub.getQueryResult({
JSON.stringify("selector": {
"docType": "land",
"owner": nic
})
});
The reason is that your query needs to be a string, not an object.

Distinct values in Azure Search Suggestions?

I am offloading my search feature on a relational database to Azure Search. My Products tables contains columns like serialNumber, PartNumber etc.. (there can be multiple serialNumbers with the same partNumber).
I want to create a suggestor that can autocomplete partNumbers. But in my scenario I am getting a lot of duplicates in the suggestions because the partNumber match was found in multiple entries.
How can I solve this problem ?
The Suggest API suggests documents, not queries. If you repeat the partNumber information for each serialNumber in your index and then suggest based on partNumber, you will get a result for each matching document. You can see this more clearly by including the key field in the $select parameter. Azure Search will eliminate duplicates within the same document, but not across documents. You will have to do that on the client side, or build a secondary index of partNumbers just for suggestions.
See this forum thread for a more in-depth discussion.
Also, feel free to vote on this UserVoice item to help us prioritize improvements to Suggestions.
I'm facing this problem myself. My solution does not involve a new index (this will only get messy and cost us money).
My take on this is a while-loop adding 'UserIdentity' (in your case, 'partNumber') to a filter, and re-search until my take/top-limit is met or no more suggestions exists:
public async Task<List<MachineSuggestionDTO>> SuggestMachineUser(string searchText, int take, string[] searchFields)
{
var indexClientMachine = _searchServiceClient.Indexes.GetClient(INDEX_MACHINE);
var suggestions = new List<MachineSuggestionDTO>();
var sp = new SuggestParameters
{
UseFuzzyMatching = true,
Top = 100 // Get maximum result for a chance to reduce search calls.
};
// Add searchfields if set
if (searchFields != null && searchFields.Count() != 0)
{
sp.SearchFields = searchFields;
}
// Loop until you get the desired ammount of suggestions, or if under desired ammount, the maximum.
while (suggestions.Count < take)
{
if (!await DistinctSuggestMachineUser(searchText, take, searchFields, suggestions, indexClientMachine, sp))
{
// If no more suggestions is found, we break the while-loop
break;
}
}
// Since the list might me bigger then the take, we return a narrowed list
return suggestions.Take(take).ToList();
}
private async Task<bool> DistinctSuggestMachineUser(string searchText, int take, string[] searchFields, List<MachineSuggestionDTO> suggestions, ISearchIndexClient indexClientMachine, SuggestParameters sp)
{
var response = await indexClientMachine.Documents.SuggestAsync<MachineSearchDocument>(searchText, SUGGESTION_MACHINE, sp);
if(response.Results.Count > 0){
// Fix filter if search is triggered once more
if (!string.IsNullOrEmpty(sp.Filter))
{
sp.Filter += " and ";
}
foreach (var result in response.Results.DistinctBy(r => new { r.Document.UserIdentity, r.Document.UserName, r.Document.UserCode}).Take(take))
{
var d = result.Document;
suggestions.Add(new MachineSuggestionDTO { Id = d.UserIdentity, Namn = d.UserNamn, Hkod = d.UserHkod, Intnr = d.UserIntnr });
// Add found UserIdentity to filter
sp.Filter += $"UserIdentity ne '{d.UserIdentity}' and ";
}
// Remove end of filter if it is run once more
if (sp.Filter.EndsWith(" and "))
{
sp.Filter = sp.Filter.Substring(0, sp.Filter.LastIndexOf(" and ", StringComparison.Ordinal));
}
}
// Returns false if no more suggestions is found
return response.Results.Count > 0;
}
public async Task<List<string>> SuggestionsAsync(bool highlights, bool fuzzy, string term)
{
SuggestParameters sp = new SuggestParameters()
{
UseFuzzyMatching = fuzzy,
Top = 100
};
if (highlights)
{
sp.HighlightPreTag = "<em>";
sp.HighlightPostTag = "</em>";
}
var suggestResult = await searchConfig.IndexClient.Documents.SuggestAsync(term, "mysuggestion", sp);
// Convert the suggest query results to a list that can be displayed in the client.
return suggestResult.Results.Select(x => x.Text).Distinct().Take(10).ToList();
}
After getting top 100 and using distinct it works for me.
You can use the Autocomplete API for that where does the grouping by default. However, if you need more fields together with the result, like, the partNo plus description it doesn't support it. The partNo will be distinct though.

Resources