GAN discriminator detach - gradient

Hello, I am new to the GANs. I wanted to ask why do we need to use detach() in the discriminator. I highlighted it in red. It is a part from Cyclegan by Alladdin person Github. Thank you for response.
with torch.cuda.amp.autocast():
fake_horse = gen_H(zebra) # generating fake horse
D_H_real = disc_H(horse) # classifying real horse
D_H_fake = ***disc_H(fake_horse.detach())***
H_reals += D_H_real.mean().item()
H_fakes += D_H_fake.mean().item()
D_H_real_loss = mse(D_H_real, torch.ones_like(D_H_real))
D_H_fake_loss = mse(D_H_fake, torch.zeros_like(D_H_fake))
D_H_loss = D_H_real_loss + D_H_fake_loss
fake_zebra = gen_Z(horse)
D_Z_real = disc_Z(zebra)
D_Z_fake = disc_Z(fake_zebra.detach())
D_Z_real_loss = mse(D_Z_real, torch.ones_like(D_Z_real))
D_Z_fake_loss = mse(D_Z_fake, torch.zeros_like(D_Z_fake))
D_Z_loss = D_Z_real_loss + D_Z_fake_loss
# put it togethor
D_loss = (D_H_loss + D_Z_loss)/2

Related

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

How exactly is tensorflow.control_dependecy applied?

self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
with tf.control_dependencies([optimizer_op]):
self.optimizer = control_ops
i call self.optimizer with the session
The code above is not updating the gradients. However if i change the control dependencies part of the code to the one below it works perfectly fine except that it misses out on a final exponential moving average (self.ema_op) update, which is not desirable to me:
self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
# with tf.control_dependencies(optimizer_op):
# self.optimizer = control_ops
with tf.control_dependencies([self.ema_op] + update_ops_):
self.optimizer = optimizer.apply_gradients(zip(clipped_gradients, variables))
Please tell me what am i missing?
You need to define the tensorflow operations under the with statement, not just set the variable. Doing self.optimizer = control_ops has no effect because you did not create any tensorflow operations.
Without fully understanding your problem I think you want something like this:
with tf.control_dependencies(optimizer_op):
control_ops = tf.group([self.ema_op] + update_ops_)
self.optimizer = control_ops
The with statement enters a block, under which any new ops you create in tensorflow will be dependent upon optimizer_op in this case.

how to add extra price to cart programmatically in prestahop 1.7

Am new to prestashop 1.7. I want to add extra cost for customization product on adding to cart in prestashop 1.7. Please any body help me.
add own customization data to cart.
$idProduct = Tools::getValue('pid'); // for me it's always one
$qty=Tools::getValue('qty'); // always add one item
$token = Tools::getValue('token');
$customData_front = Tools::getValue('front_view');
$customData_back = Tools::getValue('back_view');
$customData = Tools::getValue('customdata');
$attribute =Tools::getValue('id_product_attribute')
if (is_null($this->context->cart->id)) {
$this->context->cart->add();
$this->context->cookie->__set('id_cart', $this->context->cart->id);
}
// get cart id if exists
if ($this->context->cookie->id_cart)
{
$cart = new Cart($this->context->cookie->id_cart);
}
// create new cart if needed
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart($this->context->cookie->id_cart);
$cart->id_customer = (int)($this->context->cookie->id_customer);
$cart->id_address_delivery = (int) (Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
$cart->id_lang = (int)($this->context->cookie->id_lang);
$cart->id_currency = (int)($this->context->cookie->id_currency);
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
$this->context->cookie->id_cart = (int)($cart->id);
}
$product = new Product((int)$idProduct);
if ($attribute > 0) {
$minimal_quantity = (int)Attribute::getAttributeMinimalQty($this->id_product_attribute);
} else {
$minimal_quantity = (int)$product->minimal_quantity;
}
// add customizatated text
$check =serialize($customData);
$id_address_delivery = $cart->id_address_delivery;
$customization = $this->context->cart->addTextFieldToProduct((int)($idProduct), 9, Product::CUSTOMIZE_TEXTFIELD, serialize($customData));
$exising_customization = Db::getInstance()->executeS('SELECT id_customization FROM '._DB_PREFIX_.'customized_data ORDER BY id_customization DESC LIMIT 0,1');
$customization = $exising_customization[0]['id_customization'];
Db::getInstance()->execute('UPDATE ps_customization SET in_cart = 1, id_product_attribute = '.$attribute.',id_address_delivery='.$id_address_delivery.',quantity='.$minimal_quantity.' WHERE id_customization = ' .$customization);
// get product to add into cart
$productToAdd = new Product((int)($idProduct), true, (int)($this->context->cookie->id_lang));
$cart->update();
$this->context->cart->updateQty((int)($qty),(int)($idProduct),(int)($attribute),$customization,'up',(int)($id_address_delivery));
$cart->update();
In that I want add additional cost every customization.

"Module already present - choose a different name." vtiger 6.4

I followed all the steps mentioned on create custom module in vtiger 6 to create custom module but I am getting the error Module already present - choose a different name
Please advice.
As your are using vtiger 6.4 , there are lot of difference between vTiger 6 and vtiger6.4.
Try with the below script as I am using same for new module creation. Use new module name. And change the UI Types and field labels as per your requirement.
<?php
$Vtiger_Utils_Log = true;
include_once('vtlib/Vtiger/Menu.php');
include_once('vtlib/Vtiger/Module.php');
$module = new Vtiger_Module();
$module->name = 'Your_MODULE_NAME';
$module->parent = 'Tools';
$module->save();
$module->initTables();
$module->initWebservice();
$block = new Vtiger_Block();
$block->label = 'LBL_INFORMATION_DETAIL';
$module->addBlock($block); //to create a new block
$field1 = new Vtiger_Field();
$field1->name = 'browse';
$field1->table=$module->basetable;
$field1->label= 'Upload Csv';
$field1->column = 'browse';
$field1->columntype = 'VARCHAR(255)';
$field1->uitype= 28;
$field1->typeofdata = 'V~O';
$block->addField($field1);
$field2 = new Vtiger_Field();
$field2->name = 'fieldid';
$field2->table=$module->basetable;
$field2->label= 'Record ID';
$field2->uitype= 4;
$field2->column = 'fieldid';
$field2->columntype = 'VARCHAR(255)';
$field2->typeofdata = 'V~M';
$block->addField($field2);
$module->setEntityIdentifier($field2);
$field3 = new Vtiger_Field();
$field3->name = 'age';
$field3->table=$module->basetable;
$field3->label= 'Age';
$field3->uitype= 1;
$field3->column = 'age';
$field3->columntype = 'VARCHAR(100)';
$field3->typeofdata = 'V~O';
$block->addField($field3);
$field4 = new Vtiger_Field();
$field4->name = 'statusrecord';
$field4->table=$module->basetable;
$field4->label= 'Status';
$field4->uitype= 15;
$field4->column = 'statusrecord';
$field4->columntype = 'VARCHAR(255)';
$field4->setPicklistValues( Array('new','closed','closedwithfailure','inprogress'));
$field4->typeofdata = 'V~M';
$block->addField($field4);
// Recommended common fields every Entity module should have (linked to core table)
$field5 = new Vtiger_Field();
$field5->name = 'assigned_user_id';
$field5->label = 'Assigned To';
$field5->table = 'Vtiger_crmentity';
$field5->column = 'smownerid';
$field5->uitype = 53;
$field5->typeofdata = 'V~M';
$block->addField($field5);
$field6 = new Vtiger_Field();
$field6->name = 'CreatedTime';
$field6->label= 'Created Time';
$field6->table = 'Vtiger_crmentity';
$field6->column = 'createdtime';
$field6->uitype = 70;
$field6->typeofdata = 'T~O';
$field6->displaytype= 2;
$block->addField($field6);
$field7 = new Vtiger_Field();
$field7->name = 'ModifiedTime';
$field7->label= 'Modified Time';
$field7->table = 'Vtiger_crmentity';
$field7->column = 'modifiedtime';
$field7->uitype = 70;
$field7->typeofdata = 'T~O';
$field7->displaytype= 2;
$block->addField($field7);
// Filter Setup
$filter1 = new Vtiger_Filter();
$filter1->name = 'All';
$filter1->isdefault = true;
$module->addFilter($filter1);
// Add fields to the filter create
$filter1->addField($field7, 2);
$filter1->addField($field3, 3);
$filter1->addField($field4, 5);
/** Set sharing access of this module */
$module->setDefaultSharing();
/** Enable and Disable available tools */
$module->enableTools(Array('Import', 'Export'));
$module->disableTools('Merge');
?>
You can also refer Entity-Module-Documentation

Get SOAP attachment

There is a lot of questions with same subject, but no replies, especially about receiving. There exist example how to send attachment, but I didn't found how to receive it.
Is there any solution on python for receiving attachments? I even agree to change my SOAP tool from suds to anything that will works.
Thank you in advance.
I solved it with suds.
def GetWithFile(self, client, servicename, modelthings):
func = client.get_suds_func('Retrieve' + servicename)
clientclass = func.clientclass({})
SoapClient = clientclass(func.client, func.method)
binding = func.method.binding.input
soap_xml = binding.get_message(func.method, [modelthings], {})
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentInfo="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentData="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'ignoreEmptyElements="true"')
SoapClient.last_sent(soap_xml)
plugins = PluginContainer(SoapClient.options.plugins)
plugins.message.marshalled(envelope=soap_xml.root())
if SoapClient.options.prettyxml:
soap_xml = soap_xml.str()
else:
soap_xml = soap_xml.plain()
soap_xml = soap_xml.encode('utf-8')
plugins.message.sending(envelope=soap_xml)
request = Request(SoapClient.location(), soap_xml)
request.headers = SoapClient.headers()
reply = SoapClient.options.transport.send(request)
print(reply)
Files = []
boundary = self.find_substring(reply.headers['content-type'], 'boundary="', '"')
if boundary is not "":
list_of_data = reply.message.split(boundary)
list_of_data.pop(0)
list_of_data.pop(len(list_of_data) - 1)
soap_body = '<SOAP-ENV:Envelope' + self.find_substring(list_of_data[0], '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'
for line in list_of_data[1:]:
File = SMFile()
Files.append(File)
File.filename = self.find_substring(line, 'Content-Location: ', '\r\n')
File.key = self.find_substring(line, 'Content-ID: ', '\r\n')
idx = line.index( 'Content-ID:' )
start_idx = line.index( '\r\n\r\n' , idx ) + len('\r\n\r\n')
fin_idx = line.rindex( '\r\n--', start_idx )
File.body = line[start_idx: fin_idx]
File.size = fin_idx - start_idx
else:
soap_body = '<SOAP-ENV:Envelope' + self.find_substring(reply.message, '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'
ctx = plugins.message.received(reply=soap_body)
soap_body = ctx.reply
if SoapClient.options.retxml:
answer = soap_body
else:
answer = SoapClient.succeeded(binding, soap_body)
dict = {}
self.FieldsToDict(answer.model.instance, dict)
return {u'body': answer, u'Files': Files}
Here we extract some low level of suds, being able to fix any field in envelope. Then, after reply was got, we parse all boundaries and receive as many files, as we got.