DragDrop setting SelectionData format - drag-and-drop

I am playing a little with drag and drop under gtk#.
When calling
protected virtual void OnDragDataGet (object o, Gtk.DragDataGetArgs args)
{
byte[] data = GetSomeData();
args.SelectionData.Set(args.Context.Targets[0], 0, data);
}
an error occurs:
Gtk-CRITICAL **: _gtk_selection_request: assertion `(data.format >= 8) && (data.format % 8 == 0)' failed
however setting the format to 8 works fine:
protected virtual void OnDragDataGet (object o, Gtk.DragDataGetArgs args)
{
byte[] data = GetSomeData();
args.SelectionData.Set(args.Context.Targets[0], 8, data);
}
I have found some examples on drag and drop, all use 8 as the format for sending the data. (Using 0 was acually a typo.) However I have not found what this format does, or why 8 works, whereas 0 does not.
Can someone explain what "fomat" does ?

From
http://www.go-mono.com/docs/index.aspx?link=M%3aGtk.SelectionData.Set%28Gdk.Atom%2cSystem.Int32%2cSystem.Byte[]%29:
format (number of bits in a unit) - set this to 8 and encode your data as UTF-8

Related

Convert two 16 Bit Registers to 32 Bit real value flutter

I am using a Modbus flutter lib, reading 2 registers I obtain:
[22136, 4660]
This means: 0x12345678 I need a function to convert it to a 32 bit real value: 305419896, in easymodbustcp library I found:
/**
* Convert two 16 Bit Registers to 32 Bit real value
* #param registers 16 Bit Registers
* #return 32 bit real value
*/
public static float ConvertRegistersToFloat(int[] registers) throws IllegalArgumentException
{
if (registers.length != 2)
throw new IllegalArgumentException("Input Array length invalid");
int highRegister = registers[1];
int lowRegister = registers[0];
byte[] highRegisterBytes = toByteArray(highRegister);
byte[] lowRegisterBytes = toByteArray(lowRegister);
byte[] floatBytes = {
highRegisterBytes[1],
highRegisterBytes[0],
lowRegisterBytes[1],
lowRegisterBytes[0]
};
return ByteBuffer.wrap(floatBytes).getFloat();
}
Any help to do it in flutter / dart?
This can be done with bit shifts and a bitwise or. You need to shift the 2 higher bytes by 16 bits, then or it to get the value you want.
void main() {
List<int> vals = [22136, 4660];
int result = vals[1] << 16 | vals[0];
print(result);//305419896
}
You could also achieve the same result in this case by replacing the bitwise or with addition.
void main() {
List<int> vals = [22136, 4660];
int result = (vals[1] << 16) + vals[0];
print(result);//305419896
}

OnKeyDown event incorrect encoding

I catch all the character typed while the document is receiving focus using following code:
RootPanel.get().addDomHandler(new KeyDownHandler() {
#Override
public void onKeyDown(KeyDownEvent event) {
char key = (char) event.getNativeKeyCode();
String keyString = String.valueOf(key);
if (!event.isShiftKeyDown())
keyString = keyString.toLowerCase();
System.out.print(keyString);
}
}, KeyDownEvent.getType());
When the device that is sending key events is using ASCII (we cannot control what encoding gets used) then we get the following output:
www¾mitcom¾m3
What can we do so that we get the correctly encoded input in Java?
event.getNativeKeyCode() gives you a key code, which is not a character. From documentation: Gets the key code (code associated with the physical key) associated with this event.. Dot pressed on my keyboard gives me 190. Also to mention in Java char is 16-bit type, while int is 32-bit, i.e. generally (char) integerVal is an unsafe operation.
Now what you probably want to use is event.getNativeEvent().getCharCode(). The problem is that it's always 0 in KeyDownEvent. Therefore, I would suggest to use KeyPressHandler & KeyPressEvent. Your code would look like:
private void onKeyPress(KeyPressEvent event) {
char c = (char) event.getNativeEvent().getCharCode();
String s = String.valueOf(c);
if (event.isShiftKeyDown()) {
s = s.toUpperCase();
}
GWT.log(s);
}
RootPanel.get().addDomHandler(this::onKeyPress, KeyPressEvent.getType());

Teensy 3.2 Hellokeypad sketch compile errors

I'm getting a compiler error when I try and compile the HelloKeypad demo sketch.
I'm on a Windows 7 machine using a Teensy 3.2 board.
I bought a keypad like this one: https://www.adafruit.com/products/1824
I downloaded the keypad.zip file from here:
https://www.pjrc.com/teensy/td_libs_Keypad.html
and I'm using the example sketch from the same web page:
/* #file HelloKeypad.pde
|| #version 1.0
|| #author Alexander Brevig
|| #contact alexanderbrevig#gmail.com
||
|| #description
|| | Demonstrates the simplest use of the matrix Keypad library.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();
if (key){
Serial.println(key);
}
}
Here is the compiler message.
Arduino: 1.6.6 (Windows 7), TD: 1.26, Board: "Teensy 3.2 / 3.1, Serial + Keyboard + Mouse + Joystick, 96 MHz optimized (overclock), US English"
In file included from C:\Users\FRESH1~1\AppData\Local\Temp\arduino_827e3ed6878980f03915bd59f832243c\HelloKeypad.ino:10:0:
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:80:27: error: expected class-name before '{' token
class Keypad : public Key {
^
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:90:2: error: 'Key' does not name a type
Key key[LIST_MAX];
^
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:95:2: error: 'KeyState' does not name a type
KeyState getState();
^
C:\Users\fresh1011\Documents\Arduino\libraries\Keypad/Keypad.h:119:28: error: 'KeyState' has not been declared
void transitionTo(byte n, KeyState nextState);
^
Multiple libraries were found for "Keypad.h"
Used: C:\Users\fresh1011\Documents\Arduino\libraries\Keypad
Not used: C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries\Keypad
exit status 1
Error compiling.
Is the Keypad.zip file out of date?
Thanks for any help.
Maybe use Arduino IDE 1.6.3 instead of 1.6.6.
According to the following post in the pjrc forum it solves the problem for the library support.

iTextSharp 5.5.6 PdfCopy Failing with "Cannot access a closed file"

This seems to be similar to this question: Merging Tagged PDF without ruining the tags
I'm using the latest iTextSharp NuGet package (v5.5.6) trying to merge two tagged PDFs. When calling Document.Close() I'm getting an ObjectDisposedException originating from PdfCopy.FlushIndirectObjects().
at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.get_Position()
at iTextSharp.text.io.RAFRandomAccessSource.Get(Int64 position, Byte[] bytes, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\io\RAFRandomAccessSource.cs:line 96
at iTextSharp.text.io.IndependentRandomAccessSource.Get(Int64 position, Byte[] bytes, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\io\IndependentRandomAccessSource.cs:line 76
at iTextSharp.text.pdf.RandomAccessFileOrArray.Read(Byte[] b, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\RandomAccessFileOrArray.cs:line 235
at iTextSharp.text.pdf.RandomAccessFileOrArray.ReadFully(Byte[] b, Int32 off, Int32 len) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\RandomAccessFileOrArray.cs:line 264
at iTextSharp.text.pdf.RandomAccessFileOrArray.ReadFully(Byte[] b) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\RandomAccessFileOrArray.cs:line 254
at iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw(PRStream stream, RandomAccessFileOrArray file) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfReader.cs:line 2406
at iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw(PRStream stream) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfReader.cs:line 2443
at iTextSharp.text.pdf.PRStream.ToPdf(PdfWriter writer, Stream os) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PRStream.cs:line 224
at iTextSharp.text.pdf.PdfIndirectObject.WriteTo(Stream os) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfIndirectObject.cs:line 157
at iTextSharp.text.pdf.PdfWriter.PdfBody.Write(PdfIndirectObject indirect, Int32 refNumber, Int32 generation) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfWriter.cs:line 389
at iTextSharp.text.pdf.PdfWriter.PdfBody.Add(PdfObject objecta, Int32 refNumber, Int32 generation, Boolean inObjStm) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfWriter.cs:line 379
at iTextSharp.text.pdf.PdfCopy.WriteObjectToBody(PdfIndirectObject objecta) in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfCopy.cs:line 1238
at iTextSharp.text.pdf.PdfCopy.FlushIndirectObjects() in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfCopy.cs:line 1186
at iTextSharp.text.pdf.PdfCopy.FlushTaggedObjects() in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfCopy.cs:line 884
at iTextSharp.text.pdf.PdfDocument.Close() in d:\Downloads\itextsharp-master\src\core\iTextSharp\text\pdf\PdfDocument.cs:line 825
Here is the code that is producing the exception. If I don't call copy.SetTagged() and don't pass true as the third argument to GetImportedPage() the code executes without exception, but ignores all tagging.
using(var ms = new MemoryStream())
{
var doc = new Document();
var copy = new PdfSmartCopy(doc, ms);
copy.SetTagged();
doc.Open();
string[] files = new string[]{#"d:\tagged.pdf", #"d:\tagged.pdf"};
foreach(var f in files)
{
var reader = new PdfReader(f);
int pages = reader.NumberOfPages;
for(int i = 0; i < pages;)
copy.AddPage(copy.GetImportedPage(reader, ++i, true));
copy.FreeReader(reader);
reader.Close();
}
// ObjectDisposedException
doc.Close();
ms.Flush();
File.WriteAllBytes(#"d:\pdf.merged.v5.pdf", ms.ToArray());
}
Looking at the 5.5.6 source branch it looks like RAFRandomAccessSource.cs line 96 is the culprit.
public virtual int Get(long position, byte[] bytes, int off, int len) {
if (position > length)
return -1;
// Not thread safe!
if (raf.Position != position)
raf.Position has been disposed at this point, but I can't tell from where it has been disposed.
I'm hoping that I just need to do something more than simply call copy.SetTagged() and pass true to GetImportedPage() to fix the issue.
You are closing the PdfReader instances too early. You can only trigger:
reader.Close();
after you close the PdfSmartCopy instance, hence you have to rethink where you create the different PdfReader objects (not inside the loop).
The reason why the different PdfReader instances have to remain open is purely technical: merging structured trees (where all the tagging information is stored) isn't trivial. This can only happen at the moment all the other work is done. It requires access to the original structures of the separate documents. If you close the PdfReader to such a document, that structure can no longer be retrieved.

Using 'incr' with spymemcached client

I am trying set up a very basic hit rate monitor in memcached using the spymemcached-2.8.4 client however the value stored in memcached never actually seems to increment... Is this a bug or am I missing something?
public static void checkHitRate(String clientId) throws FatalException, ForbiddenException {
MemcachedClient memcachedClient;
try {
memcachedClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
Integer hitRate = (Integer) memcachedClient.get(clientId);
if (hitRate == null) {
memcachedClient.set(clientId, 1800, 1);
} else if (hitRate > 500) {
throw new ForbiddenException("Hit rate too high. Try again later");
} else if (hitRate <= 500) {
memcachedClient.incr(clientId, 1);
}
} catch (IOException e) {
throw new FatalException("Could not read hit rate from Memcached.");
}
}
I know its possible in memcached:
(TELENT output)
set clientId_1 0 200 1
1
STORED
incr clientId_1 1
2
get clientId_1
VALUE clientId_1 0 1
2
END
For incr/decr memcached server considers stored values as string representation of integer,
Adding an item like
memcachedClient.set(clientId, 1800, 1);
adds value as an integer that's why memcached is unable to increment it.
Use
memcachedClient.set(clientId, 1800, "1");
instead. It will work as you need.
You can use another incr signature:
System.out.println("Incr result: " + memcachedClient.incr("testIncrKey", 1, 1));
That works for me with spymemcached-2.8.4 client.
Also, looks like there was an issue with incr spymemcached.
You should not use Integer since it will be converted back to String and stored as String on memcached server.
If you open using xmemcached then you can use specific Counter construct, e.g.
Counter counter=client.getCounter("counter",0);
counter.incrementAndGet();
counter.decrementAndGet();
counter.addAndGet(-10);
read more on it in xmemcached documentation: