can anybody help me with solving my problem of Hex2Bin and Bin2Hex functions?
First I was trying to make the conversion Hex2Bin. I would like to call the AddIn function from macro so I called createUNOservice:
Function fcHex2Bin(arg as variant, NumberOfBits As integer) as string
Dim oService as Object
oService = createUNOService("com.sun.star.sheet.addin.Analysis")
sArg = cStr(arg)
fcHex2Bin = oService.getHex2Bin(sArg,NumberOfBits)
End Function
but all the time ends with fault message like "The object variable is not set.". I already don't know why.
My final goal would be to make all functions of Calc running in macros, but at this moment I would be glad to have two functions Hex2Bin and Bin2Hex running - anyhow.
My LibreOffice version:
Version: 7.1.3.2 (x64) / LibreOffice Community
Build ID: 47f78053abe362b9384784d31a6e56f8511eb1c1
CPU threads: 8; OS: Windows 10.0 Build 19042; UI render: Skia/Raster; VCL: win
Locale: cs-CZ (cs_CZ); UI: cs-CZ
Calc: CL
Thank you for your help.
This way works.
Function fcHex2Bin(aNum As String, rPlaces As Any) As String
Dim oFunc As Object
oFunc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
Dim aArgs(0 to 1) As Variant
aArgs(0) = aNum
aArgs(1) = rPlaces
fcHex2Bin = oFunc.callFunction("com.sun.star.sheet.addin.Analysis.getHex2Bin", aArgs())
End Function
As for why the other way does not work, many analysis functions require a hidden XPropertySet object as the first argument. The following code produces informative error messages:
REM IllegalArgumentException: expected 3 arguments, got 1
sResult = oService.getHex2Bin(ThisComponent.getPropertySetInfo())
REM IllegalArgumentException: arg no. 0 expected: "com.sun.star.beans.XPropertySet"
sResult = oService.getHex2Bin(ThisComponent.getPropertySetInfo(), "2", 4)
However I tried passing ThisComponent.getPropertySetInfo().getProperties() from a Calc spreadsheet and it still didn't work, so I'm not exactly sure what is required to do it that way.
The documentation at https://help.libreoffice.org/latest/he/text/sbasic/shared/calc_functions.html does not really explain this. You could file a bug report about missing documentation, perhaps related to https://bugs.documentfoundation.org/show_bug.cgi?id=134032.
Related
I'm following this tutorial that codes a sentiment analysis classifier using BERT with the huggingface library and I'm having a very odd behavior. When trying the BERT model with a sample text I get a string instead of the hidden state. This is the code I'm using:
import transformers
from transformers import BertModel, BertTokenizer
print(transformers.__version__)
PRE_TRAINED_MODEL_NAME = 'bert-base-cased'
PATH_OF_CACHE = "/home/mwon/data-mwon/paperChega/src_classificador/data/hugingface"
tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
sample_txt = 'When was I last outside? I am stuck at home for 2 weeks.'
encoding_sample = tokenizer.encode_plus(
sample_txt,
max_length=32,
add_special_tokens=True, # Add '[CLS]' and '[SEP]'
return_token_type_ids=False,
padding=True,
truncation = True,
return_attention_mask=True,
return_tensors='pt', # Return PyTorch tensors
)
bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
last_hidden_state, pooled_output = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print([last_hidden_state,pooled_output])
that outputs:
4.0.0
['last_hidden_state', 'pooler_output']
While the answer from Aakash provides a solution to the problem, it does not explain the issue. Since one of the 3.X releases of the transformers library, the models do not return tuples anymore but specific output objects:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print(type(o))
print(o.keys())
Output:
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions
odict_keys(['last_hidden_state', 'pooler_output'])
You can return to the previous behavior by adding return_dict=False to get a tuple:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask'],
return_dict=False
)
print(type(o))
Output:
<class 'tuple'>
I do not recommend that, because it is now unambiguous to select a specific part of the output without turning to the documentation as shown in the example below:
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], return_dict=False, output_attentions=True, output_hidden_states=True)
print('I am a tuple with {} elements. You do not know what each element presents without checking the documentation'.format(len(o)))
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], output_attentions=True, output_hidden_states=True)
print('I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; {} '.format(o.keys()))
Output:
I am a tuple with 4 elements. You do not know what each element presents without checking the documentation
I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states', 'attentions'])
I faced the same issue while learning how to implement Bert. I noticed that using
last_hidden_state, pooled_output = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
is the issue. Use:
outputs = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
and extract the last_hidden state using
output[0]
You can refer to the documentation here which tells you what is returned by the BertModel
I'm trying to write a PowerShell script that will generate a table of information with two columns: a name, and a date (which will be retrieved from a third-party application - in this case svn.exe).
The overall script works well, but I'm struggling to get the date that the server sends back into the DataTable. Here's a simplified version of my script:
# Set up a DataTable and initialise columns
$table = New-Object system.Data.DataTable “Test Table”
$col1 = New-Object system.Data.DataColumn Name,([string])
$col2 = New-Object system.Data.DataColumn DateFromServer,([DateTime])
$table.columns.add($col1)
$table.columns.add($col2)
# Create a new row and add the data
$row = $table.NewRow()
$row.Name = "Test"
$lastCommit = GetDateFromExternalApp
$lastCommit.GetType() # this returns DateTime as I would expect
$row.DateFromServer = $lastCommit # this throws up an error
$table.Rows.Add($row)
# Output the table
$table | Format-Table -AutoSize
# This function simulates what the actual function does
# (the real one goes to SVN and pulls down data, but it
# ends up with the same resulting date)
Function GetDateFromExternalApp
{
$externalAppDate = "2012-09-17T16:33:57.177516Z"
return [DateTime]($externalAppDate)
}
The problem (noted in comments in the script above) is that while the function seems to be happily returning a DateTime instance, when I try to add this into the table row's DateFromServer column it's throwing up an error:
Exception setting "DateFromServer": "Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.IConvertible'.Couldn't store <18/09/2012 2:33:57 AM> in DateFromServer Column. Expected type is DateTime." At line:13 char:6
+ $row. <<<< DateFromServer = $lastCommit
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
However, the call to $lastCommit.GetType() shows that this is indeed a DateTime - and in fact if I add this line somewhere in the script:
$lastCommit
then I can see a nicely formatted datetime, suggesting that it is indeed parsing it and converting it correctly:
Date : 18/09/2012 12:00:00 AM
Day : 18
DayOfWeek : Tuesday
DayOfYear : 262
Hour : 2
Kind : Local
Millisecond : 177
Minute : 33
Month : 9
Second : 57
Ticks : 634835324371775160
TimeOfDay : 02:33:57.1775160
Year : 2012
DateTime : Tuesday, 18 September 2012 2:33:57 AM
As such I'm quite puzzled as to why I'm getting the exception above. I realise that PowerShell does function return values differently than C#, but it looks to me like the function is returning the right type!
The issue here is due to a bug in PowerShell's type adaptation system (I would recommend reporting this to Microsoft if you have not already done so).
When you work with objects in PowerShell, you are actually working with a PSObject wrapper. Most calls (like GetType) are forwarded to the underlying object, though you can add additional members that do not interact with the object itself:
PS> Get-Date | Add-Member NoteProperty Yowza 'for example' -PassThru | Format-List y*
Yowza : for example
Year : 2012
Normally this is not an issue, as PowerShell has extensive type coercion capabilities. In the case of DataRow however, there appears to be a bug with the DataRowAdapter type used to support the property access syntax. If you use the indexer directly, $row['DateFromServer'] = $lastCommit instead of $row.DateFromServer, the value is correctly unwrapped before it is sent to the .NET type.
You can also get around this by unwrapping the value yourself, either using a cast (as vonPryz already showed: [DateTime]$lastCommit), or by retrieving the BaseObject ($lastCommit.PSObject.BaseObject).
I'd like to know the reason for this behaviour too.
Anyway, you can work around the problem by casting the date variable as DateTime or by explicitly declaring it to be one. Like so,
...
$row.DateFromServer = [DateTime]$lastCommit # Doesn't throw exception
...
Or
...
[DateTime]$lastCommit = GetDateFromExternalApp
$row.DateFromServer = $lastCommit # Doesn't throw exception
...
I suspect the reason is as stated in the error message:
"Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.IConvertible'...Expected type is DateTime." At line:13 char:6
What that is saying is that PowerShell tried to convert $lastCommit into a date and time but failed. The best way is, as vonPryz suggests - cast it to [datetime]
To see the issue more clearly, try looking at the both:
$lastcommit.gettype() and
$row.DateFromServer.gettype()
I don't have the GetDateFromExternalApp to check
How I can solve this error message
Microsoft VBScript runtime error
'800a01a8' Object required: 'lUATRef'
/cmgtest/transaction/viewPCReqForm.asp,
line 284
this is some source code that I wrote below
function checkUATReq(aUATRef)
Dim correctness,lUATRef,uatRef
correctness = False
lUATRef = aUATRef
uatRef = lUATRef.Substring(1,2)
rwriteln uatRef
'sqlCheckUATReq = "select * from PC_DETAIL where ID ='"&uatReqRef&"'"
'rwriteln uatReqRef
End function
Seems like your function isn't getting a parameter passed to it. Check whether aUATRef is getting initialized.
In VBScript, Strings aren't objects. You should use the Mid function to get a portion of a string:
uatRef = Mid(IUATRef, 1, 2)
I'm trying to open cmd.exe on a new process and pass some code to programatically eject a device; but when trying to do this all I get is:
"Error #2044: Unhandled IOErrorEvent:. text=Error #3218: Error while writing data to NativeProcess.standardInput."
Here's my code:
private var NP:NativeProcess = new NativeProcess();
private function EjectDevice():void
{
var RunDLL:File = new File("C:\\Windows\\System32\\cmd.exe");
var NPI:NativeProcessStartupInfo = new NativeProcessStartupInfo();
NPI.executable = RunDLL;
NP.start(NPI);
NP.addEventListener(Event.STANDARD_OUTPUT_CLOSE, CatchOutput, false, 0, true);
NP.standardInput.writeUTFBytes("start C:\\Windows\\System32\\rundll32.exe shell32.dll,Control_RunDLL hotplug.dll");
NP.closeInput();
}
I also tried with writeUTF instead of writeUTFBytes, but I still get the error. Does anyone have an idea of what I'm doing wrong?.
Thanks for your time :)
Edward.
Maybe cmd.exe doesn't handle standardInput like a normal process.
You could try passing what you want to execute as parameters to the cmd process, rather than writing to the standard input
I think
cmd.exe /C "start C:\Windows\System32\rundll32.exe shell32.dll,Control_RunDLL hotplug.dll"
is the format to pass something as a parameter to cmd to execute immediately.
This site has an example of passing process parameters using a string vector:
http://blogs.adobe.com/cantrell/archives/2009/11/demo_of_nativeprocess_apis.html
Try it without the last line "NP.closeInput();"
See also:
http://help.adobe.com/en_US/as3/dev/WSb2ba3b1aad8a27b060d22f991220f00ad8a-8000.html
I agree with abudaan, you shouldn't need to closeInput().
Also, suggest you add a line break at the end of the writeUTFBytes() call, e.g.:
NP.standardInput.writeUTFBytes("start C:\\Windows\\System32\\rundll32.exe shell32.dll,Control_RunDLL hotplug.dll **\n**");
Lastly, I recommend you listen to other events on the NativeProcess, I use a block of code something like this:
NP.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStdOutData);
NP.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onStdErrData);
NP.addEventListener(Event.STANDARD_OUTPUT_CLOSE, onStdOutClose);
NP.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, onStdInputProgress);
NP.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
NP.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, onIOError);
NP.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
with the normal event handler functions that at least trace what they receive.
Best of luck - I've just spent a few hours refining NativeProcess with cmd.exe - its fiddly. But I got there in the end and you will too.
Upon compiling, I am getting the following error:
C:\UDK\UDK-2010-03\Development\Src\FixIt\Classes\ZInteraction.uc(41) : Error, Unrecognized member 'OpenMenu' in class 'GameUISceneClient'
Line 41 is the following:
GetSceneClient().OpenMenu("ZInterface.ZNLGWindow");
But when I search for OpenMenu, I find that it is indeed defined in GameUISceneClient.uc of the UDK:
Line 1507: exec function OpenMenu( string MenuPath, optional int PlayerIndex=INDEX_NONE )
It looks like I have everything correct. So what's wrong? Why can't it find the OpenMenu function?
From the wiki page on Legacy:Exec Function:
Exec Functions are functions that a player or user can execute by typing its name in the console. Basically, they provide a way to define new console commands in UnrealScript code.
Okay, so OpenMenu has been converted to a console command. Great. But still, how do I execute it in code? The page doesn't say!
More searching revealed this odd documentation page, which contains the answer:
Now then, there is also a function
within class Console called 'bool
ConsoleCommand(coerce string s)'. to
call your exec'd function,
'myFunction' from code, you type:
* bool isFunctionThere; //optional
isFunctionThere = ConsoleCommand("myFunction myArgument");
So, I replaced my line with the following:
GetSceneClient().ConsoleCommand("OpenMenu ZInterface.ZNLGWindow");
Now this causes another error which I covered in my other question+answer a few minutes ago. But that's it!
Not sure if this is your intent, but if you are trying to create a UIScene based on an Archetype that has been created in the UI Editor, you want to do something like this:
UIScene openedScene;
UIScene mySceneArchetype;
mySceneArchetype = UIScene'Package.Scene';
GameSceneClient = class'UIRoot'.static.GetSceneClient();
//Open the Scene
if( GameSceneClient != none && MySceneArchetype != none )
{
GameSceneClient.OpenScene(mySceneArchetype,LocalPlayer(PlayerOwner.Player), openedScene);
}