def test_getitem_setitem_datetime_tz_pytz(self): tm._skip_if_no_pytz() from pytz import timezone as tz from pandas import date_range N = 50 # testing with timezone, GH #2785 rng = date_range('1/1/1990', periods=N, freq='H', tz='US/Eastern') ts = Series(np.random.randn(N), index=rng) # also test Timestamp tz handling, GH #2789 result = ts.copy() result["1990-01-01 09:00:00+00:00"] = 0 result["1990-01-01 09:00:00+00:00"] = ts[4] assert_series_equal(result, ts) result = ts.copy() result["1990-01-01 03:00:00-06:00"] = 0 result["1990-01-01 03:00:00-06:00"] = ts[4] assert_series_equal(result, ts) # repeat with datetimes result = ts.copy() result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = 0 result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = ts[4] assert_series_equal(result, ts) result = ts.copy() # comparison dates with datetime MUST be localized! date = tz('US/Central').localize(datetime(1990, 1, 1, 3)) result[date] = 0 result[date] = ts[4] assert_series_equal(result, ts)
def test_getitem_setitem_datetime_tz_dateutil(self): tm._skip_if_no_dateutil() from dateutil.tz import tzutc from pandas.tslib import _dateutil_gettz as gettz tz = lambda x: tzutc() if x == 'UTC' else gettz( x) # handle special case for utc in dateutil from pandas import date_range N = 50 # testing with timezone, GH #2785 rng = date_range('1/1/1990', periods=N, freq='H', tz='US/Eastern') ts = Series(np.random.randn(N), index=rng) # also test Timestamp tz handling, GH #2789 result = ts.copy() result["1990-01-01 09:00:00+00:00"] = 0 result["1990-01-01 09:00:00+00:00"] = ts[4] assert_series_equal(result, ts) result = ts.copy() result["1990-01-01 03:00:00-06:00"] = 0 result["1990-01-01 03:00:00-06:00"] = ts[4] assert_series_equal(result, ts) # repeat with datetimes result = ts.copy() result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = 0 result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = ts[4] assert_series_equal(result, ts) result = ts.copy() result[datetime(1990, 1, 1, 3, tzinfo=tz('US/Central'))] = 0 result[datetime(1990, 1, 1, 3, tzinfo=tz('US/Central'))] = ts[4] assert_series_equal(result, ts)
def add_event(request): username = request.user.username form = NewEventForm(request.POST or None) if request.method == 'POST': if form.is_valid(): e_name = form.cleaned_data['e_name'] e_startdate = datetime.strptime( form.cleaned_data['e_startdate'], '%Y/%m/%d %I:%M %p').replace(tzinfo=tz('Asia/Taipei')) e_enddate = datetime.strptime( form.cleaned_data['e_enddate'], '%Y/%m/%d %I:%M %p').replace(tzinfo=tz('Asia/Taipei')) e_place = form.cleaned_data['e_place'] e_description = form.cleaned_data['e_description'] e_deadline = datetime.strptime( form.cleaned_data['e_deadline'], '%Y/%m/%d %I:%M %p').replace(tzinfo=tz('Asia/Taipei')) event = Event.objects.create( e_name=e_name, e_startdate=e_startdate, e_enddate=e_enddate, e_place=e_place, e_description=e_description, e_deadline=e_deadline, e_postdate=timezone.localtime(timezone.now()), e_organizer=request.user) participation = Participation.objects.create( p_event=event, p_member=event.e_organizer) notification = Notification.objects.create( n_from=User.objects.get(username='******'), n_to=request.user, n_timestamp=timezone.localtime(timezone.now()), n_content='你已成功發佈了新活動:%s!\n\ 活動詳情請<a href="/event_details?eventid=%d">按此</a>' % ( event.e_name, event.id)) return render(request, 'event_added.html', {'username': username, 'event': event}) else: return render(request, 'add_event.html', {'username': username, 'form': form}) else: form.initial['e_startdate'] = timezone.localtime(timezone.now( )).strftime('%Y/%m/%d %I:%M %p') form.initial['e_enddate'] = timezone.localtime(timezone.now( )).strftime('%Y/%m/%d %I:%M %p') form.initial['e_deadline'] = timezone.localtime(timezone.now( )).strftime('%Y/%m/%d %I:%M %p') return render(request, 'add_event.html', {'username': username, 'form': form})
def __init__(self, timezone, format = '%Y-(%m)%b-%d %T, %a w%V, %Z', sync_to = 1): ''' Constructor @param timezone:str The timezone @param format:str The format as in the `date` command @param sync_to:float The time parameter to sync to, the number of seconds between the reads ''' self.utc = tz('UTC') self.timezone = tz(timezone) self.format = format self.sync_to = sync_to
def test_set_timezone(self): from .views import TimezoneView from pytz import timezone as tz request = self.factory.post("/abc", {"timezone": "America/Denver"}) self.add_session(request) response = TimezoneView.as_view()(request) self.assertEqual(response.status_code, 200) self.assertIn("detected_timezone", request.session) self.assertTrue(tz(request.session["detected_timezone"])) temp = tz(request.session["detected_timezone"]) self.assertIsInstance(temp, BaseTzInfo)
def check_attending_party(self): current_time = timezone.now().astimezone(tz('US/Central')) if self.attending: if current_time > self.attending.time_end: self.attending = None self.save()
def get_tonight_parties(self): current_time = timezone.now().astimezone(tz('US/Central')) tonight_begin = current_time - timedelta(hours=current_time.hour) + timedelta(hours=18) tonight_end = current_time - timedelta(hours=current_time.hour) + timedelta(hours=30) parties = self.get_all_related_parties() return [party for party in parties if party.time_begin < tonight_end and party.time_end > tonight_begin]
def test_effective(self): self.news = create(Builder('news').within(self.newsfolder)) difference = datetime.now(tz('Europe/Zurich')) -\ self.news.effective().asdatetime() # The folllowing Calculation is the same as timedelta.total_seconds() # but since it isn't available in python2.6 we need to calculate it ourself # https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds self.assertLess((difference.microseconds + (difference.seconds + difference.days * 24 * 3600) * 10 ** 6) / 10.0 ** 6, 60)
def clean(self): startdate = datetime.strptime(self.cleaned_data['e_startdate'], '%Y/%m/%d %I:%M %p') startdate = startdate.replace(tzinfo=tz('Asia/Taipei')) enddate = datetime.strptime(self.cleaned_data['e_enddate'], '%Y/%m/%d %I:%M %p') enddate = enddate.replace(tzinfo=tz('Asia/Taipei')) deadline = datetime.strptime(self.cleaned_data['e_deadline'], '%Y/%m/%d %I:%M %p') deadline = deadline.replace(tzinfo=tz('Asia/Taipei')) if timezone.localtime(timezone.now()) > startdate: msg = '活動開始日期必須在今天之後!' self.add_error('e_startdate', msg) if timezone.localtime(timezone.now()) > deadline: msg = '截止報名日期必須在今天之後!' self.add_error('e_deadline', msg) if timezone.localtime(timezone.now()) > enddate: msg = '活動結束日期必須在今天之後!' self.add_error('e_enddate', msg) if deadline > startdate: msg = '截止報名日期必須在活動開始日期之前!' self.add_error('e_deadline', msg) if startdate > enddate: msg = '活動開始日期必須在結束日期之前!' self.add_error('e_startdate', msg) if enddate < startdate: msg = '活動結束日期必須在開始日期之後!' self.add_error('e_enddate', msg) if enddate < deadline: msg = '活動結束日期必須在截止報名日期之後!' self.add_error('e_enddate', msg)
def test_range_tz(self): # GH 2906 _skip_if_no_pytz() from pytz import timezone as tz start = datetime(2011, 1, 1, tzinfo=tz('US/Eastern')) end = datetime(2011, 1, 3, tzinfo=tz('US/Eastern')) dr = date_range(start=start, periods=3) self.assert_(dr.tz == tz('US/Eastern')) self.assert_(dr[0] == start) self.assert_(dr[2] == end) dr = date_range(end=end, periods=3) self.assert_(dr.tz == tz('US/Eastern')) self.assert_(dr[0] == start) self.assert_(dr[2] == end) dr = date_range(start=start, end=end) self.assert_(dr.tz == tz('US/Eastern')) self.assert_(dr[0] == start) self.assert_(dr[2] == end)
def run_server(auction, mapping_expire_time, logger, timezone='Europe/Kiev'): app.config.update(auction.worker_defaults) # Replace Flask custom logger app.logger_name = logger.name app._logger = logger app.config['auction'] = auction app.config['timezone'] = tz(timezone) app.config['SESSION_COOKIE_PATH'] = '/tenders/{}'.format(auction.auction_doc_id) app.config['SESSION_COOKIE_NAME'] = 'auction_session' app.oauth = OAuth(app) app.remote_oauth = app.oauth.remote_app( 'remote', consumer_key=app.config['OAUTH_CLIENT_ID'], consumer_secret=app.config['OAUTH_CLIENT_SECRET'], request_token_params={'scope': 'email'}, base_url=app.config['OAUTH_BASE_URL'], access_token_url=app.config['OAUTH_ACCESS_TOKEN_URL'], authorize_url=app.config['OAUTH_AUTHORIZE_URL'] ) @app.remote_oauth.tokengetter def get_oauth_token(): return session.get('remote_oauth') os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true' # Start server on unused port lisener = get_lisener(auction.worker_defaults["STARTS_PORT"], host=auction.worker_defaults.get("WORKER_BIND_IP", "")) app.logger.info( "Start server on {0}:{1}".format(*lisener.getsockname()), extra={"JOURNAL_REQUEST_ID": auction.request_id} ) server = WSGIServer(lisener, app, log=_LoggerStream(logger), handler_class=AuctionsWSGIHandler) server.start() # Set mapping mapping_value = "http://{0}:{1}/".format(*lisener.getsockname()) create_mapping(auction.worker_defaults["REDIS_URL"], auction.auction_doc_id, mapping_value) app.logger.info("Server mapping: {} -> {}".format( auction.auction_doc_id, mapping_value, mapping_expire_time ), extra={"JOURNAL_REQUEST_ID": auction.request_id}) # Spawn events functionality spawn(push_timestamps_events, app,) spawn(check_clients, app, ) return server
def test_range_tz_dateutil(self): # GH 2906 tm._skip_if_no_dateutil() # Use maybe_get_tz to fix filename in tz under dateutil. from pandas.tslib import maybe_get_tz tz = lambda x: maybe_get_tz('dateutil/' + x) start = datetime(2011, 1, 1, tzinfo=tz('US/Eastern')) end = datetime(2011, 1, 3, tzinfo=tz('US/Eastern')) dr = date_range(start=start, periods=3) self.assert_(dr.tz == tz('US/Eastern')) self.assert_(dr[0] == start) self.assert_(dr[2] == end) dr = date_range(end=end, periods=3) self.assert_(dr.tz == tz('US/Eastern')) self.assert_(dr[0] == start) self.assert_(dr[2] == end) dr = date_range(start=start, end=end) self.assert_(dr.tz == tz('US/Eastern')) self.assert_(dr[0] == start) self.assert_(dr[2] == end)
def post(self, request, *args, **kwargs): timezone = request.POST.get("timezone", None) if not timezone: return HttpResponse("No 'timezone' parameter provided", status=400) try: if "none" in str(timezone).lower(): timezone = settings.TIME_ZONE else: timezone = str(timezone) temp = tz(timezone) except UnknownTimeZoneError: return HttpResponse("Invalid 'timezone' value provided", status=400) except: return HttpResponse("An unknown error occurred while trying to parse the timezone", status=500) request.session["detected_timezone"] = timezone return HttpResponse(timezone, status=200)
def _get_timezone(self, obj, change_type): """Ask the user to input an offset for a particular Dexcom G4 Platinum CGM device.""" res = input('What timezone were you in at %s? ' %(obj.user_time)) dst = input('Do you think this was a shift to/from DST? (y/n) ') td_offset = tz(res).utcoffset(parse_datetime(obj.user_time)) offset = td_offset.days * 24 + td_offset.seconds/SECONDS_IN_HOUR timezone = res if dst == 'y': change_type += '; shift to/from DST' # fall back is -1; reverse it to undo change if parse_datetime(obj.user_time).month > 6: offset += 1 # spring forward is +1; reverse it to undo change else: offset -= 1 print('Offset from UTC is %d.' %offset) print() return (timezone, offset, change_type)
def run(self): print('Running {} on PID {}'.format(self.name, self.pid)) while True: # print(self.name) worker_info = WorkerInfo.objects.get(name='NewWorker') if worker_info.last_run < dt.now() - timedelta(hours=24): with NewMatchScraper() as scraper: new_matches_links = scraper.get_links() print('Znaleziono {} nowych meczy'.format(len(new_matches_links))) for link in new_matches_links: new_match = Match() with MatchPageScraper(link) as scraper: match_info = scraper.get_match_info() for key, value in match_info.items(): setattr(new_match, key, value) new_match.bets.append(scraper.get_bets()) new_match.save() print('Dodano nowy mecz: {}'.format(new_match.title)) worker_info.last_run = dt.now(tz('UTC')) worker_info.save() sleep(self.worker_delay)
def __init__ (self, *args, **kwargs): super(WordDeltaCounter, self).__init__(*args, **kwargs) now = datetime.utcnow() now = tz('UTC').localize(now) self.end_time = now - (timedelta(microseconds=now.microsecond)) self.alert = False
from markupsafe import escape app = Flask(__name__) #handle CORS requests from a different address (localhost:3000) CORS(app, resources={r"/*": {"origins": "http://*****:*****@app.route('/search/') @cross_origin(origin='localhost') def handle_search(): #a different SQL query for each item table #partial matching is allowed via LIKE search_inventory = "SELECT * FROM Inventory WHERE type LIKE %s OR vendor LIKE %s" search_food = "SELECT * FROM Food WHERE category LIKE %s OR vendor LIKE %s OR accommodations LIKE %s" search_recipes = "SELECT name, webLink FROM Recipe WHERE name LIKE %s" #get the user's search query and split into keywords query = request.args.get('query') keywords = query.split()
async def get_weather(weather): """For .weather command, gets the current weather of a city.""" if not OWM_API: await weather.edit( "`Get an API key from` https://openweathermap.org/ `first.`") return APPID = OWM_API if not weather.pattern_match.group(1): CITY = DEFCITY if not CITY: await weather.edit( "`Please specify a city or set one as default using the WEATHER_DEFCITY config variable.`" ) return else: CITY = weather.pattern_match.group(1) timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f'{country}'] except KeyError: await weather.edit("`Invalid country.`") return CITY = newcity[0].strip() + "," + countrycode.strip() url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}' request = get(url) result = json.loads(request.text) if request.status_code != 200: await weather.edit("`Invalid country.`") return cityname = result['name'] curtemp = result['main']['temp'] humidity = result['main']['humidity'] min_temp = result['main']['temp_min'] max_temp = result['main']['temp_max'] desc = result['weather'][0] desc = desc['main'] country = result['sys']['country'] sunrise = result['sys']['sunrise'] sunset = result['sys']['sunset'] wind = result['wind']['speed'] winddir = result['wind']['deg'] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = (360 / len(dirs)) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") return xx await weather.edit( f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Humidity:** `{humidity}%`\n" + f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Sunrise:** `{sun(sunrise)}`\n" + f"**Sunset:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
def half_hour_french_timestamp_to_utc_hourly_timestamp(timestamp): hourly_french_timestamp = timestamp + timedelta(minutes=timestamp.minute) utc_hourly_timestamp = hourly_french_timestamp.astimezone(tz("UTC")) return datetime.fromtimestamp(utc_hourly_timestamp.timestamp())
async def time_func(tdata): """For .time command, return the time of 1. The country passed as an argument, 2. The default userbot country(set it by using .settime), 3. The server where the userbot runs. """ con = tdata.pattern_match.group(1).title() tz_num = tdata.pattern_match.group(2) t_form = "%H:%M" d_form = "%d/%m/%y - %A" c_name = "" if len(con) > 4: try: c_name = c_n[con] except KeyError: c_name = con timezones = await get_tz(con) elif COUNTRY: c_name = COUNTRY tz_num = TZ_NUMBER timezones = await get_tz(COUNTRY) else: await edit_or_reply( tdata, f"𓆰 𝑺𝑶𝑼𝑹𝑪𝑬 𝑰𝑪𝑺𝑺 - 𝑻𝑰𝑴𝑬𝒁𝑶𝑵𝑬 𓆪 \n 𓍹ⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧⵧ𓍻 \n⪼ الوقت **{dt.now().strftime(t_form)}** في **{dt.now().strftime(d_form)}**", ) return if not timezones: await edit_or_reply(tdata, "`Invaild country.`") return if len(timezones) == 1: time_zone = timezones[0] elif len(timezones) > 1: if tz_num: tz_num = int(tz_num) time_zone = timezones[tz_num - 1] else: return_str = f"`{c_name} has multiple timezones:`\n\n" for i, item in enumerate(timezones): return_str += f"`{i+1}. {item}`\n" return_str += "\n`Choose one by typing the number " return_str += "in the command.`\n" return_str += f"`Example: .ctime {c_name} 2`" await edit_or_reply(tdata, return_str) return dtnow1 = dt.now(tz(time_zone)).strftime(t_form) dtnow2 = dt.now(tz(time_zone)).strftime(d_form) if c_name != COUNTRY: await edit_or_reply( tdata, f"`It's` **{dtnow1}**` on `**{dtnow2}** `in {c_name} ({time_zone} timezone).`", ) return if COUNTRY: await edit_or_reply( tdata, f"`It's` **{dtnow1}**` on `**{dtnow2}** `here, in {COUNTRY}" f"({time_zone} timezone).`", ) return
PROJECT_RUNTIME_MODE = 'test' # project path define MODULE_PATH = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) # reaper ROOT_PATH = os.path.dirname(MODULE_PATH) # log path define LOG_DIR = os.path.join(MODULE_PATH, 'log') # log formatter defin LOG_FORMATTER = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # timezone settings # TIMEZONE_PST8PDT = tz('PST8PDT') TIMEZONE_PST8PDT = tz('US/Pacific') TIMEZONE_CHINA = tz('Asia/Shanghai') TIMEZONE_GMT = tz('GMT') # time format DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' # api version define API_VERSION = "/v1" # production stage config PROD_CONFIG = {'timezone': TIMEZONE_PST8PDT, 'logging_level': logging.WARN} # development stage config DEVELOP_CONFIG = { 'timezone': TIMEZONE_PST8PDT, 'logging_level': logging.DEBUG, 'mongo_alert_queue': {
def archived_callback(request, format=None): """ Respond upon receiving a notification from the capture service that an archive is complete. Given: >>> client, callback_data, django_settings, _ = [getfixture(f) for f in ['client', 'webhook_callback', 'settings', 'mock_download']] >>> url = reverse('archived_callback') >>> user = User.objects.get(id=callback_data['userid']) >>> assert user.archives.count() == 0 By default, we do not expect the data to be signed. >>> response = client.post(url, callback_data, content_type='application/json') >>> check_response(response) >>> user.refresh_from_db() >>> assert user.archives.count() == 1 Signature verification can be enabled via Django settings. >>> django_settings.VERIFY_WEBHOOK_SIGNATURE = True >>> django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM = generate_hmac_signing_key() >>> response = client.post(url, callback_data, content_type='application/json') >>> check_response(response, status_code=400, content_includes='Invalid signature') >>> response = client.post(url, callback_data, content_type='application/json', ... HTTP_X_HOOK_SIGNATURE='foo' ... ) >>> check_response(response, status_code=400, content_includes='Invalid signature') >>> response = client.post(url, callback_data, content_type='application/json', ... HTTP_X_HOOK_SIGNATURE=sign_data(humps.camelize(callback_data), django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM) ... ) >>> check_response(response, content_includes='ok') >>> user.refresh_from_db() >>> assert user.archives.count() == 2 Hashes are calculated if not supplied by the POSTed data. >>> assert all(key not in callback_data for key in ['hash', 'hash_algorithm']) >>> assert all(archive.hash and archive.hash_algorithm for archive in user.archives.all()) If we send a timestamp with our initial request and receive it back, we store that value: >>> assert str(user.archives.last().requested_at.timestamp()) == callback_data['user_data_field'] If we do not send a timestamp with our initial request, or if the webhook payload does not include it, we default to 00:00:00 UTC 1 January 1970. >>> del callback_data['user_data_field'] >>> response = client.post(url, callback_data, content_type='application/json', ... HTTP_X_HOOK_SIGNATURE=sign_data(humps.camelize(callback_data), django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM) ... ) >>> check_response(response) >>> assert user.archives.last().requested_at.timestamp() == 0.000000 The POSTed `userid` must match the id of a registered user. >>> callback_data['userid'] = User.objects.last().id + 1 >>> assert not User.objects.filter(id=callback_data['userid']).exists() >>> response = client.post(url, callback_data, content_type='application/json', ... HTTP_X_HOOK_SIGNATURE=sign_data(humps.camelize(callback_data), django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM) ... ) >>> check_response(response, status_code=400, content_includes=['user', 'Invalid', 'does not exist']) Note: though jobid and hash should be unique, it is not enforced by this application (as is clear from the examples above). Finally: let's demonstrate that DRF is indeed handling camelcase conversion for us. >>> response_from_snake_case_post = client.post(url, callback_data, content_type='application/json', ... HTTP_X_HOOK_SIGNATURE=sign_data(humps.camelize(callback_data), django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM) ... ) >>> response_from_camel_case_post = client.post(url, humps.camelize(callback_data), content_type='application/json', ... HTTP_X_HOOK_SIGNATURE=sign_data(humps.camelize(callback_data), django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, django_settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM) ... ) >>> assert response_from_snake_case_post.data == response_from_camel_case_post.data >>> assert humps.camelize(response_from_snake_case_post.data) == response_from_snake_case_post.data """ if settings.VERIFY_WEBHOOK_SIGNATURE: # DRF will have deserialized the request data and decamelized all the keys... # which messes up the signature check. We recamelize here, just for that check. camelcase_data = humps.camelize(request.data) if not is_valid_signature( request.headers.get('x-hook-signature', ''), camelcase_data, settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY, settings.CAPTURE_SERVICE_WEBHOOK_SIGNING_KEY_ALGORITHM ): raise serializers.ValidationError('Invalid signature.') # for now, calculate file hash, if not included in POST # (hashing is not yet a feature of the capture service) hash = request.data.get('hash') hash_algorithm = request.data.get('hash_algorithm') if request.data.get('access_url') and (not hash or not hash_algorithm): if settings.OVERRIDE_ACCESS_URL_NETLOC: url = override_access_url_netloc(request.data['access_url'], internal=True) else: url = request.data['access_url'] hash, hash_algorithm = get_file_hash(url) # retrieve the datetime from our user_data_field ts = float(request.data.get('user_data_field', '0.000000')) requested_at = datetime.datetime.fromtimestamp(ts, tz(settings.TIME_ZONE)) # validate and save serializer = ArchiveSerializer(data={ 'user': request.data.get('userid'), 'jobid': request.data.get('jobid'), 'requested_at': requested_at, 'hash': hash, 'hash_algorithm': hash_algorithm }) if serializer.is_valid(): serializer.save() if not ts: logger.warning(f'No requested_at timestamp received for archive {serializer.instance.id}; defaulting to Unix Epoch.') return ApiResponse({'status': 'ok'}, status=status.HTTP_200_OK) return ApiResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def weather(update: Update, context: CallbackContext): bot=context.bot message = update.effective_message city = message.text[len('/weather '):] if city: APPID = WEATHER_API result = None timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in city: newcity = city.split(",") if len(newcity[1]) == 2: city = newcity[0].strip() + "," + newcity[1].strip() else: country = get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f'{country}'] except KeyError: weather.edit("`Invalid country.`") return city = newcity[0].strip() + "," + countrycode.strip() url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={APPID}' request = get(url) result = json.loads(request.text) if request.status_code != 200: info = f"No weather information for this location!" bot.send_message(chat_id = update.effective_chat.id, text=info, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) return cityname = result['name'] curtemp = result['main']['temp'] humidity = result['main']['humidity'] min_temp = result['main']['temp_min'] max_temp = result['main']['temp_max'] country = result['sys']['country'] sunrise = result['sys']['sunrise'] sunset = result['sys']['sunset'] wind = result['wind']['speed'] weath = result['weather'][0] desc = weath['main'] icon = weath['id'] condmain = weath['main'] conddet = weath['description'] if icon <= 232: # Rain storm icon = "⛈" elif icon <= 321: # Drizzle icon = "🌧" elif icon <= 504: # Light rain icon = "🌦" elif icon <= 531: # Cloudy rain icon = "⛈" elif icon <= 622: # Snow icon = "��" elif icon <= 781: # Atmosphere icon = "🌪" elif icon <= 800: # Bright icon = "☀�" elif icon <= 801: # A little cloudy icon = "⛅�" elif icon <= 804: # Cloudy icon = "��" ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A %d %b, %H:%M").lstrip("0").replace(" 0", " ") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%H:%M").lstrip("0").replace(" 0", " ") return xx if city: info = f"*{cityname}, {fullc_n}*\n" info += f"`{time}`\n\n" info += f"• **Temperature:** `{celsius(curtemp)}°C\n`" info += f"• **Condition:** `{condmain}, {conddet}` " + f"{icon}\n" info += f"• **Humidity:** `{humidity}%`\n" info += f"• **Wind:** `{kmph[0]} km/h`\n" info += f"• **Sunrise**: `{sun(sunrise)}`\n" info += f"• **Sunset**: `{sun(sunset)}`" bot.send_message(chat_id = update.effective_chat.id, text=info, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def run_server(auction, mapping_expire_time, logger, timezone='Europe/Kiev', bids_form=BidsForm, bids_handler=BidsHandler, form_handler=form_handler, cookie_path=AUCTION_SUBPATH): app = initialize_application() add_url_rules(app) app.config.update(auction.worker_defaults) # Replace Flask custom logger app.logger_name = logger.name app._logger = logger app.config['timezone'] = tz(timezone) app.config['SESSION_COOKIE_PATH'] = '/{}/{}'.format( cookie_path, auction.context['auction_doc_id']) app.config['SESSION_COOKIE_NAME'] = 'auction_session' app.oauth = OAuth(app) app.gsm = getGlobalSiteManager() app.context = app.gsm.queryUtility(IContext) app.bids_form = bids_form app.bids_handler = bids_handler() app.form_handler = form_handler app.remote_oauth = app.oauth.remote_app( 'remote', consumer_key=app.config['OAUTH_CLIENT_ID'], consumer_secret=app.config['OAUTH_CLIENT_SECRET'], request_token_params={'scope': 'email'}, base_url=app.config['OAUTH_BASE_URL'], access_token_url=app.config['OAUTH_ACCESS_TOKEN_URL'], authorize_url=app.config['OAUTH_AUTHORIZE_URL']) @app.remote_oauth.tokengetter def get_oauth_token(): return session.get('remote_oauth') os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true' # Start server on unused port request_id = generate_request_id() listener = get_lisener(auction.worker_defaults["STARTS_PORT"], host=auction.worker_defaults.get( "WORKER_BIND_IP", "")) app.logger.info("Start server on {0}:{1}".format(*listener.getsockname()), extra={"JOURNAL_REQUEST_ID": request_id}) server = WSGIServer(listener, app, log=_LoggerStream(logger), handler_class=AuctionsWSGIHandler) server.start() # Set mapping mapping_value = "http://{0}:{1}/".format(*listener.getsockname()) create_mapping(auction.worker_defaults, auction.context['auction_doc_id'], mapping_value) app.logger.info("Server mapping: {} -> {}".format( auction.context['auction_doc_id'], mapping_value, mapping_expire_time), extra={"JOURNAL_REQUEST_ID": request_id}) # Spawn events functionality spawn( push_timestamps_events, app, ) spawn( check_clients, app, ) return server
# project fun mode (deploy/test) PROJECT_RUNTIME_MODE = os.environ.get('PROJECT_RUNTIME_MODE', 'test') IS_DEPLOY = False if os.environ.get('IS_DEPLOY', 'False') in ['False', 'false'] else True # project path define MODULE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # reaper ROOT_PATH = os.path.dirname(MODULE_PATH) # log path define LOG_DIR = os.path.join(MODULE_PATH, 'log') # log formatter defin LOG_FORMATTER = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # timezone settings TIMEZONE_PST8PDT = tz('PST8PDT') # TIMEZONE_PST8PDT = tz('US/Pacific') TIMEZONE_CHINA = tz('Asia/Shanghai') TIMEZONE_GMT = tz('GMT') # time format DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' # api version define API_VERSION = "/v1" # production stage config PROD_CONFIG = { 'timezone': TIMEZONE_PST8PDT, 'logging_level': logging.WARN } # development stage config
async def get_weather(event): # sourcery no-metrics "To get the weather report of a city." if not Config.OPEN_WEATHER_MAP_APPID: return await edit_or_reply( event, "`Get an API key from` https://openweathermap.org/ `first.`") input_str = "".join(event.text.split(maxsplit=1)[1:]) CITY = gvarstatus("DEFCITY") or "Delhi" if not input_str else input_str timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = f"{newcity[0].strip()},{newcity[1].strip()}" else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: return await edit_or_reply(event, "`Invalid Country.`") CITY = f"{newcity[0].strip()},{countrycode.strip()}" url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={Config.OPEN_WEATHER_MAP_APPID}" async with aiohttp.ClientSession() as _session: async with _session.get(url) as request: requeststatus = request.status requesttext = await request.text() result = json.loads(requesttext) if requeststatus != 200: return await edit_or_reply(event, "`Invalid Country.`") cityname = result["name"] curtemp = result["main"]["temp"] humidity = result["main"]["humidity"] min_temp = result["main"]["temp_min"] max_temp = result["main"]["temp_max"] pressure = result["main"]["pressure"] feel = result["main"]["feels_like"] desc = result["weather"][0] desc = desc["main"] country = result["sys"]["country"] sunrise = result["sys"]["sunrise"] sunset = result["sys"]["sunset"] wind = result["wind"]["speed"] winddir = result["wind"]["deg"] cloud = result["clouds"]["all"] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = 360 / len(dirs) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") await edit_or_reply( event, f"🌡**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"🥰**Human Feeling** `{celsius(feel)}°C | {fahrenheit(feel)}°F`\n" + f"🥶**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"🥵**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"☁️**Humidity:** `{humidity}%`\n" + f"🧧**Pressure** `{pressure} hPa`\n" + f"🌬**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"⛈**Cloud:** `{cloud} %`\n" + f"🌄**Sunrise:** `{sun(sunrise,ctimezone)}`\n" + f"🌅**Sunset:** `{sun(sunset,ctimezone)}`\n\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`\n", )
ord_dict_1 = OrderedDict({1: 'one', 2: 'two'}) ord_dict_2 = OrderedDict({2: 'two', 1: 'one'}) print( f'\tIs first unorder dict equals to second? {unord_dict_1 == unord_dict_2}' ) # true; order doesn't matter print(f'\tIs first order dict equals to second? {ord_dict_1 == ord_dict_2}' ) # false; order matters and differs print() Person = namedtuple('Person', 'name lastname age') john = Person(name='John', lastname='Wick', age=42) print(f'\tName tuple Person \'jonh\' -> {john}') print(f'\t{john.name}\'s age: {john.age}') print() print("----------------------- Datetime ------------------------") ct = dt.now() ct = tz('Europe/Madrid').localize(ct.replace(tzinfo=None)) print(f'\tCurrent datetime with Spain timezone: {ct}') print( f'\tOther format: {ct.year}-{ct.month}-{ct.day} {ct.hour}:{ct.minute}:{ct.second}.{ct.microsecond} {ct.tzinfo}' ) fakebday = dt(1992, 5, 23) fakebday = fakebday.replace(year=1996) print(f'\tBirthday + 4 years: {fakebday}') days = td(days=5 * 365 / 12) print(f'\tFive months ago in Tokyo: {dt.now(tz("Asia/Tokyo")) - days}' ) # pytz is fully compatible with datetime module
class TestAssibleJSONEncoder: """ Namespace for testing AssibleJSONEncoder. """ @pytest.fixture(scope='class') def mapping(self, request): """ Returns object of Mapping mock class. The object is used for testing handling of Mapping objects in AssibleJSONEncoder.default(). Using a plain dictionary instead is not suitable because it is handled by default encoder of the superclass (json.JSONEncoder). """ class M(Mapping): """Mock mapping class.""" def __init__(self, *args, **kwargs): self.__dict__.update(*args, **kwargs) def __getitem__(self, key): return self.__dict__[key] def __iter__(self): return iter(self.__dict__) def __len__(self): return len(self.__dict__) return M(request.param) @pytest.fixture def assible_json_encoder(self): """Return AssibleJSONEncoder object.""" return AssibleJSONEncoder() ############### # Test methods: @pytest.mark.parametrize('test_input,expected', [ (datetime(2019, 5, 14, 13, 39, 38, 569047), '2019-05-14T13:39:38.569047'), (datetime(2019, 5, 14, 13, 47, 16, 923866), '2019-05-14T13:47:16.923866'), (date(2019, 5, 14), '2019-05-14'), (date(2020, 5, 14), '2020-05-14'), (datetime(2019, 6, 15, 14, 45, tzinfo=tz('UTC')), '2019-06-15T14:45:00+00:00'), (datetime(2019, 6, 15, 14, 45, tzinfo=tz('Europe/Helsinki')), '2019-06-15T14:45:00+01:40'), ]) def test_date_datetime(self, assible_json_encoder, test_input, expected): """ Test for passing datetime.date or datetime.datetime objects to AssibleJSONEncoder.default(). """ assert assible_json_encoder.default(test_input) == expected @pytest.mark.parametrize( 'mapping,expected', [ ({ 1: 1 }, { 1: 1 }), ({ 2: 2 }, { 2: 2 }), ({ 1: 2 }, { 1: 2 }), ({ 2: 1 }, { 2: 1 }), ], indirect=['mapping'], ) def test_mapping(self, assible_json_encoder, mapping, expected): """ Test for passing Mapping object to AssibleJSONEncoder.default(). """ assert assible_json_encoder.default(mapping) == expected @pytest.mark.parametrize('test_input,expected', vault_data()) def test_assible_json_decoder_vault(self, assible_json_encoder, test_input, expected): """ Test for passing AssibleVaultEncryptedUnicode to AssibleJSONEncoder.default(). """ assert assible_json_encoder.default(test_input) == { '__assible_vault': expected } assert json.dumps( test_input, cls=AssibleJSONEncoder, preprocess_unsafe=True ) == '{"__assible_vault": "%s"}' % expected.replace('\n', '\\n') @pytest.mark.parametrize('test_input,expected', [ ({ 1: 'first' }, { 1: 'first' }), ({ 2: 'second' }, { 2: 'second' }), ]) def test_default_encoder(self, assible_json_encoder, test_input, expected): """ Test for the default encoder of AssibleJSONEncoder.default(). If objects of different classes that are not tested above were passed, AssibleJSONEncoder.default() invokes 'default()' method of json.JSONEncoder superclass. """ assert assible_json_encoder.default(test_input) == expected @pytest.mark.parametrize( 'test_input', [1, 1.1, 'string', [1, 2], set('set'), True, None]) def test_default_encoder_unserializable(self, assible_json_encoder, test_input): """ Test for the default encoder of AssibleJSONEncoder.default(), not serializable objects. It must fail with TypeError 'object is not serializable'. """ with pytest.raises(TypeError): assible_json_encoder.default(test_input)
async def get_weather(weather): """ For .weather command, gets the current weather of a city. """ if not OWM_API: return await weather.edit( "**Obtenha uma chave de API de** https://openweathermap.org **primeiro.**" ) APPID = OWM_API anonymous = False if not weather.pattern_match.group(1): CITY = DEFCITY elif weather.pattern_match.group(1).lower() == "anon": CITY = DEFCITY anonymous = True else: CITY = weather.pattern_match.group(1) if not CITY: return await weather.edit( "**Especifique uma cidade ou defina uma como padrão usando a ConfigVar WEATHER_DEFCITY.**" ) timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: return await weather.edit("**País inválido.**") CITY = newcity[0].strip() + "," + countrycode.strip() url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}" request = get(url) result = json.loads(request.text) if request.status_code != 200: return await weather.edit("**País inválido.**") cityname = result["name"] curtemp = result["main"]["temp"] humidity = result["main"]["humidity"] min_temp = result["main"]["temp_min"] max_temp = result["main"]["temp_max"] desc = result["weather"][0] desc = desc["main"] country = result["sys"]["country"] sunrise = result["sys"]["sunrise"] sunset = result["sys"]["sunset"] wind = result["wind"]["speed"] winddir = result["wind"]["deg"] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = 360 / len(dirs) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str((f - 273.15) * 9 / 5 + 32).split(".") return temp[0] def celsius(c): temp = str(c - 273.15).split(".") return temp[0] def sun(unix): return datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") results = ( f"**Temperatura:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Temp. Min.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Temp. Max.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Umidade:** `{humidity}%`\n" + f"**Vento:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Nascer do Sol:** `{sun(sunrise)}`\n" + f"**Pôr do Sol:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`") if not anonymous: results += f"`{cityname}, {fullc_n}`" await weather.edit(results)
def get_week_parties(self): current_time = timezone.now().astimezone(tz('US/Central')) next_week = current_time + timedelta(weeks=1) parties = self.get_all_related_parties() return [party for party in parties if party.time_begin < next_week and party.time_end > current_time]
def current_time(): ## Activate the Europe time zone. timezone.activate(tz(settings.CURRENT_TIME_ZONE)) return timezone.localtime(timezone.now())
def __init__( self, trello_apiKey='', #apiKey для подключения к trello trello_token='', #apiToken для подключения к trello local_timezone='Asia/Tomsk'): self.API_KEY = trello_apiKey self.TOKEN = trello_token self.local_timezone = tz(local_timezone) self.filter_dates = [] self.database_is_updating = False #Подключение к Trello try: self.trello_client = TrelloClient( api_key=self.API_KEY, token=self.TOKEN, ) except Exception as err: print( f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: [ERROR] Failed to connect to Trello via API: {err}' ) else: print( f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: [MSG] Connection to Trello established successful' ) #Создание файла БД и таблиц в БД try: self.db = TinyDB('tar_database.json') #self.db.drop_tables() !!!!!!!!!!!!!!!!!!!!! self.report = self.db.table('report') self.worktime = self.db.table('worktime') self.local_boards = self.db.table('boards') self.local_lists = self.db.table('lists') self.local_cards = self.db.table('cards') self.local_persons = self.db.table('persons') self.local_cards_has_persons = self.db.table('cards_has_persons') except Exception as err: print( f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: [ERROR] Failed to setup tar_database: {err}' ) else: print( f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: [MSG] tar_database created' ) self.basic_template = [{ 0: 'Перечень Задач', 'cards': [ 'П3 - Описание автоматизируемых функций', 'П5 - Описание информационного обеспечения', 'В1 - Описание входных сигналов и данных', 'В2 - Описание выходных сигналов (сообщений)', 'ПА - Описание программного обеспечения', 'ПБ - Описание алгоритма', 'П6 - Описание информационной базы', 'С9 - Чертеж форм (видеокадра)', 'И3 - Руководство оператора', 'И3 - Руководство программиста', 'И4 - Инструкция по ведению БД', 'ПМИ - Программа и методика испытаний', 'ПО ПЛК - Программа контроллера', 'ПО Панели - Программа панели оператора', 'ПО АРМ - Программа рабочего места оператора', 'ПО БД - База данных', 'Ежедневная планерка', 'Планирование цели (спринт)', 'Анализ завершения цели (спринта)' ] }, { 1: 'Комплекс Задач', 'cards': [] }, { 2: 'В Работе', 'cards': [] }, { 3: 'Согласование выполнения', 'cards': [] }, { 4: 'Завершены', 'cards': [] }, { 5: 'Отменены', 'cards': [] }] self.db.drop_table('worktime') self.worktime.insert({ 'work_day_starts': '09:00:00', 'work_day_ends': '18:00:00', 'work_day_duration': '09:00:00', 'lunch_hours_starts': '13:00:00', 'lunch_hours_ends': '14:00:00', 'lunch_duration': '01:00:00', 'day_work_hours': '08:00:00', 'work_days': '5', 'week_work_hours': '1 day, 16:00:00', 'update_period': '00:02:00' })
def update(self): self.data = self.model.objects(match_date__lte=(dt.now(tz('UTC')) - timedelta(minutes=115))) print('Znaleziono {} zakończonych meczy'.format(len(self.data)))
def download_file(source_name, variable_name, out_path, param_dict, start, end, session=None): """ Download a single file specified by ``param_dict``, ``start``, ``end``, and save it to a directory constructed by combining ``source_name``, ``variable_name`` and ``out_path``. Returns None. Parameters ---------- source_name : str Name of source dataset, e.g. ``TenneT`` variable_name : str Name of variable, e.g. ``solar`` out_path : str Base download directory in which to save all downloaded files param_dict : dict Info required for download, e.g. url, url-parameter, filename. start : datetime.date start of data in the file end : datetime.date end of data in the file session : requests.session, optional If not given, a new session is created. """ if session is None: session = requests.session() logger.info( 'Downloading data:\n ' 'Source: {}\n ' 'Variable: {}\n ' 'Data starts: {:%Y-%m-%d} \n ' 'Data ends: {:%Y-%m-%d}' .format(source_name, variable_name, start, end) ) # Each file will be saved in a folder of its own, this allows us to preserve # the original filename when saving to disk. container = os.path.join( out_path, source_name, variable_name, start.strftime('%Y-%m-%d') + '_' + end.strftime('%Y-%m-%d') ) os.makedirs(container, exist_ok=True) # Get number of months between now and start (required for TransnetBW). count = ( datetime.now().month - start.month + (datetime.now().year - start.year) * 12 ) if source_name == 'Elia': start = tz('Europe/Brussels').localize( datetime.combine(start, time())).astimezone(tz('UTC') ) end = tz('Europe/Brussels').localize( datetime.combine(end+timedelta(days=1), time())).astimezone(tz('UTC') ) url_params = {} # A dict for paramters # For most sources, we can use HTTP get method with paramters-dict if param_dict['url_params_template']: for key, value in param_dict['url_params_template'].items(): url_params[key] = value.format( u_start=start, u_end=end, u_transnetbw=count ) url = param_dict['url_template'] # For other sources that use urls without parameters (e.g. Svenska Kraftnaet) else: url = param_dict['url_template'].format( u_start=start, u_end=end, u_transnetbw=count ) # Attempt the download if there is no file yet. count_files = len(os.listdir(container)) if count_files == 0: resp = session.get(url, params=url_params) # Get the original filename try: original_filename = ( resp.headers['content-disposition'] .split('filename=')[-1] .replace('"', '') .replace(';', '') ) # For cases where the original filename can not be retrieved, # I put the filename in the param_dict except KeyError: if 'filename' in param_dict: original_filename = param_dict['filename'].format(u_start=start, u_end=end) else: logger.info( 'original filename could neither be retrieved from server nor sources.yml' ) original_filename = 'data' logger.info('Downloaded from URL: %s Original filename: %s', resp.url, original_filename) #Save file to disk filepath = os.path.join(container, original_filename) with open(filepath, 'wb') as output_file: for chunk in resp.iter_content(1024): output_file.write(chunk) elif count_files == 1: logger.info('There is already a file: %s', os.listdir(container)[0]) else: logger.info('There must not be more than one file in: %s. Please check ', container)
def emit(panchaanga, time_format="hh:mm", scripts=None, output_stream=None): """Write out the panchaanga TeX using a specified template """ # day_colours = {0: 'blue', 1: 'blue', 2: 'blue', # 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} compute_lagnams = panchaanga.computation_system.options.set_lagnas if scripts is None: scripts = [sanscript.DEVANAGARI] month = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'} WDAY = {0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'} template_file = open(os.path.join(os.path.dirname(__file__), 'templates/daily_cal_template.tex')) template_lines = template_file.readlines() for i in range(len(template_lines)): print(template_lines[i][:-1], file=output_stream) year = panchaanga.start_date.year logging.debug(year) samvatsara_id = (year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = (jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][samvatsara_id], jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][(samvatsara_id % 60) + 1]) yname = samvatsara_names[0] # Assign year name until Mesha Sankranti print('\\mbox{}', file=output_stream) print('\\renewcommand{\\yearname}{%d}' % year, file=output_stream) print('\\begin{center}', file=output_stream) print('{\\sffamily \\fontsize{80}{80}\\selectfont %d\\\\[0.5cm]}' % year, file=output_stream) print('\\mbox{\\fontsize{48}{48}\\selectfont %s–%s}\\\\' % samvatsara_names, file=output_stream) print('\\mbox{\\fontsize{32}{32}\\selectfont %s } %%' % jyotisha.custom_transliteration.tr('kali', scripts[0]), file=output_stream) print('{\\sffamily \\fontsize{43}{43}\\selectfont %d–%d\\\\[0.5cm]}\n\\hrule\n\\vspace{0.2cm}' % (year + 3100, year + 3101), file=output_stream) print('{\\sffamily \\fontsize{50}{50}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchaanga.city.name, file=output_stream) print('{\\sffamily \\fontsize{23}{23}\\selectfont {%s}\\\\[0.2cm]}' % jyotisha.custom_transliteration.print_lat_lon(panchaanga.city.latitude, panchaanga.city.longitude), file=output_stream) print('\\hrule', file=output_stream) print('\\end{center}', file=output_stream) print('\\clearpage\\pagestyle{fancy}', file=output_stream) daily_panchaangas = panchaanga.daily_panchaangas_sorted() for d, daily_panchaanga in enumerate(daily_panchaangas): if daily_panchaanga.date < panchaanga.start_date or daily_panchaanga.date > panchaanga.end_date: continue [y, m, dt] = [daily_panchaanga.date.year, daily_panchaanga.date.month, daily_panchaanga.date.day] # checking @ 6am local - can we do any better? local_time = tz(panchaanga.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = daily_panchaanga.julian_day_start tithi_data_str = '' for iTithi, tithi_span in enumerate(daily_panchaanga.sunrise_day_angas.tithis_with_ends): (tithi_ID, tithi_end_jd) = (tithi_span.anga.index, tithi_span.jd_end) # if tithi_data_str != '': # tithi_data_str += '\\hspace{1ex}' tithi = '\\raisebox{-1pt}{\\moon[scale=0.8]{%d}}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.names.NAMES['TITHI_NAMES'][scripts[0]][tithi_ID] if tithi_end_jd is None: if iTithi == 0: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram (tridinaspRk)', scripts[0])) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (tithi_data_str, tithi, time.Hour( 24 * (tithi_end_jd - daily_panchaanga.jd_sunrise)).toString(format='gg-pp'), time.Hour(24 * (tithi_end_jd - jd)).toString( format=time_format)) nakshatra_data_str = '' for iNakshatra, nakshatra_span in enumerate(daily_panchaanga.sunrise_day_angas.nakshatras_with_ends): (nakshatra_ID, nakshatra_end_jd) = (nakshatra_span.anga.index, nakshatra_span.jd_end) if nakshatra_data_str != '': nakshatra_data_str += '\\hspace{1ex}' nakshatra = jyotisha.names.NAMES['NAKSHATRA_NAMES'][scripts[0]][nakshatra_ID] if nakshatra_end_jd is None: if iNakshatra == 0: nakshatra_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatra_data_str, nakshatra, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: nakshatra_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}' % \ (nakshatra_data_str, nakshatra, time.Hour( 24 * (nakshatra_end_jd - daily_panchaanga.jd_sunrise)).toString(format='gg-pp'), time.Hour(24 * (nakshatra_end_jd - jd)).toString( format=time_format)) rashi_data_str = '' for iRaashi, raashi_span in enumerate(daily_panchaanga.sunrise_day_angas.raashis_with_ends): if iRaashi == 0: (rashi_ID, rashi_end_jd) = (raashi_span.anga.index, raashi_span.jd_end) # if rashi_data_str != '': # rashi_data_str += '\\hspace{1ex}' rashi = jyotisha.names.NAMES['RASHI_SUFFIXED_NAMES'][scripts[0]][rashi_ID] if rashi_end_jd is None: rashi_data_str = '%s\\mbox{%s}' % (rashi_data_str, rashi) else: rashi_data_str = '%s\\mbox{%s \\RIGHTarrow \\textsf{%s}}' % \ (rashi_data_str, rashi, time.Hour(24 * (rashi_end_jd - jd)).toString( format=time_format)) if compute_lagnams: lagna_data_str = 'लग्नम्–' for lagna_ID, lagna_end_jd in daily_panchaanga.lagna_data: lagna = jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][lagna_ID] lagna_data_str = '%s\\mbox{%s\\RIGHTarrow\\textsf{%s}} ' % \ (lagna_data_str, lagna, time.Hour(24 * (lagna_end_jd - jd)).toString( format=time_format)) yoga_data_str = '' for iYoga, yoga_span in enumerate(daily_panchaanga.sunrise_day_angas.yogas_with_ends): (yoga_ID, yoga_end_jd) = (yoga_span.anga.index, yoga_span.jd_end) # if yoga_data_str != '': # yoga_data_str += '\\hspace{1ex}' yoga = jyotisha.names.NAMES['YOGA_NAMES'][scripts[0]][yoga_ID] if yoga_end_jd is None: if iYoga == 0: yoga_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yoga_data_str, yoga, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: yoga_data_str = '%s\\mbox{%s\\Too{}}' % \ (yoga_data_str, yoga) else: yoga_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (yoga_data_str, yoga, time.Hour(24 * (yoga_end_jd - daily_panchaanga.jd_sunrise)).toString( format='gg-pp'), time.Hour(24 * (yoga_end_jd - jd)).toString( format=time_format)) if yoga_end_jd is not None: yoga_data_str += '\\mbox{%s\\Too{}}' % ( jyotisha.names.NAMES['YOGA_NAMES'][scripts[0]][(yoga_ID % 27) + 1]) karana_data_str = '' for numKaranam, karaNa_span in enumerate(daily_panchaanga.sunrise_day_angas.karanas_with_ends): (karana_ID, karana_end_jd) = (karaNa_span.anga.index, karaNa_span.jd_end) # if numKaranam == 1: # karana_data_str += '\\hspace{1ex}' karana = jyotisha.names.NAMES['KARANA_NAMES'][scripts[0]][karana_ID] if karana_end_jd is None: karana_data_str = '%s\\mbox{%s\\Too{}}' % \ (karana_data_str, karana) else: karana_data_str = '%s\\mbox{%s\\To{}\\textsf{%s (%s)}}\\hspace{1ex}' % \ (karana_data_str, karana, time.Hour( 24 * (karana_end_jd - daily_panchaanga.jd_sunrise)).toString(format='gg-pp'), time.Hour(24 * (karana_end_jd - jd)).toString( format=time_format)) sunrise = time.Hour(24 * (daily_panchaanga.jd_sunrise - jd)).toString( format=time_format) sunset = time.Hour(24 * (daily_panchaanga.jd_sunset - jd)).toString(format=time_format) moonrise = time.Hour(24 * (daily_panchaanga.jd_moonrise - jd)).toString( format=time_format) moonset = time.Hour(24 * (daily_panchaanga.jd_moonset - jd)).toString( format=time_format) braahma_start = time.Hour(24 * (daily_panchaanga.day_length_based_periods.braahma.jd_start - jd)).toString( format=time_format) praatahsandhya_start = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.praatas_sandhyaa.jd_start - jd)).toString(format=time_format) praatahsandhya_end = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.praatas_sandhyaa_end.jd_start - jd)).toString(format=time_format) saangava = time.Hour(24 * (daily_panchaanga.day_length_based_periods.saangava.jd_start - jd)).toString( format=time_format) madhyaahna = time.Hour(24 * (daily_panchaanga.day_length_based_periods.madhyaahna.jd_start - jd)).toString( format=time_format) madhyahnika_sandhya_start = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.maadhyaahnika_sandhyaa.jd_start - jd)).toString(format=time_format) madhyahnika_sandhya_end = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.maadhyaahnika_sandhyaa_end.jd_start - jd)).toString(format=time_format) aparaahna_muhuurta = time.Hour(24 * (daily_panchaanga.day_length_based_periods.aparaahna_muhuurta.jd_start - jd)).toString( format=time_format) sayahna = time.Hour(24 * (daily_panchaanga.day_length_based_periods.saayaahna.jd_start - jd)).toString( format=time_format) sayamsandhya_start = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.saayam_sandhyaa.jd_start - jd)).toString(format=time_format) sayamsandhya_end = time.Hour( 24 * (daily_panchaanga.day_length_based_periods.pradosha.jd_end - jd)).toString(format=time_format) ratriyama1 = time.Hour(24 * (daily_panchaanga.day_length_based_periods.raatri_yaama_1.jd_start - jd)).toString( format=time_format) shayana_time_end = time.Hour(24 * (daily_panchaanga.day_length_based_periods.shayana.jd_start - jd)).toString( format=time_format) dinaanta = time.Hour(24 * (daily_panchaanga.day_length_based_periods.dinaanta.jd_start - jd)).toString( format=time_format) rahu = '%s--%s' % ( time.Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_start - jd)).toString( format=time_format), time.Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_end - jd)).toString( format=time_format)) yama = '%s--%s' % ( time.Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_start - jd)).toString( format=time_format), time.Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_end - jd)).toString( format=time_format)) gulika = '%s--%s' % ( time.Hour(24 * (daily_panchaanga.day_length_based_periods.gulika.jd_start - jd)).toString( format=time_format), time.Hour(24 * (daily_panchaanga.day_length_based_periods.gulika.jd_end - jd)).toString( format=time_format)) if daily_panchaanga.solar_sidereal_date_sunset.month == 1: # Flip the year name for the remaining days yname = samvatsara_names[1] # Assign samvatsara, ayana, rtu # sar_data = '{%s}{%s}{%s}' % (yname, jyotisha.names.NAMES['AYANA_NAMES'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month], jyotisha.names.NAMES['RTU_NAMES'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month]) if daily_panchaanga.solar_sidereal_date_sunset.month_transition is None: month_end_str = '' else: _m = daily_panchaangas[d - 1].solar_sidereal_date_sunset.month if daily_panchaanga.solar_sidereal_date_sunset.month_transition >= daily_panchaangas[d + 1].jd_sunrise: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], time.Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset.month_transition - daily_panchaangas[d + 1].julian_day_start)).toString(format=time_format)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], time.Hour( 24 * (daily_panchaanga.solar_sidereal_date_sunset.month_transition - daily_panchaanga.julian_day_start)).toString(format=time_format)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][daily_panchaanga.solar_sidereal_date_sunset.month], daily_panchaanga.solar_sidereal_date_sunset.day, month_end_str) print('\\caldata{%s}{%s}{%s{%s}{%s}{%s}%s}' % (month[m], dt, month_data, jyotisha.names.get_chandra_masa(daily_panchaanga.lunar_month_sunrise.index, jyotisha.names.NAMES, scripts[0]), jyotisha.names.NAMES['RTU_NAMES'][scripts[0]][int(ceil(daily_panchaanga.lunar_month_sunrise.index))], jyotisha.names.NAMES['VARA_NAMES'][scripts[0]][daily_panchaanga.date.get_weekday()], sar_data), file=output_stream) if daily_panchaanga.jd_moonrise > daily_panchaangas[d + 1].jd_sunrise: moonrise = '---' if daily_panchaanga.jd_moonset > daily_panchaangas[d + 1].jd_sunrise: moonset = '---' if daily_panchaanga.jd_moonrise < daily_panchaanga.jd_moonset: print('{\\sunmoonrsdata{%s}{%s}{%s}{%s}' % (sunrise, sunset, moonrise, moonset), file=output_stream) else: print('{\\sunmoonsrdata{%s}{%s}{%s}{%s}' % (sunrise, sunset, moonrise, moonset), file=output_stream) print( '{\\kalas{%s %s %s %s %s %s %s %s %s %s %s %s %s %s}}}' % (braahma_start, praatahsandhya_start, praatahsandhya_end, saangava, madhyahnika_sandhya_start, madhyahnika_sandhya_end, madhyaahna, aparaahna_muhuurta, sayahna, sayamsandhya_start, sayamsandhya_end, ratriyama1, shayana_time_end, dinaanta), file=output_stream) if compute_lagnams: print('{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{%s}\n}' % (tithi_data_str, nakshatra_data_str, rashi_data_str, yoga_data_str, karana_data_str, lagna_data_str), file=output_stream) else: print('{\\tnykdata{%s}%%\n{%s}{%s}%%\n{%s}%%\n{%s}{\\scriptsize %s}\n}' % (tithi_data_str, nakshatra_data_str, rashi_data_str, yoga_data_str, karana_data_str, ''), file=output_stream) rules_collection = rules.RulesCollection.get_cached( repos_tuple=tuple(panchaanga.computation_system.options.fest_repos)) fest_details_dict = rules_collection.name_to_rule # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! print('{%s}' % '\\eventsep '.join( [f.tex_code(scripts=scripts, timezone=Timezone(timezone_id=panchaanga.city.timezone), fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values())]), file=output_stream) print('{%s} ' % WDAY[daily_panchaanga.date.get_weekday()], file=output_stream) print('\\cfoot{\\rygdata{%s}{%s}{%s}}' % (rahu, yama, gulika), file=output_stream) if m == 12 and dt == 31: break print('\\end{document}', file=output_stream)
def update(self): self.data = self.model.objects(match_date__gte=dt.now(tz('UTC')), match_date__lte=dt.now(tz('UTC')) + timedelta(days=1)) print('Znaleziono {} dzisiajszych meczy'.format(len(self.data)))
def write_monthly_tex(panchaanga, template_file, scripts=None, temporal=None): """Write out the panchaanga TeX using a specified template """ if scripts is None: scripts = [sanscript.DEVANAGARI] day_colours = { 0: 'blue', 1: 'blue', 2: 'blue', 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue' } month = { 1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER' } MON = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } WDAY = { 0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat' } monthly_template_file = open( os.path.join(os.path.dirname(__file__), 'templates/monthly_cal_template.tex')) template_lines = template_file.readlines() for i in range(0, len(template_lines) - 3): print(template_lines[i][:-1]) samvatsara_id = (panchaanga.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = '%s–%s' % ( jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][samvatsara_id], jyotisha.names.NAMES['SAMVATSARA_NAMES'][scripts[0]][ (samvatsara_id % 60) + 1]) print('\\mbox{}') print('{\\sffamily\\fontsize{60}{25}\\selectfont %d\\\\[0.5cm]}' % panchaanga.year) print( '\\mbox{\\font\\x="Siddhanta:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names) print('\\mbox{\\font\\x="Siddhanta:script=deva" at 32 pt\\x %s } %%' % jyotisha.custom_transliteration.tr('kali', scripts[0])) print('{\\sffamily\\fontsize{32}{25}\\selectfont %d–%d\\\\[0.5cm]}' % (panchaanga.year + 3100, panchaanga.year + 3101)) print( '{\\sffamily\\fontsize{48}{25}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchaanga.city.name) print('{\\sffamily\\fontsize{16}{25}\\selectfont {%s}\\\\[0.5cm]}' % jyotisha.custom_transliteration.print_lat_lon( panchaanga.city.latitude, panchaanga.city.longitude)) print('\\hrule') print('\\newpage') print('\\centering') print('\\centerline{\\LARGE {{%s}}}' % jyotisha.custom_transliteration.tr('mAsAntara-vizESAH', scripts[0])) print('\\begin{multicols*}{3}') print('\\TrickSupertabularIntoMulticols') print( '\\begin{supertabular}' + '{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}c>{\\hangindent=2ex}panchaanga{8cm}}' ) mlast = 1 daily_panchaangas = panchaanga.daily_panchaangas_sorted() for d in range(panchaanga.duration_prior_padding, jyotisha.panchaanga.temporal.MAX_SZ - 1): [y, m, dt, t] = time.jd_to_utc_gregorian(panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() daily_panchaanga = daily_panchaangas[d] rules_collection = rules.RulesCollection.get_cached(repos_tuple=tuple( panchaanga.computation_system.options.fest_repos)) fest_details_dict = rules_collection.name_to_rule if len(daily_panchaanga.festival_id_to_instance) != 0: if m != mlast: mlast = m print('\\\\') print('%s & %s & %s & {\\raggedright %s} \\\\' % (MON[m], dt, WDAY[daily_panchaanga.date.get_weekday()], '\\\\'.join([ f.tex_code(scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict) for f in sorted( daily_panchaanga.festival_id_to_instance.values()) ]))) if m == 12 and dt == 31: break print('\\end{supertabular}') print('\\end{multicols*}') print('\\renewcommand{\\tamil}[1]{%') print( '{\\fontspec[Scale=0.9,FakeStretch=0.9]{Noto Sans Tamil}\\fontsize{7}{12}\\selectfont #1}}' ) # print('\\clearpage') month_text = '' W6D1 = W6D2 = '' for d in range(panchaanga.duration_prior_padding, jyotisha.panchaanga.temporal.MAX_SZ - 1): [y, m, dt, t] = time.jd_to_utc_gregorian(panchaanga.jd_start + d - 1).to_date_fractional_hour_tuple() # checking @ 6am local - can we do any better? local_time = tz(panchaanga.city.timezone).localize( datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = daily_panchaanga.julian_day_start if dt == 1: currWeek = 1 if m > 1: month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) month_text = W6D1 = W6D2 = '' if currWeek < 6: if daily_panchaanga.date.get_weekday( ) != 0: # Space till Sunday for i in range(daily_panchaanga.date.get_weekday(), 6): print("\\mbox{} & %% %d" % currWeek) print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') # Begin tabular print('\\begin{tabular}{|c|c|c|c|c|c|c|}') print( '\\multicolumn{7}{c}{\\Large \\bfseries \\sffamily %s %s}\\\\[3mm]' % (month[m], y)) print('\\hline') WDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] print(' & '.join( ['\\textbf{\\textsf{%s}}' % _day for _day in WDAY_NAMES]) + ' \\\\ \\hline') # Blanks for previous weekdays for i in range(0, daily_panchaanga.date.get_weekday()): if i == 0: month_text += '\n' + ("{W6D1} &") elif i == 1: month_text += '\n' + ("{W6D2} &") else: month_text += '\n' + ("{} &") tithi_data_str = '' for tithi_span in daily_panchaanga.sunrise_day_angas.tithis_with_ends: (tithi_ID, tithi_end_jd) = (tithi_span.anga.index, tithi_span.jd_end) # if tithi_data_str != '': # tithi_data_str += '\\hspace{2ex}' tithi = '\\moon[scale=0.6]{%d}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.names.NAMES['TITHI_NAMES'][scripts[0]][tithi_ID] if tithi_end_jd is None: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (tithi_data_str, tithi, Hour(24 * (tithi_end_jd - jd)).toString( format=panchaanga.fmt), '\\hspace{2ex}') nakshatra_data_str = '' for nakshatra_span in daily_panchaanga.sunrise_day_angas.nakshatras_with_ends: (nakshatra_ID, nakshatra_end_jd) = (nakshatra_span.anga.index, nakshatra_span.jd_end) # if nakshatra_data_str != '': # nakshatra_data_str += '\\hspace{2ex}' nakshatra = jyotisha.names.NAMES['NAKSHATRA_NAMES'][ scripts[0]][nakshatra_ID] if nakshatra_end_jd is None: nakshatra_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatra_data_str, nakshatra, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: nakshatra_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (nakshatra_data_str, nakshatra, Hour(24 * (nakshatra_end_jd - jd)).toString(format=panchaanga.fmt), '\\hspace{2ex}') yoga_data_str = '' for yoga_span in daily_panchaanga.sunrise_day_angas.yogas_with_ends: (yoga_ID, yoga_end_jd) = (yoga_span.anga.index, yoga_span.jd_end) # if yoga_data_str != '': # yoga_data_str += '\\hspace{2ex}' yoga = jyotisha.names.NAMES['YOGA_NAMES'][scripts[0]][yoga_ID] if yoga_end_jd is None: yoga_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yoga_data_str, yoga, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: yoga_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (yoga_data_str, yoga, Hour(24 * (yoga_end_jd - jd)).toString( format=panchaanga.fmt), '\\hspace{2ex}') karana_data_str = '' for numKaranam, karaNa_span in enumerate( daily_panchaanga.sunrise_day_angas.karanas_with_ends): (karana_ID, karana_end_jd) = (karaNa_span.anga.index, karaNa_span.jd_end) # if numKaranam == 1: # karana_data_str += '\\hspace{2ex}' if numKaranam == 2: karana_data_str = karana_data_str + '\\\\' karana = jyotisha.names.NAMES['KARANA_NAMES'][ scripts[0]][karana_ID] if karana_end_jd is None: karana_data_str = '%s\\mbox{%s\\To{}%s}' % \ (karana_data_str, karana, jyotisha.custom_transliteration.tr('ahOrAtram', scripts[0])) else: karana_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (karana_data_str, karana, Hour(24 * (karana_end_jd - jd)).toString(format=panchaanga.fmt), '\\hspace{2ex}') sunrise = Hour(24 * (daily_panchaanga.jd_sunrise - jd)).toString( format=panchaanga.fmt) sunset = Hour(24 * (daily_panchaanga.jd_sunset - jd)).toString( format=panchaanga.fmt) saangava = Hour( 24 * (daily_panchaanga.day_length_based_periods.saangava.jd_start - jd)).toString(format=panchaanga.fmt) rahu = '%s--%s' % ( Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_start - jd)).toString(format=panchaanga.fmt), Hour(24 * (daily_panchaanga.day_length_based_periods.raahu.jd_end - jd)).toString(format=panchaanga.fmt)) yama = '%s--%s' % ( Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_start - jd)).toString(format=panchaanga.fmt), Hour(24 * (daily_panchaanga.day_length_based_periods.yama.jd_end - jd)).toString(format=panchaanga.fmt)) if daily_panchaanga.solar_sidereal_date_sunset.month_transition is None: month_end_str = '' else: _m = daily_panchaangas[d - 1].solar_sidereal_date_sunset.month if daily_panchaanga.solar_sidereal_date_sunset.month_transition >= daily_panchaangas[ d + 1].jd_sunrise: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], Hour(24 * (daily_panchaanga.solar_sidereal_date_sunset. month_transition - daily_panchaangas[d + 1].julian_day_start)).toString( format=panchaanga.fmt)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][_m], Hour(24 * (daily_panchaanga.solar_sidereal_date_sunset. month_transition - daily_panchaanga.julian_day_start) ).toString(format=panchaanga.fmt)) month_data = '\\sunmonth{%s}{%d}{%s}' % ( jyotisha.names.NAMES['RASHI_NAMES'][scripts[0]][ daily_panchaanga.solar_sidereal_date_sunset.month], daily_panchaanga.solar_sidereal_date_sunset.day, month_end_str) if currWeek < 6: month_text += '\n' + ( '\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday()], dt, month_data, jyotisha.names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise, jyotisha.names.NAMES, scripts[0]))) month_text += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) month_text += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) month_text += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! month_text += '\n' + ('{%s}' % '\\eventsep '.join([ f.tex_code(scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values()) ])) else: if daily_panchaanga.date.get_weekday() == 0: W6D1 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday( )], dt, month_data, jyotisha.names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise, jyotisha.names.NAMES, scripts[0]))) W6D1 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) W6D1 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) W6D1 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D1 += '\n' + ('{%s}' % '\\eventsep '.join([ f.tex_code(scripts=scripts, timezone=Timezone(panchaanga.city.timezone), fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values()) ])) elif daily_panchaanga.date.get_weekday() == 1: W6D2 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[daily_panchaanga.date.get_weekday( )], dt, month_data, jyotisha.names.get_chandra_masa( daily_panchaanga.lunar_month_sunrise, jyotisha.names.NAMES, scripts[0]))) W6D2 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, saangava)) W6D2 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatra_data_str, yoga_data_str, karana_data_str)) W6D2 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D2 += '\n' + ('{%s}' % '\\eventsep '.join([ f.tex_code(scripts=scripts, timezone=panchaanga.city.timezone, fest_details_dict=fest_details_dict) for f in sorted(daily_panchaanga.festival_id_to_instance.values()) ])) else: # Cannot be here, since we cannot have more than 2 days in week 6 of any month! pass if daily_panchaanga.date.get_weekday() == 6: month_text += '\n' + ("\\\\ \\hline %%END OF WEEK %d" % (currWeek)) currWeek += 1 else: if currWeek < 6: month_text += '\n' + ("&") if m == 12 and dt == 31: break month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) if currWeek < 6: for i in range(daily_panchaanga.date.get_weekday() + 1, 6): print("{} &") if daily_panchaanga.date.get_weekday() != 6: print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') print(template_lines[-2][:-1]) print(template_lines[-1][:-1])
def writeMonthlyTeX(panchangam, template_file): """Write out the panchangam TeX using a specified template """ day_colours = {0: 'blue', 1: 'blue', 2: 'blue', 3: 'blue', 4: 'blue', 5: 'blue', 6: 'blue'} month = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'} MON = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} WDAY = {0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'} template_lines = template_file.readlines() for i in range(0, len(template_lines) - 3): print(template_lines[i][:-1]) samvatsara_id = (panchangam.year - 1568) % 60 + 1 # distance from prabhava samvatsara_names = '%s–%s' % (jyotisha.panchangam.temporal.NAMES['SAMVATSARA_NAMES'][panchangam.script][samvatsara_id], jyotisha.panchangam.temporal.NAMES['SAMVATSARA_NAMES'][panchangam.script][(samvatsara_id % 60) + 1]) print('\\mbox{}') print('{\\sffamily\\fontsize{60}{25}\\selectfont %d\\\\[0.5cm]}' % panchangam.year) print('\\mbox{\\font\\x="Siddhanta:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names) print('\\mbox{\\font\\x="Siddhanta:script=deva" at 32 pt\\x %s } %%' % jyotisha.custom_transliteration.tr('kali', panchangam.script)) print('{\\sffamily\\fontsize{32}{25}\\selectfont %d–%d\\\\[0.5cm]}' % (panchangam.year + 3100, panchangam.year + 3101)) print('{\\sffamily\\fontsize{48}{25}\\selectfont \\uppercase{%s}\\\\[0.2cm]}' % panchangam.city.name) print('{\\sffamily\\fontsize{16}{25}\\selectfont {%s}\\\\[0.5cm]}' % jyotisha.custom_transliteration.print_lat_lon(panchangam.city.latitude, panchangam.city.longitude)) print('\\hrule') print('\\newpage') print('\\centering') print('\\centerline{\\LARGE {{%s}}}' % jyotisha.custom_transliteration.tr('mAsAntara-vizESAH', panchangam.script)) print('\\begin{multicols*}{3}') print('\\TrickSupertabularIntoMulticols') print('\\begin{supertabular}' + '{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}c>{\\hangindent=2ex}p{8cm}}') panchangam.get_kaalas() mlast = 1 for d in range(1, jyotisha.panchangam.temporal.MAX_SZ - 1): [y, m, dt, t] = swe.revjul(panchangam.jd_start_utc + d - 1) # checking @ 6am local - can we do any better? local_time = tz(panchangam.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = panchangam.jd_start_utc - tz_off / 24.0 + d - 1 if len(panchangam.festivals[d]) != 0: if m != mlast: mlast = m print('\\\\') print('%s & %s & %s & {\\raggedright %s} \\\\' % (MON[m], dt, WDAY[panchangam.weekday[d]], '\\\\'.join([jyotisha.custom_transliteration.tr(f, panchangam.script).replace('★', '$^\\star$') for f in sorted(set(panchangam.festivals[d]))]))) if m == 12 and dt == 31: break print('\\end{supertabular}') print('\\end{multicols*}') print('\\renewcommand{\\tamil}[1]{%') print('{\\fontspec[Scale=0.9,FakeStretch=0.9]{Noto Sans Tamil}\\fontsize{7}{12}\\selectfont #1}}') # print('\\clearpage') month_text = '' W6D1 = W6D2 = '' for d in range(1, jyotisha.panchangam.temporal.MAX_SZ - 1): [y, m, dt, t] = swe.revjul(panchangam.jd_start_utc + d - 1) # checking @ 6am local - can we do any better? local_time = tz(panchangam.city.timezone).localize(datetime(y, m, dt, 6, 0, 0)) # compute offset from UTC in hours tz_off = (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).seconds) / 3600.0 # What is the jd at 00:00 local time today? jd = panchangam.jd_midnight[d] if dt == 1: if m > 1: month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) month_text = W6D1 = W6D2 = '' if currWeek < 6: if panchangam.weekday[d] != 0: # Space till Sunday for i in range(panchangam.weekday[d], 6): print("\\mbox{} & %% %d" % currWeek) print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') currWeek = 1 # Begin tabular print('\\begin{tabular}{|c|c|c|c|c|c|c|}') print('\\multicolumn{7}{c}{\\Large \\bfseries \\sffamily %s %s}\\\\[3mm]' % ( month[m], y)) print('\\hline') WDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] print(' & '.join(['\\textbf{\\textsf{%s}}' % _day for _day in WDAY_NAMES]) + ' \\\\ \\hline') # Blanks for previous weekdays for i in range(0, panchangam.weekday[d]): if i == 0: month_text += '\n' + ("{W6D1} &") elif i == 1: month_text += '\n' + ("{W6D2} &") else: month_text += '\n' + ("{} &") tithi_data_str = '' for tithi_ID, tithi_end_jd in panchangam.tithi_data[d]: # if tithi_data_str != '': # tithi_data_str += '\\hspace{2ex}' tithi = '\\moon[scale=0.6]{%d}\\hspace{2pt}' % (tithi_ID) + \ jyotisha.panchangam.temporal.NAMES['TITHI_NAMES'][panchangam.script][tithi_ID] if tithi_end_jd is None: tithi_data_str = '%s\\mbox{%s\\To{}%s}' % \ (tithi_data_str, tithi, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: tithi_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (tithi_data_str, tithi, jyotisha.panchangam.temporal.Time(24 * (tithi_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') nakshatram_data_str = '' for nakshatram_ID, nakshatram_end_jd in panchangam.nakshatram_data[d]: # if nakshatram_data_str != '': # nakshatram_data_str += '\\hspace{2ex}' nakshatram = jyotisha.panchangam.temporal.NAMES['NAKSHATRAM_NAMES'][panchangam.script][nakshatram_ID] if nakshatram_end_jd is None: nakshatram_data_str = '%s\\mbox{%s\\To{}%s}' % \ (nakshatram_data_str, nakshatram, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: nakshatram_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (nakshatram_data_str, nakshatram, jyotisha.panchangam.temporal.Time(24 * (nakshatram_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') yogam_data_str = '' for yogam_ID, yogam_end_jd in panchangam.yogam_data[d]: # if yogam_data_str != '': # yogam_data_str += '\\hspace{2ex}' yogam = jyotisha.panchangam.temporal.NAMES['YOGAM_NAMES'][panchangam.script][yogam_ID] if yogam_end_jd is None: yogam_data_str = '%s\\mbox{%s\\To{}%s}' % \ (yogam_data_str, yogam, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: yogam_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (yogam_data_str, yogam, jyotisha.panchangam.temporal.Time(24 * (yogam_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') karanam_data_str = '' for numKaranam, (karanam_ID, karanam_end_jd) in enumerate(panchangam.karanam_data[d]): # if numKaranam == 1: # karanam_data_str += '\\hspace{2ex}' if numKaranam == 2: karanam_data_str = karanam_data_str + '\\\\' karanam = jyotisha.panchangam.temporal.NAMES['KARANAM_NAMES'][panchangam.script][karanam_ID] if karanam_end_jd is None: karanam_data_str = '%s\\mbox{%s\\To{}%s}' % \ (karanam_data_str, karanam, jyotisha.custom_transliteration.tr('ahOrAtram', panchangam.script)) else: karanam_data_str = '%s\\mbox{%s\\To{}\\textsf{%s%s}}' % \ (karanam_data_str, karanam, jyotisha.panchangam.temporal.Time(24 * (karanam_end_jd - jd)).toString(format=panchangam.fmt), '\\hspace{2ex}') sunrise = jyotisha.panchangam.temporal.Time(24 * (panchangam.jd_sunrise[d] - jd)).toString(format=panchangam.fmt) sunset = jyotisha.panchangam.temporal.Time(24 * (panchangam.jd_sunset[d] - jd)).toString(format=panchangam.fmt) sangava = jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['saGgava'][0] - jd)).toString(format=panchangam.fmt) rahu = '%s--%s' % ( jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['rahu'][0] - jd)).toString(format=panchangam.fmt), jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['rahu'][1] - jd)).toString(format=panchangam.fmt)) yama = '%s--%s' % ( jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['yama'][0] - jd)).toString(format=panchangam.fmt), jyotisha.panchangam.temporal.Time(24 * (panchangam.kaalas[d]['yama'][1] - jd)).toString(format=panchangam.fmt)) if panchangam.solar_month_end_time[d] is None: month_end_str = '' else: _m = panchangam.solar_month[d - 1] if panchangam.solar_month_end_time[d] >= panchangam.jd_sunrise[d + 1]: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % (jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][panchangam.script][_m], jyotisha.panchangam.temporal.Time(24 * (panchangam.solar_month_end_time[d] - panchangam.jd_midnight[d + 1])).toString(format=panchangam.fmt)) else: month_end_str = '\\mbox{%s{\\tiny\\RIGHTarrow}\\textsf{%s}}' % (jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][panchangam.script][_m], jyotisha.panchangam.temporal.Time(24 * (panchangam.solar_month_end_time[d] - panchangam.jd_midnight[d])).toString(format=panchangam.fmt)) month_data = '\\sunmonth{%s}{%d}{%s}' % (jyotisha.panchangam.temporal.NAMES['RASHI_NAMES'][panchangam.script][panchangam.solar_month[d]], panchangam.solar_month_day[d], month_end_str) if currWeek < 6: month_text += '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[panchangam.weekday[d]], dt, month_data, jyotisha.panchangam.temporal.get_chandra_masa(panchangam.lunar_month[d], jyotisha.panchangam.temporal.NAMES, panchangam.script))) month_text += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, sangava)) month_text += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatram_data_str, yogam_data_str, karanam_data_str)) month_text += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! month_text += '\n' + ('{%s}' % '\\eventsep '.join( [jyotisha.custom_transliteration.tr(f, panchangam.script).replace('★', '$^\\star$') for f in sorted(set(panchangam.festivals[d]))])) else: if panchangam.weekday[d] == 0: W6D1 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[panchangam.weekday[d]], dt, month_data, jyotisha.panchangam.temporal.get_chandra_masa(panchangam.lunar_month[d], jyotisha.panchangam.temporal.NAMES, panchangam.script))) W6D1 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, sangava)) W6D1 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatram_data_str, yogam_data_str, karanam_data_str)) W6D1 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D1 += '\n' + ('{%s}' % '\\eventsep '.join( [jyotisha.custom_transliteration.tr(f, panchangam.script) for f in sorted(set(panchangam.festivals[d]))])) elif panchangam.weekday[d] == 1: W6D2 = '\n' + ('\\caldata{\\textcolor{%s}{%s}}{%s{%s}}%%' % (day_colours[panchangam.weekday[d]], dt, month_data, jyotisha.panchangam.temporal.get_chandra_masa(panchangam.lunar_month[d], jyotisha.panchangam.temporal.NAMES, panchangam.script))) W6D2 += '\n' + ('{\\sundata{%s}{%s}{%s}}%%' % (sunrise, sunset, sangava)) W6D2 += '\n' + ('{\\tnyk{%s}%%\n{%s}%%\n{%s}%%\n{%s}}%%' % (tithi_data_str, nakshatram_data_str, yogam_data_str, karanam_data_str)) W6D2 += '\n' + ('{\\rahuyama{%s}{%s}}%%' % (rahu, yama)) # Using set as an ugly workaround since we may have sometimes assigned the same # festival to the same day again! W6D2 += '\n' + ('{%s}' % '\\eventsep '.join( [jyotisha.custom_transliteration.tr(f, panchangam.script) for f in sorted(set(panchangam.festivals[d]))])) else: # Cannot be here, since we cannot have more than 2 days in week 6 of any month! pass if panchangam.weekday[d] == 6: month_text += '\n' + ("\\\\ \\hline %%END OF WEEK %d" % (currWeek)) currWeek += 1 else: if currWeek < 6: month_text += '\n' + ("&") if m == 12 and dt == 31: break month_text = month_text.replace('W6D1', W6D1) month_text = month_text.replace('W6D2', W6D2) print(month_text) if currWeek < 6: for i in range(panchangam.weekday[d] + 1, 6): print("{} &") if panchangam.weekday[d] != 6: print("\\\\ \\hline") print('\\end{tabular}') print('\n\n') print(template_lines[-2][:-1]) print(template_lines[-1][:-1])
def __init__(self, *args, **kwargs): super(WordDeltaCounter, self).__init__(*args, **kwargs) now = datetime.utcnow() now = tz('UTC').localize(now) self.end_time = now - (timedelta(microseconds=now.microsecond)) self.alert = False
async def get_weather(weather): """ For .weather command, gets the current weather of a city. """ if not OWM_API: await weather.edit( "`Get an API key from` https://openweathermap.org/ `first.`") return APPID = OWM_API if not weather.pattern_match.group(1): CITY = DEFCITY if not CITY: await weather.edit("`Please specify a city or set one as default.`" ) return else: CITY = weather.pattern_match.group(1) timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: await weather.edit("`Invalid country.`") return CITY = newcity[0].strip() + "," + countrycode.strip() url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}" request = requests.get(url) result = json.loads(request.text) if request.status_code != 200: await weather.edit(f"`Invalid country.`") return cityname = result["name"] curtemp = result["main"]["temp"] humidity = result["main"]["humidity"] min_temp = result["main"]["temp_min"] max_temp = result["main"]["temp_max"] pressure = result["main"]["pressure"] feel = result["main"]["feels_like"] desc = result["weather"][0] desc = desc["main"] country = result["sys"]["country"] sunrise = result["sys"]["sunrise"] sunset = result["sys"]["sunset"] wind = result["wind"]["speed"] winddir = result["wind"]["deg"] cloud = result["clouds"]["all"] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", # "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = 360 / len(dirs) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") return xx await weather.edit( f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Human Feeling** `{celsius(feel)}°C | {fahrenheit(feel)}°F`\n" + f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Humidity:** `{humidity}%`\n" + f"**Pressure** `{pressure} hPa`\n" + f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Cloud:** `{cloud} %`\n" + f"**Sunrise:** `{sun(sunrise)}`\n" + f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`\n")
def update(self): self.data = self.model.objects(match_date__gte=dt.now(tz('UTC')) + timedelta(days=1)) print('Znaleziono {} meczy w tym tygodniu'.format(len(self.data)))
async def get_weather(weather): """ For .weather command, gets the current weather of a city. """ if not OWM_API: return await weather.edit( f"Dapatkan kunci API dahulu dari [OpenWeatherMap](https://openweathermap.org/)" ) APPID = OWM_API if not weather.pattern_match.group(1): CITY = DEFCITY if not CITY: return await weather.edit( "`Harap tentukan kota atau tetapkan sebagai default menggunakan variabel config` **WEATHER_DEFCITY**." ) else: CITY = weather.pattern_match.group(1) timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: return await weather.edit("`Negara tidak valid.`") CITY = newcity[0].strip() + "," + countrycode.strip() url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}" request = get(url) result = json.loads(request.text) if request.status_code != 200: return await weather.edit(f"`Negara tidak valid!`") cityname = result["name"] curtemp = result["main"]["temp"] humidity = result["main"]["humidity"] min_temp = result["main"]["temp_min"] max_temp = result["main"]["temp_max"] desc = result["weather"][0] desc = desc["main"] country = result["sys"]["country"] sunrise = result["sys"]["sunrise"] sunset = result["sys"]["sunset"] wind = result["wind"]["speed"] winddir = result["wind"]["deg"] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = 360 / len(dirs) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") return xx await weather.edit( f"**Suhu** : `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Suhu Min.** : `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Suhu Mak.** : `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Kelembaban** : `{humidity}%`\n" + f"**Angin** : `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Terbit** : `{sun(sunrise)}`\n" + f"**Terbenam** : `{sun(sunset)}`\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`" )
async def time_func(tdata): """For .time command, return the time of 1. The country passed as an argument, 2. The default userbot country(set it by using .settime), 3. The server where the userbot runs. """ con = tdata.pattern_match.group(1).title() tz_num = tdata.pattern_match.group(2) t_form = "%H:%M" d_form = "%d/%m/%y - %A" c_name = "" if len(con) > 4: try: c_name = c_n[con] except KeyError: c_name = con timezones = await get_tz(con) elif COUNTRY: c_name = COUNTRY tz_num = TZ_NUMBER timezones = await get_tz(COUNTRY) else: await edit_or_reply( tdata, f"`الـوقت الان` **{dt.now().strftime(t_form)}**` لـتاريـخ `**{dt.now().strftime(d_form)}** الـيوم", ) return if not timezones: await edit_or_reply(tdata, "البـلد غيـر مـوجود 𖠕") return if len(timezones) == 1: time_zone = timezones[0] elif len(timezones) > 1: if tz_num: tz_num = int(tz_num) time_zone = timezones[tz_num - 1] else: return_str = f"`{c_name} لها مناطق زمنية متعددة:`\n\n" for i, item in enumerate(timezones): return_str += f"`{i+1}. {item}`\n" return_str += "\n`اختر واحدة عن طريق كتابة الرقم " return_str += "في الأمر.`\n" return_str += f"`مثال: .ctime {c_name} 2`" await edit_or_reply(tdata, return_str) return dtnow1 = dt.now(tz(time_zone)).strftime(t_form) dtnow2 = dt.now(tz(time_zone)).strftime(d_form) if c_name != COUNTRY: await edit_or_reply( tdata, f"`الـوقت الان` **{dtnow1}**` فـي `**{dtnow2}** `فـي {c_name} ({time_zone} timezone).`", ) return if COUNTRY: await edit_or_reply( tdata, f"`It's` **{dtnow1}**` on `**{dtnow2}** `here, in {COUNTRY}" f"({time_zone} timezone).`", ) return
def befriend(request): """ POSTs are used only when sending an initial friend request. GETs are used when accepting a request or sending an initial request. """ context = RequestContext(request) user = get_user(request.user) if user.user_type == "student": if request.method == "GET": email = request.GET["email"] friend = Student.objects.get(email=email) message = "Something went <strong>horribly wrong.</strong>" # The student is accepting a friend request try: friendship = Friendship.objects.get(requesting_student=friend, requested_student=user) if friendship.accepted: message = "You're <strong>already friends!</strong>" return HttpResponse( json.dumps({"status": "fail", "message": message}), content_type="application/json" ) else: friendship.accepted = True friendship.save() # Increase student sights. friend.sight.add(user.society) user.sight.add(friend.society) message = "<strong>Friendship succeeded!</strong> Please refresh the page." return HttpResponse( json.dumps({"status": "success", "message": message}), content_type="application/json" ) # The student is sending an initial friend request except: if user != friend: if friend in Student.objects.filter(society=user.society): message = "You can't add a <strong>fellow organization member</strong> to your friends list." else: if friend not in user.get_associated_students(): friendship = Friendship( requesting_student=user, requested_student=friend, time_sent=timezone.now().astimezone(tz("US/Central")), ) friendship.save() message = ( "<strong>Friend request sent!</strong><br>Please refresh the page or add more friends." ) return HttpResponse( json.dumps({"status": "success", "message": message}), content_type="application/json" ) else: message = "<strong>You can't add yourself to your friends list!</strong>" return HttpResponse(json.dumps({"status": "fail", "message": message}), content_type="application/json") # Create the intial friend request. if request.method == "POST": message = "Something went <strong>horribly wrong.</strong>" try: email = request.POST["email"] friend = Student.objects.get(email=email) except: return HttpResponse(json.dumps({"status": "fail", "message": message}), content_type="application/json") if friend: if friend != user: if friend in Student.objects.filter(society=user.society): message = "You can't add a <strong>fellow organization member</strong> to your friends list." return HttpResponse( json.dumps({"status": "fail", "message": message}), content_type="application/json" ) else: if friend not in user.get_associated_students(): friendship = Friendship( requesting_student=user, requested_student=friend, time_sent=timezone.now().astimezone(tz("US/Central")), ) friendship.save() message = ( "<strong>Friend request sent!</strong> Please refresh the page or add more friends." ) return HttpResponse( json.dumps({"status": "success", "message": message}), content_type="application/json" ) else: message = "<strong>You can't add yourself to your friends list!</strong>" return HttpResponse(json.dumps({"status": "fail", "message": message}), content_type="application/json") message = "Something went <strong>horribly wrong.</strong>" return HttpResponse(json.dumps({"status": "fail", "message": message}), content_type="application/json")
async def get_weather(weather): if not OWM_API: return await weather.edit( "`Get an API key from` https://openweathermap.org/ `first.`") APPID = OWM_API if not weather.pattern_match.group(1): CITY = DEFCITY if not CITY: return await weather.edit( "`Please specify a city or set one as default using the WEATHER_DEFCITY config variable.`" ) else: CITY = weather.pattern_match.group(1) timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: return await weather.edit("`Invalid country.`") CITY = newcity[0].strip() + "," + countrycode.strip() url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}" request = get(url) result = json.loads(request.text) if request.status_code != 200: return await weather.edit("`Invalid country.`") cityname = result["name"] curtemp = result["main"]["temp"] humidity = result["main"]["humidity"] min_temp = result["main"]["temp_min"] max_temp = result["main"]["temp_max"] desc = result["weather"][0] desc = desc["main"] country = result["sys"]["country"] sunrise = result["sys"]["sunrise"] sunset = result["sys"]["sunset"] wind = result["wind"]["speed"] winddir = result["wind"]["deg"] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = 360 / len(dirs) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): return datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") await weather.edit( f"**Suhu🌡️:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Min. Suhu❄️.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Maks. Suhu🔆.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Kelembaban🍄:** `{humidity}%`\n" + f"**Angin🎏:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Matahari terbit🌄:** `{sun(sunrise)}`\n" + f"**Matahari terbenam🌅:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
def process_alerts(product, now = datetime.now(), old = _PAST_TIMEFRAME, new = None, debug = False, debug_file = sys.stdout, send_email = True, address = None): delta = defaultdict(WordDeltaCounter) # Resolve date if not isinstance(now, datetime) and isinstance(now, date): now = datetime.combine(now, time(0,0,0)) #if not isinstance(now, datetime): # I don't feel like checking this. It's not a likely exception. #raise Exception('"now" must me of type datetime or date.') now_string = now.strftime('%Y-%m-%d %H:%M:%S') now = tz('US/Pacific').localize(now) # Product related vars if product.lower() == 'desktop': new = new if new else _DESKTOP_TIMEFRAME where_product = ('product = "firefox"' + '\nAND LEFT(platform,7) IN("Windows","OS X","Linux")') flavor = 'word-based' subject = 'Desktop Input Alert' address = address if address else _DESKTOP_EMAIL elif product.lower() == 'android': new = new if new else _ANDROID_TIMEFRAME where_product = 'product = "Firefox for Android"' flavor = 'android-word-based' subject = 'Android Input Alert' address = address if address else _ANDROID_EMAIL else: raise Exception('product must be "desktop" or "android".') # Resolve debug info if debug and not isinstance(debug_file, file): warn('Debug file should be type <file>, outputting to stdout.') debug_file = sys.stdout is_print = not debug or debug_file != sys.stdout if is_print: print 'Generating %s for %s' % (subject, now_string) # Retrieve old timeframe where = (where_product + '\nAND created > DATE_SUB(:now, INTERVAL :old WEEK)' + '\nAND created < DATE_SUB(:now, INTERVAL :new HOUR)') base_total = _aggregate(where, delta, True, now_string, old, new) # Retrieve new timeframe after_comments = {} where = (where_product + '\nAND created > DATE_SUB(:now, INTERVAL :new HOUR)' + '\nAND created < :now') after_total = _aggregate(where, delta, False, now_string, old, new, comments = after_comments) if (after_total < _MIN_DENOM_THRESHOLD or base_total < _MIN_DENOM_THRESHOLD): warn('NOT ENOUGH FEEDBACK %d before and %d after' % (base_total, after_total)) return #Generate alerts alerted_feedback = {} # Determine if we should alert for each word and add the alert feedback to a # dict for spam detection for (k,v) in delta.iteritems(): v.set_thresholds(diff_pct = _DIFF_PCT_MIN, diff_abs = _DIFF_ABS_MIN) v.set_potentials(base = base_total, after = after_total) v.end_time = tz('UTC').normalize(now) if (v.is_significant and v.severity >= _ALERT_SEV_MIN and v.after.count >= _MIN_COUNT_THRESHOLD): for link_item in v.after.link_list: alerted_feedback[link_item[0]] = link_item[1] v.alert = True # Find spam test_spam = { x: after_comments[x] for x in alerted_feedback.keys() } spam = SpamDetector().check_entries_for_spam(test_spam) # Remove spam after_total -= len(spam.keys()) for (k,v) in delta.iteritems(): if (v.alert): for s in spam.keys(): if s in v.after.link_list: v.after.remove(link = (s, alerted_feedback[s])) v.alert = False # Reprocess alerts while removing spam has_alerts = False email_list = set() for (k,v) in delta.iteritems(): v.set_potentials(base = base_total, after = after_total) if v.is_significant and v.after.count >= _MIN_COUNT_THRESHOLD: if v.severity >= _ALERT_SEV_MIN: if is_print: print 'Emitting alert for %s' % v.after.sorted_metadata[0] v.emit(timeframe = new, flavor = flavor, debug = debug, debug_file = debug_file) has_alerts = True if send_email and v.severity >= _EMAIL_SEV_MIN: email_list.add(v) if not has_alerts: # This is super fishy but technically valid usecase. # Might alert on this in the future if is_print: print 'No alerts today' return # Now send an email, looking up each piece of feedback. if email_list: _email_results(email_list, subject, address, after_comments)
def enlighten_datetime(obj): """Make a Dexcom object timezone-aware with utc_time and display_time attributes.""" obj.display_time = parse_datetime(obj.user_time).replace(tzinfo=DexcomTZ(obj.display_offset)).isoformat() current_tz = tz(obj.timezone) obj.utc_time = current_tz.localize(parse_datetime(obj.user_time)).astimezone(pytz.utc).isoformat()
def make_auctions_app(global_conf, redis_url='redis://localhost:9002/1', redis_password='', redis_database='', sentinel_cluster_name='', sentinels='', external_couch_url='http://localhost:5000/auction', internal_couch_url='http://localhost:9000/', proxy_internal_couch_url='http://localhost:9000/', auctions_db='database', hash_secret_key='', timezone='Europe/Kiev', preferred_url_scheme='http', debug=False, auto_build=False, event_source_connection_limit=1000, limit_replications_progress=99, limit_replications_func='any' ): """ [app:main] use = egg:openprocurement.auction#auctions_server redis_url = redis://:passwod@localhost:1111/0 external_couch_url = http://localhost:1111/auction internal_couch_url = http://localhost:9011/ auctions_db = auction timezone = Europe/Kiev """ auctions_server = components.queryUtility(IAuctionsServer) auctions_server.proxy_connection_pool = ConnectionPool( factory=Connection, max_size=20, backend='gevent' ) auctions_server.proxy_mappings = Memoizer({}) auctions_server.event_sources_pool = deque([]) auctions_server.config['PREFERRED_URL_SCHEME'] = preferred_url_scheme auctions_server.config['limit_replications_progress'] = float( limit_replications_progress ) auctions_server.config['limit_replications_func'] = limit_replications_func auctions_server.config['REDIS'] = { 'redis': redis_url, 'redis_password': redis_password, 'redis_database': redis_database, 'sentinel_cluster_name': sentinel_cluster_name, 'sentinel': loads(sentinels) } auctions_server.config['event_source_connection_limit'] = int( event_source_connection_limit ) auctions_server.config['EXT_COUCH_DB'] = urljoin( external_couch_url, auctions_db ) auctions_server.add_url_rule( '/' + auctions_db + '/<path:path>', 'couch_server_proxy', couch_server_proxy, methods=['GET']) auctions_server.add_url_rule( '/' + auctions_db + '/', 'couch_server_proxy', couch_server_proxy, methods=['GET'], defaults={'path': ''}) auctions_server.add_url_rule( '/' + auctions_db + '_secured/<path:path>', 'auth_couch_server_proxy', auth_couch_server_proxy, methods=['GET']) auctions_server.add_url_rule( '/' + auctions_db + '_secured/', 'auth_couch_server_proxy', auth_couch_server_proxy, methods=['GET'], defaults={'path': ''}) auctions_server.config['INT_COUCH_URL'] = internal_couch_url auctions_server.config['PROXY_COUCH_URL'] = proxy_internal_couch_url auctions_server.config['COUCH_DB'] = auctions_db auctions_server.config['TIMEZONE'] = tz(timezone) auctions_server.couch_server = Server( auctions_server.config.get('INT_COUCH_URL'), session=Session(retry_delays=range(10)) ) if auctions_server.config['COUCH_DB'] not in auctions_server.couch_server: auctions_server.couch_server.create(auctions_server.config['COUCH_DB']) auctions_server.db = auctions_server.\ couch_server[auctions_server.config['COUCH_DB']] auctions_server.config['HASH_SECRET_KEY'] = hash_secret_key sync_design(auctions_server.db) for entry_point in iter_entry_points(PKG_NAMESPACE): plugin = entry_point.load() plugin(components) return auctions_server
def make_auctions_app(global_conf, redis_url='redis://localhost:7777/0', external_couch_url='http://localhost:5000/auction', internal_couch_url='http://localhost:9000/', proxy_internal_couch_url='http://localhost:9000/', auctions_db='auctions', hash_secret_key='', timezone='Europe/Kiev', preferred_url_scheme='http', debug=False, auto_build=False, event_source_connection_limit=1000 ): """ [app:main] use = egg:openprocurement.auction#auctions_server redis_url = redis://:passwod@localhost:1111/0 external_couch_url = http://localhost:1111/auction internal_couch_url = http://localhost:9011/ auctions_db = auction timezone = Europe/Kiev """ auctions_server.proxy_connection_pool = ConnectionPool( factory=Connection, max_size=20, backend="gevent" ) auctions_server.proxy_mappings = Memoizer({}) auctions_server.event_sources_pool = deque([]) auctions_server.config['PREFERRED_URL_SCHEME'] = preferred_url_scheme auctions_server.config['REDIS_URL'] = redis_url auctions_server.config['event_source_connection_limit'] = int(event_source_connection_limit) auctions_server.config['EXT_COUCH_DB'] = urljoin( external_couch_url, auctions_db ) auctions_server.add_url_rule( '/' + auctions_db + '/<path:path>', 'couch_server_proxy', couch_server_proxy, methods=['GET']) auctions_server.add_url_rule( '/' + auctions_db + '/', 'couch_server_proxy', couch_server_proxy, methods=['GET'], defaults={'path': ''}) auctions_server.add_url_rule( '/' + auctions_db + '_secured/<path:path>', 'auth_couch_server_proxy', auth_couch_server_proxy, methods=['GET']) auctions_server.add_url_rule( '/' + auctions_db + '_secured/', 'auth_couch_server_proxy', auth_couch_server_proxy, methods=['GET'], defaults={'path': ''}) auctions_server.config['INT_COUCH_URL'] = internal_couch_url auctions_server.config['PROXY_COUCH_URL'] = proxy_internal_couch_url auctions_server.config['COUCH_DB'] = auctions_db auctions_server.config['TIMEZONE'] = tz(timezone) auctions_server.redis = Redis(auctions_server) auctions_server.db = Database( urljoin(auctions_server.config.get('INT_COUCH_URL'), auctions_server.config['COUCH_DB']), session=Session(retry_delays=range(10)) ) auctions_server.config['HASH_SECRET_KEY'] = hash_secret_key sync_design(auctions_server.db) auctions_server.config['ASSETS_DEBUG'] = True if debug else False assets.auto_build = True if auto_build else False return auctions_server
def happening(self): current_time = timezone.now().astimezone(tz('US/Central')) return self.time_begin < current_time and self.time_end > current_time
def update(self): self.data = self.model.objects(end_date__gte=dt.now(tz('UTC')), end_date__lte=dt.now(tz('UTC')) + timedelta(minutes=110)) print('Znaleziono {} trwających meczy'.format(len(self.data)))
import pytest from datetime import datetime from pytz import timezone as tz from assible.module_utils.common.text.converters import _json_encode_fallback @pytest.mark.parametrize('test_input,expected', [ (set([1]), [1]), (datetime(2019, 5, 14, 13, 39, 38, 569047), '2019-05-14T13:39:38.569047'), (datetime(2019, 5, 14, 13, 47, 16, 923866), '2019-05-14T13:47:16.923866'), (datetime(2019, 6, 15, 14, 45, tzinfo=tz('UTC')), '2019-06-15T14:45:00+00:00'), (datetime(2019, 6, 15, 14, 45, tzinfo=tz('Europe/Helsinki')), '2019-06-15T14:45:00+01:40'), ]) def test_json_encode_fallback(test_input, expected): """ Test for passing expected objects to _json_encode_fallback(). """ assert _json_encode_fallback(test_input) == expected @pytest.mark.parametrize('test_input', [ 1, 1.1, u'string', b'string',
def get_time_pst(): date = dt.now(tz=pz.utc) date = date.astimezone(tz('US/Pacific')) return date.strftime('%I:%M%p').lstrip('0')
def __init__(self, timezone): if not timezone: raise NoTimezoneSet self._timezone = tz(timezone) self._datetime = datetime.now(self._timezone)
async def time_func(tdata): """ For .time command, return the time of 1. The country passed as an argument, 2. The default userbot country(set it by using .settime), 3. The server where the userbot runs. """ con = tdata.pattern_match.group(1).title() tz_num = tdata.pattern_match.group(2) t_form = "%H:%M" saved_props = await get_time() if is_mongo_alive() else None saved_country = saved_props['timec'] if saved_props else None saved_tz_num = saved_props['timezone'] if saved_props else None if con: try: c_name = c_n[con] except KeyError: c_name = con timezones = await get_tz(con) elif saved_country: c_name = saved_country tz_num = saved_tz_num timezones = await get_tz(saved_country) else: await tdata.edit(f"`It's` **{dt.now().strftime(t_form)}** `here.`") return if not timezones: await tdata.edit(INV_CON) return if len(timezones) == 1: time_zone = timezones[0] elif len(timezones) > 1: if tz_num: tz_num = int(tz_num) if len(timezones) >= tz_num: time_zone = timezones[tz_num - 1] else: await tdata.edit(TZ_NOT_FOUND) return else: return_str = f"{c_name} has multiple timezones:\n" for i, item in enumerate(timezones): return_str += f"{i+1}. {item}\n" return_str += "Choose one by typing the number " return_str += "in the command. Example:\n" return_str += f".time {c_name} 2" await tdata.edit(return_str) return dtnow = dt.now(tz(time_zone)).strftime(t_form) if not con and saved_country: await tdata.edit(f"`It's` **{dtnow}** `here, in {saved_country}" f"({time_zone} timezone).`") return await tdata.edit( f"`It's` **{dtnow}** `in {c_name}({time_zone} timezone).`")
async def get_weather(weather): """ .weather komutu bir bölgenin hava durumunu OpenWeatherMap üzerinden alır. """ if not OWM_API: await weather.edit(LANG['NEED_API_KEY']) return APPID = OWM_API if not weather.pattern_match.group(1): CITY = DEFCITY if not CITY: await weather.edit(LANG['NO_CITY']) return else: CITY = weather.pattern_match.group(1) timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f'{country}'] except KeyError: await weather.edit(LANG['INVALID_COUNTRY']) return CITY = newcity[0].strip() + "," + countrycode.strip() url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}' request = get(url) result = json.loads(request.text) if request.status_code != 200: await weather.edit(LANG['INVALID_COUNTRY']) return cityname = result['name'] curtemp = result['main']['temp'] humidity = result['main']['humidity'] min_temp = result['main']['temp_min'] max_temp = result['main']['temp_max'] desc = result['weather'][0] desc = desc['main'] country = result['sys']['country'] sunrise = result['sys']['sunrise'] sunset = result['sys']['sunset'] wind = result['wind']['speed'] winddir = result['wind']['deg'] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = (360 / len(dirs)) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") return xx await weather.edit( f"**{LANG['TEMP']}:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**{LANG['MIN_TEMP']}:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**{LANG['MAX_TEMP']}:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**{LANG['HUMIDITY']}:** `{humidity}%`\n" + f"**{LANG['WIND_SPEED']}:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**{LANG['SUNRISE']}:** `{sun(sunrise)}`\n" + f"**{LANG['SUNSET']}:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
async def weather_get(message: Message): """ this function can get weather info """ OWM_API = Config.OPEN_WEATHER_MAP if not OWM_API: await message.edit( "<code>Oops!!get the API from</code> " "<a href='https://openweathermap.org'>HERE</a> " "<code>& add it to Heroku config vars</code> (<code>OPEN_WEATHER_MAP</code>)", disable_web_page_preview=True, parse_mode="html", del_in=0) return APPID = OWM_API if not message.input_str: CITY = Config.WEATHER_DEFCITY if not CITY: await message.edit( "`Please specify a city or set one as default!`", del_in=0) return else: CITY = message.input_str timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in CITY: newcity = CITY.split(",") if len(newcity[1]) == 2: CITY = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f'{country}'] except KeyError: await message.edit("`Invalid country.`", del_in=0) return CITY = newcity[0].strip() + "," + countrycode.strip() url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}' async with aiohttp.ClientSession() as ses, ses.get(url) as res: req_status = res.status res_text = await res.text() result = json.loads(res_text) if req_status != 200: await message.edit(r"`Invalid country.. ¯\_(ツ)_/¯`", del_in=0) return cityname = result['name'] curtemp = result['main']['temp'] humidity = result['main']['humidity'] min_temp = result['main']['temp_min'] max_temp = result['main']['temp_max'] desc = result['weather'][0] desc = desc['main'] country = result['sys']['country'] sunrise = result['sys']['sunrise'] sunset = result['sys']['sunset'] wind = result['wind']['speed'] winddir = result['wind']['deg'] ctimezone = tz(c_tz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = c_n[f"{country}"] # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", # "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = (360 / len(dirs)) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") return xx await message.edit( f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Humidity:** `{humidity}%`\n" + f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Sunrise:** `{sun(sunrise)}`\n" + f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`") await CHANNEL.log(f"check `{CITY}` weather results")
def process_alerts(product, now=datetime.now(), old=_PAST_TIMEFRAME, new=None, debug=False, debug_file=sys.stdout, send_email=True, address=None): delta = defaultdict(WordDeltaCounter) # Resolve date if not isinstance(now, datetime) and isinstance(now, date): now = datetime.combine(now, time(0, 0, 0)) #if not isinstance(now, datetime): # I don't feel like checking this. It's not a likely exception. #raise Exception('"now" must me of type datetime or date.') now_string = now.strftime('%Y-%m-%d %H:%M:%S') now = tz('US/Pacific').localize(now) # Product related vars if product.lower() == 'desktop': new = new if new else _DESKTOP_TIMEFRAME where_product = ('product = "firefox"' + '\nAND LEFT(platform,7) IN("Windows","OS X","Linux")') flavor = 'word-based' subject = 'Desktop Input Alert' address = address if address else _DESKTOP_EMAIL elif product.lower() == 'android': new = new if new else _ANDROID_TIMEFRAME where_product = 'product = "Firefox for Android"' flavor = 'android-word-based' subject = 'Android Input Alert' address = address if address else _ANDROID_EMAIL else: raise Exception('product must be "desktop" or "android".') # Resolve debug info if debug and not isinstance(debug_file, file): warn('Debug file should be type <file>, outputting to stdout.') debug_file = sys.stdout is_print = not debug or debug_file != sys.stdout if is_print: print 'Generating %s for %s' % (subject, now_string) # Retrieve old timeframe where = (where_product + '\nAND created > DATE_SUB(:now, INTERVAL :old WEEK)' + '\nAND created < DATE_SUB(:now, INTERVAL :new HOUR)') base_total = _aggregate(where, delta, True, now_string, old, new) # Retrieve new timeframe after_comments = {} where = (where_product + '\nAND created > DATE_SUB(:now, INTERVAL :new HOUR)' + '\nAND created < :now') after_total = _aggregate(where, delta, False, now_string, old, new, comments=after_comments) if (after_total < _MIN_DENOM_THRESHOLD or base_total < _MIN_DENOM_THRESHOLD): warn('NOT ENOUGH FEEDBACK %d before and %d after' % (base_total, after_total)) return #Generate alerts alerted_feedback = {} # Determine if we should alert for each word and add the alert feedback to a # dict for spam detection for (k, v) in delta.iteritems(): v.set_thresholds(diff_pct=_DIFF_PCT_MIN, diff_abs=_DIFF_ABS_MIN) v.set_potentials(base=base_total, after=after_total) v.end_time = tz('UTC').normalize(now) if (v.is_significant and v.severity >= _ALERT_SEV_MIN and v.after.count >= _MIN_COUNT_THRESHOLD): for link_item in v.after.link_list: alerted_feedback[link_item[0]] = link_item[1] v.alert = True # Find spam test_spam = {x: after_comments[x] for x in alerted_feedback.keys()} spam = SpamDetector().check_entries_for_spam(test_spam) # Remove spam after_total -= len(spam.keys()) for (k, v) in delta.iteritems(): if (v.alert): for s in spam.keys(): if s in v.after.link_list: v.after.remove(link=(s, alerted_feedback[s])) v.alert = False # Reprocess alerts while removing spam has_alerts = False email_list = set() for (k, v) in delta.iteritems(): v.set_potentials(base=base_total, after=after_total) if v.is_significant and v.after.count >= _MIN_COUNT_THRESHOLD: if v.severity >= _ALERT_SEV_MIN: if is_print: print 'Emitting alert for %s' % v.after.sorted_metadata[0] v.emit(timeframe=new, flavor=flavor, debug=debug, debug_file=debug_file) has_alerts = True if send_email and v.severity >= _EMAIL_SEV_MIN: email_list.add(v) if not has_alerts: # This is super fishy but technically valid usecase. # Might alert on this in the future if is_print: print 'No alerts today' return # Now send an email, looking up each piece of feedback. if email_list: _email_results(email_list, subject, address, after_comments)
async def fetch_weather(weather): """ For .weather command, gets the current weather of a city. """ if OWM_API is None: await weather.edit(NO_API_KEY) return saved_props = await get_weather() \ if is_mongo_alive() \ else None if not weather.pattern_match.group(1): if 'weather_city' in saved_props: city = saved_props['weather_city'] else: await weather.edit("`Please specify a city or set one as default.`" ) return else: city = weather.pattern_match.group(1) timezone_countries = { timezone: country for country, timezones in countrytz.items() for timezone in timezones } if "," in city: newcity = city.split(",") if len(newcity[1]) == 2: city = newcity[0].strip() + "," + newcity[1].strip() else: country = await get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f'{country}'] except KeyError: await weather.edit(INV_PARAM) return city = newcity[0].strip() + "," + countrycode.strip() url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OWM_API}' request = get(url) result = loads(request.text) if request.status_code != 200: await weather.edit(INV_PARAM) return cityname = result['name'] curtemp = result['main']['temp'] humidity = result['main']['humidity'] min_temp = result['main']['temp_min'] max_temp = result['main']['temp_max'] desc = result['weather'][0] desc = desc['main'] country = result['sys']['country'] sunrise = result['sys']['sunrise'] sunset = result['sys']['sunset'] wind = result['wind']['speed'] winddir = result['wind']['deg'] ctimezone = tz(countrytz[country][0]) time = datetime.now(ctimezone).strftime("%A, %I:%M %p") fullc_n = countryname[f"{country}"] # dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", # "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] div = (360 / len(dirs)) funmath = int((winddir + (div / 2)) / div) findir = dirs[funmath % len(dirs)] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(fahr): temp = str(((fahr - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(celc): temp = str((celc - 273.15)).split(".") return temp[0] def sun(unix): suntime = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p") return suntime await weather.edit( f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n" + f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n" + f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n" + f"**Humidity:** `{humidity}%`\n" + f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" + f"**Sunrise:** `{sun(sunrise)}`\n" + f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" + f"`{cityname}, {fullc_n}`\n" + f"`{time}`")