Commenting in Python: Is -- legitimate? - python

I have inherited a set of Python code, and I think I know the answer to this, but wish to be sure.
It looks like both #s and --s are used interchangeably throughout the code to signify comments but any searches I am doing do not yield information about using the --.
I used to do the --s within Teradata a long time ago. Am I missing something?
Adding in some additional information too: I am running the code within Spyder (Python3.6). Perhaps that will shed more light on what is going on.
Below is an example of the -- seeming to work:
qry = """
select s2019.sk2019,
s2018.sk2018
from (select distinct h1.key sk2019,
e.Territory Territory2019 from cdw.fact_header
left join cdw.dim_event e on h1.event = e.event
where e.sy in (2019)
and e.program_name = 'xyz'
and a.Country = 'USA'
-- and h1.code = 'DC'
and h1.key > 0

One line comments are done using the # while multiline comments are done using the triple-quote
""" Text here
and here"""
the -- comment is used in sqlite with python. Do you have that comment inside a query that is also written inside a string/triple-quote comment? Like:
""" SELECT * FROM TABLE
--WHERE N = X"""
UPDATE 1:
Here you can see and example of comment inside the query done in a python code
query = """ SELECT * FROM TABLE
--WHERE N = X"""
By putting -- inside the query, before WHERE I've made everything that follows ignored. So when the query is executed I will only execute the first line of the query.

Related

Django rank search in Postgres not matching

I have a Tutorial model with name 'building'.
Here is search.
tutorial_search = Tutorial.objects.annotate(
rank=SearchRank(SearchVector('name'), query)
).filter(rank__gte=0.0001).order_by('-rank')
This query finds my model
query = 'bui:*'
But this one doesnt
query = 'buildi:*'
I cant figure out what is causing it. Is it english accent?
Seems like simple search.
EDIT:
I tried pure SQL queries in postgres, and I get the same result.
This works:
SELECT to_tsvector('building') ## to_tsquery('(build:*)');
Returns True
But this one:
SELECT to_tsvector('building') ## to_tsquery('(buildi:*)');
Returns False
Why?
Thanks!
If I understood you asked for the motivations of the behavior of your queries.
You can test the lexems generated from your words in your queries as below:
SELECT ts_lexize('english_stem', 'building');
ts_lexize
-----------
{build}
SELECT ts_lexize('english_stem', 'build');
ts_lexize
-----------
{build}
SELECT ts_lexize('english_stem', 'buildi');
ts_lexize
-----------
{buildi}
As you can see the lexems generated by 'building' and 'build' are the same ('build') and 'buildi' generate a different 'buildi'.
This is because the first two work and the third does not.
More info in the Testing and Debugging Text Search documentation.

Django Q object query filtering with multiple conditions failing

I am trying to apply multiple conditions to my filter. The model looks like this
class modelChat(models.Model):
source = models.ForeignKey(modelEmployer,related_name = 'rsource',on_delete=models.CASCADE,null=True,default=None,blank=True)
job = models.ForeignKey(modelJob,on_delete=models.CASCADE,null=True,default=None,blank=True)
destination = models.ForeignKey(modelEmployer,related_name = 'rdestination',on_delete=models.CASCADE,null=True,default=None,blank=True)
Initially I am trying to obtain an instance of chat that involves 2 parties based on a job. At one point source can be a destination and sometimes the destination can be the source. but the job remains the same.
This is what my query looks like
querySet = modelChat.objects.filter(
(Q(source=modelEmployerSourceInstance) | Q(destination=modelEmployerSourceInstance))
&
(Q(destination=modelEmployerDestinationInstance) | Q(destination=modelEmployerDestinationInstance))
&
Q(job_id=job_id)
)
The job id is correct and I know there is only one item in the DB. However this query alway returns back an empty item. Any suggestions why this is wrong and how I can fix it ?
I can't say for sure if that's the problem since you forgot to show what you really have in your DB but here:
(Q(destination=modelEmployerDestinationInstance) | Q(destination=modelEmployerDestinationInstance))
I assume you want:
(Q(source=modelEmployerDestinationInstance) | Q(destination=modelEmployerDestinationInstance))
instead...
Note that the logical would be much more obvious with shorter names, ie source and destination instead of modelEmployerSourceInstance modelEmployerDestinationInstance:
q = (
(Q(source=source) | Q(destination=source))
& (Q(source=destination | Q(destination=destination))
& Q(job_id=job_id)
)
querySet = modelChat.objects.filter(q)
Meaningful names are a good thing, but they have to be short and distinct enough. With "modelEmployerXXXInstance", you have four words to parse, and with the only distinctive (hence relevant) part of the name being in third position, your brain tends to skip over this part. The "model", "Employer" and "Instance" parts are actually just noise.

Query from more than one table Python Mysql Connector

I have the following sql query:
SELECT
pc.patente,
cs.cpc_group_codigo_cpc_group
FROM
patente_pc pc
,
patente_cpc cpc,
cpc_subgroup cs,
cpc_group cg
WHERE
pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND
cpc.cpc = cs.codigo_cpc_subgroup AND
cs.cpc_group_codigo_cpc_group = cg.codigo_cpc_group
GROUP BY
pc.patente, cs.cpc_group_codigo_cpc_group
I add this query to python, separating line by line the string in a tuple to not have a problem with the syntax..
and it executes correctly
but when I need to retrieve the data, I use
lista_cpcs = []
lista_patentes = []
for (pc.patente, cs.cpc_group_codigo_cpc_group) in cursor:
lista_cpcs.append(cs.cpc_group_codigo_cpc_group)
lista_patentes.append(pc.patente)
return [lista_cpcs, lista_patentes]
and I get the error Global name 'pc' is not defined
I get whats happening, it's interpreting pc and cs as python modules, but they are from the sql..
how to work in this?
Ps: I search for python mysql connector and didn't found anything with this.
The variables in your for loop: (pc.patente, cs.cpc_group_codigo_cpc_group) are user defined; the names used do not have anything to do with the names from the query. Thus, you can call them whatever you want. You may consider using (pc__patente, cs__cpc_group_codigo_cpc_group) or something.
The problem is that the dot notation in python != the dot notation from your SQL.
Got it, sorry for the post..
Searching in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html
I learned a few attributes of the cursor, and using the Eclipse debugger I saw that it comes just the name, not the table connection..so I use
for (patente, cpc_group_codigo_cpc_group) in cursor:
lista_cpcs.append(cpc_group_codigo_cpc_group)
lista_patentes.append(patente)
and it's working now, and thanks for the help #Scott

Parsing specific keywords in Select Statements and formatting

I have a sample select statement:
Select D.account_csn, D.account_key, D.industry_id, I.industry_group_nm, I.industry_segment_nm From ecs.DARN_INDUSTRY I JOIN ecs.DARN_ACCOUNT D
ON I.SRC_ID=D.INDUSTRY_ID
WHERE D.ACCOUNT_CSN='5070000240'
I would like to parse the select statements into separate files. The first file name is called ecs.DARN_INDUSTRY
and inside the file it should look like this:
industry_group_nm
industry_segment_nm
Similarly another file called ecs.DARN_ACCOUNT and the content looks like this:
account_csn
account_key
industry_id
How do I do this in Bash or Python??
I doubt you will find a truly simple answer (maybe someone can prove otherwise). However, you might find python-sqlparse useful.
Parsing general SQL statments will be complicated and it is difficult to guess exactly what you are trying to accomplish. However, I think you are trying to extract the tables and corresponding column references via sql parsing, in which case, look at this question which basically asks that very thing directly.
Here is a long working command through awk,
awk 'NR==1{gsub(/^.*\./,"",$5);gsub(/^.*\./,"",$6);gsub(/.$/,"",$5); printf $5"\n"$6"\n" > "DARN_INDUSTRY"; gsub(/^.*\./,"",$2);gsub(/^.*\./,"",$3);gsub(/^.*\./,"",$4);gsub(/.$/,"",$2);gsub(/.$/,"",$3);gsub(/.$/,"",$4); printf $2"\n"$3"\n"$4"\n" > "DARN_ACCOUNT"}' file
Explanation:
gsub(/^.*\./,"",$5) remove all the characters upto the first . symbol in colum number 5.
printf $5"\n"$6"\n" > "DARN_INDUSTRY" redirects the output of printf command to the file named DARN_INDUSTRY.
gsub(/.$/,"",$4) Removes the last character in column 4.

Writing MySQL databases in Python using mySQLdb

So I have the following code, and it works:
for count in range(0,1000):
L=[random.randint(0, 127),random.randint(0, 127),random.randint(0, 127)]
random.randint(0, 127)
name=''.join(map(chr,L))
number=random.randint(0,1000)
x.execute('insert into testTable set name=(%s), number=(%s)', (name, number))
Above, x is just the cursor I made (obviously). I just create a random string from ASCII values and a random number and write it to my database (this was a purely BS example so that I knew it worked)/
Then,
I have in another script:
x.execute('insert into rooms set \
room_name=(%s),\
room_sqft=(%s),\
room_type=(%s),\
room_purpose=(%s) ,\
room_floor_number=(%s)',
(name, sqft, roomType, room_use_ranking, floor))
And I get a syntax error: invalid syntax on the first line, right at the x. part of x.execute.
What is different between the two lines? In the problem code, all arguments but name are ints (name is a string) that are gotten from a int(raw_input(...)) type prompt that catches bad input errors.
Clearly this works, but what is going wrong in the second piece of code?
Thanks,
nkk
There's a problem on the line BEFORE the x.execute. (x is unexpected at this point). Can you link more of the file?
Also, try this formatting, which can clear up this sort of thing by making the string one blob. (Your syntax highlighter should show it as one big multi-line string, too!)
sql = '''
INSERT INTO rooms
SET room_name=(%s),
room_sqft=(%s),
room_type=(%s),
room_purpose=(%s),
room_floor_number=(%s)
'''
x.execute(sql, (name, sqft, roomType, room_use_ranking, floor))

Categories