Why is CASE - WHEN - ELSE not working for me in pgadmin in this once instance? - case

Working with postgres 9.4 and using PGAdmin III: I have a schema with a character field that MAY contain "new lines" (NLs), or MAY contain double spaces, or neither. I need to divide the field into 3 segments by either of the above factors or by 26 characters in length.
If the total length is 26 or less, I just copy it as is.
If it has NLs, then I split it by those.
If no NLs but it has double spaces, I split it by those.
Finally, if none of the above, I want to split it into 3 26 character chunks.
For context; the column is data entered by customers into a 3 line box. anywhere from 4 characters up to 78. Some use NLs, some use spaces to push the text to the next line, some have luck with spacing so use neither.
Here's the part of the query to gather the first line:
CASE WHEN LENGTH(detail) < 27 THEN detail
WHEN detail LIKE E'%\n%' THEN SPLIT_PART(detail,E'\n',1)
WHEN detail LIKE E'% %' THEN SPLIT_PART(detail,E' ',1)
ELSE LEFT(detail, 26)
END AS line1,
When I test this on a sample schema, the first three parts work exactly as I need but the "ELSE" part never does. The LEFT statement workout outside of the CASE statement but not within.
I've tried enclosing it with a SELECT clause, nesting several CASE-WHEN-ELSE statements, and other things to no avail.
Oddly, it DOES work if I take out the "SPLIT_PART" line referring to '% %'.
Short of giving up on the double-space split, is there another solution, or have I just formatted something wrong?

CASE WHEN LENGTH(detail) < 27 THEN detail
WHEN detail LIKE '%\n%' THEN SPLIT_PART(detail,'\n',1)
WHEN position(' ' in detail) > 0 THEN SPLIT_PART(detail,' ',1)
ELSE left(detail,26)

After another bit of time mucking about, I suspected the LIKE E'% %' might be the issue - and it was. Simply changing it to LIKE E' ' allows it to work like I wanted.
Added:
Turns out the best solution is a combination of "position" to determine if the double space exists, and split-part to separate correctly at the location.

Related

Parsing strings with grep/str_extract

As part of my feature engineering, I need to parse text strings from different languages and keep text enclosed within parentheses. Everything was going well until I encountered a very strange phenomenon. For some languages, the parentheses I need to find look slightly different, and various regexp options fail.
I'm pasting screen-shots because strangely, copying and pasting the strange parentheses changes it to a 'normal' one, so I can't set up a different regex to find those separately.
Notice that the parentheses in the first entry look normal, but for the second entry, it appears sort of 'sharp'
If I use stringr's str_extract, the first instance works fine, but the second fails.
But, the encodings are the same. Anyone know what's going on?
[Edit: here are the results of dput on these same examples. dput apparently sees the parentheses as equivalent, even though grep does not]
c("Obnaružena poterâ šaga na (Motor šprica pipettora R1).", "(STAT tàn zhen Z zhóu ma dá) tàn cè dào diu bù<U+3002>")
Finally, I am actually copy and pasting the two parentheses from R into the code window below; they do appear different this way. First is normal, second is the strange one.
( (

SQLite 3 substract in update query gives near "–": syntax error

I am trying to execute update query with subtraction inside:
UPDATE categories_ns
SET
nsright = nsright – 10
WHERE
nsright > 9
And I am getting [Err] 1 - near "–": syntax error.
Could you please help me to understand why its happens ?
Thanks!
And yet again someone is having issues with Unicode having so many similar symbols and some of them getting into code by accident.
– and - are different symbols. The former is not a valid minus, the latter is.
The difference in dashes' lengths is often unclear in many monospaced fonts. You can view your code in a non-monospaced one so the difference becomes obvious. But first and foremost, avoid copying code that may not be what it looks like.
Some document processors and websites out there, for instance:
Replace quotes with fancier ones (like ˝)
Replace << and >> with « and »
Replace a "minus" constructs like - with a proper dash (–, —?)
...all of which make sense for prose or poems, but not code.

SQLite X'...' notation with column data

I am trying to write a custom report in Spiceworks, which uses SQLite queries. This report will fetch me hard drive serial numbers that are unfortunately stored in a few different ways depending on what version of Windows and WMI were on the machine.
Three common examples (which are enough to get to the actual question) are as follows:
Actual serial number: 5VG95AZF
Hexadecimal string with leading spaces: 2020202057202d44585730354341543934383433
Hexadecimal string with leading zeroes: 3030303030303030313131343330423137454342
The two hex strings are further complicated in that even after they are converted to ASCII representation, each pair of numbers are actually backwards. Here is an example:
3030303030303030313131343330423137454342 evaluates to 00000000111430B17ECB
However, the actual serial number on that hard drive is 1141031BE7BC, without leading zeroes and with the bytes swapped around. According to other questions and answers I have read on this site, this has to do with the "endianness" of the data.
My temporary query so far looks something like this (shortened to only the pertinent section):
SELECT pd.model as HDModel,
CASE
WHEN pd.serial like "30303030%" THEN
cast(('X''' || pd.serial || '''') as TEXT)
WHEN pd.serial like "202020%" THEN
LTRIM(X'2020202057202d44585730354341543934383433')
ELSE
pd.serial
END as HDSerial
The result of that query is something like this:
HDModel HDSerial
----------------- -------------------------------------------
Normal Serial 5VG95AZF
202020% test case W -DXW05CAT94843
303030% test case X'3030303030303030313131343330423137454342'
This shows that the X'....' notation style does convert into the correct (but backwards) result of W -DXW05CAT94843 when given a fully literal number (the 202020% line). However, I need to find a way to do the same thing to the actual data in the column, pd.serial, and I can't find a way.
My initial thought was that if I could build a string representation of the X'...' notation, then perhaps cast() would evaluate it. But as you can see, that just ends up spitting out X'3030303030303030313131343330423137454342' instead of the expected 00000000111430B17ECB. This means the concatenation is working correctly, but I can't find a way to evaluate it as hex the same was as in the manual test case.
I have been googling all morning to see if there is just some syntax I am missing, but the closest I have come is this concatenation using the || operator.
EDIT: Ultimately I just want to be able to have a simple case statement in my query like this:
SELECT pd.model as HDModel,
CASE
WHEN pd.serial like "30303030%" THEN
LTRIM(X'pd.serial')
WHEN pd.serial like "202020%" THEN
LTRIM(X'pd.serial')
ELSE
pd.serial
END as HDSerial
But because pd.serial gets wrapped in single quotes, it is taken as a literal string instead of taken as the data contained in that column. My hope was/is that there is just a character or operator I need to specify, like X'$pd.serial' or something.
END EDIT
If I can get past this first hurdle, my next task will be to try and remove the leading zeroes (the way LTRIM eats the leading spaces) and reverse the bytes, but to be honest, I would be content even if that part isn't possible because it wouldn't be hard to post-process this report in Excel to do that.
If anyone can point me in the right direction I would greatly appreciate it! It would obviously be much easier if I was using PHP or something else to do this processing, but because I am trying to have it be an embedded report in Spiceworks, I have to do this all in a single SQLite query.
X'...' is the binary representation in sqlite. If the values are string, you can just use them as such.
This should be a start:
sqlite> select X'3030303030303030313131343330423137454342';
00000000111430B17ECB
sqlite> select ltrim(X'3030303030303030313131343330423137454342','0');
111430B17ECB
I hope this puts you on the right path.

Tool/script to find and modify numerical values in CSS file?

I simply want to go through and find every numerical value in a single, or batch of, CSS files and multiple times two, then save.
Any suggestions for the easiest way to do this?
Using regular expressions could solve your problem. For example, in python you could do the following:
import re
input = "#content {width:100px;height:20.5%;font-size:150.25%;margin-left:-20px;padding:2 0 -20 14.33333;}"
regex = re.compile("-?[.0-9]+")
scaled_numbers = [float(n)*2 for n in re.findall(regex, input)]
split_text = re.split(regex, input)
output = ''
for i in range(len(scaled_numbers)):
output += "%s%.2f" % (split_text[i], scaled_numbers[i])
output += split_text[-1]
This code could be reduced in length, but I've deliberately left it less compact for readability. One flaw with it is that it contracts floats to only 2 decimal places, but that can be easily changed if you really need extended decimals (change the number in "%s%.2f" to the desired number of places).
Note also that this code could change the names of CSS selectors (for example, #footer-2 would become #footer-4.00). If you wanted to avoid that, you'll need to adjust the code to ignore text outside of {...}.

odbc_result_all formatting

$selectVolID = "Select COUNT(VolunteerID) from planetVolunteers";
$getVolID = odbc_exec($connect, $selectVolID);
echo odbc_result_all($getVolID);
gives:
Expr1000
49
1
49 is the correct count. I want to change the Expr1000 to something legible and get rid of that 1 (which i assume means there are no more values to count).
You can use an alias in the SELECT statement to a more descriptive name:
SELECT COUNT(VoluneerID) NumVolunteers from ...
Depending on the underlying database engine, it is possible that the AS keyword migh be needed in front of the alias.
I have dealt very little with PHP, so I do not know about the 1 that is printed.
The number at the end should be the total number of rows returned. The best way I know of to remove it would be to put it in a hidden input, which means you can refer to it later with javascript or something if you really needed to, and also lets you hide it easily.. anything wrapped around the odbc_results_all function only effects the returning row count instead of the whole table (so you can use anything, maybe a div will be better).
echo "<input value=\"" . odbc_result_all($getVolID) . "\" type=\"text\" style=\"display:none;\">";

Resources