Creating a variable by passing alrd made variables into a function (R language) - function

I am a little bit confuse on running my code I already write the code for the first and second prompts on the screenshot. But, it won't run when I hit resources. I ask my friend, it's correct. I'm so lost.
Prompt:
Create a variable my_intro by passing your variables my_name and my_age
into your make_introduction() function
Using the str_count function, create a variable occurrences that stores
the # of times the letter "e" appears in my_intro
my code:
make_introduction <- function(name, age){
cat("Hello, my name is", name, ",", " ", "and I'm", age,"years old.")
}
make_introduction("Stephanie",20)
make_introduction <- function(my_name, my_age){
cat(" ", "Hello, my name is", my_name, ",", " ", "and I'm", my_age,"years old.")
}
my_intro <- make_introduction(my_name, my_age)
occurences <- str_count(my_intro, "e")

Related

Why is isspace() returning false for strings from the docx python library that are empty?

My objective is to extract strings from numbered/bulleted lists in multiple Microsoft Word documents, then to organize those strings into a single, one-line string where each string is ordered in the following manner: 1.string1 2.string2 3.string3 etc. I refer to these one-line strings as procedures, consisting of 'steps' 1., 2., 3., etc.
The reason it has to be in this format is because the procedure strings are being put into a database, the database is used to create Excel spreadsheet outputs, a formatting macro is used on the spreadsheets, and the procedure strings in question have to be in this format in order for that macro to work properly.
The numbered/bulleted lists in MSword are all similar in format, but some use numbers, some use bullets, and some have extra line spaces before the first point, or extra line spaces after the last point.
The following text shows three different examples of how the Word documents are formatted:
Paragraph Keyword 1: arbitrary text
1. Step 1
2. Step 2
3. Step 3
Paragraph Keyword 2: arbitrary text
Paragraph Keyword 3: arbitrary text
• Step 1
• Step 2
• Step 3
Paragraph Keyword 4: arbitrary text
Paragraph Keyword 5: arbitrary text
Step 1
Step 2
Step 3
Paragraph Keyword 6: arbitrary text
(For some reason the first two lists didn't get indented in the formatting of the post, but in my word document all the indentation is the same)
When the numbered/bulleted list is formatted without line extra spaces, my code works fine, e.g. between "paragraph keyword 1:" and "paragraph keyword 2:".
I was trying to use isspace() to isolate the instances where there are extra line spaces that aren't part of the list that I want to include in my procedure strings.
Here is my code:
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def extractStrings(file):
doc = file
for i in range(len(doc.paragraphs)):
str1 = doc.paragraphs[i].text
if "Paragraph Keyword 1:" in str1:
start1=i
if "Paragraph Keyword 2:" in str1:
finish1=i
if "Paragraph Keyword 3:" in str1:
start2=i
if "Paragraph Keyword 4:" in str1:
finish2=i
if "Paragraph Keyword 5:" in str1:
start3=i
if "Paragraph Keyword 6:" in str1:
finish3=i
print("----------------------------")
procedure1 = ""
y=1
for x in range(start1 + 1, finish1):
temp = str((doc.paragraphs[x].text))
print(temp)
if not temp.isspace():
if y > 1:
procedure1 = (procedure1 + " " + str(y) + "." + temp)
else:
procedure1 = (procedure1 + str(y) + "." + temp)
y=y+1
print(procedure1)
print("----------------------------")
procedure2 = ""
y=1
for x in range(start2 + 1, finish2):
temp = str((doc.paragraphs[x].text))
print(temp)
if not temp.isspace():
if y > 1:
procedure2 = (procedure2 + " " + str(y) + "." + temp)
else:
procedure2 = (procedure2 + str(y) + "." + temp)
y=y+1
print(procedure2)
print("----------------------------")
procedure3 = ""
y=1
for x in range(start3 + 1, finish3):
temp = str((doc.paragraphs[x].text))
print(temp)
if not temp.isspace():
if y > 1:
procedure3 = (procedure3 + " " + str(y) + "." + temp)
else:
procedure3 = (procedure3 + str(y) + "." + temp)
y=y+1
print(procedure3)
print("----------------------------")
del doc
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
import docx
doc1 = docx.Document("docx_isspace_experiment_042420.docx")
extractStrings(doc1)
del doc1
Unfortunately I have no way of putting the output into this post, but the problem is that whenever there is a blank line in the word doc, isspace() returns false, and a number "x." is assigned to empty space, so I end up with something like: 1. 2.Step 1 3.Step 2 4.Step 3 5. 6. (that's the last iteration of print(procedure3) from the code)
The problem is that isspace() is returning false even when my python console output shows that the string is just a blank line.
Am I using isspace() incorrectly? Is there something in the string I am not detecting that is causing isspace() to return false? Is there a better way to accomplish this?
Use the test:
# --- for s a str value, like paragraph.text ---
if s.strip() == "":
print("s is a blank line")
str.isspace() returns True if the string contains only whitespace. An empty str contains nothing, and so therefore does not contain whitespace.

transforming / updating / typecasting list values from int & num to strings

I'm retrieving data from a MySQL database using an R script and then writing it to a CSV, but I'm having an issue where two of the columns of data that I want to write out as strings are being written out as integers and numbers (in this case, in scientific notation).
I would like to have these written out as string values instead, but I'm not finding this is a straightforward task, in spite of doing a fair bit of googling and experimentation.
The relevant code:
conn <- dbConnect(MySQL(), host = "127.0.0.1", user="REDACTED", password="REDACTED", dbname="REDACTED", port=8906)
type_data <- dbGetQuery(conn, paste("SELECT * FROM ", arg, " WHERE 1 LIMIT 10", sep=""))
# Problem: "Subscribed" and "TimeUpdated" are coming through as numbers instead of strings
write.csv(type_data, paste("./",arg,".csv", sep=""), row.names=F)
dbDisconnect(conn)
Desired results:
"Id","EntityId","EntityType","CommunicationType","Subscribed","TimeUpdated"
"0002INKRyUolIrjG5DbUa0lDqUjxt","4374484","PERSON","MFS","1","1385297883000000000"
"0004WaXpmvbOh3WG3hd6kQtPINibv","8361929","PERSON","MFS","1","1437798832740631885"
"0005l1fy1TJiFhyiEK2IXRCxfqee5","4197014","PERSON","SURVEYS_AND_POLLS","0","1146917239000000000"
"0008Qb2ra1PoSLgbumc2wmDfvexx8","4155704","PERSON","MFS","1","1345053223000000000"
"000C1IKgHrFaqmlHlKGGhigGyoaw4","4515071","PERSON","PARTNER","1","1215098959000000000"
"000Czw8Gv5w3eNoOmOFVTKLIuc2ti","4372360","PERSON","MFS","1","1384952236000000000"
"000DOsk9xlYKvs11PzZFRgmOpYfiA","4347384","PERSON","SURVEYS_AND_POLLS","1","1177513307000000000"
"000IQ4TKYHAbb334zFYdWVCZZfMYo","4470083","PERSON","PARTNER","1","1446945757133940400"
"000LbifV4rUa2MhxFlVZ52PSek5kG","499194","PERSON","SURVEYS_AND_POLLS","0","1097867573000000000"
Actual results:
"Id","EntityId","EntityType","CommunicationType","Subscribed","TimeUpdated"
"0002INKRyUolIrjG5DbUa0lDqUjxt","4374484","PERSON","MFS",1,1.385297883e+18
"0004WaXpmvbOh3WG3hd6kQtPINibv","8361929","PERSON","MFS",1,1437798832740631808
"0005l1fy1TJiFhyiEK2IXRCxfqee5","4197014","PERSON","SURVEYS_AND_POLLS",0,1.146917239e+18
"0008Qb2ra1PoSLgbumc2wmDfvexx8","4155704","PERSON","MFS",1,1.345053223e+18
"000C1IKgHrFaqmlHlKGGhigGyoaw4","4515071","PERSON","PARTNER",1,1.215098959e+18
"000Czw8Gv5w3eNoOmOFVTKLIuc2ti","4372360","PERSON","MFS",1,1.384952236e+18
"000DOsk9xlYKvs11PzZFRgmOpYfiA","4347384","PERSON","SURVEYS_AND_POLLS",1,1.177513307e+18
"000IQ4TKYHAbb334zFYdWVCZZfMYo","4470083","PERSON","PARTNER",1,1446945757133940480
"000LbifV4rUa2MhxFlVZ52PSek5kG","499194","PERSON","SURVEYS_AND_POLLS",0,1.097867573e+18
"000OWvUHdmjeL34XzuVLmHQBple7X","4176205","PERSON","MFS",1,1.143985154e+18
Assistance would be most appreciated!
Thanks to #Bernhard for the help with this - here's a working solution.
options(scipen = 999) # so that TimeUpdated isn't outputted using scientific notation
conn <- dbConnect(MySQL(), host = "127.0.0.1", user="REDACTED", password="REDACTED", dbname="REDACTED", port=8906)
type_data <- dbGetQuery(conn, paste("SELECT * FROM ", arg, " WHERE 1", sep=""))
# convert the subscribed and timeupdated columns to strings
type_data$Subscribed <- as.character(type_data$Subscribed)
type_data$TimeUpdated <- as.character(type_data$TimeUpdated)
write.csv(type_data, paste(args[[1]], "/", arg, ".csv", sep=""), row.names=F)
dbDisconnect(conn)

vimscript: commands that work in mappings, but not in functions

How can I rewrite these 2 commands, which work fine in a mapping, so that they will work in a function?
:if has_key(glos,#g)==1<cr>:let #j=eval('glos.'.#g)<cr>
The function concerned is executed by vim without comment, but #j remains unchanged, as if they had failed, but no message/error is generated.
Here is the complete code involved, the command that loads the dictionary, the function that does not work, and the mapping from that function that does.
" read the glossary into the dictionary, glos
let glos=eval(join(readfile("glossary.dict")))
" 2click item of interest and this will
" send image filepath to xv
" if item all-caps find same at start of its line
" If capitalized at eol find same at start of its line
" if all lower-case at eol find next occurrence of same
" look lower-case or capitalized word up in glossary.txt
" find _\d\+ (page no.) alone on its line in text
com! F call F()
function! F()
normal "ayiw"cyE"by$
let #c=substitute(#c,"[,.?':;!]\+","","g")
if #c=~'images\/ss\d\d\d*'
let #i='!display -geometry +0+0 '.#c.' &'
pkill display
#i
elseif #c==toupper(#c)
let #n=search('^'.#c,'sw')
elseif #c!=#b
let #f=3
let #g=tolower(#c)
while #f>0
try
let #j=eval('glos.'.#g)
catch
let #f=#f-1
let #g=strpart(#g,0,strlen(#g)-1)
continue
endtry
break
endwh
if #f>0
let #h=substitute(#j," glosimgs.*",'','')
if #h!=#j
let #i='!xv -geometry +0+380 '.substitute(#j,'^.\{-}\( glosimgs.*\)$','\1','').' &'
!pkill xv
#i
endif
echo #h
else
echo 'No matching entry for '.#c
endif
elseif #c=~'\u\l\+$'
let #n=search('^'.#c,'sw')
elseif #c=~'\l\+$'
norm *
elseif #c=~'^_\w\+$'
let #/='^'.#c.'$'
norm nzz
endif
endfunction
map <silent> <2-LeftMouse> "ayiw"cyE"by$:let #c=substitute(#c,"[,.?':;!]\+","","g")<cr>:if #c=~'images\/ss\d\d\d*'<cr>:let #i='!display -geometry +0+0 '.#c.' &'<cr>:pkill display<cr>:#i<cr>:elseif #c==toupper(#c)<cr>:let #n=search('^'.#c,'sw')<cr>:elseif #c!=#b<cr>:let #f=3<cr>:let #g=tolower(#c)<cr>:while #f>0<cr>:try<cr>:let #j=eval('glos["'.#g.'"]')<cr>:catch<cr>:let #f=#f-1<cr>:let #g=strpart(#g,0,strlen(#g)-1)<cr>:continue<cr>:endtry<cr>:break<cr>:endwh<cr>:if #f>0<cr>:let #h=substitute(#j," glosimgs.*",'','')<cr>:if #h!=#j<cr>:let #i='!xv -geometry +0+380 '.substitute(#j,'^.\{-}\( glosimgs.*\)$','\1','').' &'<cr>:!pkill xv<cr>:#i<cr>:endif<cr><cr<cr>>:echo #h<cr>:else<cr>:echo 'No matching entry for '.#c<cr>:endif<cr>:elseif #c=~'\u\l\+$'<cr>:let #n=search('^'.#c,'sw')<cr>:elseif #c=~'\l\+$'<cr>:norm *<cr>:elseif #c=~'^_\w\+$'<cr>:let #/='^'.#c.'$'<cr>:norm nzz<cr>:endif<cr>
Specifically, I should have written:
:if has_key(**g:**glos,#g)==1:let #j=eval('**g:**glos.'.#g)
:h g: goes straight to the heart of the matter; in a function all references are local to that function, so references to any variable outside the function must be global, by prepending 'g:' to the variable name. As I created the dictionary independent of the function, the function must reference it as a global item.
Of course, if you are not aware of 'g:', it is rather difficult to find that help reference, but that's a frequent problem using help.
And, of course, the ** surrounding g: aren't required, that's what this site gives you in lieu of bolded text, apparently.

New to autoit, what is wrong with this variable?

so today I just started learning this language, and I'm trying to make my script with parts of example scripts from https://www.autoitscript.com/autoit3/docs/functions.
I'm trying to run a mysql query and I'm getting "Variable Undeclared" error even if it declared as a Global one (atleast i think i declared it as one..)
Basically what my script should do is make an ID for every machine in my LAN store it into a txt file in AppData and then insert it into a db.
#include <MsgBoxConstants.au3>
#include <FileConstants.au3>
#include "EzMySql.au3"
#include <Array.au3>
Example()
Func Example()
$id = Random(1, 1000, 1);Numar random de la 1 la 100
Local Const $sFilePath = #AppDataDir & "\id.txt" ; Selectare %appdata% si id.txt
Local $iFileExists = FileExists($sFilePath)
If $iFileExists Then
Else
; Create a temporary file to write data to.
If Not FileCreate($sFilePath, $ID & #CRLF) Then Return MsgBox($MB_SYSTEMMODAL, "", "O eroare s-a produs in timp ce se scria fila temporara")
; Open the file for writing (append to the end of a file) and store the handle to a variable.
Global $hFileOpen = FileOpen($sFilePath, $FO_APPEND)
If $hFileOpen = -1 Then
MsgBox($MB_SYSTEMMODAL, "", "O eroare s-a produs in timp ce se citea fila.")
Return False
EndIf
; Read the contents of the file using the handle returned by FileOpen.
Global $sFileRead = FileRead($hFileOpen)
; Close the handle returned by FileOpen.
FileClose($hFileOpen)
EndIf
EndFunc
; Create a file.
Func FileCreate($sFilePath, $sString)
Local $bReturn = True ; Create a variable to store a boolean value.
If FileExists($sFilePath) = 0 Then $bReturn = FileWrite($sFilePath, $sString) = 1 ; If FileWrite returned 1 this will be True otherwise False.
Return $bReturn ; Return the boolean value of either True of False, depending on the return value of FileWrite.
EndFunc ;==>FileCreate
$name=#ComputerName
If Not _EzMySql_Startup() Then
MsgBox(0, "Error Starting MySql", "Error: "& #error & #CR & "Error string: " & _EzMySql_ErrMsg())
Exit
EndIf
If Not _EzMySql_Open("127.0.0.1", "root", "", "vrgaming", "3306") Then
MsgBox(0, "Error opening Database", "Error: "& #error & #CR & "Error string: " & _EzMySql_ErrMsg())
Exit
EndIf
If Not _EzMySql_Exec("INSERT INTO `lan` (id, nume) VALUES ('"& $sFileRead &"', '"& $name &"')") Then
MsgBox(0, "Error opening Database", "Error: "& #error & #CR & "Error string: " & _EzMySql_ErrMsg())
Exit
EndIf
_EzMySql_Close()
_EzMySql_ShutDown()
Exit
There are a number of logic issues with the code, that makes it a little tricky to follow.
The error in this case is almost certainly caused because "id.txt" exists, and so $iFileExists evaluates to true, and the global variable is never created.
Then you are creating a new "id.txt", for writing, before reading all the data, so $sFileRead will always be blank and FileRead will set #error as you are trying to read from a file opened for writing.
Now, I think you want the $sFileRead to be whatever the contents of id.txt is, and id.txt should be created with a new random id if it doesn't exist. If so then you need to move the code that opens and reads the file outside of the Else...Endif block (in addition to changing FileOpen to use $FO_READ).
This answer doesn't address the questionable programming practice and code structure.

Racket : How do i print the mysql result in a HTML page

I am trying print the values from the DB on the HTML page generated in APPLICATION.rkt
but this is what i see when i execute the code below
&createstring;&db-conn;SELECT * from students
Here is what I am trying to execute:
#lang racket
(require db)
(require web-server/servlet)
(provide/contract (start (request? . -> . response?)))
(define db-conn
(virtual-connection
(lambda () (mysql-connect #:server "localhost"
#:port 8889
#:database "SOB"
#:user "root"
#:password "root"))))
(define (start request)
(define (createstring id name sid)
(string-append "id is " id "and name is " name "and sid is " sid))
(response/xexpr
'(html
(head (title "SOB"))
(body
,#(map (h1) (map createstring (in-query db-conn "SELECT * from students"))))
)))
(require web-server/servlet-env)
(serve/servlet start
#:launch-browser? #f
#:quit? #f
#:listen-ip #f
#:port 8080
#:extra-files-paths
(list (build-path "/Users/lalith/Documents/LALITH FILES/MDX/SOB/" "htmlfiles"))
#:servlet-path
"/servlets/APPLICATION.rkt")
Any suggestions as to what I'm doing wrnog?
There are a couple problems.
First, use quasiquote (or "backquote") instead of quote; otherwise you can't escape from it with ,# (ie, unquote-splicing). In other words, change
'(html ___)
to
`(html ___)
Then, inside the ,# escape, your maps are wrong, and map doesn't work with in-query anyway. You probably want something like this instead:
,#(for/list ([(id name sid)
(in-query db-conn "SELECT id, name, sid from students")])
`(h1 ,(createstring id name sid)))
Or something like that. (The code above would make a level-1 header for each row in the table, if that's what you want.)
Edited in response to comment: It looks like id is a numeric column in the database. If you have a recent version of Racket, I recommend using ~a, which is like string-append but automatically converts non-string values to strings first. Change the definition of createstring to this:
(define (createstring id name sid)
(~a "id is " id "and name is " name "and sid is " sid))
In older versions of Racket (before ~a), use format instead (see the docs for how).