from andorLib import *
import time
import matplotlib.pyplot as plt
import timeit
import numpy as np
import pandas as pd
import sys

andor = Andor()
andor.loadLibrary()

fig, ax = plt.subplots(nrows=1, ncols=1)
ax.set_ylabel('Detector Temperature [Celsius]')
ax.set_xlabel('Time [Sec]')
ax.set_ylim(ymin=-100, ymax=60)
plt.ioff()

def getformattedtime():
    #formatted_time = float(f'{time.time():.1f}')
    formatted_time = np.round(time.time())
    return formatted_time

def format_output(val1, val2):
    output = float(f'{val2-val1:.3f}')
    return output

def printProgressBar(i,max,postText):
    n_bar =25 #size of progress bar
    j= i/max
    sys.stdout.write('\r')
    sys.stdout.write(f"[{'=' * int(n_bar * j):{n_bar}s}] {int(100 * j)}%  {postText}")
    sys.stdout.flush()

def user_input_prompt(prompt_message):
    prompt = input(f'[USER INPUT] {prompt_message}? (y/n): ')
    return prompt

def sys_message(message, next_op):
    print(f'[SYSTEM MESSAGE] {message}: {next_op}')

def pre_initialization():
    connected_cams = andor.GetAvailableCameras()
    print(f'Getting Number of Connected Cameras: [{connected_cams[0]}]')

    cam_handle = andor.GetCameraHandle(connected_cams[1]-1)
    print(f'Getting Camera Handle: [{cam_handle[0]}]')

    set_cam = andor.SetCurrentCamera(cam_handle[1])
    print(f'Setting Active Camera: [{set_cam}]')

def initialize_camera():
    andor.Initialize()
    andor.SetReadMode(mode=4)
    andor.SetAcquisitionMode(mode=1)
    andor.SetShutter(1, 0, 20, 20)
    andor.SetADChannel(0)
    detector_dimensions = andor.GetDetector()
    andor.SetImage(hbin=1, vbin=1, hstart=1, hend=detector_dimensions[1], vstart=1, vend=detector_dimensions[2])
    andor.GetDetector()
    andor.GetCameraSerialNumber()

def begin_cooling():
    cool_to_temp = -90
    andor.SetTemperature(cool_to_temp)
    cooling_data = [[], []]

    andor.CoolerON()

    get_temp = andor.GetTemperature()
    temp = get_temp[1]
    lock = get_temp[0]

    cooldown_counter = 0

    cooling_data[0].append(cooldown_counter)
    cooling_data[1].append(temp)

    print(f'[COOLING DETECTOR TO {cool_to_temp} C]')

    while lock != 'DRV_TEMP_STABILIZED':
        cooldown_counter = cooldown_counter + 1

        print(f'COOLING [{cooldown_counter}, {temp}, {lock}]')

        cooling_data[0].append(cooldown_counter)
        cooling_data[1].append(temp)

        time.sleep(1)

        get_temp = andor.GetTemperature()
        temp = get_temp[1]
        lock = get_temp[0]

    get_temp = andor.GetTemperature()
    temp = get_temp[1]
    lock = get_temp[0]

    cooling_data[0].append(cooldown_counter)
    cooling_data[1].append(temp)

    print(f'COOLING [{cooldown_counter}, {temp}, {lock}]')
    ax.errorbar(cooling_data[0], cooling_data[1], linestyle='none', marker='s', ms=2, color='black')
    ax.axhline(cool_to_temp, linewidth=1, color='red')
    plt.savefig(f'/home/alex/fits_images/savefits_tests/cooling_plot.png')

def take_images_for_readout_times():
    exp_time = 0.0
    pag_dict = {0: 1.00,
                1: 2.00,
                2: 4.00
                }

    vss_dict = {0: 38.0,
                1: 76.0
                }

    hss_dict = {0: 5.00,
                1: 3.00,
                2: 1.00,
                3: 0.05
                }

    d = {'Indices': [],
         'PAG': [],
         'VSS (um)': [],
         'HSS (MHz)': [],
         't_01': [],
         't_02': [],
         't_03': [],
         't_12': [],
         't_13': [],
         't_23': []
         }

    readtime_data = []
    counter = 1
    steps = 5
    for pag_index in range(3):
        for vs_index in range(2):
            for hs_index in range(4):
                print(f'{pag_index},{vs_index},{hs_index} [{counter} of 24]')
                andor.SetExposureTime(exp_time)
                andor.SetPreAmpGain(pag_index)
                andor.SetVSSpeed(vs_index)
                andor.SetHSSpeed(typ=0, index=hs_index)

                printProgressBar(0, steps, 'Starting Acquisition')
                t_0 = getformattedtime()
                andor.StartAcquisition()

                printProgressBar(1, steps, 'Getting Acquired Data')
                t_1 = getformattedtime()
                data = []
                andor.GetAcquiredData16(data)
                t_2 = getformattedtime()

                printProgressBar(2, steps, 'Writing to FITS')
                andor.saveFits()
                t_3 = getformattedtime()

                printProgressBar(3, steps, 'Calculating Readout Times')
                t_01 = format_output(t_0, t_1)
                t_02 = format_output(t_0, t_2)
                t_03 = format_output(t_0, t_3)

                t_12 = format_output(t_1, t_2)
                t_13 = format_output(t_1, t_3)
                '''
                print(f't_12: {t_12}')
                print(f't_13: {t_13}')
                '''
                t_23 = format_output(t_2, t_3)
                # print(f't_23: {t_23}')

                indicies = f'({pag_index},{vs_index},{hs_index})'

                printProgressBar(4, steps, 'Creating Data Frame')
                d['Indices'].append(indicies)
                d['PAG'].append(pag_dict[pag_index])
                d['VSS (um)'].append(vss_dict[vs_index])
                d['HSS (MHz)'].append(hss_dict[hs_index])
                d['t_01'].append(t_01)
                d['t_02'].append(t_02)
                d['t_03'].append(t_03)
                d['t_12'].append(t_12)
                d['t_13'].append(t_13)
                d['t_23'].append(t_23)
                printProgressBar(5, steps, 'Complete')
                counter = counter + 1

                print('\n')
    readtime_df = pd.DataFrame(data=d)
    print(readtime_df)

def take_image():
    # exp_time = float(input('Input Exp Time: '))
    exp_time = 0.0
    pre_amp_gain_index = int(input('Input Pre Amp Gain Index: '))
    vs_index = int(input('Input Vertical Shift Speed Index: '))
    hs_index = int(input('Input Horizontal Shift Speed Index: '))

    andor.SetExposureTime(exp_time)
    andor.SetPreAmpGain(pre_amp_gain_index)
    andor.SetVSSpeed(vs_index)
    andor.SetHSSpeed(typ=0, index=hs_index)

    andor.StartAcquisition()

    start_time = timeit.default_timer()

    data = []

    andor.GetAcquiredData16(data)

    end_time_1 = timeit.default_timer()
    read_time_1 = end_time_1 - start_time
    print(f'PAG_{pre_amp_gain_index}_VSS_{vs_index}_HSS_{hs_index}_runtime_1: {read_time_1}')

    andor.saveFits()

    end_time_2 = timeit.default_timer()
    read_time_2 = end_time_2 - start_time
    print(f'PAG_{pre_amp_gain_index}_VSS_{vs_index}_HSS_{hs_index}_runtime_2: {read_time_2}')

def cool_up():
    get_temp = andor.GetTemperature()
    temp = get_temp[1]
    lock = get_temp[0]

    andor.CoolerOFF()
    coolup_counter = 0

    print(f'[Waiting for Detector to Warm Above -20 C]')

    while temp <= -20:
        coolup_counter = coolup_counter + 1
        print(f'COOLING [{coolup_counter}, {temp}, {lock}]')
        time.sleep(1)
        get_temp = andor.GetTemperature()
        temp = get_temp[1]
        lock = get_temp[0]

def shutdown():
    get_temp = andor.GetTemperature()
    temp = get_temp[1]

    if temp >= -20:
        andor.ShutDown()

pre_init_command = user_input_prompt('Begin Pre-Initialization')
if pre_init_command == 'y':
    # pre init functions go here
    pre_initialization()
    sys_message('Pre-Initialization Complete', 'Ready to Initialize Camera')

    init_camera_command = user_input_prompt('Initialize Camera')
    if init_camera_command == 'y':
        # camera init functions go here
        initialize_camera()
        sys_message('Initialization Complete', 'Ready to Begin Cooling')

        cooling_on_command = user_input_prompt('Turn Cooler ON')
        if cooling_on_command == 'y':
            # cooling on function goes here
            begin_cooling()
            sys_message('Cooling Complete', 'Ready to Begin Acquisition')

            start_acquisition_command = user_input_prompt('Start Acquisition')
            if start_acquisition_command == 'y':
                # start acquisition function goes here
                take_images_for_readout_times()
                sys_message('Acquisition Complete', 'Ready to Cool Up')

                cooling_off_command = user_input_prompt('Turn Cooler OFF')
                while cooling_off_command == 'n':
                    take_additional_acquisition_command = user_input_prompt('Begin Another Acquisition')
                    # start acquisition function goes here
                    take_image()
                    sys_message('Acquisition Complete', 'Ready to Cool Up')

                    cooling_off_command = user_input_prompt('Turn Cooler OFF')
                # Cool up function goes here
                cool_up()
                sys_message('Cool Up Completed', 'Shutting Down')
                # Shut down function goes here
                andor.ShutDown()

            if start_acquisition_command == 'n':
                sys_message('Acquisition Cancelled', 'Please Wait for Camera to Cool Up')
                # Cool up function goes here
                cool_up()
                sys_message('Cool Up Completed', 'Shutting Down')
                # Shut down function goes here
                andor.ShutDown()

        if cooling_on_command == 'n':
            sys_message('Cooling Cancelled', 'Shutting Down')
            andor.ShutDown()

    if init_camera_command == 'n':
        sys_message('Camera Initialization Cancelled', 'Shutting Down')
        andor.ShutDown()

if pre_init_command == 'n':
    sys_message('Pre-Initialization Cancelled', 'Shutting Down')


from main import app
from flask import jsonify

data = app.config.get('DATA')

@app.route("/cities")
@app.route("/cities/<city_name>")
def cities(city_name=None):
    ''' Retieves the cities data'''

    if city_name:
        city_data = data[data['cities'] == city_name]
        if len(city_data):
            return city_data.to_json(), 200
        else:
            return jsonify({'city': None}), 404
    else:
        cities = data.get('cities')
        return cities.to_json(), 200

@app.route("/citizens")
@app.route("/citizens/<city_name>")
def citizens(city_name=None):
    ''' Retieves the citizens data'''

    if city_name:
        city_data = data[data['cities'] == city_name ]
        if len(city_data):
            return jsonify({city_name: city_data.get('citizens').to_json()}), 200
        else:
            return jsonify({'city': None}), 404
    else:
        citizens = data.get('citizens')
        return citizens.to_json(), 200


import os.path

import odoo, base64, tempfile
import zipfile
from odoo import fields, models, api
from odoo.exceptions import UserError
from datetime import datetime

class TestOrder(models.Model):
    _name = 'test.order'
    _inherit = ['mail.thread']

    name = fields.Char(translate=True)

    test_order_id = fields.Many2one('test.order')
    potential_test_order_ids = fields.Many2many('test.order','test_order_potential_test_order_rel','test_order_id','potential_test_order_id')

    c1 = fields.Char(inverse=False)
    f1 = fields.Float(inverse=False)
    f2 = fields.Float()

    @api.onchange('c1')
    def onchange_for_f1(self):
        self.f1 = self.c1

    def test(self):
        _zip = self.env['ir.attachment'].search([
            ('res_model','=',self._name),('res_id','=',self.id),('name','like','%.zip')],limit=1)

        with tempfile.TemporaryDirectory() as _directory_path:
            with open(os.path.join(tempfile.gettempdir(), _zip.name), 'wb') as _zip_file:
                _zip_file.write(base64.b64decode(_zip.datas))
                zip_object = zipfile.ZipFile(_zip_file.name)
                for attachment_name in zip_object.namelist():
                    attachment_path = zip_object.extract(attachment_name,_directory_path)
                    with open(attachment_path, 'rb') as attachment_file:
                        self.env['ir.attachment'].create({
                            'datas': base64.b64encode(attachment_file.read()),
                            'res_id': self.id,
                            'res_model': self._name,
                            'name': attachment_name,
                        })


#!/usr/bin/env python

import os
import sys,re
from Bio import SeqIO

src_dir = "C:/Users/Huiluo/Desktop/HKU-microbiology/pneumococcus/script/temp/"
des_dir = "C:/Users/Huiluo/Desktop/HKU-microbiology/pneumococcus/script/temp/cleaned/"
fasta_list = []
for file in os.listdir(src_dir):
    if file.endswith('fas'):
        fasta_list.append(file)

for fasta in fasta_list:
    print (fasta)
    in_fasta = open(os.path.join(src_dir,fasta))
    out_fasta = open(os.path.join(des_dir,fasta),'a')
    for line in in_fasta:
        if line.startswith(">"):
            line = line.split("|")
            out_fasta.write(line[0]+"\n")
        else:
            out_fasta.write(line)
    in_fasta.close()
    out_fasta.close()


FLPGROUP   = None
SUPERHASH  = None
TIMESTAMP  = 0
DIRTREE    = None #dict (file/dir -> dict)
MYTREEFILE = None #string
JOBS       = None #dict (socket -> job)
INITIAL    = False

# string constants
LOGFILE    = '.flplog'
TREEFILE   = '.flptree.'
PEERFILE   = '.flppeers'
PROG       = "flp"
SEP        = ":"

# networking
LANIP      = None  #string
UDPPORT    = 21331
TCPPORT    = 11337
INTERFC    = ''
SIZE       = 1024
BACKLOG    = 5
UDPSOCK    = None #socket
TCPSOCK    = None #socket
RUNNING    = 0
PEERGROUP  = None #dict (ip -> baum)
LISTEN     = None #list (sockets)
SEND       = None #list (sockets)
LOGGER     = None
BC_TIME    = 5.00 # seconds

# messages (group will be added in when main is started)
INFOMSG    = "info"
INITMSG    = "init"
REQUESTMSG = "request"
FINMSG     = "finished"
#evtl splitten in erfolgs- und fail message

# dictionary strings
TIMESTAMP_STR = 'TIME'
HASH_STR      = 'HASH'
DIR_STR       = 'FILES'
PATH_STR      = 'PATH'


import numpy as np
import pandas as pd

import warnings
warnings.simplefilter('ignore', np.RankWarning)

def continuum(data, ties):
    cont = pd.Series(index=data.index, dtype='float64')
    # line through left and middle tie points
    slope = (data[ties[1]] - data[ties[0]]) / (ties[1] - ties[0])
    cont[:ties[1]] = data[ties[0]] + slope * (cont[:ties[1]].index - ties[0])
    # line through middle and right tie points
    slope = (data[ties[2]] - data[ties[1]]) / (ties[2] - ties[1])
    cont[ties[1]:] = data[ties[1]] + slope * (cont[ties[1]:].index - ties[1])
    return cont

def smooth(band):
    return band.rolling(window=3, center=True).mean()

def polynomial_approximation(band, deg=4):
    return np.poly1d(np.polyfit(band.index, band, deg))

def center(band):
    left, right = band.index[0], band.index[-1]
    poly = polynomial_approximation(band)

    crit_x = poly.deriv().roots
    crit_x = np.real_if_close(crit_x[np.isreal(crit_x)])
    crit_x = crit_x[left <= crit_x]
    crit_x = crit_x[crit_x <= right]
    if len(crit_x) == 0:
        return None

    crit_y = np.vectorize(poly)(crit_x)
    index = np.argmin(crit_y)
    x, y = crit_x[index], crit_y[index]
    is_min = poly.deriv().deriv()(x) > 0
    if not is_min:
        return None

    return x, y

def integrated_depth(band):
    return np.trapz(1 - band, band.index)

def asymmetry(band, ctr_x):
    ctr_left = band[:ctr_x].index[-1]
    ctr_right = band[ctr_x:].index[0]
    ctr_y = (band[ctr_left] + (ctr_x - ctr_left) *
             (band[ctr_right] - band[ctr_left]) / (ctr_right - ctr_left))
    band = pd.concat([
        band[:ctr_left],
        pd.Series([ctr_y], index=[ctr_x]),
        band[ctr_right:]
    ])
    left = band[:ctr_x]
    asym = integrated_depth(left) / integrated_depth(band)

    return asym

def transform_pixel(pin, wavelengths, ties, glass, depth_wavelengths,
                    dynamic_tie_ranges=None, center_range=200):
    """There are 20 output parameters for each pixel.
    1-3. The 3 tie points.
    4-6. reflectance at 3 tie points.
    7. 1um band minimum. The wavelength with the minimum (continuum-removed)
       reflectance.
    8. 1um band center. The wavelength of the minimum of the 4th-degree
       polynomial fit to the (continuum-removed) band within center_range of
       the band minimum.
    9. 1um band depth. 1 - y, where y is the (continuum-removed)
       reflectance at the band center.
    10. 1um band integrated band depth. The integral of 1 - y over the band.
    11. 1um band asymmetry. The "area of a band" is the area between the band
        and the line y=1 in the continuum-removed reflectance graph; i.e.
        integral across the band of (1 - y) where y is (continuum-removed)
        reflectance.
        The band asymmetry is defined as the portion of the band that's left of
        the band center.
    12-16. Same as 7-11, but for the 2um band.
    17. Interband distance. (2um band center) - (1um band center).
    18. Glass band depth.
    19-. Band depth at the specified wavelengths.
    """

    num_parameters = 18 + len(depth_wavelengths or [])

    data = pd.Series(data=pin, index=wavelengths)
    pout = np.full(num_parameters, np.nan, dtype=pin.dtype)

    # Boxcar smoothing
    data = smooth(data)

    if dynamic_tie_ranges:
        initial_cont = continuum(data, ties)
        initial_removed = data / initial_cont
        ties = [
            initial_removed[start:end].idxmax()
            for start, end in dynamic_tie_ranges
        ]

    # 3 tie point wavelengths
    pout[0:3] = ties

    # reflectance values at the 3 tie points
    pout[3:6] = data[ties]

    # continuum removal
    cont = continuum(data, ties)
    removed = data / cont

    # 1um band
    left1, right1 = ties[0], ties[1]
    band1 = removed[left1:right1]
    minimum1 = band1.idxmin()
    ctr1 = center(band1[minimum1 - center_range:minimum1 + center_range])
    if ctr1 is not None:
        x1, y1 = ctr1
        depth1 = 1 - y1
        ibd1 = integrated_depth(band1)
        asym1 = asymmetry(band1, x1)
        pout[6:11] = [minimum1, x1, depth1, ibd1, asym1]

    # 2um band
    left2, right2 = ties[1], ties[2]
    band2 = removed[left2:right2]
    minimum2 = band2.idxmin()
    ctr2 = center(band2[minimum2 - center_range:minimum2 + center_range])
    if ctr2 is not None:
        x2, y2 = ctr2
        depth2 = 1 - y2
        ibd2 = integrated_depth(band2)
        asym2 = asymmetry(band2, x2)
        pout[11:16] = [minimum2, x2, depth2, ibd2, asym2]

    # interband distance
    if ctr1 is not None and ctr2 is not None:
        pout[16] = x2 - x1

    # glass band depth
    pout[17] = 1 - removed[glass].mean()

    # other band depths
    pout[18:] = 1 - removed[depth_wavelengths]

    return pout

def output_band_names(depth_wavelengths):
    return [
        '1st tie point',
        '2nd tie point',
        '3rd tie point',
        'reflectance at 1st tie point',
        'reflectance at 2nd tie point',
        'reflectance at 3rd tie point',
        '1um band minimum',
        '1um band center',
        '1um band depth',
        '1um integrated band depth',
        '1um band asymmetry',
        '2um band minimum',
        '2um band center',
        '2um band depth',
        '2um band integrated band depth',
        '2um band asymmetry',
        'interband distance',
        'glass band depth',
    ] + [
        f'band depth at {x}nm'
        for x in depth_wavelengths
    ]


#!/usr/bin/env python

import matplotlib.pyplot as plt
import numpy as np

# EXAMPLE FROM:  http://matplotlib.org/examples/pylab_examples/simple_plot.html

def curvy_function(t):
    return t*np.sin(2*np.pi*t) + 0.2*np.cos(7*np.pi*t)

def main():
    """
    Draw an interesting function
    """

    t = np.linspace(0.0, 1.0, 50)
    s = curvy_function(t)
    plt.plot(t, s)

    plt.xlabel('time (s)')
    plt.ylabel('position (m)')
    plt.title('a curvy plot!')
    plt.grid(True)
    # plt.savefig("curvy_plot.png")
    plt.show()

if __name__ == "__main__":
    main()


import numpy as np
import matplotlib.pyplot as plt

col_1 = 87;
col_2 = 130;

data = np.genfromtxt('data.txt', usecols=(col_1-1, col_2-1),
  invalid_raise=False)

y_1 = data[:, 0]
y_2 = data[:, 1]
row_num = np.arange(len(data))

plt.scatter(row_num, y_1, label='Col 87', alpha=0.3, edgecolors='none')
plt.scatter(row_num, y_2, label='Col 130', alpha=0.3, edgecolors='none')

plt.legend(loc=1)
plt.xlabel('Row Num')
plt.ylabel('Value')

plt.show()


import gi
gi.require_version('Wnck', '3.0')

from dbus import service
import dbus
import json
from vasak import icons
from gi.repository import Wnck
from datetime import datetime

class VasakMaster(dbus.service.Object):
    def __init__(self, notify):
        self.minimized_windows = []
        self.notify = notify
        bus_name = service.BusName(
            "ar.net.vasak.os.desktop.service", dbus.SessionBus())
        service.Object.__init__(
            self, bus_name, "/ar/net/vasak/os/desktop/service")
        self.get_screen().connect('window-opened', self.window_open_cb)
        self.get_screen().connect('window-closed', self.window_closed_cb)

    def get_screen(self):
        return Wnck.Screen.get(0)

    def window_open_cb(self, screen, window):
        self.send_windwos_to_desktop()

    def window_closed_cb(self, screen, closed_window):
        for win in self.minimized_windows:
            if win is closed_window:
                self.minimized_windows.remove(closed_window)
        self.send_windwos_to_desktop()

    def send_windwos_to_desktop(self):
        windows = self.get_windows_to_desktop()
        self.update_windows(windows)

    @dbus.service.signal('ar.net.vasak.os.desktop.service', signature='s')
    def update_windows(self, windows):
        return str(windows)

    def name_valid(self, name):
        return (name != 'navale' and
                name != 'vasak-desktop' and
                name != 'hydriam' and
                name != 'Navale' and
                name != 'Vasak Desktop' and
                name != 'Hydriam')

    def get_windows_to_desktop(self):
        temp_list = []
        for win in self.get_windows():
            if (win.get_window_type() < 1 and
                    self.name_valid(win.get_class_instance_name())):
                datawin = {
                    "name": win.get_class_instance_name().replace("-", " "),
                    "id": win.get_xid(),
                    "icon": icons.get(win.get_class_instance_name())
                }
                temp_list.append(datawin)

        return json.dumps(temp_list)

    def get_windows(self):
        return self.get_screen().get_windows()

    @dbus.service.method('ar.net.vasak.os.desktop.service', in_signature='s', out_signature='')
    def toggle_window(self, id_window):
        for win in self.get_windows():
            if win.get_xid() == int(id_window):
                if win.is_minimized():
                    win.unminimize(datetime.timestamp(datetime.now()))
                else:
                    win.minimize()

    @dbus.service.method('ar.net.vasak.os.desktop.service', in_signature='', out_signature='s')
    def get_notifications(self):
        return str(self.notify.get_notifications())

    @dbus.service.method('ar.net.vasak.os.desktop.service', in_signature='s', out_signature='')
    def add_notification(self, noti):
        print(noti)
        self.notify.add_notification(json.loads(noti))


import feedparser
from park_api.geodata import GeoData
from park_api.util import utc_now

# Falls das hier jemals einer von den Menschen
# hinter OpenDataZürich lesen sollte: Ihr seid so toll <3
geodata = GeoData(__file__)

def parse_html(xml_data):
    feed = feedparser.parse(xml_data)

    try:
        last_updated = feed["entries"][0]["updated"]
    except KeyError:
        last_updated = utc_now()

    data = {
        "lots": [],
        # remove trailing timezone for consensistency
        "last_updated": last_updated.replace("Z", "")
    }

    for entry in feed["entries"]:
        summary = parse_summary(entry["summary"])
        title_elements = parse_title(entry["title"])

        lot_identifier = (title_elements[2] + " " + title_elements[0]).strip()
        lot = geodata.lot(lot_identifier)

        data["lots"].append({
            "name": title_elements[0],
            "address": title_elements[1],
            "id": lot.id,
            "state": summary[0],
            "free": summary[1],
            "total": lot.total,
            "coords": lot.coords,
            "forecast": False,
            "lot_type": title_elements[2]
        })

    return data

def parse_summary(summary):
    """Parse a string from the format 'open /   41' into both its params"""
    summary = summary.split("/")

    summary[0] = summary[0].strip()
    if "?" in summary[0]:
        summary[0] = "nodata"

    try:
        summary[1] = int(summary[1])
    except ValueError:
        summary[1] = 0
    return summary

def parse_title(title):
    """
    Parse a string from the format 'Parkgarage am Central / Seilergraben'
    into both its params
    """
    types = ["Parkhaus", "Parkplatz"]

    name = title.split(" / ")[0]
    address = title.split(" / ")[1]
    type = ""
    if name.split(" ")[0] in types:
        type = name.split(" ")[0]
        name = " ".join(name.split(" ")[1:])

    return name, address, type


# https://programmers.co.kr/learn/courses/30/lessons/42583
# 스택/큐

# 다시 풀어보기
# 올라간 후 얼마나 이동했는지 확인하는 방법 참고!!
# deque로 popleft()를 쓰면 TC 5번에서 시간초과 -> deque를 없애면 통과
# 다른 사람 코드 참고 - 클래스로 구현한 코드 ↓
# https://programmers.co.kr/learn/courses/30/lessons/42583/solution_groups?language=python3

def solution(bridge_length, weight, truck_weights):
    answer = 0
    # 현재 다리 위에 있는지 확인하는 리스트
    on_bridge = [0] * bridge_length

    while len(on_bridge):
        # 시간을 늘려주고 맨 처음에 있는 트럭을 빼준다(자동으로 앞으로 밀리면서 카운트)
        answer += 1
        on_bridge.pop(0)
        # 트럭이 남아 있다면
        if truck_weights:
            # 다리위에 올릴 수 있다면 대기 목록에서 pop해서 올려준다.
            if sum(on_bridge) + truck_weights[0] <= weight:
                on_bridge.append(truck_weights.pop(0))
            # 못 올린다면 0을 올려준다.
            else:
                on_bridge.append(0)

    return answer

def solution(bridge_length, weight, truck_weights):
    answer = 0
    trucks_on_bridge = [0] * bridge_length
    while len(trucks_on_bridge):
        answer += 1
        trucks_on_bridge.pop(0)
        if truck_weights:
            if sum(trucks_on_bridge) + truck_weights[0] <= weight:
                trucks_on_bridge.append(truck_weights.pop(0))
            else:
                trucks_on_bridge.append(0)
    return answer

print(solution(2, 10, [7, 4, 5, 6]))
print(solution(100, 100, [10]))
print(solution(100, 100, [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]	))


import logging
import requests

logging.basicConfig(level=logging.INFO)

def to_api(x):
  """Return correct github repo link for API call"""
  return x.replace('/issues', "").replace('github.com', 'api.github.com/repos')

def get_stars(url):
  """Given github api url, request content and return stargazers_count"""
  r = requests.get(url)
  return r.json()['stargazers_count']

if __name__ == '__main__':
  import json

  with open("data/package_urls.json", "r") as f:
    urls = json.load(f)

  github_api_links = {k: to_api(v['github_url']) for k, v in urls.iteritems()
                      if v['github_url'] is not None}
  stars = {pkg: get_stars(url) for pkg, url in github_api_links.iteritems()}

  with open("data/github_stars.json", "w") as f:
    json.dump(stars, f)