TypeError: Cannot read property 'roles' of null - command

I tried to create a command of -clear (amount) and the coomand doing well but the permissions dont
this is what the error i get
TypeError: Cannot read property 'roles' of null
at Client.<anonymous> (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\main.js:448:23)
at Client.emit (events.js:327:22)
at MessageCreateAction.handle (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\elyas\OneDrive\שולחן העבודה\discordbot\node_modules\ws\lib\websocket.js:825:20)
and here the code:
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
const deltef = args[1]
const amount = parseInt(args[1]);
if(message.member.roles.cache.has('715841880482512897')) {
if(args[0] == 'clear') {
if (isNaN(amount)) {
message.reply('that doesn\'t seem to be a valid number.');
} else if (amount < 2 || amount > 100) {
message.reply('you need to input a number between 2 and 100.');
}
else if (amount > 2 || amount < 100)
message.channel.bulkDelete(args[1]);
message.channel.send("deleted" + " " + deltef + " " + "messages" + ('✅'))
}
}
}
);
if you can help i will be happy

Are you trying to use this command in DM's? Because according to the Discord.JS documentation message.member is only available in guilds, what means if you try to use it in DM's it will be undefined.
https://discord.js.org/#/docs/main/master/class/Message?scrollTo=member
I recommend limiting commanmd usage only to guilds so things like this can't happen.
client.on('message', message => {
if (message.author.bot || message.channel.type === "dm") return;
// your code...
})

Related

Protractor need to break from For LOOP when if is executed

Can anyone Please Help me in this in the below code, my requirement is once If is true, I should come out from For loop
===================================================
for (i = 0; i < 50; i++) {
element(By.xpath("//*[text() = '" + InvoiceREFnumberCompany + "']")).isPresent().then(function(result) {
if (result )
{
element(By.xpath("//*[text() = '" + InvoiceREFnumberCompany + "']")).click();
break;
}
else
{
obj1.ClickOnRefreshButton.click();
}
});
}
Output
Failures:
NPOInvoice-Fire -- NPO Fire Collabrate with PTC user
Message:
[31m Failed: Illegal break statement[0m
Stack:
SyntaxError: Illegal break statement

TypeError: Cannot read property 'markets' of undefined (line 23)

TypeError: Cannot read property 'markets' of undefined (line 23)
I use the same database without touching anything for 6 months, it had never failed, today this error started to appear and I've tried to find the fault but I'm not able to find the fault when collecting the data.
Here is the basis from which I collect the values (you can access the data map by clicking on the link):
https://webhooks.mongodb-stitch.com/api/client/v2.0/app/oddsbf-dvyne/service/http/incoming_webhook/webhook0
Here is the script I use:
const response = UrlFetchApp.fetch("https://webhooks.mongodb-stitch.com/api/client/v2.0/app/oddsbf-dvyne/service/http/incoming_webhook/webhook0");
const mongo_matches = JSON.parse(response.getContentText());
const matches = mongo_matches.map(function(match) {
var over = '-'
var under = '-'
if(match['markets']['over_25'] !== undefined &&
match['markets']['over_25']['over']['odds'] !== undefined &&
(match['markets']['over_25']['over']['odds']['availableToBack'].length > 0 &&
match['markets']['over_25']['under']['odds']['availableToBack'].length > 0 )){
over = match['markets']['over_25']['over']['odds']['availableToBack'][0] !== undefined ? match['markets']['over_25']['over']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['markets']['over_25']['over']['odds']['availableToLay'][0]['price']['$numberDouble']
under = match['markets']['over_25']['under']['odds']['availableToBack'][0] !== undefined ? match['markets']['over_25']['under']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['markets']['over_25']['under']['odds']['availableToLay'][0]['price']['$numberDouble']
}
return [
match['markets']['marketStartTime'],
match['markets']['lastSaved'],
match['markets']['competition'],
match['markets']['homeTeam']['runnerName'],
match['markets']['awayTeam']['runnerName'],
match['markets']['homeTeam']['odds']['availableToBack'][0] !== undefined ? match['markets']['homeTeam']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['markets']['homeTeam']['odds']['availableToLay'][0]['price']['$numberDouble'],
match['markets']['awayTeam']['odds']['availableToBack'][0] !== undefined ? match['markets']['awayTeam']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['markets']['awayTeam']['odds']['availableToLay'][0]['price']['$numberDouble'],
match['markets']['draw']['odds']['availableToBack'][0] !== undefined ? match['markets']['draw']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['draw']['markets']['odds']['availableToLay'][0]['price']['$numberDouble'],
under,
over,
];
});
Line 23 that is giving the error is this one:
match['markets']['draw']['odds']['availableToBack'][0] !== undefined ? match['markets']['draw']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['draw']['markets']['odds']['availableToLay'][0]['price']['$numberDouble'],
Replace line 23 with this:
match['markets']['draw']['odds']['availableToBack'][0] !== undefined ? match['markets']['draw']['odds']['availableToBack'][0]['price']['$numberDouble'] : match['markets']['draw']['odds']['availableToLay'][0]['price']['$numberDouble'],
Update:
Logger.log(mongo_matches['draw'])
Logger.log(mongo_matches['matches'])
both return null. Meaning that you can't access an information from a null object.

Cannot resolve element with ID while signing a part of SOAP REQUEST X509

I had the following error while trying to sign a part of SOAP Request :
org.apache.xml.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID _53ea293168db637b15e2d4d7894
at org.apache.xml.security.utils.resolver.implementations.ResolverFragment.engineResolve(ResolverFragment.java:86)
at org.apache.xml.security.utils.resolver.ResourceResolver.resolve(ResourceResolver.java:279)
at org.apache.xml.security.signature.Reference.getContentsBeforeTransformation(Reference.java:417)
at org.apache.xml.security.signature.Reference.dereferenceURIandPerformTransforms(Reference.java:597)
at org.apache.xml.security.signature.Reference.calculateDigest(Reference.java:689)
at org.apache.xml.security.signature.Reference.generateDigestValue(Reference.java:396)
at org.apache.xml.security.signature.Manifest.generateDigestValues(Manifest.java:206)
at org.apache.xml.security.signature.XMLSignature.sign(XMLSignature.java:595)
It comes from the resolution of the URI declared on the reference tag.
Here is the java code i'm using for signing via X509 :
KeyStore.PrivateKeyEntry pke = ISKeyStoreManager.getInstance().getPrivateKeyEntry(keyStoreAlias, keyAlias);
AlgorithmStrings algStrings = AlgorithmStrings.getAlgDSStrings( pke.getPrivateKey(), signatureAlgorithmString, digestAlgorithmString);
String resultantXPath = StringUtils.join(xpaths, '|');
Transforms transforms = new Transforms(originalDocument);
NodeList targetDocumentList = obtainNodesForXPath(originalDocument, resultantXPath, nc);
if(targetDocumentList != null && targetDocumentList.getLength() > 0)
{
if(targetDocumentList.item(0).hasAttributes()){
Node attrId = targetDocumentList.item(0).getAttributes().getNamedItem("Id");
if(attrId != null && !attrId.getNodeValue().equals("")){
uri = new StringBuilder().append('#').append(attrId.getNodeValue()).toString();
}
else{
((Element) targetDocumentList.item(0)).setAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
((Element) targetDocumentList.item(0)).setAttribute("wsu:Id", idForXmlObject);
}
}
else{
((Element) targetDocumentList.item(0)).setAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
((Element) targetDocumentList.item(0)).setAttribute("wsu:Id", idForXmlObject);
}
}else{
log.debug("Target not found in the original document with xpath: " + resultantXPath);
}
transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
if (resultantXPath != null) {
log.debug("Instantiation XPATHContainer");
XPathContainer xpathC = new XPathContainer(originalDocument);
xpathC.setXPath(resultantXPath);
if ((ncMap != null) && (!ncMap.isEmpty())) {
for (Map.Entry<String,String> e : ncMap.entrySet()) {
log.debug("Adding namespace to XPATH Container: " + e.getKey() + " -> " + e.getValue());
xpathC.setXPathNamespaceContext(e.getKey(), e.getValue());
}
}
transforms.addTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", xpathC.getElement());
}
log.debug("Instantiation Signature");
XMLSignature sig = new XMLSignature(originalDocument, null, algStrings.signatureAlgorithm, canonicalizationAlg);
sig.setFollowNestedManifests(true);
log.debug("Ajout des assertions de transformation");
sig.addDocument("", transforms, algStrings.digestMethod);
if (idAttrForSignature != null) {
sig.setId(idAttrForSignature);
}
log.debug("DOMToString: " + serializeDOMToString(originalDocument));
// signature node insertion
NodeList nodeList = obtainNodesForXPath(originalDocument, insertSignatureAtXPath, nc);
if(nodeList != null && nodeList.getLength() > 0){
Node nodeSignature = nodeList.item(0);
Node childNode = nodeSignature.getFirstChild();
if (childNode != null) {
if (addSignatureAsLastElement)
nodeSignature.appendChild(sig.getElement());
else
nodeSignature.insertBefore(sig.getElement(), childNode);
}
else nodeSignature.appendChild(sig.getElement());
}
else{
throw new ServiceException("INVALID_SIGNATURE_NODE_SELECTOR_XPATH");
}
// Public key insertion
//X509Data x509Data = getX509Data(includeCertChain, certificateData, originalDocument, pke);
//KeyInfoReference kir = new KeyInfoReference(x509Data.getDocument());
SecurityTokenReference str = new SecurityTokenReference(sig.getKeyInfo().getDocument());
str.setKeyIdentifier(ISKeyStoreAccessorUtil.getIaikCertificate(pke.getCertificate()));
sig.getKeyInfo().getElement().appendChild(str.getElement());
log.debug("DOMToString: " + serializeDOMToString(originalDocument));
//sig.getSignedInfo().addResourceResolver(new ResolverXPointer());
((Element)(sig.getSignedInfo().getElement().getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Reference").item(0))).setAttribute("URI", uri);
log.debug("DOMToString: " + serializeDOMToString(originalDocument));
//sig.addDocument(uri, trans);
// Signature generation
sig.sign(pke.getPrivateKey());
Do you have any proposition of workaround ? or another way to set URI attribute ?
Thank you for helping !
I found it.
I added InclusiveNamespaces so that the sign method can figure out that ID is on a specific namespace defined attribute.

Handling a unique key Constraint Violation with powershell and SQL

I'm writing a script to insert a GUID into a SQL table. In order to stop duplicates, I have made the table GUID column unique.
So now I need to catch the violation and ignore if its a duplicate and continue the script. So write the new GUIDS but ignore the duplicates.
What would be the best way to catch and deal with the violation?
I've seen a few options on this site, but none work for me, most fail with The Catch block is missing its statement block. or other errors.
Example of the catch block I've been trying
catch(SqlException ex)
{
sqlException = ex.InnerException as System.Data.SqlClient.SqlException;
if (sqlException.Number == 2601 || sqlException.Number == 2627)
{
ErrorMessage = "Cannot insert duplicate values.";
}
else
{
ErrorMessage = "Error while saving data.";
}
}
and the errors:
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:15 char:6
+ catch (UpdateException ex)
+ ~
The Catch block is missing its statement block.
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:18 char:32
+ if (innerException != null && innerException.Number == 2627 || innerExceptio ...
+ ~~
The token '&&' is not a valid statement separator in this version.
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:18 char:65
+ if (innerException != null && innerException.Number == 2627 || innerExceptio ...
+ ~~
The token '||' is not a valid statement separator in this version.
At D:\Software Approval Requests\GetApprovalRequestsNew2.ps1:23 char:28
+ if (innerException != null && (innerException.Number == 2627 || innerException.N ...

for each group by date in coffeescript

which pulls data from and reformats it.
Promise = require "bluebird"
request = Promise.promisify require "request"
moment = require "moment"
cdn = require('config').server.cloudFrontDomain
toTitleCase = require "titlecase"
exports.getStocks = (path) ->
return new Promise (resolve, reject) ->
request path
.then (body) ->
germanStock = []
germanStocks = JSON.parse body.body
germanStocks.forEach (stock) ->
obj = {}
this.parsePart = (remaining) ->
value = remaining.value
dashIndex = value.lastIndexOf '-'
if dashIndex != -1
remaining.value = value.substring 0, dashIndex - 1
return value.substring(dashIndex + 1).trim()
else
return ''
remaining =
value: stock.name
size = parsePart remaining
colour = parsePart remaining
name = remaining.value
sku = stock.sku
styleId = sku.split(/-/)[0]
colorcode = /^(.*)-(.*)([0-9])$/.exec(sku)?[2]
bgStyle = "url(//#{cdn}/assets/product_shots/thumbs/#{styleId}-#{colorcode}.jpg)"
obj.id = sku
obj.name = name
obj.colorUrl = bgStyle
obj.colour = toTitleCase(colour.toLowerCase())
obj.size = size
obj.stock = stock.stock
obj.inProduction = ''
obj.office = 'DE'
stock.preorders.forEach (i, idx) ->
date = moment(i.date).format('DD-MM-YYYY')
if idx != stock.preorders.length - 1
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date + ', '
else
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date
germanStock.push obj
resolve germanStock
.catch (err) ->
reject err
where my data is like:
{
"id":1,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - XS",
"sku":"SS01-BB0",
"stock":81,
"active":true,
"preorders":[
{
"id":92549,
"amount":160,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":200,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":1000,
"date":"2016-06-21T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":81,
"preOrdersSum":1360
},
{
"id":2,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - S",
"sku":"SS01-BB1",
"stock":339,
"active":true,
"preorders":[
{
"id":92551,
"amount":240,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92438,
"amount":160,
"date":"22016-06-19T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":339,
"preOrdersSum":400
},
what is the correct way to group each preorders quantity that is on the same date, so that instead of getting:
160 due on 19-06-2016, 200 due on 19-06-2016, 1000 due on 21-06-2016
i get 360 due on 19-06-2016, 1000 due on 21-06-2016
any advice much appreciated.
You could just use an object with the date as key and the total amount for the date as value.
For each preorder, add it's amount at it's date index in this object. At the end of the iteration print the content of the object:
moment = require "moment"
data = [
{
id:1
stamp: "2014-09-25T12:55:30Z"
name: " MENS T-SHIRT - BRIGHT BLUE - XS"
sku: "SS01-BB0"
stock:81
active:true
preorders:[
{
id:92549
amount:160
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:200
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:1000
date: "2016-06-21T22:00:00Z"
}
]
discountMatrix:0.0
stockNormalized:81
preOrdersSum:1360
}
]
obj = {}
obj.inProduction = ""
amountByDate = {}
# for each document in your data
for doc in data
# for each preorder in your document
for preorder in doc.preorders
# add it's amount in the index equals to it's date
if amountByDate[preorder.date]
amountByDate[preorder.date] += preorder.amount
else
# or create the index with the value if it doesn't exist
amountByDate[preorder.date] = preorder.amount
for date, amount of amountByDate
if obj.inProduction != ""
obj.inProduction = obj.inProduction.concat ", #{amount} due on #{moment(date).format('DD-MM-YYYY')}"
else
obj.inProduction = obj.inProduction.concat "#{amount} due on #{moment(date).format('DD-MM-YYYY')}"
console.log obj.inProduction
Result:
360 due on 20-06-2016, 1000 due on 22-06-2016