Best Python code snippet using localstack_python
fetcher.py
Source:fetcher.py
...58 # Convert the US eastern time to UTC time59 trade_datetime_text = Fetcher.edt_to_utc(trade_datetime_text)60 f.trade_datetime = parse(trade_datetime_text)61 column_idx += 262 f.price = Fetcher._parse_float(data[column_idx])63 column_idx += 164 f.days_low = Fetcher._parse_float(data[column_idx])65 column_idx += 166 f.days_high = Fetcher._parse_float(data[column_idx])67 column_idx += 168 f.price_change = Fetcher._parse_float(data[column_idx])69 column_idx += 170 f.volume = Fetcher._parse_float(data[column_idx])71 column_idx += 172 f.market_cap_in_millions = Fetcher._parse_number_in_millions(data[column_idx])73 column_idx += 174 f.book_value = Fetcher._parse_float(data[column_idx])75 column_idx += 176 f.ebitda_in_millions = Fetcher._parse_number_in_millions(data[column_idx])77 column_idx += 178 f.dividend_share = Fetcher._parse_float(data[column_idx])79 column_idx += 180 f.dividend_pay_date = Fetcher._parse_date_str(data[column_idx], "%m/%d/%Y")81 column_idx += 182 f.ex_dividend_date = Fetcher._parse_date_str(data[column_idx], "%m/%d/%Y")83 column_idx += 184 f.dividend_yield = Fetcher._parse_float(data[column_idx])85 column_idx += 186 f.earning_share = Fetcher._parse_float(data[column_idx])87 column_idx += 188 f.price_book = Fetcher._parse_float(data[column_idx])89 column_idx += 190 f.price_sales = Fetcher._parse_float(data[column_idx])91 return True92 def fetch_historical(self, f, start_date, end_date, num_retries=3):93 """94 :param f: the financial object95 :type f: pyvalue.yahoofinance.financial.Financial96 :param start_date: the start date97 :type start_date: str98 :param end_date: the end data99 :type end_date: str100 :param num_retries: the number of retries101 :type num_retries: int102 :return:103 """104 stock = f.stock105 start_year, start_month, start_day = Fetcher._split_date_str(start_date)106 end_year, end_month, end_day = Fetcher._split_date_str(end_date)107 url = (r'http://ichart.finance.yahoo.com/table.csv?s={0}'108 r'&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d&ignore=.csv'109 .format(stock, start_month-1, start_day, start_year, end_month-1, end_day, end_year))110 for try_idx in range(num_retries):111 try:112 response = urllib2.urlopen(url)113 csv = response.read()114 if len(csv.strip()) == 0:115 raise YahooFinanceFetcherException("Empty response of the http request.")116 Fetcher._parse_historical_csv(csv, f)117 return True118 except Exception as err:119 traceback.print_exc()120 LogInfo.info(stock + " : " + err.message + " in the " + str((try_idx + 1)) + " time")121 if try_idx == num_retries - 1:122 LogInfo.error('Failed to retrieve information for ' + stock)123 return False124 @staticmethod125 def _parse_historical_csv(csv, f):126 """127 :param csv: the return csv data from Yahoo finance128 :type csv: str129 :param f: the financial object130 :type f: pyvalue.yahoofinance.financial.Financial131 :return:132 """133 lines = csv.split('\n')[1:] # skip the first line (header)134 daily_records = []135 for line in lines:136 line = line.strip()137 if len(line) == 0:138 continue139 elems = line.split(',')140 record = DailyRecord()141 column_idx = 0142 date_text = elems[column_idx]143 record.date = datetime.strptime(date_text, "%Y-%m-%d").date()144 column_idx += 1145 record.open = elems[column_idx]146 column_idx += 1147 record.high = elems[column_idx]148 column_idx += 1149 record.low = elems[column_idx]150 column_idx += 1151 record.close = elems[column_idx]152 column_idx += 1153 record.volume = elems[column_idx]154 column_idx += 1155 record.adj_close = elems[column_idx]156 daily_records.append(record)157 f.stock_historical = daily_records158 return len(f.stock_historical)159 @staticmethod160 def _parse_number_in_millions(val):161 if val is None or val == 'N/A' or val == 'n/a' or val == 'NA' or val == 'na':162 return None163 val = val.strip()164 if val.endswith("B"):165 return float(val[:-1])*1000166 elif val.endswith("M"):167 return float(val[:-1])168 elif val.endswith("K"):169 return float(val[:-1])/1000.0170 else:171 return float(val[:-1])/(1000.0*1000.0)172 @staticmethod173 def _split_date_str(date_str, format_template='%Y-%m-%d'):174 date_str = date_str.replace("'", "")175 date_str = date_str.replace("\"", "")176 if format_template == '%Y-%m-%d':177 tokens = date_str.split('-')178 year = int(tokens[0])179 month = int(tokens[1])180 day = int(tokens[2])181 return year, month, day182 elif format_template == '%m/%d/%Y':183 tokens = date_str.split('/')184 year = int(tokens[2])185 month = int(tokens[0])186 day = int(tokens[1])187 return year, month, day188 else:189 raise YahooFinanceFetcherException("Unknown format template for date parser : "+format_template)190 @staticmethod191 def _parse_date_str(date_str, format_template='%Y-%m-%d'):192 if date_str == 'N/A' or date_str == '':193 return None194 year, month, day = Fetcher._split_date_str(date_str, format_template)195 return datetime.strptime(str(year)+"-"+str(month)+"-"+str(day), "%Y-%m-%d").date()196 @staticmethod197 def _parse_float(val_str):198 if val_str == 'N/A' or val_str == 'n/a' or val_str == 'NA':199 return None200 else:201 return float(val_str)202 @staticmethod203 def edt_to_utc(date, mask='%m/%d/%Y %I:%M%p'):204 """205 Convert EDT (Eastern Daylight Time) to UTC206 :param date: EDT date string e.g. '5/26/2014 4:00pm'207 :param mask: format of input date e.g '%m/%d/%Y %I:%M%'208 :return: UTC date string e.g '2014-03-05 12:23:00'209 """210 utc = pytz.utc211 eastern = pytz.timezone('US/Eastern')...
lambda_function.py
Source:lambda_function.py
...41 # type: (dict) -> dict42 file_content = obj['Body'].read()43 json_content = json.loads(file_content)44 return json_content45def _parse_float(s):46 try:47 return float(s)48 except ValueError:49 return s50def _parse_int(s):51 try:52 return int(s)53 except ValueError:54 return s55def get_fields_parser():56 # type: () -> dict57 return {58 "lineItem_UsageAmount": (_parse_float, float),59 "lineItem_BlendedRate": (_parse_float, float),...
vasp_parse.py
Source:vasp_parse.py
1#from pymatgen.io.vasp.inputs import PotcarSingle2import pymatgen.io.vasp.inputs as vin3import re4class parse_potcar(object):5 parse_functions = {6 "LULTRA": vin._parse_bool,7 "LUNSCR": vin._parse_bool,8 "LCOR": vin._parse_bool,9 "LPAW": vin._parse_bool,10 "EATOM": vin._parse_float,11 "RPACOR": vin._parse_float,12 "POMASS": vin._parse_float,13 "ZVAL": vin._parse_float,14 "RCORE": vin._parse_float,15 "RWIGS": vin._parse_float,16 "ENMAX": vin._parse_float,17 "ENMIN": vin._parse_float,18 "EMMIN": vin._parse_float,19 "EAUG": vin._parse_float,20 "DEXC": vin._parse_float,21 "RMAX": vin._parse_float,22 "RAUG": vin._parse_float,23 "RDEP": vin._parse_float,24 "RDEPT": vin._parse_float,25 "QCUT": vin._parse_float,26 "QGAM": vin._parse_float,27 "RCLOC": vin._parse_float,28 "IUNSCR": vin._parse_int,29 "ICORE": vin._parse_int,30 "NDATA": vin._parse_int,31 "VRHFIN": vin._parse_string,32 "LEXCH": vin._parse_string,33 "TITEL": vin._parse_string,34 "STEP": vin._parse_list,35 "RRKJ": vin._parse_list,36 "GGA": vin._parse_list37 }38 def __init__(self, data):39 search_lines = re.findall(r"(?s)(parameters from PSCTR are:"40 r".*?END of PSCTR-controll parameters)",41 data) #.group(2)42 self.all_keywords = []43 for i in range(len(search_lines)):44 keywords = {}45 for key, val in re.findall(r"(\S+)\s*=\s*(.*?)(?=;|$)",46 search_lines[i],47 flags=re.MULTILINE):48 try:49 keywords[key] = self.parse_functions[key](val)50 except KeyError:51 warnings.warn("Ignoring unknown variable type %s" % key)52 self.all_keywords.append(keywords)53 def get_max_enmax(self):54 max_enmax = 055 for i in range(len(self.all_keywords)):56 enmax = self.all_keywords[i]['ENMAX']57 if max_enmax < enmax:58 max_enmax = enmax59 return max_enmax60# p=PotcarSingle(file.read())...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!