Parse data as time with function (Python) - python-3.6

Getting the following error following an execution of the following code. Using Py3 on Jupyter.
def parse_date(date):
if date == '':
return None
else:
return dt.strptime(str(date, '%d/%m/%y').date()`
raw_data_1.Date = raw_data_1.Date.apply(parse_date)
raw_data_2.Date = raw_data_2.Date.apply(parse_date)
File "<ipython-input-16-262d54bff117>", line 9
raw_data_1.Date = raw_data_1.Date.apply(parse_date)
^
SyntaxError: invalid syntax

Related

How to paste multi line code in Meteor shell

When I paste a multi line code like
const f = () => {
console.log("Hello");
};
in Meteor shell, it seems to be that every line is executed. I get this Error:
};
^
Uncaught SyntaxError: Unexpected token '}'
Is there a chance to paste multi line code in Meteor shell? It would be helpful in order to try out some code snippets.

TypeError: send_message() got an unexpected keyword argument 'parse_mode'

Below is the code that I use for a telegram bot that posts new updates from my preferred subreddit. This is not my code (I found it online on stack overflow) but I keep getting this error. I've searched everywhere but there wasn't any solution I could find. Anyway here it is, even slight information of which direction should I go would be greatly appreciated.
import telebot
import praw
import config
bot_token = 'x'
bot_chatID = '#monsterKing_bot'
bot = telebot.TeleBot(bot_token)
reddit = praw.Reddit(client_id='x', \
client_secret='x', \
user_agent='x', \
username='x ', \
password='x')
def reddit_scraper(submission):
news_data = []
subreddit = reddit.subreddit('coronavirus')
new_subreddit = subreddit.new(limit=500)
for submission in subreddit.new(limit=5):
data = {}
data['title'] = submission.title
data['link'] = submission.url
news_data.append(data)
return news_data
def get_msg(news_data):
msg = '\n\n\n'
for news_item in news_data:
title = news_item['title']
link = news_item['link']
msg += title+'\n[Read the full article -->]'
msg += '\n\n'
return msg
subreddit = reddit.subreddit('coronavirus')
new_subreddit = subreddit.new(limit=500)
for submission in subreddit.new(limit=1):
news_data = reddit_scraper(submission)
if len(news_data) > 0:
msg = get_msg(news_data)
status = bot.send_message(chat_id='#monsterKing_bot', text=msg, parse_mode=telegram.ParseMode.HTML)
if status:
print(status)
else:
print('No updates.')
Full error message below:
Traceback (most recent call last):
File "c:\Users\mayan\Downloads\redditscraperbot.py", line 42, in <module>
status = bot.send_message(chat_id='#monsterKing_bot', text=msg, parse_mode=telegram.ParseMode.HTML)
TypeError: send_message() got an unexpected keyword argument 'parse_mode'
try pip install pyTelegramBotAPI instead of pip install telebot
My chat id was wrong. Chat id is a number we can get from another bot (userinfobot)
chat_id= 1261748gd278 not chat_id=#name...

Unit test for exception raised in custom GNU radio python block

I have created a custom python sync block for use in a gnuradio flowgraph. The block tests for invalid input and, if found, raises a ValueError exception. I would like to create a unit test to verify that the exception is raised when the block indeed receives invalid input data.
As part of the python-based qa test for this block, I created a flowgraph such that the block receives invalid data. When I run the test, the block does appear to raise the exception but then hangs.
What is the appropriate way to test for this? Here is a minimal working example:
#!/usr/bin/env python
import numpy as np
from gnuradio import gr, gr_unittest, blocks
class validate_input(gr.sync_block):
def __init__(self):
gr.sync_block.__init__(self,
name="validate_input",
in_sig=[np.float32],
out_sig=[np.float32])
self.max_input = 100
def work(self, input_items, output_items):
in0 = input_items[0]
if (np.max(in0) > self.max_input):
raise ValueError('input exceeds max.')
validated_in = output_items[0]
validated_in[:] = in0
return len(output_items[0])
class qa_validate_input (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_check_valid_data(self):
src_data = (0, 201, 92)
src = blocks.vector_source_f(src_data)
validate = validate_input()
snk = blocks.vector_sink_f()
self.tb.connect (src, validate)
self.tb.connect (validate, snk)
self.assertRaises(ValueError, self.tb.run)
if __name__ == '__main__':
gr_unittest.run(qa_validate_input, "qa_validate_input.xml")
which produces:
DEPRECATED: Using filename with gr_unittest does no longer have any effect.
handler caught exception: input exceeds max.
Traceback (most recent call last):
File "/home/xxx/devel/gnuradio3_8/lib/python3.6/dist-packages/gnuradio/gr/gateway.py", line 60, in eval
try: self._callback()
File "/home/xxx/devel/gnuradio3_8/lib/python3.6/dist-packages/gnuradio/gr/gateway.py", line 230, in __gr_block_handle
) for i in range(noutputs)],
File "qa_validate_input.py", line 21, in work
raise ValueError('input exceeds max.')
ValueError: input exceeds max.
thread[thread-per-block[1]: <block validate_input(2)>]: SWIG director method error. Error detected when calling 'feval_ll.eval'
^CF
======================================================================
FAIL: test_check_valid_data (__main__.qa_validate_input)
----------------------------------------------------------------------
Traceback (most recent call last):
File "qa_validate_input.py", line 47, in test_check_valid_data
self.assertRaises(ValueError, self.tb.run)
AssertionError: ValueError not raised by run
----------------------------------------------------------------------
Ran 1 test in 1.634s
FAILED (failures=1)
The top_block's run() function does not call the block's work() function directly but starts the internal task scheduler and its threads and waits them to finish.
One way to unit test the error handling in your block is to call the work() function directly
def test_check_valid_data(self):
src_data = [[0, 201, 92]]
output_items = [[]]
validate = validate_input()
self.assertRaises(ValueError, lambda: validate.work(src_data, output_items))

why the Python logging module throwing Attribute error?

I am working with the logging module for the first time. I was able to write the program as per my requirement. The logic written inside the try and except is also working almost successfully, and logs are getting generated in the log file. But for some reason I am seeing "AttributeError" on my IDE console for all the "logging.info" and "logging.exception". So, to cross verify I commented out all those location and this time my code ran without any error, but nothing was getting logged in the log file. Which was quite obvious. Below is the whole program
import logging
from logging.handlers import TimedRotatingFileHandler
logger = logging.handlers.TimedRotatingFileHandler('amitesh.log', when='midnight', interval=1)
logger.suffix = '%y_%m_%d.log'
# create a logging format
LOGGING_MSG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger.setFormatter(LOGGING_MSG_FORMAT)
LOGGING_DATE_FORMAT = '%d-%b-%y %H:%M:%S'
# create basic configuration
logging.basicConfig(level=logging.INFO, format=LOGGING_MSG_FORMAT, datefmt=LOGGING_DATE_FORMAT)
root_logger = logging.getLogger('')
# add the handlers to the logger
root_logger.addHandler(logger)
while True:
print(" ")
print("This is a Logging demo")
print(" ")
logging.info("new request came")
print(" ")
try:
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(x / y)
except ZeroDivisionError as msg:
print("cannot divide with zero")
logging.exception(msg)
print(" ")
except ValueError as msg:
print("enter only integer value")
logging.exception(msg)
print(" ")
logging.info("executed successfully")
print(" ")
Below is the error message from my IDE console:
return self._fmt.find(self.asctime_search) >= 0
AttributeError: 'Formatter' object has no attribute 'find'
Call stack:
File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 68, in <module>
logging.info("new request came")
Message: 'new request came'
Arguments: ()
I have gone through the internet in last 2 days without any luck.
Please help me figure out my mistake(s).
added more error:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 388, in usesTime
return self._fmt.find(self.asctime_search) >= 0
AttributeError: 'Formatter' object has no attribute 'find'
Call stack:
File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 68, in <module>
logging.info("new request came")
Message: 'new request came'
Arguments: ()
Thank you.
Removed format=LOGGING_MSG_FORMAT, LOGGING_MSG_FORMAT and defined the values inside the basicConfig with "format" param directly as the parameter "format" takes a String not the type Formatter.

R source file from RConnection (JRI) "could not find function"

I'm trying to source a R script file from an org.rosuda.REngine.Rserve.RConnection and then calling a function from that script, but am getting, "Error: could not find function "main".
Start Rserve from terminal
> require(Rserve)
Loading required package: Rserve
> Rserve()
Starting Rserve...
"C:\Users\slenzi\DOCUME~1\R\WIN-LI~1\3.3\Rserve\libs\x64\Rserve.exe"
> Rserve: Ok, ready to answer queries.
Error: could not find function "main"
External script rdbcTest1.R
require(RJDBC)
main <- function() {
jdbcDriver <- JDBC(driverClass = dbDriverClass, classPath = dbDriverPath)
jdbcConnection <- dbConnect(jdbcDriver, dbUrl, dbUser, dbPwd)
dbResult <- dbGetQuery(jdbcConnection, dbQuery)
dbDisconnect(jdbcConnection)
return(dbResult)
}
Java Code
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngine;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
REXP result = null;
RConnection c = null;
try {
c = new RConnection();
String driverPath = "C:/temp/ojbdc6.jar";
String scriptPath = "C:/temp/rdbcTest1.R";
c.assign("dbUser", "foo");
c.assign("dbPwd", "******");// commented out
c.assign("dbUrl", "jdbc:oracle:thin:#myhost:1511:ecogtst");
c.assign("dbDriverClass", "oracle.jdbc.driver.OracleDriver");
c.assign("dbDriverPath", driverPath);
// assign query to execute
c.assign("dbQuery", "SELECT count(*) FROM prs.members");
String evalSource = String.format("try(source(\"%s\", local=TRUE), silent=TRUE)", scriptPath);
c.eval("evalSource");
// debug
result = c.eval("ls()");
logger.info("REXP debug => " + result.toDebugString());
result = c.eval("main()");
} catch (RserveException e) {
logger.error("error running script test, " + e.getMessage());
} finally {
if(c != null){
c.close();
}
}
Output
evaluating => try(source("C:/temp/rdbcTest1.R", local=TRUE), silent=TRUE)
REXP debug => org.rosuda.REngine.REXPString#61c6bc05[6]{"dbDriverClass","dbDriverPath","dbPwd","dbQuery","dbUrl","dbUser"}
Error: could not find function "main"
error running oracle script test, eval failed, request status: error code: 127
Running the script directly from the R terminal it works fine. When ran from RConnection I can see the values of the variables I assign (c.assign(...)) but not the main() function from the sourced script.
What am I missing in regards to sourcing a script? How can I access a function from the script?
Thanks.
** UPDATE **
I got the following to work, but if anyone has any idea why source() doesn't seem to work in my example above, please let me know!
RConnection c = ...
REXP x = c.parseAndEval("try(eval(parse(file=\"C:/temp/rdbcTest3.R\")), silent=TRUE)")

Resources