Implementing custom prefix using uuid - uuid

I went through the documentation for python UUID module.
>>> uuid.uuid4()
UUID('82fe5629-6680-4b13-a4e3-7a082f10e038')
>>> uuid.uuid4()
UUID('b2721a42-5645-4deb-bbbd-6ba1a55820d8')
>>> uuid.uuid4()
UUID('632736f8-a935-4335-a56d-56cd8ebc7dbf')
>>> uuid.uuid4()
UUID('a3519262-72d6-40ce-8e49-f65e8637ec07')
Every time it generates a random value. But my question is, what if I need to fix the first value and rest of them would be random. Is it possible?
e.g.,
>>> uuid.somefn("a3519262")
UUID('a3519262-72d6-40ce-8e49-f65e8637ec07')
>>> uuid.somefn("a3519262")
UUID('a3519262-a935-4335-a56d-56cd8ebc7dbf')
Reason I was looking for this solution:
I have multiple systems talking to a centralized system, So based on the uuid I want to segregate the source/load on the system for metrics purpose. Any alternative solution is also welcome.
Thanks in advance.

Been finding this solution for quite sometimes but just to make your work done! I think you would do a very hacky way to implement this.
>>>custom_uuid = str(uuid.uuid4())
>>>custom_uuid
'a3519262-72d6-40ce-8e49-f65e8637ec07'
So you can manipulate the string before storing it into a database or something like that.
>>>custom_uuid
'a3519262-72d6-40ce-8e49-f65e8637ec07'
>>>"prefix_" + custom_uuid
>>>'prefix_a3519262-72d6-40ce-8e49-f65e8637ec07'
>>>'a3519262-72d6-40ce-8e49-f65e8637ec07' + "_suffix"
>>>'a3519262-72d6-40ce-8e49-f65e8637ec07_suffix'

Related

Convert python literal_eval string to hy

I would like to convert the following to Hy, but I can't seem to figure out how to do it; is there perhaps a way to convert a string of python code to the hy syntax? I don't know if py would work because the evaluated result of f_back may not be safe.
import ast, inspect
def test(f_back):
return ast.literal_eval(f"inspect.currentframe(){'.f_back' * f_back}")
You could always evaluate x = x.f_back repeatedly in a loop instead of using metaprogramming for this.
To address the more general question, Hy itself only implements the Hy-to-Python direction, not Python to Hy. There's Hikaru Ikuta's py2hy, which doesn't work with recent releases of Hy, but he's recently talked about updating it, so that may change soon.

Clean dataset with many dfferent words for one thing

At the moment I have a dataset of ingredients. The problem is that it is not very clean because it contains many different names for the same thing. Here are a few examples:
Mehl = Weizenmehl, Mehl Type360
or
Eier = Eier, Ei(er), Ei
I thought of maybe deleting those brackets and making many if statements which are looking for different things like "Mehl" but there I would have to also look for something like "Dinkel" because of
Dinkelmehl != Mehl
I could do it but it would be very laborious because that's a big dataset. Are there some other methods maybe with a dictionary or something? I hope you can help me thank you!
Frederick!
Yes, you can use map method from pandas. First, I would suggest to clean special characters (!"#$%&/) and the use the map for Eier,Ei, Mehl, Tomaten....
I attach the documentation of map: map in df pandas
VG

GradCam Implementation in TFJS

I'm trying to implement GradCam (https://arxiv.org/pdf/1610.02391.pdf) in tfjs, based on the following Keras Tutorial (http://www.hackevolve.com/where-cnn-is-looking-grad-cam/) and a simple image classification demo from tfjs, similar to (https://github.com/tensorflow/tfjs-examples/blob/master/webcam-transfer-learning/index.js) with a simple dense, fully-connected layer at the end.
However, I'm not able to retrieve the gradients needed for the gradcam computation. I tried different ways to retrieve gradients for the last sequential layer, but did not succeed, as types of tf.LayerVariable from the respective layer is not convertible to the respective type of tf.grads or tf.layerGrads.
Did anybody already succeeded to get the gradients from sequential layer to a tf.function like object?
I'm not aware of the ins and outs of the implementation, but I think something along the lines of this: http://jlin.xyz/advis/ is what you're looking for?
Source code is available here: https://github.com/jaxball/advis.js (not mine!)
This official example in the tfjs-examples repo should be close to, if not exactly, what you want:
https://github.com/tensorflow/tfjs-examples/blob/master/visualize-convnet/cam.js#L49

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

Automatically Generate C Code From Header

I want to generate empty implementations of procedures defined in a header file. Ideally they should return NULL for pointers, 0 for integers, etc, and, in an ideal world, also print to stderr which function was called.
The motivation for this is the need to implement a wrapper that adapts a subset of a complex, existing API (the header file) to another library. Only a small number of the procedures in the API need to be delegated, but it's not clear which ones. So I hope to use an iterative approach, where I run against this auto-generated wrapper, see what is called, implement that with delegation, and repeat.
I've see Automatically generate C++ file from header? but the answers appear to be C++ specific.
So, for people that need the question spelled out in simple terms, how can I automate the generation of such an implementation given the header file? I would prefer an existing tool - my current best guess at a simple solution is using pycparser.
update Thanks guys. Both good answers. Also posted my current hack.
so, i'm going to mark the ea suggestion as the "answer" because i think it's probably the best idea in general. although i think that the cmock suggestion would work very well in tdd approach where the library development was driven by test failures, and i may end up trying that. but for now, i need a quicker + dirtier approach that works in an interactive way (the library in question is a dynamically loaded plugin for another, interactive, program, and i am trying to reverse engineer the sequence of api calls...)
so what i ended up doing was writing a python script that calls pycparse. i'll include it here in case it helps others, but it is not at all general (assumes all functions return int, for example, and has a hack to avoid func defs inside typedefs).
from pycparser import parse_file
from pycparser.c_ast import NodeVisitor
class AncestorVisitor(NodeVisitor):
def __init__(self):
self.current = None
self.ancestors = []
def visit(self, node):
if self.current:
self.ancestors.append(self.current)
self.current = node
try:
return super(AncestorVisitor, self).visit(node)
finally:
if self.ancestors:
self.ancestors.pop(-1)
class FunctionVisitor(AncestorVisitor):
def visit_FuncDecl(self, node):
if len(self.ancestors) < 3: # avoid typedefs
print node.type.type.names[0], node.type.declname, '(',
first = True
for param in node.args.params:
if first: first = False
else: print ',',
print param.type.type.names[0], param.type.declname,
print ')'
print '{fprintf(stderr, "%s\\n"); return 0;}' % node.type.declname
print '#include "myheader.h"'
print '#include <stdio.h>'
ast = parse_file('myheader.h', use_cpp=True)
FunctionVisitor().visit(ast)
UML modeling tools are capable of generating default implementation in the language of choice. Generally there is also a support for importing source code (including C headers). You can try to import your headers and generate source code from them. I personally have experience with Enterprise Architect and it supports both of these operations.
Caveat: this is an unresearched answer as I haven't had any experience with it myself.
I think you might have some luck with a mocking framework designed for unit testing. An example of such a framework is: cmock
The project page suggests it will generate code from a header. You could then take the code and tweak it.

Resources