Best Python code snippet using molecule_python
logistics.py
Source:logistics.py  
1import numpy as np2import matplotlib as mpl3import time4import sys5import warnings6from typing import List, Union7from functools import reduce8910if True:11    # suppress reportUnboundVariable:12    start_time = None 13    1415def print_version_info(dependencies:List[str], py_full:bool=False):16    """17        Prints version info for python and related dependencies.1819        --Parameters--20        * dependencies : List[str] //21            Contains additional dependencies (beyond python) 22            required to run the current script. e.g. 23            ['numpy', 'matplotlib'].24        * py_full : bool, optional //25            True corresponds to printing the python version 26            in its full form; False corresponds to printing 27            in the form: #.x.x,  28                * by default False.29    """    30    31    head = 'versions:'32    prefix = ' ' * (len(head)+1)33    py_vers_template = '3.x.x'34    py_vers_len = len(py_vers_template)35    py_vers = sys.version if py_full else sys.version[:py_vers_len]3637    print(head + ' python--' + py_vers)38    if 'numpy' in dependencies:39        print(prefix + 'numpy--' + np.__version__)40    if 'matplotlib' in dependencies:41        print(prefix + 'matplotlib--' + mpl.__version__)424344def print_file_info(filename:str=None, location:str=None, ):45    """46        Prints information about the current python file 47        to the terminal output.4849        --Parameters--50        * filename : str, optional //51            Name of the current file,  52                * by default None.53        * location : str, optional //54            Path to the current file, not including filename,  55                * by default None.56    """    5758    if location:59        print(f'location: "{location}"') 60    if filename:61        print(f'filename: "{filename}"') 626364def seconds_to_timestring(t:float, full_str:bool=False)->str:65    """66        Converts a time in fractional seconds into a printable string.6768        --Parameters--69        * t : float // 70            Time in fractional seconds. 71        * full_str : bool, optional // 72            Option used to force output string to be 73            of the form hh:mm:ss.ss, 74                * by default False. 7576        --Returns--77        * out : str // 78            Printable string of one of the following forms:79            80                hh:mm:ss.ss if (full_str option is True) OR ((1 hour) < t) ; 81                mm:ss.ss otherwise.82    """    8384    time_parts = reduce(85        lambda part_tuple, divisor:86            divmod(part_tuple[0], divisor) + part_tuple[1:], 87            [(int(t * 100),), 100, 60, 60]88    )89    h, m, s, cs = time_parts90    91    if full_str == True or h >= 1:92        out = f'{h:02d}:{m:02d}:{s:02d}.{cs:02d}'93    else:94        out = f'{m:02d}:{s:02d}.{cs:02d}'9596    return out979899def print_time_required(100    init_time:float, 101    prefix:str='', 102    full_str:bool=False, 103):104    """105        Prints the time elapsed from init_time according 106        to the python interpreter. Note that 107        time.perf_counter() is used rather than 108        time.process_time(), meaning that time is recorded 109        while python is asleep using time.sleep(). 110111        --Parameters--112        * init_time : float // 113            A time which must be bound at the start of the user's 114            "stopwatch" (free choice of the user) using the time module. 115        * prefix: str, optional //116            Gets printed on the same line just before the displayed117            time-requirement message,118                * by default ''.119        * full_str : bool, optional // 120            Option used to force printed string to be 121            of the form hh:mm:ss.ss, 122                * by default False. 123    """    124125    time_req = time.perf_counter() - init_time126    time_str = seconds_to_timestring(time_req, full_str=full_str)127    print(prefix + f'time required: {time_str:s}')128    129130def print_total_time(start_time:float, full_str:bool=False):131    """132        Prints the total time for the current script. 133134        --Parameters--135        * start_time : float // 136            Time of beginning NEW RUN for current script--should 137            be bound at the start of current script using the 138            time module. 139        * full_str : bool, optional // 140            Option used to force printed string to be 141            of the form hh:mm:ss.ss, 142                * by default False.  143    """    144    145    elapsed_time = time.perf_counter() - start_time146    time_str = seconds_to_timestring(elapsed_time, full_str=full_str)147    print(f'runtime: {time_str:s}')148149150def housekeeping_initial(151    ignore_warnings:bool=False, 152    location:str=None,153    filename:str=None,154    print_version:Union[bool, List]=False,155    dependencies:List[str]=None,156):157    """158        Initial setup to make terminal output more legible.159160        --Parameters--161        * ignore_warnings : bool, optional // 162            Option to quiet all warnings from the terminal,  163                * by default False. 164        * location : str, optional // 165            Path to the current file,  166                * by default None. 167        * filename : str, optional // 168            Name of the current file,  169                * by default None. 170        * print_version : Union[bool, List], optional // 171            Option to print version info--if this option is 172            True, then one must provide strings of required 173            dependencies in the dependcies parameter, 174            e.g. ['numpy', 'matplotlib'];175            can also be set as [bool, bool] where the first bool 176            is the normal print_version option, and the second bool 177            controls whether the python version should be printed 178            in full (defaults to False if print_version is given 179            as a single bool),  180                * by default False. 181        * dependencies : List[str], optional // 182            List of required dependencies, 183            e.g. ['numpy', 'matplotlib'], 184                * only required if (print_version == True) 185                OR (print_version[0] == True), 186                * by default None. 187    """    188    189    line = '=' * 40190    191    global start_time192    start_time = time.perf_counter()193    194    if ignore_warnings:195        warnings.filterwarnings('ignore')196    197    print()198    199    py_full = print_version[1] if type(print_version) == list else False200    if print_version == True or print_version[0] == True:201        print_version_info(dependencies=dependencies, py_full=py_full)202    203    print_file_info(filename=filename, location=location)204    print('--NEW RUN--')205    print(line)206    print()207208209def housekeeping_final(210    location:str=None,211    filename:str=None,212    print_timing:bool=False,213):214    """215        Final cleanup to make terminal output more legible. 216217        --Parameters--218        * location : str, optional // 219            Path to the current file,  220                * by default None. 221        * filename : str, optional // 222            Name of the current file,  223                * by default None. 224        * print_timing : bool, optional // 225            Option to print the total time required for the 226            current script, 227                * by default False. 228    """    229230    line = '=' * 40231    232    print()233    print(line)234    print_file_info(filename=filename, location=location) 235    if print_timing:236        print_total_time(237            start_time=start_time, full_str=False238        )239    print('--DONE--')240    print()241    242243def print_loop_progress(244    index:int, 245    index_max:int, 246    prefix:str='', 247):248    """249        Goes inside the body of a (for/while) loop to 250        repeatedly print the current progress, along with 251        an optional message, as the interpreter steps 252        though the loop. 253254        --Parameters--255        * index : int // 256            The integer index representing the current step 257            of the loop (one might need to create this using 258            enumerate() ). 259        * index_max : int // 260            The integer corresponding to the loop's (inclusive) stop 261            condition--often needs to be 1 less than the stop 262            parameter for a range iterable.s263        * prefix: str, optional //264            Gets printed on the same line just before the displayed265            progress, 266                * by default ''. 267    """    268269    percent_complete = 100 * (index) // index_max270    print(271        '\r' + prefix + f'progress: {percent_complete:0.0f}%',272        flush=True, end=''273    )274    if index == index_max: # condition for last step in loop
...asprin
Source:asprin  
...49  --help-clingo[=<n>]\t\t: Print clingo {1=basic|2=more|3=full} help and exit50Default call : asprin --number=1 <inputfiles>51Inner call   : asprin.parser     <inputfiles> | clingo --outf=3 - asprin.py52"""53def print_version():54    print "asprin version 1.1.1"55    56if __name__ == '__main__':57    args = sys.argv[1:]58    clingoOptions = []59    files         = []60    finished = False61    showClingoOutput=False62    showWarning=False63    onlyParse=False64    printCall=False65    clingoFiles = []66    inConstant = False67    printVersion = False68    dir = os.path.dirname(os.path.abspath(__file__))69    clingo=dir+"/clingo" if os.path.isfile(dir+"/clingo") else "clingo"70    asprin_parser=dir+"/asprin.parser" if os.path.isfile(dir+"/asprin.parser") else "asprin.parser"71    asprin_py=dir+"/asprin.py" if os.path.isfile(dir+"/asprin.py") else "asprin.py"72    for i in args:73    74        # CLINGO OPTIONS AND FILES75        if inConstant:76            clingoOptions.append("-c " + i)77            inConstant = False78        elif i=="-c" or i=="--const":79            inConstant=True80        elif (re.match( r'^[0-9]+$',i)): clingoOptions.append("-c _asprin_n=" + i);81        elif i[0] != '-':82            files.append(i) # OPTIONS START WITH -83        84        # BASIC OPTIONS85        elif i.startswith("--number="):86            clingoOptions.append("-c _asprin_n=" + i[9:])87        elif i.startswith("-n="):88            clingoOptions.append("-c _asprin_n=" + i[3:])89        elif i=="--project":90            clingoOptions.append("-c _asprin_project=1")91        elif i=="--help=1" or i=="-h=1" or i=="--help" or i=="-h":92            print_version()93            print_basic()94            finished=True95        elif i=="--version":96            printVersion = True 97        elif i=="--help=2" or i=="-h=2":98            print_version()99            print_full()100            finished=True101        elif i.startswith("--help-clingo"):102            os.system(clingo + " --help" + i[13:])103            finished=True104        105        # EXTENDED SOLVE OPTIONS106        elif i=="--release-last":107            clingoOptions.append("-c _asprin_release_last=1")108        elif i=="--no-opt-improving":109            clingoOptions.append("-c _asprin_no_opt_improving=1")110        elif i=="--do-external":111            clingoOptions.append("-c _asprin_do_external=1")112        elif i=="--no-syntax-check":113            clingoOptions.append("-c _asprin_no_syntax_check=1")114        elif i=="--no-boolean-formula":115            clingoOptions.append("-c _asprin_no_boolean_formula=1")116        elif i.startswith("--preference-trans-ext="):117            clingoOptions.append("-c _asprin_tr=" + i[23:])118        elif i.startswith("--steps="):119            clingoOptions.append("-c _asprin_steps=" + i[8:])120        elif i.startswith("--domain-heuristic="):121            matchObj = re.match( r'(init|factor|level|sign|true|false)(,-?[0-9]+)?$',i[19:])122            if matchObj:123                clingoOptions.append("--heuristic=Domain")124                clingoOptions.append("-c _asprin_heuristic=1")125                clingoOptions.append("-c _asprin_heuristic_mode=" + matchObj.group(1))126                if matchObj.group(2): clingoOptions.append("-c _asprin_heuristic_value=" + matchObj.group(2)[1:])127            else:128                print_version()129                print "ERROR (asprin): format of option --domain-heuristic is not correct"130                sys.exit()131        elif i.startswith("--mode="):132            opt = i[7:]133            if (opt != "0") and (opt != "1"):134                print_version()135                print "ERROR (asprin): format of option --mode is not correct"136                sys.exit()137            clingoOptions.append("-c _asprin_mode=" + opt)138                139        # EXTENDED SHOW OPTIONS140        elif i=="--show-clingo":141            showClingoOutput=True142        elif i=="--hide-asprin":143            clingoOptions.append("-c _asprin_no_print=1")144        elif i=="--show-optimal":145            clingoOptions.append("-c _asprin_no_print=-1")146        147        # HIDDEN OPTIONS148        elif i=="--experiments":149            clingoOptions.append("-c _asprin_no_syntax_check=1 -c _asprin_no_print=-1 --quiet --stats=2 --verbose=2")150            showClingoOutput=True151        152        # EXTENDED BASIC OPTIONS153        elif i=="--parse":154            onlyParse=True155        elif i=="--print-call":156            printCall=True157        elif i.startswith("--to-clingo="):158            clingoFiles.append(i[12:])159        elif i.startswith("--clingo="):160            clingo=i[13:]161        162        # ELSE163        else: clingoOptions.append(i)164   165    if not showClingoOutput: clingoOptions.append(" --outf=3 ")166    if not finished:167        if printVersion:168            print_version()169            os.system(asprin_parser + " --version")170            print171            os.system(clingo + " --version")172        elif printCall:173            print_version()174            os.system("echo \"" + asprin_parser + " " + ' '.join(files) + " | " + clingo + " - " + asprin_py + " " + ' '.join(clingoOptions) + " " + ' '.join(clingoFiles) + " \" ")175        elif onlyParse:176            os.system(asprin_parser + " " + ' '.join(files))177        else: 178            print_version()179            os.system(asprin_parser + " " + ' '.join(files) + " | " + clingo + " - " + asprin_py + " " + ' '.join(clingoOptions) + " " + ' '.join(clingoFiles))...views.py
Source:views.py  
1from flask import Flask, render_template, request, redirect, url_for, jsonify, make_response2from sqlalchemy import and_3from app import models, db, app, forms, mail4from flask.ext.mail import Message, Mail5from config import ADMINS, HOST_BASE, MSG_TEXT, NEW_USERS_BEFORE_ADMIN_MAIL6import json7import datetime8@app.route("/", methods=['POST', 'GET'])9def index():10    form = forms.CredentialsForm()11    if form.validate_on_submit():12        name = form.name.data.strip()13        surname = form.surname.data.strip()14        email = form.email.data.strip()15        u = models.Aasi(name=name, surname=surname, email=email)16        print u17        db.session.add(u)18        db.session.commit()19        _send_verification_mail(u)20        return redirect(url_for('form_success'))21    return render_template('index.html', form=form)22@app.route("/verify/<verification_str>")23def verify_email(verification_str):24    u = models.Aasi.query.filter_by(verification_string=verification_str).first()25    if u:26        u.verified = True27        db.session.commit()28        # is this a stupid way to handle sending mail to admins?29        new_users = models.Aasi.query.filter_by(verified=True, print_version=0).count()30        if new_users >= NEW_USERS_BEFORE_ADMIN_MAIL:31            latest = db.session.query(db.func.max(models.Aasi.print_version)).one()[0]32            _send_admin_mail(latest+1)33        return render_template('success.html')34    return "your email is not yet verified!"35@app.route("/success", methods=['GET'])36def form_success():37    return render_template('wait_for_verification.html')38    #return redirect(url_for('debug'))39@app.route("/pdf/<version>")40@app.route("/pdf")41def generate_pdf(version=None):42    import StringIO43    from flask_weasyprint import HTML, render_pdf44    now = datetime.datetime.now().strftime('%d.%m.%Y');45    #users = models.Aasi.query.all()46    # fetch the latest print_version from the database47    latest = db.session.query(db.func.max(models.Aasi.print_version)).one()[0]48    if version == None or version == 0:49        # if no version parameter given, print all50        users = models.Aasi.query.filter_by(verified=True)51    elif int(version) <= latest:52        # otherwise fetch older print versions and create the pdf53        users = models.Aasi.query.filter_by(verified=True, print_version=int(version))54    else:55        # else, get all the unprinted ones and append their version56        users = models.Aasi.query.filter_by(verified=True, print_version=0)57        for user in users:58            user.print_version = latest+159            db.session.add(user)60        db.session.commit()61        # TODO: find a way to refresh the session?62        users = models.Aasi.query.filter_by(verified=True, print_version=latest+1)63    html = render_template('piikki.html', users=users, now=now)64    return render_pdf(HTML(string=html))65    #return html66    # TODO: send the pdf to all the admins67@app.route("/debug")68def debug():69    """70        Prints all users.71        Add a query parameter reset=True, to reset72        all print_versions73    """74    users = models.Aasi.query.all()75    res = request.args.get('reset')76    if res == 'True':77        for user in users:78            user.print_version = 079            db.session.add(user)80        db.session.commit()81    return jsonify(json_list = [u.as_dict() for u in users])82def _send_verification_mail(aasi):83    msg = Message('Askipiikin verifiointi', sender=ADMINS[0])84    msg.add_recipient(aasi.email)85    verify_link = "<a href='" + HOST_BASE + url_for('verify_email', verification_str=aasi.verification_string) + "'>verifioi</a>"86    msg.html = MSG_TEXT.format(link=verify_link)87    mail.send(msg)88def _send_admin_mail(version):89    # TODO: test this90    msg = Message('Askipiikkiprintit versio {}'.format(version), sender=ADMINS[0])91    msg.html = "Printtaa uudet piikit: <a href=" + HOST_BASE + url_for('generate_pdf', version=version) + ">versio {}</a>".format(version)92    print "Sending admin mail nao!"93    print msg.html94    for email in ADMINS:95        print "Sent mail to " + email96        temp = msg97        temp.add_recipient(email)...general_tree_1.py
Source:general_tree_1.py  
1#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#2#--------------------#3# General Tree Class #4#--------------------#5class TreeNode:6    def __init__(self, data):7        self.data = data8        self.children = []9        self.parent = None10    def add_child(self, child):11        child.parent = self12        self.children.append(child)13    def get_level(self):14        '''15        Get level by counting the number of ancestors16        '''17        level = 018        p = self.parent19        while p:20            level += 121            p = p.parent22        return level23    def print_tree(self, print_version, max_level):24        '''25        Printing Data Elements in all nodes26        Recursion27        print only name -> print_version == 'Name'28        print only designation --> print_version == 'Designation'29        print all --> print_version == 'ALL'30        '''31        # Data32        spaces = ' ' * 3 * self.get_level()33        prefix = spaces + "|__" if self.parent else ""34        if self.get_level() <= max_level:35            if (print_version == 'Name'):36                data_to_print = prefix + self.data['Name']37            elif (print_version == 'Designation'):38                data_to_print = prefix + self.data['Designation']39            elif (print_version == 'both'):40                data_to_print = prefix + self.data['Name'] + ' ({d})'.format(d=self.data['Designation'])41            else:42                pass43            print(data_to_print)44            if (len(self.children) > 0):45                for child in self.children:46                    child.print_tree(print_version=print_version, max_level=max_level)47#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#48#----------------#49# Main Functions #50#----------------#51def build_product_tree():52    '''53    Tree54    Company Hierarchy55    '''56    # Root Node (Level 0)57    root_node = {'Name': 'Nilupul', 'Designation': 'CEO'}58    root = TreeNode(data=root_node)59    # Nodes (Level 1) - CTO, HR Head60    cto_dict = {'Name': 'Chinmay', 'Designation': 'CTO'}61    hr_head_dict = {'Name': 'Gels', 'Designation': 'HR Head'}62    cto, hr_head = TreeNode(data=cto_dict), TreeNode(data=hr_head_dict)63    root.add_child(child=cto), root.add_child(child=hr_head)64    # Nodes (Level 2) - Infrastructure Head, Application Head, Recruitment Manager, Policy Manager65    infra_head_dict = {'Name': 'Vishwa', 'Designation': 'Infrastrucuture Head'}66    app_head_dict = {'Name': 'Aamir', 'Designation': 'Application Head'}67    rec_manager_dict = {'Name': 'Peter', 'Designation': 'Recruitment Manager'}68    policy_manager_dict = {'Name': 'Waqas', 'Designation': 'Policy Manager'}69    infra_head, app_head = TreeNode(data=infra_head_dict), TreeNode(data=app_head_dict)70    rec_manager, policy_manager = TreeNode(data=rec_manager_dict), TreeNode(data=policy_manager_dict)71    cto.add_child(child=infra_head), cto.add_child(child=app_head)72    hr_head.add_child(child=rec_manager), hr_head.add_child(child=policy_manager)73    # Nodes (Level 3) - Cloud Manager, App Manager74    cloud_manager_dict = {'Name': 'Dhaval', 'Designation': 'Cloud Manager'}75    app_manager_dict = {'Name': 'Abhijit', 'Designation': 'App Manager'}76    cloud_manager, app_manager = TreeNode(data=cloud_manager_dict), TreeNode(data=app_manager_dict)77    infra_head.add_child(child=cloud_manager), infra_head.add_child(child=app_manager)78    return root79#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#80#------#81# Main #82#------#83if __name__ == '__main__':84    root = build_product_tree()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
