CMagazin.h
class CMagazin
{
char *m_nume;
list<CProdus*>List_produse;
public:
void printExpirabile( const char* data);
~CMagazin();
};
CMagazin.cpp
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
**if (p > xdata)**->this problem
}
}
}
CAliment.h
class CAliment :
public CProdus
{
char *m_expirare;
public:
bool operator >(const char*date);
~CAliment();
};
CAliment.cpp
bool CAliment::operator>(const char * date)
{
if (atoi(this->m_expirare) < atoi(date))
{
return 1;
}
else
{
return 0;
}
}
its about ">" operator.in CMagazin.cpp dont use my operator...i need help.
what can i do?I need ">" in CMagazin class. class CAliment its a class derived from CProdus.
Answer is: in Class CProdus the operator must be declared virtual, and in
CMagazin.cpp
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
if (p->operator>( xdata))-> make this!
{
p->print();
}
}
}
}
CProdus*p - is a pointer , need to have object for use this operator -> Try (*p)>xdata
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
if ((*p)>( xdata))-> make this!
{
p->print();
}
}
}
}
Related
I'm trying to implement a remove method from scratched for the LinkedList class and like the title says, I've been getting the :
"incompatible types: T cannot be converted to LinkedList.Node"
Here's my code :
public class LinkedList<T> implements LinkedListInterface<T> {
private Node head;
private Node tail;
private int count;
public LinkedList () {
head = null;
tail = null;
count = 0;
}
class Node {
T data;
Node next;
Node(T data) {
this.data = data;
next = null;
}
}
public Node getHead() {
return head;
}
public T remove(int pos) throws ListException {
if (pos < 1 || pos > count) {
throw new ListException("Invalid position to remove from");
}
Node removedItem = null;
if (count == 1) {
removedItem = head.data; // Here it says the error
head = null;
tail = null;
}
else if (pos == 1) {
removedItem = head.data;
head = head.next;
}
else if (pos == count) {
removedItem = tail.data; // Same error
Node prev = jump(pos - 2);
prev.next = null;
tail = prev;
}
else {
Node prev = jump(pos - 2);
removedItem = prev.next.data; // Same error
prev.next = prev.next.next;
}
count--;
return removedItem; // Same error
}
}
I've been so confused on how to fix it, I tried putting this.head.data or this.tail.data but to no avail, any ideas? Thanks
I am trying to wrap the libcups library https://github.com/apple/cups to be used in my Swift project.
I have tried some of the examples in https://www.cups.org/doc/cupspm.html and they are working fine.
However I am struggling when it comes to wrapping the C code to be used in a Swift project.
I have been searching online on how to wrap C libraries in Swift but has not been able to have much progress.
Here is the C code
#include <stdio.h>
#include <cups/cups.h>
typedef struct {
int num_dests;
cups_dest_t *dests;
} my_user_data_t;
int my_dest_cb(my_user_data_t *user_data, unsigned flags, cups_dest_t *dest) {
if (flags & CUPS_DEST_FLAGS_REMOVED) {
user_data->num_dests = cupsRemoveDest(dest->name, dest->instance, user_data->num_dests, &(user_data->dests));
} else {
user_data->num_dests = cupsCopyDest(dest, user_data->num_dests, &(user_data->dests));
}
return 1;
}
int my_get_dests(cups_ptype_t type, cups_ptype_t mask, cups_dest_t **dests) {
my_user_data_t user_data = { 0, NULL };
if (!cupsEnumDests(CUPS_DEST_FLAGS_NONE, 1000, NULL, type, mask, (cups_dest_cb_t)my_dest_cb, &user_data)) {
cupsFreeDests(user_data.num_dests, user_data.dests);
*dests = NULL;
return 0;
} else {
*dests = user_data.dests;
return user_data.num_dests;
}
}
int main(int argc, const char * argv[]) {
cups_dest_t *dests = NULL;
int num_dests = my_get_dests(0, 0, &dests);
printf("Destination found: %d\n", num_dests);
cups_dest_t *dest;
int i;
const char *value;
for (i = num_dests, dest = dests; i > 0; i--, dest++) {
if (dest->instance == NULL) {
value = cupsGetOption("printer-info", dest->num_options, dest->options);
printf("%s (%s)\n", dest->name, value ? value : "No description");
}
}
return 0;
}
Here is the same thing but in Swift
let destinationsCallback: cups_dest_cb_t = { user_data, flags, dest in
// (void *user_data, unsigned flags, cups_dest_t *dest)
var userDataPointer = user_data!.assumingMemoryBound(to: my_user_data_t.self).pointee
var destData = dest!.pointee
if destData.instance != nil {
print("\(String(cString: destData.name))/\(String(cString: destData.instance))")
} else {
print(String(cString: destData.name))
}
if flags == CUPS_DEST_FLAGS_REMOVED {
userDataPointer.num_dests = cupsRemoveDest(destData.name, destData.instance, userDataPointer.num_dests, &(userDataPointer.dests))
} else {
userDataPointer.num_dests = cupsCopyDest(dest, userDataPointer.num_dests, &(userDataPointer.dests))
}
return 1
}
func getDestinations(type: UInt32, mask: UInt32, dests: UnsafeMutablePointer<cups_dest_t>) -> Int32 {
var userData = my_user_data_t(num_dests: 0, dests: nil)
if cupsEnumDests(UInt32(CUPS_DEST_FLAGS_NONE), 1000, nil, type, mask, destinationsCallback, &userData) != 1 {
return 0
} else {
return userData.num_dests
}
}
I am not able to get the userData to return the correct value which I am assuming is due to the way I handle the pointers.
Greatly appreciate if I am able to get some advice.
IMHO the best way to work with such C libraries in Swift is to work with them in Objective-C. Nevertheless, the main issue seems to be that you are not writing back changes to userData, that's why you always get your initial value. You need to update it in your callback like this
let userDataPointer = user_data!.assumingMemoryBound(to: my_user_data_t.self)
var userData = userDataPointer.pointee
...
// make some changes to userData
userDataPointer.pointee = userData
return 1
Also there seems to be some differences between your C code and the Swift one, like checking flags with 'flags == CUPS_DEST_FLAGS_REMOVED' which, in general, is incorrect way to check flags, and comparing result of cupsEnumDests with 1 when in the original code you check that result is not 0.
NSS comes with very little documentation, and a heavily vestigial API. How does it work? It is used for firefox on Window and Mac, and Chrome as well on linux. How do I install, uninstall, and check installation of my own Root Cert?
See this gist, here: https://gist.github.com/pehrlich/08852e8f7da81e136d70
The meat of it is CertificateNSS.cpp, copied here:
#include "stdafx.h"
#include "CertificateNSS.h"
#include "Certificate.h"
#include <boost/filesystem/operations.hpp>
#include <nss.h>
#include <cert.h>
#include <certdb.h>
ProfileLocker::ProfileLocker(const boost::filesystem::path& profilePath) : m_isValid(false)
{
GetSharedMutex().lock();
m_isValid = (NSS_InitReadWrite(profilePath.string().c_str()) == SECSuccess);
if (!m_isValid) {
GetSharedMutex().unlock();
}
}
ProfileLocker::~ProfileLocker()
{
if (m_isValid) {
NSS_Shutdown();
GetSharedMutex().unlock();
}
}
std::mutex& ProfileLocker::GetSharedMutex()
{
static std::mutex s_mutex;
return s_mutex;
}
std::vector<boost::filesystem::path> CertificateNSS::GetUserProfiles()
{
std::vector<boost::filesystem::path> profiles;
const auto path = GetProfilesDirectory();
if (!boost::filesystem::is_directory(path)) {
return profiles;
}
boost::filesystem::directory_iterator endIt;
for (boost::filesystem::directory_iterator it(path); it != endIt; ++it) {
if (boost::filesystem::is_directory(it->status())) {
profiles.push_back(it->path());
}
}
return profiles;
}
bool CertificateNSS::Install() const
{
std::string derCert = m_cert.GetBytes(CertEncoding::DER);
if (derCert.empty()) {
return false;
}
bool wasInstalled = false;
CERTCertDBHandle* certdb = CERT_GetDefaultCertDB();
if (certdb) {
SECItem cert = { siBuffer, (unsigned char*)derCert.c_str(), static_cast<unsigned int>(derCert.size()) };
SECItem* certArray[1] = { &cert };
SECCertUsage noOpUsage = certUsageUserCertImport; // Not used, but required
CERTCertificate** certificates = nullptr;
wasInstalled = (CERT_ImportCerts(certdb, noOpUsage, 1, certArray, &certificates, PR_TRUE, PR_TRUE,
const_cast<char*>(Certificate::GetNickname().c_str())) == SECSuccess);
if (certificates[0]) {
CERTCertTrust trust = { CERTDB_TRUSTED_CA | CERTDB_VALID_CA, 0, 0 };
CERT_ChangeCertTrust(certdb, certificates[0], &trust);
CERT_DestroyCertificate(certificates[0]);
}
}
return wasInstalled;
}
bool CertificateNSS::IsInstalled() const
{
std::string derCert = m_cert.GetBytes(CertEncoding::DER);
if (derCert.empty()) {
return false;
}
bool wasInstalled = false;
SECItem cert = { siBuffer, (unsigned char*)derCert.c_str(), static_cast<unsigned int>(derCert.size()) };
CERTCertDBHandle* certdb = CERT_GetDefaultCertDB();
if (certdb) {
CERTCertificate* certificate = CERT_FindCertByDERCert(certdb, &cert);
if (certificate) {
wasInstalled = true;
CERT_DestroyCertificate(certificate);
}
}
return wasInstalled;
}
bool CertificateNSS::Uninstall() const
{
std::string derCert = m_cert.GetBytes(CertEncoding::DER);
if (derCert.empty()) {
return false;
}
bool wasUninstalled = false;
SECItem cert = { siBuffer, (unsigned char*)derCert.c_str(), static_cast<unsigned int>(derCert.size()) };
CERTCertDBHandle* certdb = CERT_GetDefaultCertDB();
if (certdb) {
CERTCertificate* certificate = CERT_FindCertByDERCert(certdb, &cert);
if (certificate) {
wasUninstalled = (SEC_DeletePermCertificate(certificate) == SECSuccess);
CERT_DestroyCertificate(certificate);
}
}
return wasUninstalled;
}
bool CertificateNSS::UninstallAll()
{
bool wasUninstalled = true;
CERTCertDBHandle* certdb = CERT_GetDefaultCertDB();
if (!certdb) {
return true;
}
// Delete up to 100 profiles
for (int i = 0; i < 100; i++) {
bool failed = true;
CERTCertificate* certificate = CERT_FindCertByNickname(certdb, Certificate::GetNickname().c_str());
if (certificate) {
wasUninstalled = (SEC_DeletePermCertificate(certificate) == SECSuccess);
if (wasUninstalled) {
failed = false;
}
CERT_DestroyCertificate(certificate);
}
if (failed) {
break;
}
}
return wasUninstalled;
}
I am using JavaCC to print an AST in a particular format.
I need it to be like this :
LetNode( Identier(X), ExprNode( PlusNode( IntegerLiteral(8), IntegerLiteral(2) )))
but I am getting:
Start(LetNode(Identifier(x)(ExprNode(IntegerLiteral(5)(PlusNode(IntegerLiteral(5)()))
I am using the dump method to print this:
public void dump(String prefix) {
System.out.print(toString(prefix));
System.out.print("(");
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode)children[i];
if (n != null) {
n.dump(prefix +"");
}
}
System.out.print(")");
}
}
}
The output without any modification is :
Start
Sxl
Statement
VariableDecl
Identifier
Type
Expression
SimpleExpression
Term
Factor
Literal
IntegerLiteral
AdditiveOp
Term
Factor
Literal
IntegerLiteral
My method:
void AdditiveOp():
{}
{
(Plus() /*#Add(2)*/ | Minus() | Or())
}
void Plus():
{
}
{
(< PLUS >)
#PlusNode
}
If I remove the /* */ it does not work as it says it expects something else not +
Any help would be greatly appreciated!
The usual way to make an AST with JJT for an expression grammar is to do something like this
void AdditiveExpression() #void :
{ Token t ; }
{
MultiplicativeExpression()
( "+" MultiplicativeExpression() #Add(2)
| "-" MultiplicativeExpression() #Subtract(2)
)*
}
I can't find any working code examples for replacing bookmark contents. The code should be able to handle both the case replace empty bookmark and replace bookmark with preexisting content.
For example: If I have this text in a Word document:
"Between the following periods comes Bookmark1.. Between next periods comes Bookmark2.."
and I want to insert the text "BM1" between the first periods, and "BM2" between the next.
After the first replacement run, the replacements are inserted correctly.
But after the next replacement run, all of the text on the line after Bookmark1 gets deleted, and then the replacement for Bookmark2 gets inserted.
This is my c# code:
var doc = WordprocessingDocument.Open(#"file.docx", true);
public static Dictionary<string, wd.BookmarkStart> FindAllBookmarksInWordFile(WordprocessingDocument file)
{
var bookmarkMap = new Dictionary<String, wd.BookmarkStart>();
foreach (var headerPart in file.MainDocumentPart.HeaderParts)
{
foreach (var bookmarkStart in headerPart.RootElement.Descendants<wd.BookmarkStart>())
{
if (!bookmarkStart.Name.ToString().StartsWith("_"))
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
}
foreach (var bookmarkStart in file.MainDocumentPart.RootElement.Descendants<wd.BookmarkStart>())
{
if (!bookmarkStart.Name.ToString().StartsWith("_"))
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
return bookmarkMap;
}
/*extension methods*/
public static bool IsEndBookmark(this OpenXmlElement element, BookmarkStart startBookmark)
{
return IsEndBookmark(element as BookmarkEnd, startBookmark);
}
public static bool IsEndBookmark(this BookmarkEnd endBookmark, BookmarkStart startBookmark)
{
if (endBookmark == null)
return false;
return endBookmark.Id.Value == startBookmark.Id.Value;
}
/* end of extension methods */
public static void SetText(BookmarkStart bookmark, string value)
{
RemoveAllTexts(bookmark);
bookmark.Parent.InsertAfter(new Run(new Text(value)), bookmark);
}
private static void RemoveAllTexts(BookmarkStart bookmark)
{
if (bookmark.ColumnFirst != null) return;
var nextSibling = bookmark.NextSibling();
while (nextSibling != null)
{
if (nextSibling.IsEndBookmark(bookmark) || nextSibling.GetType() == typeof(BookmarkStart))
break;
foreach (var item in nextSibling.Descendants<Text>())
{
item.Remove();
}
nextSibling = nextSibling.NextSibling();
}
}
I have looked around a long time for a general solution.
Any help is appreciated! -Victor
Maybe this can help you
first:delete bookmarkContent
second:find bookMark => insert value
public static void InsertTest1(WordprocessingDocument doc, string bookMark, string txt)
{
try
{
RemoveBookMarkContent(doc, bookMark);
MainDocumentPart mainPart = doc.MainDocumentPart;
BookmarkStart bmStart = findBookMarkStart(doc, bookMark);
if (bmStart == null)
{
return;
}
Run run = new Run(new Text(txt));
bmStart.Parent.InsertAfter<Run>(run, bmStart);
}
catch (Exception c)
{
//not Exception
}
}
public static void RemoveBookMarkContent(WordprocessingDocument doc, string bmName)
{
BookmarkStart bmStart = findBookMarkStart(doc, bmName);
BookmarkEnd bmEnd = findBookMarkEnd(doc, bmStart.Id);
while (true)
{
var run = bmStart.NextSibling();
if (run == null)
{
break;
}
if (run is BookmarkEnd && (BookmarkEnd)run == bmEnd)
{
break;
}
run.Remove();
}
}
private static BookmarkStart findBookMarkStart(WordprocessingDocument doc, string bmName)
{
foreach (var footer in doc.MainDocumentPart.FooterParts)
{
foreach (var inst in footer.Footer.Descendants<BookmarkStart>())
{
if (inst.Name == bmName)
{
return inst;
}
}
}
foreach (var header in doc.MainDocumentPart.HeaderParts)
{
foreach (var inst in header.Header.Descendants<BookmarkStart>())
{
if (inst.Name == bmName)
{
return inst;
}
}
}
foreach (var inst in doc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
if (inst is BookmarkStart)
{
if (inst.Name == bmName)
{
return inst;
}
}
}
return null;
}
This code works but not when the bookmark is placed within a field/formtext (a gray box).
private static void SetNewContents(wd.BookmarkStart bookmarkStart, string text)
{
if (bookmarkStart.ColumnFirst != null) return;
var itemsToRemove = new List<OpenXmlElement>();
var nextSibling = bookmarkStart.NextSibling();
while (nextSibling != null)
{
if (IsEndBookmark(nextSibling, bookmarkStart))
break;
if (nextSibling is wd.Run)
itemsToRemove.Add(nextSibling);
nextSibling = nextSibling.NextSibling();
}
foreach (var item in itemsToRemove)
{
item.RemoveAllChildren();
item.Remove();
}
bookmarkStart.Parent.InsertAfter(new wd.Run(new wd.Text(text)), bookmarkStart);
}