I have this simple model written in Alloy:
module login
sig Email {}
sig Password {}
sig User {
login: one Login
}
sig Login {
email: one Email,
password: one Password,
owner: one User,
}
fact {
all u:User | u.login.owner = u
}
assert a {
all l:Login | one l.owner
all u:User | one u.login.email
all u:User | u.login.owner = u
}
check a for 3
If I run this with the alloy analyser GUI it says:
No counterexample found. Assertion may be valid. 11ms.
But if I run the same model with the API in my java program it returns:
---OUTCOME---
Unsatisfiable.
And not even 1 solutions is shown.
Can anyone help me to detect the problem?
Here goes the code in java using the API:
A4Reporter rep = new A4Reporter();
try {
Module loaded_model = CompUtil.parseEverything_fromFile(rep, null, model.getModelpath());
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.SAT4J;
Command cmd = loaded_model.getAllCommands().get(0);
A4Solution sol = TranslateAlloyToKodkod.execute_command(rep, loaded_model.getAllReachableSigs(), cmd, options);
System.out.println(sol.toString());
while (sol.satisfiable()) {
System.out.println("[Solution]:");
System.out.println(sol.toString());
sol = sol.next();
}
} catch (Err e){
e.printStackTrace();
}
Thanks
In both cases no counter-examples are found.
Be aware that the command obtained via the method call loaded_model.getAllCommands().get(0) is check a for 3 in other words, you ask Alloy to look for counter examples.
If you would like to obtain an instance satisfying your constraints - i.e., not a counter-example - you should use a command containing the keyword run instead of check.
Related
I'm trying to test a few components that are using MSAL for authentication.
Thus far, I have a simple test, which test if my component can render, as follows:
// <MsalInstanceSnippet>
const msalInstance = new PublicClientApplication({
auth: {
clientId: config.appId,
redirectUri: config.redirectUri
},
cache: {
cacheLocation: 'sessionStorage',
storeAuthStateInCookie: true
}
});
When I run the test, I'm getting the following error:
BrowserAuthError: crypto_nonexistent: The crypto object or function is not available. Detail:Browser crypto or msCrypto object not available.
10 |
11 | // <MsalInstanceSnippet>
> 12 | const msalInstance = new PublicClientApplication({
| ^
13 | auth: {
14 | clientId: config.appId,
15 | redirectUri: config.redirectUri
at BrowserAuthError.AuthError [as constructor] (node_modules/#azure/msal-common/dist/error/AuthError.js:27:24)
at new BrowserAuthError (node_modules/#azure/msal-browser/src/error/BrowserAuthError.ts:152:9)
at Function.Object.<anonymous>.BrowserAuthError.createCryptoNotAvailableError (node_modules/#azure/msal-browser/src/error/BrowserAuthError.ts:172:16)
at new BrowserCrypto (node_modules/#azure/msal-browser/src/crypto/BrowserCrypto.ts:31:36)
at new CryptoOps (node_modules/#azure/msal-browser/src/crypto/CryptoOps.ts:45:30)
at PublicClientApplication.ClientApplication (node_modules/#azure/msal-browser/src/app/ClientApplication.ts:108:58)
at new PublicClientApplication (node_modules/#azure/msal-browser/src/app/PublicClientApplication.ts:49:9)
at Object.<anonymous> (src/App.test.tsx:12:22)
I'm unsure what the above means, but as far as I can understand, this error is occurring because the session is not authenticated.
My question can therefore be divided into the following:
What does this error mean?
How can I solve this error? (Can we bypass MSAL by any chance for testing purposes?)
You need to add crypto to your Jest config in jest.config.js:
module.exports = {
// ...
globals: {
// ...
crypto: require("crypto")
}
};
For eslint issue
try this way
import crypto from 'crypto';
module.exports = {
// ...
globals: {
// ...
crypto,
}
};
I tried adding crypto to my jest.config.js, but it didn't work. Then I tried adding it package.json. It was also pointless giving this error.
Out of the box, Create React App only supports overriding these Jest options:
• clearMocks
• collectCoverageFrom
• coveragePathIgnorePatterns
• coverageReporters
• coverageThreshold
• displayName
• extraGlobals
• globalSetup
• globalTeardown
• moduleNameMapper
• resetMocks
• resetModules
• restoreMocks
• snapshotSerializers
• testMatch
• transform
• transformIgnorePatterns
• watchPathIgnorePatterns.
These options in your package.json Jest configuration are not currently supported by Create React App:
In my case, I have a custom hook that has a dependency with msalInstance
I can prevent the above error by mocking my hook as said here
But still, this wasn't a good solution because if I have many hooks like this. So what I did was mock msalInstance in setupTests.ts file
jest.mock('./msal-instance', () => ({
getActiveAccount: () => ({}),
acquireTokenSilent: () => Promise.resolve({ accessToken: '' }),
}));
This is my msal-instance.ts
import {
PublicClientApplication,
EventType,
EventMessage,
AuthenticationResult,
} from '#azure/msal-browser';
import { msalConfig } from './authConfig';
const msalInstance = new PublicClientApplication(msalConfig);
// Account selection logic is app dependent. Adjust as needed for different use cases.
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0]);
}
msalInstance.addEventCallback((event: EventMessage) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload as AuthenticationResult;
const { account } = payload;
msalInstance.setActiveAccount(account);
}
});
export default msalInstance;
For react version 17.x.x you can install "#wojtekmaj/enzyme-adapter-react-17" package and after that you can create a src/setupTests.js file. You can add all your environment variables and other configurations to this file as follows:
//This is for the issue above
const nodeCrypto = require("crypto");
window.crypto = {
getRandomValues: function (buffer) {
return nodeCrypto.randomFillSync(buffer);
},
};
//It is also possible to add ENV variables
window.ENV = {
ApiURL: {
lessonsUrl: "https://myApiURL.com/APIendpoint",
}
CloudUiUrl: "localhost:3000",
};
When you run your tests #wojtekmaj/enzyme-adapter-react-17 will take the settings in this file automatically.
I am currently attempting to read/write to memory through the use of JNA for Java. For the past week I have tried a multitude of solutions, mostly from [similar projects][1] I have found online, but nothing has resolved my problem.
I know I am receiving the correct process ID of the program, then I create a Pointer using the openProcess method. Then I call getBaseAddress using the newly created Pointer. The problem I believe lies within the EnumProcessModules/Psapi method/class.
Truthfully I am slightly in over my head but this is one of the last issues I am having with this program. My overall goal is to find the base address of the program, use various offsets to access the information I am trying to modify, and then modify it appropriately. The program is 32-bit, which I have seen other people say you need to use a EnumProcessModulesEx method for? but truthfully I am unsure of how/where to implement that.
Any help would be appreciated!
You're getting an Access Denied error because Windows requires you to enable Debug privilege on your current process before accessing the memory of another process. So you will need to both run your program as Administrator, and before you call your OpenProcess code, enable debug privilege.
Here's the JNA code in my application that does this. It's a static method as I only call it once for the entire application:
/**
* Enables debug privileges for this process, required for OpenProcess() to get
* processes other than the current user
*
* #return {#code true} if debug privileges were successfully enabled.
*/
private static boolean enableDebugPrivilege() {
HANDLEByReference hToken = new HANDLEByReference();
boolean success = Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
WinNT.TOKEN_QUERY | WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
if (!success) {
LOG.error("OpenProcessToken failed. Error: {}", Native.getLastError());
return false;
}
try {
WinNT.LUID luid = new WinNT.LUID();
success = Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid);
if (!success) {
LOG.error("LookupPrivilegeValue failed. Error: {}", Native.getLastError());
return false;
}
WinNT.TOKEN_PRIVILEGES tkp = new WinNT.TOKEN_PRIVILEGES(1);
tkp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
success = Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tkp, 0, null, null);
int err = Native.getLastError();
if (!success) {
LOG.error("AdjustTokenPrivileges failed. Error: {}", err);
return false;
} else if (err == WinError.ERROR_NOT_ALL_ASSIGNED) {
LOG.debug("Debug privileges not enabled.");
return false;
}
} finally {
Kernel32.INSTANCE.CloseHandle(hToken.getValue());
}
return true;
}
I'm not sure from looking at your code whether you also have the right permissions for OpenProcess. Be sure you have the VM_READ permission. Here's what I use, your mileage may vary (I assume you'll need writing permissions as well).
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(
WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ,
false, processID);
i'm trying to make a plugin, it must block a specified commands setted by config. i've maked this but it doesn't block any command.
Code:
#EventHandler(priority = EventPriority.HIGHEST)
public void onPreprocess(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
String command = event.getMessage();
List<String> bCmds = this.plugin.cfg.getStringList("blocked-commands");
for (String bCmd : bCmds)
{
if(command.equalsIgnoreCase(bCmd))
{
event.setCancelled(true);
}
}
}
Config:
blocked-commands:
- /pl
- /op
- /sp
- /gravityblock
PS: I've tried to use:
String command = event.getMessage().subString(1);
Thanks for Help... :)
Registered events? implemented listner?
Also your code will not work with additional arguments in the command.
If it contains spaces, split it with " " and get the first element to just get the command
if (cmd.contains(" ")) cmd = cmd.split(" ")[0];
As stated by Bukkit's wiiki, the priorities are called in the following order:
EventPriority.LOWEST
EventPriority.LOW
EventPriority.NORMAL
EventPriority.HIGH
EventPriority.HIGHEST
EventPriority.MONITOR
Maybe you could try to use the Lowest priority, so the event gets cancelled before the command is handled.
I also believe that the command might have arguments, so it might not be equal to the string provided, you should also try
String command = event.getMessage();
if (command.toLowerCase().startsWith("/command") ) {
//cancel
}
I have a Java program that calls an Applescript file to run, and returns information back to Java. However, I need to also pass some arguments to the Applescript file. The relevant portion of the Java file:
public static void scriptRunner(String[] args) {
// Connect to the database.
ConnectionManager.getInstance().setDBType(DBType.MYSQL);
// Prepare the AppleScript file to be executed.
String homeFolder = System.getenv("HOME");
File scriptFile = new File(homeFolder + "/Documents/Output--Test.applescript");
InputStream scriptStream = null;
try {
scriptStream = FileUtils.openInputStream(scriptFile);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not find the Output AppleScript file. Please notify Chris McGee", "File not found", JOptionPane.ERROR_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(scriptStream));
// These two lines prepare the scripting engine, ready to run the script.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("AppleScript");
// Add the parameters to the engine so they will be passed to the script.
engine.put("javaOrderNum", args[0]);
engine.put("javaShipDate", args[1]);
engine.put("javaInitials", args[2]);
engine.put("javaOverruns", args[3]);
// Run the script and evaluate the result.
log.trace("Run the script and evaluate the result.");
Object result = null;
try {
result = engine.eval(bufferedReader); // Run the script and place the result into an abstract object.
} catch (ScriptException e) {
JOptionPane.showMessageDialog(null, "Either an error occurred with the Output script or the user cancelled it.", "Script error / cancel", JOptionPane.INFORMATION_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
log.debug(result); // Check that we received the correct information back from the script.
log.debug("");
.
.
.
Sadly, the engine.put lines, as suggested from a forum I read during my searches to get this problem solved, don't seem to work. The AppleScript file:
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
set jInitials to item 3 of arguments
set jOverruns to item 4 of arguments
-- Set the correct folder variable
if (folderExists(POSIX path of "/Volumes/Users/Scripts/")) then
set server_prefix to "/Volumes/Users/Scripts/"
else if (folderExists(POSIX path of "/centralserver/Users/Scripts/")) then
set server_prefix to "/centralserver/Users/Scripts/"
else
display alert "Please connect to the central server, then try again.
If you have already done so, please let Chris McGee know."
end if
with timeout of (30 * 60) seconds
tell application "Adobe InDesign CS6"
set myJavaScript to server_prefix & "sky-artdept/Test/Output.jsx"
set myResult to do script myJavaScript with arguments {jOrderNum, jShipDate, jInitials, jOverruns} language javascript
return myResult
end tell
end timeout
on folderExists(posixPath)
return ((do shell script "if test -e " & quoted form of posixPath & "; then
echo 1;
else
echo 0;
fi") as integer) as boolean
end folderExists
I am given an error that the variable arguments is not defined. What can I try next?
I can't help with the javascript running the applescript. But, you applescript code is missing a declaration. You're asking for "item 1 of arguments" but you never define the variable arguments.
When the script is not inside any handler, it is implicit that it is inside a run() handler. And, since you're needing to pass arguments on run, you should try wrapping your script, minus the on folderExists() handler, inside a run handler that includes the arguments declaration.
on run(arguments)
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
…
end timeout
end run
on folderExists(posixPath)
…
end folderExists
Busy trying to Call RPG function from Java and got this example from JamesA. But now I am having trouble, here is my code:
AS400 system = new AS400("MachineName");
ProgramCall program = new ProgramCall(system);
try
{
// Initialise the name of the program to run.
String programName = "/QSYS.LIB/LIBNAME.LIB/FUNNAME.PGM";
// Set up the 3 parameters.
ProgramParameter[] parameterList = new ProgramParameter[2];
// First parameter is to input a name.
AS400Text OperationsItemId = new AS400Text(20);
parameterList[0] = new ProgramParameter(OperationsItemId.toBytes("TestID"));
AS400Text CaseMarkingValue = new AS400Text(20);
parameterList[1] = new ProgramParameter(CaseMarkingValue.toBytes("TestData"));
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run the program.
if (program.run() != true)
{
// Report failure.
System.out.println("Program failed!");
// Show the messages.
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
// Show each message.
System.out.println(messagelist[i]);
}
}
// Else no error, get output data.
else
{
AS400Text text = new AS400Text(50);
System.out.println(text.toObject(parameterList[1].getOutputData()));
System.out.println(text.toObject(parameterList[2].getOutputData()));
}
}
catch (Exception e)
{
//System.out.println("Program " + program.getProgram() + " issued an exception!");
e.printStackTrace();
}
// Done with the system.
system.disconnectAllServices();
The application Hangs at this lineif (program.run() != true), and I wait for about 10 minutes and then I terminate the application.
Any idea what I am doing wrong?
Edit
Here is the message on the job log:
Client request - run program QSYS/QWCRTVCA.
Client request - run program LIBNAME/FUNNAME.
File P6CASEL2 in library *LIBL not found or inline data file missing.
Error message CPF4101 appeared during OPEN.
Cannot resolve to object YOBPSSR. Type and Subtype X'0201' Authority
FUNNAME insert a row into table P6CASEPF through a view called P6CASEL2. P6CASEL2 is in a different library lets say LIBNAME2. Is there away to maybe set the JobDescription?
Are you sure FUNNAME.PGM is terminating and not hung with a MSGW? Check QSYSOPR for any messages.
Class ProgramCall:
NOTE: When the program runs within the host server job, the library list will be the initial library list specified in the job description in the user profile.
So I saw that my problem is that my library list is not setup, and for some reason, the user we are using, does not have a Job Description. So to over come this I added the following code before calling the program.run()
CommandCall command = new CommandCall(system);
command.run("ADDLIBLE LIB(LIBNAME)");
command.run("ADDLIBLE LIB(LIBNAME2)");
This simply add this LIBNAME, and LIBNAME2 to the user's library list.
Oh yes, the problem is Library list not set ... take a look at this discussion on Midrange.com, there are different work-around ...
http://archive.midrange.com/java400-l/200909/msg00032.html
...
Depe