text:
from __future__ import print_function, absolute_import, division

"""
This module compares what datasets are currently in
/smov/cos/Data (by accessing the COS database) versus all datasets currently
archived in MAST. All missing datasets will be requested and placed in
the appropriate directory in /smov/cos/Data.

Use:
    This script is intended to be used in a cron job.
"""

__author__ = "Jo Taylor"
__date__ = "04-13-2016"
__maintainer__ = "Jo Taylor"
__email__ = "jotaylor@stsci.edu"

from datetime import datetime as dt
import urllib
import time
import pickle
import os
import yaml
import argparse
import glob
import pyfastcopy
import shutil
import numpy as np
from subprocess import Popen, PIPE
from collections import defaultdict

from ..database.db_tables import load_connection
from .manualabor import parallelize, combine_2dicts, compress_files, timefunc
from .retrieval_info import BASE_DIR, CACHE

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def connect_cosdb():
    """
    Connect to the COS team's database, cos_cci, on the server greendev to
    determine which COS datasets are currently in the local repository.

    Parameters:
    -----------
        None

    Returns:
    --------
        all_smov : list
            All rootnames of all files in the COS greendev database.
    """

    # Open the configuration file for the COS database connection (MYSQL).
    config_file = os.path.join(os.environ['HOME'], "configure.yaml")
    with open(config_file, 'r') as f:
        SETTINGS = yaml.load(f)

        print("Querying COS greendev database for existing data...")
        # Connect to the database.
        Session, engine = load_connection(SETTINGS['connection_string'])
        sci_files = list(engine.execute("SELECT DISTINCT rootname FROM files "
                                        "WHERE rootname IS NOT NULL;"))
        cci_files = list(engine.execute("SELECT DISTINCT name FROM files "
                                        "WHERE rootname IS NULL AND "
                                        "LEFT(name,1)='l';"))

        # Store SQLAlchemy results as lists
        all_sci = [row["rootname"].upper() for row in sci_files]
        all_cci = [row["name"].strip("_cci.fits.gz").upper() for row in cci_files]
        all_smov = all_sci + all_cci

        # Close connection
        engine.dispose()

        return all_smov

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def get_all_mast_data():
    """
    Connect to the MAST database on HARPO and store lists of all files.

    Parameters:
    -----------
        None

    Returns:
    --------
        all_mast_priv : dictionary
            Dictionary where the keys are rootnames of proprietary files and
            the values are the corresponding proposal IDs.
        all_mast_pub : dictionary
            Dictionary where the keys are rootnames of publicly available files
            and the values are the corresponding proposal IDs.
    """

    # Get all jitter, science (ASN), and CCI datasets.
    print("Querying MAST databases for all COS data...")
    query0 = "SELECT distinct ads_data_set_name,ads_pep_id FROM "\
    "archive_data_set_all WHERE ads_instrument='cos' "\
    "AND ads_data_set_name NOT LIKE 'LZ%' AND "\
    "ads_best_version='Y' AND ads_archive_class!='EDT'\ngo"
    # Some COS observations don't have ads_instrumnet=cos
    query1 = "SELECT distinct ads_data_set_name,ads_pep_id FROM "\
    "archive_data_set_all WHERE LEN(ads_data_set_name)=9 "\
    "AND ads_data_set_name LIKE 'L%' AND ads_instrument='cos' "\
    "AND ads_best_version='Y' and ads_archive_class!='EDT'\ngo"

    # Now expand on the previous queries by only selecting non-propietary data.
    utc_dt = dt.utcnow()
    utc_str = utc_dt.strftime("%b %d %Y %I:%M:%S%p")
    query0_pub = query0.split("\ngo")[0] + " and ads_release_date<='{0}'\ngo".format(utc_str)
    query1_pub = query1.split("\ngo")[0] + " and ads_release_date<='{0}'\ngo".format(utc_str)

    query0_priv = query0.split("\ngo")[0] + " and ads_release_date>='{0}'\ngo".format(utc_str)
    query1_priv = query1.split("\ngo")[0] + " and ads_release_date>='{0}'\ngo".format(utc_str)

    all_cos_priv = janky_connect(query0_priv)
    all_l_priv = janky_connect(query1_priv)
    all_mast_sql_priv = all_cos_priv + all_l_priv

    all_cos_pub = janky_connect(query0_pub)
    all_l_pub = janky_connect(query1_pub)
    all_mast_sql_pub = all_cos_pub + all_l_pub

    all_mast_priv = _sql_to_dict(all_mast_sql_priv)
    all_mast_pub = _sql_to_dict(all_mast_sql_pub)

    return all_mast_priv, all_mast_pub

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def get_pid(rootname):

    program_id = rootname[1:4].upper()
    query = "SELECT DISTINCT proposal_id FROM executed WHERE "\
    "program_id='{0}'\ngo".format(program_id)
    prop = janky_connect(query, database="opus_rep")

    if len(prop) == 0:
        return None
    else:
        return prop[0]

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def find_missing_exts(existing, existing_root):
    """
    If something causes the code to crash mid-copy, some data products may
    not be copied. The only way to check is this to determine what the
    expected products are and compare that to what is currently in central
    store.

    Parameters:
    -----------
        existing : list
            List of all existing files currently in COSMO, this includes
            path name and filetype, e.g.
            /grp/hst/cos2/smov_testing/13974/lcqf15meq_counts.fits
        existing_root : list
            List of rootnames all existing files currently in COSMO.

    Returns:
    --------
        missing_files : list

    """

    # Split query into chunks of 10K to avoid running out of processer
    # resources.
    chunksize= 10000
    chunks = [existing_root[i:i+chunksize] for i in range(0, len(existing_root), chunksize)]

    missing_files_l = []
    pids = []
    for chunk in chunks:
        query = "SELECT distinct afi_file_name, ads_pep_id"\
        " FROM archive_files, archive_data_set_all WHERE"\
        " ads_data_set_name=afi_data_set_name"\
        " AND ads_best_version='y'"\
        " AND ads_generation_date= afi_generation_date"\
        " AND ads_archive_class=afi_archive_class"\
        " AND ads_archive_class IN ('cal','asn')"\
        " AND ads_data_set_name IN {0}\ngo".format(tuple(chunk))

        filenames = janky_connect(query)
        expected_files_d = _sql_to_dict(filenames)
        expected_files_s = set([row[0] for row in filenames])
        existing_files_s = set([os.path.basename(x).strip(".gz") for x in existing])
        missing_files_l_chunk = list(expected_files_s - existing_files_s)
        missing_files_l += missing_files_l_chunk
        if len(missing_files_l_chunk) == 0:
            continue
        pids_chunk = [int(expected_files_d[x]) for x in missing_files_l_chunk]
        pids += pids_chunk

    if len(missing_files_l) == 0:
        return None
    missing_files = _group_dict_by_pid(missing_files_l, pids)
    print("{} single extensions missing for {} programs that were already retrieved- this is probably because COSMO crashed in an earlier run.".format(len(missing_files_l), len(missing_files)))
    return missing_files

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def _sql_to_dict(sql_list, groupbykey=True):
    """
    Store results of SQL query (list) as a dictionary with proposal IDs
    as the keys and (individual) dataset rootname as the values.

    Parameters:
    -----------
        sql_list : list
            SQL results from janky_connect() stored as a list.
        groupbykey : Bool
            If True, it will sort SQL 0th results by 1st results, e.g. group
            [["ld5301rfq", "14736"], ["ld5301rtq", "14736"]] ->
            {"14736": ["ld5301rfq", "ld5301rtq"]}
            If False, it will simply turn results into dictionary, e.g.
            [["ld5301rfq", "14736"], ["ld5301rtq", "14736"]] ->
            {"ld5301rfq": "14736", "ld5301rtq": "14736"}.
            Note that, if False, PIDs will not be looked up, so NULL, MMD, CCI,
            etc. programs will not have correct PIDs.

    Returns:
    --------
        sql_dict : dictionary
            Dictionary of SQL results.
    """

    # Store results as dictionaries. Don't get podfiles (LZ*)
    sql_dict = {row[0]:row[1] for row in sql_list if not row[0].startswith("LZ_")}

    if groupbykey is True:
        badfiles = []
        for key in list(sql_dict):
            if sql_dict[key] == "NULL":
                if key.startswith("LF") or key.startswith("LN") or key.startswith("L_"):
                    sql_dict[key] = "CCI"
                elif len(key) == 9:
                    prop = get_pid(key)
                    if prop is None:
                        badfiles.append(key)
                    else:
                        sql_dict[key] = prop
                else:
                    sql_dict.pop(key, None)

    return sql_dict

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def janky_connect(query_string, database=None):
    """
    Connecting to the MAST database is near impossible using SQLAlchemy.
    Instead, connect through a subprocess call.

    Parameters:
    -----------
        query_string : str
            SQL query text.

    Returns:
    --------
        result : list
            List where each index is a list consisting of [rootname, PID]]

    """

    # Open the configuration file for the MAST database connection (TSQL).
    config_file = os.path.join(os.environ['HOME'], "configure2.yaml")
    with open(config_file, 'r') as f:
        SETTINGS = yaml.load(f)
    if database is not None:
        SETTINGS["database"] = database

    # Connect to the MAST database through tsql.
    # Should use shlex, but this strips the correct format of the username
    # for AD login, i.e. stsci\\jotaylor. Instead, do it manually.
    #command_line = "tsql -S{0} -D{1} -U{2} -P{3} -t'|||'".format(SETTINGS["server"],SETTINGS["database"], SETTINGS["username"], SETTINGS["password"])
    #args = shlex.split(command_line)
    args = ["tsql",
            "-S{}".format(SETTINGS["server"]),
            "-D{}".format(SETTINGS["database"]),
            "-U{}".format(SETTINGS["username"]),
            "-P{}".format(SETTINGS["password"]),
            "-t|||"]
    p = Popen(args,
              stdin=PIPE,
              stdout=PIPE,
              stderr=PIPE,
              close_fds=True)
    (transmit, receive, err) = (p.stdin, p.stdout, p.stderr)
    transmit.write(query_string.encode("utf-8"))
    transmit.close()
    query_result0 = receive.readlines()
    receive.close()
    error_report0 = err.readlines()
    err.close()

    query_result = [x.decode("utf-8") for x in query_result0]
    error_report = [x.decode("utf-8") for x in error_report0]

    badness = ["locale", "charset", "1>", "affected"]
    # I can't stop, someone help me.
    # https://imgur.com/xioMcFe (h/t E. Snyder)
    result = [x.strip().split("|||") if "|||" in x else x.strip()
              for x in query_result if not any(y in x for y in badness)]
    # Ensure that nothing was wrong with the query syntax.
    assert (len(error_report) < 3), "Something went wrong in query:{0}".format(error_report[2])

    return result

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def tally_cs(mydir=BASE_DIR, uniq_roots=True):
    """
    For testing purposes, tabulate all files in central store
    (/grp/hst/cos2/smov_testing/) and request all missing datasets.

    Parameters:
    -----------
        None

    Returns:
    --------
        smovfiles : list
            A list of all fits files in BASE_DIR
    """

    print ("Checking {0} for existing data...".format(mydir))
    allsmov = glob.glob(os.path.join(mydir, "*", "*fits*"))
    smovfilenames = [os.path.basename(x) for x in allsmov]
    smovroots = [x.split("_cci")[0].upper() if "cci" in x
                 else x.split("_")[0].upper()
                 for x in smovfilenames]

    if uniq_roots:
        return allsmov, smovfilenames, list(set(smovroots))
    else:
        return allsmov, smovfilenames, smovroots

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def find_missing_data(use_cs):
    """
    Compare the set of all files currently in the COS repository to the list
    all files currently ingested into MAST.

    Parameters:
    -----------
        use_cs : Bool
            Switch to find missing data comparing what is currently on
            central store, as opposed to using the COSMO database.

    Returns:
    --------
        missing_data : dictionary
            Dictionary where each key is the proposal, and values are the
            missing data.
    """

    if use_cs:
        existing, existing_filenames, existing_root = tally_cs()
    else:
        existing_root = connect_cosdb()

    print("Checking to see if there are any missing COS data...")
    missing_exts = find_missing_exts(existing, existing_root)

    mast_priv, mast_pub = get_all_mast_data()

    missing_data_priv = _determine_missing(mast_priv, existing_root)
    missing_data_pub = _determine_missing(mast_pub, existing_root)

    return missing_data_priv, missing_data_pub, missing_exts

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def _determine_missing(in_dict, existing_root):
    """
    Given a dictionary describing all (public or proprietary) data and a
    dictionary describing all the data already downloaded into central store,
    determine what datasets are missing.

    Parameters:
    -----------
        in_dict : dictionary
            For all (public or proprietary) data, a dictionary where each key
            is any PID and the value is one single dataset for that PID
            (i.e. there are multiple keys for the same PID).
        existing_root :
            For all datasets already in central store, a dictionary where each
            key is any PID and the value is one single dataset for that PID
            (i.e. there are multiple keys for the same PID).

    Returns:
    --------
        missing_data : dictionary
            A dictionary of missing data where each key is a PID and the value
            is all missing datsets for that PID.
    """

    # Determine which datasets are missing.
    missing_names = list(set(in_dict.keys()) - set(existing_root))

    missing_props = [int(in_dict[x]) if in_dict[x] not in ["CCI","NULL"]
                     else in_dict[x] for x in missing_names]

    missing_data = _group_dict_by_pid(missing_names, missing_props)

    return missing_data

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def _group_dict_by_pid(filenames, pids):
    # Create dictionaries grouped by proposal ID, it is much easier
    # to retrieve them this way.
    # For most data, determine corresponding proposal ID. CCIs and some
    # odd files will have proposal ID = NULL though.
    keys = set(pids)
    vals = [[] for x in range(len(keys))]
    outd = dict(zip(keys, vals))
    for i in range(len(filenames)):
        outd[pids[i]].append(filenames[i])

    return outd

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def pickle_missing(missing_data, pkl_file=None):
    """
    Pickle the dictionary describing missing data.

    Parameters:
    -----------
        missing_data : dictionary
            Dictionary where the key is the proposal, and values are the
            missing data.
        pkl_file : str
            Name of output pickle file.

    Returns:
    --------
        Nothing
    """

    if not pkl_file:
        pkl_file = "filestoretrieve.p"
    pickle.dump(missing_data, open(pkl_file, "wb"))
    cwd = os.getcwd()
    print("Missing data written to pickle file {0}".format(os.path.join(cwd,pkl_file)))

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def check_for_pending():
    """
    Check the appropriate URL and get the relevant information about pending
    requests.

    Parameters:
    -----------
        None

    Returns:
    --------
        num : int
            Number of pending archive requests (can be zero)
        badness : Bool
            True if something went wrong with an archive request
            (e.g. status=KILLED)
        status_url : str
            URL to check for requests
    """

    MYUSER = "jotaylor"
    status_url = "http://archive.stsci.edu/cgi-bin/reqstat?reqnum=={0}".format(MYUSER)

    tries = 5
    while tries > 0:
        try:
            urllines0 = urllib.request.urlopen(status_url).readlines()
            urllines = [x.decode("utf-8") for x in urllines0]
        except IOError:
            print("Something went wrong connecting to {0}.".format(status_url))
            tries -= 1
            time.sleep(30)
            badness = True
        else:
            tries = -100
            for line in urllines:
                mystr = "of these requests are still RUNNING"
                if mystr in line:
                    num_requests = [x.split(mystr) for x in line.split()][0][0]
                    assert (num_requests.isdigit()), "A non-number was found in line {0}!".format(line)
                    num = int(num_requests)
                    badness = False
                    break
                else:
                    badness = True

    return num, badness, status_url

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def ensure_no_pending():
    """
    Check for any pending archive requests, and if there are any, wait until
    they finish.

    Parameters:
    -----------
        None

    Returns:
    --------
        Nothing.

    """
    num_requests, badness, status_url = check_for_pending()
    while num_requests > 0:
        print("There are still {0} requests pending from a previous COSMO run, waiting 5 minutes...".format(num_requests))
        assert (badness == False), "Something went wrong during requests, check {0}".format(status_url)
        time.sleep(300)
        num_requests, badness, status_url = check_for_pending()
    else:
        print("All pending requests finished, moving on!")

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def tabulate_cache():
    """
    Determine all the datasets that are currently in the COS central store
    cache.

    Parameters:
    -----------
        None

    Returns:
    --------
        array : array
            The full path of every dataset in the cache.
        array : array
            The rootname of every datset in the cache.
    """

    print("\tTabulating list of all cache COS datasets (this may take several minutes)...")
    cos_cache = glob.glob(os.path.join(CACHE, "l*/l*/*fits*"))
    cache_filenames = [os.path.basename(x) for x in cos_cache]
    cache_roots = [x[:9].upper() for x in cache_filenames]

    return np.array(cos_cache), np.array(cache_filenames), np.array(cache_roots)

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def find_missing_in_cache(missing_dict, cache_a, cos_cache):
    total_copied = 0
    start_missing = len(missing_dict.keys())
    to_copy_d = {}
    for key in list(missing_dict):
        missing_files = missing_dict[key]
        missing_in_cache = list(set(missing_files) & set(cache_a))
        if len(missing_in_cache) == 0:
            continue
        total_copied += len(missing_in_cache)

        updated_missing = [x for x in missing_files if x not in missing_in_cache]
        updated_missing = list(set(missing_files) - set(missing_in_cache))

        if not updated_missing:
            missing_dict.pop(key, "Something went terribly wrong, {0} isn't in dictionary".format(key))
        else:
            missing_dict[key] = updated_missing

        # Create a generator where each element is an array with all
        # file types that match each missing dataset. Then concatenate all these
        # individual arrays for ease of copying.
        # Joe said this makes sense, so it's ok, right?
        try:
            to_copy = np.concatenate(tuple( (cos_cache[np.where(cache_a == x)]
                                   for x in missing_in_cache) ))
        except ValueError:
            print("RUH ROH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        to_copy_d[key] = to_copy

    end_missing = len(missing_dict.keys())

    print("\tCopying {} total root(s) from cache, {} complete PID(s)".format(
          total_copied, start_missing-end_missing))

    return missing_dict, to_copy_d
#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def copy_from_cache(to_copy):
    for pid, cache_files in to_copy.items():
        dest = os.path.join(BASE_DIR, str(pid))
        print("\tCopying {} file(s) from cache into {}".format(len(cache_files), dest))
        if not os.path.isdir(dest):
            os.mkdir(dest)

        # By importing pyfastcopy, shutil performance is automatically
        # enhanced
        compress_dest = dest
        compress_files(cache_files, outdir=compress_dest, remove_orig=False,
                       verbose=False)

    return to_copy

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def copy_cache(missing_data, missing_exts=None, prl=True):
    """
    When there are missing public datasets, check to see if any of them can
    be copied from the COS cache in central store, which is faster than
    requesting them from MAST.

    Parameters:
    -----------
        missing_data : dictionary
            Dictionary where each key is the proposal, and values are the
            missing data.
        missing_exts : dictionary
            Dictionary where each key is the proposal, and values are
            missing single raw or product files from previous COSMO runs.
        out_q : multiprocess.Queue object
            If not None, the output of this function will be passed to
            the Queue object in order to be curated during multiprocessing.

    Returns:
    --------
        missing_data : dictionary
            Dictionary where each key is the proposal, and values are the
            missing data after copying any available data from the cache.
    """

    cos_cache, cache_filenames, cache_roots = tabulate_cache()

    missing_data, to_copy_root = find_missing_in_cache(missing_data, cache_roots, cos_cache)

    if missing_exts is not None:
        print("looking at exts")
        missing_exts, to_copy_exts = find_missing_in_cache(missing_exts, cache_filenames, cos_cache)
        to_copy = combine_2dicts(to_copy_root, to_copy_exts)
        missing_ext_roots = {k:list(set([dataset[:9].upper() for dataset in v])) for k,v in missing_exts.items()}
        still_missing = combine_2dicts(missing_data, missing_ext_roots)
    else:
        to_copy = to_copy_root
        still_missing = missing_data

    if to_copy:
        parallelize("smart", "check_usage", copy_from_cache, to_copy)

    return still_missing

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def copy_entire_cache(cos_cache):
    """
    In development.
    """
    prop_map = {}
    for item in cos_cache:
        filename = os.path.basename(item)
        ippp = filename[:4]

        if not ippp in prop_map.keys():
            hdr0 = pf.getheader(item,0)
            proposid = hdr0["proposid"]
            prop_map[ippp] = proposid
        else:
            proposid = prop_map[ippp]

        dest = os.path.join(BASE_DIR, proposid, filename)
        # By importing pyfastcopy, shutil performance is automatically enhanced
        shutil.copyfile(item, dest)

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

def check_proprietary_status(rootnames):
    '''
    Given a series of rootnames, sort them by PID and proprietary status:
    65545 for proprietary (gid for STSCI/cosgo group) and 6045
    (6045 # gid for STSCI/cosstis group) for public.

    Parameters:
    -----------
        rootnames : array-like
            Rootnames to query.

    Returns:
    --------
        release_dates : dict
            A dictionary whose keys are 65545 for proprietary data, or
            6045 for public data and whose values are dictionaries
            ordered by PID and values are rootnames.
    '''
    chunksize = 10000
    chunks = [rootnames[i:i+chunksize] for i in range(0, len(rootnames), chunksize)]
    priv_id = 65545
    pub_id = 6045

    sql_results = []
    for chunk in chunks:
        query = "SELECT DISTINCT ads_data_set_name, ads_release_date, ads_pep_id "\
        "FROM archive_data_set_all "\
        "WHERE ads_best_version='Y' "\
        "AND ads_archive_class IN ('cal', 'asn') "\
        "AND ads_data_set_name IN {}\ngo".format(tuple(chunk))

        results = janky_connect(query)
        sql_results += results

    utc_dt = dt.utcnow()
    utc_str = utc_dt.strftime("%b %d %Y %I:%M:%S%p")

    propr_status = []
    filenames = []
    for row in sql_results:
        file_dt = dt.strptime(row[1], "%b %d %Y %I:%M:%S:%f%p")
        if file_dt <= utc_dt:
            propr_status.append(pub_id)
        else:
            propr_status.append(priv_id)
        filenames.append(row[0])

    return propr_status, filenames

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

@timefunc
def find_new_cos_data(pkl_it, pkl_file, use_cs=False, prl=True):
    """
    Workhorse function, determine what data already exist on disk/in the
    greendev DB and determine if data are missing. Copy any data from local
    cache if possible.

    Parameters:
    -----------
        pkl_it : Bool
            Switch to pickle final dictionary of data to requested from MAST.
        pkl_file : str
            Name of output pickle file.
        use_cs :
            Switch to find missing data comparing what is currently on
            central store, as opposed to using the COSMO database.
         prl :
            Switch to run manualabor in parallel or not.

    Returns:
    --------
        all_missing_data : dictionary
            Dictionary of all datasets that need to be requested from MAST,
            where each key is a PID and the value is a list of all missing
            datasets for that PID.
    """
    print("*"*72)
    missing_data_priv, missing_data_pub, missing_exts = find_missing_data(use_cs)
    print("\t{} proprietary program(s) missing: {}\n\t{} public program(s) missing: {}".format(
          len(missing_data_priv.keys()), list(missing_data_priv.keys()),
          len(missing_data_pub.keys()), list(missing_data_pub.keys()) ))

    if missing_data_pub:
        print("Checking to see if any missing public data is in local cache...")
        missing_data_pub_rem = copy_cache(missing_data_pub, missing_exts)
        # Some nonstandard data isn't stored in the cache (e.g. MMD), so
        # check if any other public data needs to be retrieved.
        if missing_data_pub_rem:
            all_missing_data = missing_data_priv.copy()
            for k,v in missing_data_pub_rem.items():
                if k in all_missing_data:
                    all_missing_data[k] = list(set(all_missing_data[k]) |
                                               set(v))
                else:
                    all_missing_data[k] = v
        else:
            all_missing_data = missing_data_priv
    elif missing_data_priv:
        print("All missing data are proprietary.")
        all_missing_data = missing_data_priv
    else:
        print("There are no missing data.")
        all_missing_data = {}

# Not utilized for the moment, see Issue #22 on github.
#    ensure_no_pending()

    if pkl_it:
        pickle_missing(all_missing_data, pkl_file)

    return all_missing_data

#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", dest="pkl_it", action="store_true", default=False,
                        help="Save output to pickle file")
    parser.add_argument("--pklfile", dest="pkl_file", default=None,
                        help="Name for output pickle file")
    parser.add_argument("--cs", dest="use_cs", action="store_true",
                        default=False,
                        help="Find missing data comparing to central store, not DB")
    parser.add_argument("--prl", dest="prl", action="store_false",
                        default=True, help="Parallellize functions")
    args = parser.parse_args()

    find_new_cos_data(args.pkl_it, args.pkl_file, args.use_cs,
                      args.prl, False)


text:
package com.msopentech.odatajclient.engine.data.json;

import com.msopentech.odatajclient.engine.data.AbstractPayloadObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.msopentech.odatajclient.engine.data.LinkCollectionResource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * Link from an entry, represented via JSON.
 */
public class JSONLinkCollection extends AbstractPayloadObject implements LinkCollectionResource {

    private static final long serialVersionUID = -5006368367235783907L;

    /**
     * JSON link URL representation.
     */
    static class JSONLinkURL extends AbstractPayloadObject {

        private static final long serialVersionUID = 5365055617973271468L;

        private URI url;

        public URI getUrl() {
            return url;
        }

        public void setUrl(final URI url) {
            this.url = url;
        }
    }

    @JsonProperty(value = "odata.metadata", required = false)
    private URI metadata;

    @JsonProperty(required = false)
    private URI url;

    @JsonProperty(value = "value", required = false)
    private final List<JSONLinkURL> links = new ArrayList<JSONLinkURL>();

    @JsonProperty(value = "odata.nextLink", required = false)
    private String next;

    /**
     * Gets the metadata URI.
     */
    public URI getMetadata() {
        return metadata;
    }

    /**
     * Sets the metadata URI.
     *
     * @param metadata metadata URI.
     */
    public void setMetadata(final URI metadata) {
        this.metadata = metadata;
    }

    /**
     * {@inheritDoc }
     */
    @JsonIgnore
    @Override
    public List<URI> getLinks() {
        final List<URI> result = new ArrayList<URI>();

        if (this.url == null) {
            for (JSONLinkURL link : links) {
                result.add(link.getUrl());
            }
        } else {
            result.add(this.url);
        }

        return result;
    }

    /**
     * {@inheritDoc }
     */
    @JsonIgnore
    @Override
    public void setNext(final URI next) {
        this.next = next == null ? null : next.toASCIIString();
    }

    /**
     * {@inheritDoc }
     */
    @JsonIgnore
    @Override
    public URI getNext() {
        return next == null ? null : URI.create(next);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ConsoleLib.Console;
using ConsoleLib.Console.Networking;
using ConsoleLib.Processors.JintConsoleProcessor;

namespace TestConsoleHost
{
    public class Program
    {
        static void Main(string[] args)
        {
            var test = new TestUtils();

            // Initialize the console
            var sourceObj = new object();
            ConsoleManager.Instance.InitializeProcessor(new JintConsoleProcessor());
            ConsoleManager.Instance.RegisterObjectToConsole(sourceObj, "test", test);
            ConsoleLib.Helpers.Formatters.RegisterJsonObjectFormatter(sourceObj);

            dynamic expandoTest = new ExpandoObject();;
            expandoTest.abc = "def";
            ConsoleManager.Instance.RegisterObjectToConsole(sourceObj, "expandoTest", expandoTest);

            var host = new ConsoleServiceHost("localhost", 4000);

            Console.WriteLine("Server started, waiting for commands");

            while (!test.Quit)
            {
                // Keep looping until quit has been called
                Thread.Sleep(100);
            }

            ConsoleManager.Instance.UnregisterObjectsFromSource(sourceObj);
        }

        public class TestUtils
        {
            public bool Quit { get; set; }

            public void Print(string message)
            {
                ConsoleManager.Instance.AddOutput(message);
            }
        }
    }
}


text:
from msrest.pipeline import ClientRawResponse

from .. import models

class BasicOperationsOperations(object):
    """BasicOperationsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer

        self.config = config

    def get_valid(
            self, custom_headers=None, raw=False, **operation_config):
        """Get complex type {id: 2, name: 'abc', color: 'YELLOW'}.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Basic
         <Fixtures.AcceptanceTestsBodyComplex.models.Basic>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<Fixtures.AcceptanceTestsBodyComplex.models.ErrorException>`
        """
        # Construct URL
        url = '/complex/basic/valid'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Basic', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def put_valid(
            self, complex_body, custom_headers=None, raw=False, **operation_config):
        """Please put {id: 2, name: 'abc', color: 'Magenta'}.

        :param complex_body: Please put {id: 2, name: 'abc', color: 'Magenta'}
        :type complex_body: :class:`Basic
         <Fixtures.AcceptanceTestsBodyComplex.models.Basic>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<Fixtures.AcceptanceTestsBodyComplex.models.ErrorException>`
        """
        # Construct URL
        url = '/complex/basic/valid'

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(complex_body, 'Basic')

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get_invalid(
            self, custom_headers=None, raw=False, **operation_config):
        """Get a basic complex type that is invalid for the local strong type.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Basic
         <Fixtures.AcceptanceTestsBodyComplex.models.Basic>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<Fixtures.AcceptanceTestsBodyComplex.models.ErrorException>`
        """
        # Construct URL
        url = '/complex/basic/invalid'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Basic', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_empty(
            self, custom_headers=None, raw=False, **operation_config):
        """Get a basic complex type that is empty.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Basic
         <Fixtures.AcceptanceTestsBodyComplex.models.Basic>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<Fixtures.AcceptanceTestsBodyComplex.models.ErrorException>`
        """
        # Construct URL
        url = '/complex/basic/empty'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Basic', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_null(
            self, custom_headers=None, raw=False, **operation_config):
        """Get a basic complex type whose properties are null.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Basic
         <Fixtures.AcceptanceTestsBodyComplex.models.Basic>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<Fixtures.AcceptanceTestsBodyComplex.models.ErrorException>`
        """
        # Construct URL
        url = '/complex/basic/null'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Basic', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def get_not_provided(
            self, custom_headers=None, raw=False, **operation_config):
        """Get a basic complex type while the server doesn't provide a response
        payload.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`Basic
         <Fixtures.AcceptanceTestsBodyComplex.models.Basic>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`ErrorException<Fixtures.AcceptanceTestsBodyComplex.models.ErrorException>`
        """
        # Construct URL
        url = '/complex/basic/notprovided'

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Basic', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized


text:
redirect_to: https://hub.docker.com/_/centos/
redirect_from:
- /samples/centos/
---


text:
app.controller('studentEditController', function ($http, $scope, cfpLoadingBar, $routeParams) {
	cfpLoadingBar.start();

	$scope.header = 'Students';

	$scope.userData = {
		userType: '',
		yearLevel: '',
		course: ''
	};

	getAllDropdownValues();

	// TODO -- VALIDATE USER

	function getAllDropdownValues() {

		// get courses
		$http.get(base_url + 'admin/admin/viewCourses/', {
			params: {}
		}).success(function(data) {
			// console.log(data);
			$scope.courses = data;
		}).error(function(data) {
			console.log(data);
		});

		// get year levels
		$http.get(base_url + 'admin/admin/viewYearLevels/', {
			params: {}
		}).success(function(data) {
			// console.log(data);
			$scope.yearLevels = data;
		}).error(function(data) {
			console.log(data);
		});

		// get stud types
		$http.get(base_url + 'admin/admin/viewStudTypes/', {
			params: {}
		}).success(function(data) {
			// console.log(data);
			$scope.userTypes = data;
		}).error(function(data) {
			console.log(data);
		});

	}

	getStudentData();

	// get staffs
	function getStudentData() {
		$scope.state = {};
		var rfid = $routeParams.rfid;

		// http get method
		$http.get(base_url + 'sa/StudentAssistant/viewStudentData/', {
			params: {
				rfid: rfid
			}
		}).success(function(data) {
			var userData = data[0];
			$scope.userData = userData;

			if(userData.isValidated == 1) {
				console.log(userData.isValidated);
				$scope.state = {
					isValidated: true
				};
				$scope.isValidated = true;
			}
			else if(userData.isValidated == 2) {
				$scope.state = {
					isValidated: false
				};
				$scope.isValidated = false;
			}

			console.log($scope.state);

		}).error(function(data) {
			console.log(data);
		});
	}

	$scope.validateStudent = function() {

		var params = {
			rfid: $scope.userData.rfid
		};

		// console.log(params);

		// return;

		// http post method to submit form data
		$http({
			method  : 'POST',
			url     : base_url + 'sa/StudentAssistant/validateStudent/',
			data    : $.param(params),
			headers : { 'Content-Type': 'application/x-www-form-urlencoded' },

		}).success(function(data) {
			// console.log(data);
			if(data == 1) {
				$scope.isValidated = true;
				alert('Student is now validated.');
				window.location.reload();
			}

		}).error(function(data) {
			console.log(data);
		});

	}

	cfpLoadingBar.complete();

});


text:
<?php

namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Session\Session;

class PlantControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient(array(), array(
            'PHP_AUTH_USER' => 'testuser',
            'PHP_AUTH_PW' => 'test123'
        ));

        $container = $client->getContainer();
        $container->get('session')->set('activeFarm', 1);

        $crawler = $client->request('GET', '/plants');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
}


text:
/* Galleria Fullscreen Theme 2013-11-04 | http://galleria.io/license/ | (c) Aino */

#galleria-loader{height:1px!important}

html,
body { background: #000 }
.galleria-container {
    height: 100%;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background: #000;
    -webkit-font-smoothing: antialiased;
}
.galleria-container img {
    -moz-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
}
.galleria-stage {
    width: 100%;
    height: 100%;
    position: absolute;
}
.galleria-thumbnails-container {
    position: absolute;
    bottom: 0;
    z-index: 2;
    padding-top: 16px;
    width: 100%;
}
.galleria-container.videoplay .galleria-thumbnails-container { display:none!important; }
.galleria-container.videoplay .galleria-image-nav { top:80px; bottom:80px; height:auto; }

.galleria-thumbnails-tab {
    opacity: .7;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)";
    filter: alpha(opacity=70);
    position: absolute;
    left: 50%;
    margin-left: -50px;
    top: 0;
    height: 16px;
    width: 100px;
    background: #000 url(up.gif) no-repeat 50% 5px;
    cursor: pointer;
    -moz-border-radius-topleft: 4px;
    -moz-border-radius-topright: 4px;
    -webkit-border-top-right-radius: 4px;
    -webkit-border-top-left-radius: 4px;
}
.galleria-container.light .galleria-thumbnails-tab {
    background:#fff url(up-neg.gif) no-repeat 50% 50%;
    opacity: 1;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
}
.galleria-thumbnails-tab:hover {
    opacity: 1;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
}
.galleria-thumbnails-tab.open,
.galleria-thumbnails-tab.open:hover {
    background-image: url(down.gif);
    opacity: 1;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
}
.galleria-container.light .galleria-thumbnails-tab.open,
.galleria-container.light .galleria-thumbnails-tab.open:hover {
    background-image: url(down-neg.gif);
}
.galleria-thumbnails {
    background: #000;
    overflow: hidden;
}
.galleria-thumbnails-list {
    background: #000;
    padding-top: 5px;
    padding-bottom: 5px;
    overflow: hidden;
}
.galleria-container.light .galleria-thumbnails,
.galleria-container.light .galleria-thumbnails-list {
    background:#fff;
}
.galleria-thumbnails .galleria-image {
    width: 80px;
    height: 50px;
    float: left;
    cursor: pointer;
    margin-right: 5px;
}
.galleria-thumbnails .galleria-image img { background: #000 }
.galleria-thumbnails .active { cursor: default }
.galleria-carousel .galleria-thumbnails-list {
    border-left: 30px solid #000;
    border-right: 30px solid #000;
}
.galleria-container.light .galleria-carousel .galleria-thumbnails-list {
    border-color: #fff;
}
.galleria-image-nav {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
.galleria-image-nav-right,
.galleria-image-nav-left {
    width: 100px;
    right: 0;
    top: 0;
    bottom: 0;
    background: url(r.gif) no-repeat 50% 50%;
    position: absolute;
    cursor: pointer;
    z-index: 2;
    display: none;
}
.galleria-container.smallarrows .galleria-image-nav-right {
    background-image: url(r-neg.png);
}
.galleria-image-nav-left {
    left: 0;
    right: auto;
    background-image: url(l.gif);
}
.galleria-container.smallarrows .galleria-image-nav-left {
    background-image: url(l-neg.png);
}
.galleria-loader {
    width: 30px;
    height: 30px;
    background: #fff url(loader.gif) no-repeat 50% 50%;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -15px;
    margin-left: -15px;
    z-index: 3;
}
.galleria-info {
    z-index: 4;
    font: 13px/1.4 helvetica,arial,sans-serif;
    color: #fff;
    position: absolute;
    top: 0;
    width: 100%;
    border-top: 2px solid #000;
    display: none;
    text-align: center;
    padding: 10px 0;
    background: rgba(0,0,0,.5);
    border-bottom:1px solid rgba(0,0,0,.1);
}
.galleria-container.light .galleria-info{background:rgba(255,255,255,.5);color:#000;}
.galleria-info-text {
    width: 50%;
    margin: 0 auto;
}
.galleria-info-title { font-weight: bold; display: inline-block; margin-right:10px; }
.galleria-info-description { display:inline-block; }
.galleria-thumb-nav-left,
.galleria-thumb-nav-right {
    cursor: pointer;
    display: none;
    background: url(p.gif) no-repeat 50% 50%;
    position: absolute;
    left: 5px;
    top: 21px;
    bottom: 5px;
    width: 20px;
    z-index: 3;
    opacity: .8;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";
    filter: alpha(opacity=80);
}
.galleria-container.light .galleria-thumb-nav-left{
    background-image: url(p-neg.png);
}
.galleria-thumb-nav-right {
    background-image: url(n.gif);
    left: auto;
    right: 5px;
}
.galleria-container.light .galleria-thumb-nav-right{
    background-image: url(n-neg.png);
}
.galleria-carousel .galleria-thumb-nav-left,
.galleria-carousel .galleria-thumb-nav-right { display: block }
.galleria-carousel .galleria-thumb-nav-left:hover,
.galleria-carousel .galleria-thumb-nav-right:hover { background-color: #222 }
.galleria-thumb-nav-left.disabled,
.galleria-thumb-nav-right.disabled,
.galleria-thumb-nav-left.disabled:hover,
.galleria-thumb-nav-right.disabled:hover {
    opacity: .2;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
    filter: alpha(opacity=20);
    cursor: default;
}
.galleria-container.light .galleria-carousel .galleria-thumb-nav-left:hover,
.galleria-container.light .galleria-carousel .galleria-thumb-nav-right:hover { background-color: #ddd }


text:
package excelize

import (
	"encoding/xml"
	"fmt"
	"math/rand"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func BenchmarkStreamWriter(b *testing.B) {
	file := NewFile()
	defer func() {
		if err := file.Close(); err != nil {
			b.Error(err)
		}
	}()
	row := make([]interface{}, 10)
	for colID := 0; colID < 10; colID++ {
		row[colID] = colID
	}

	for n := 0; n < b.N; n++ {
		streamWriter, _ := file.NewStreamWriter("Sheet1")
		for rowID := 10; rowID <= 110; rowID++ {
			cell, _ := CoordinatesToCellName(1, rowID)
			_ = streamWriter.SetRow(cell, row)
		}
	}

	b.ReportAllocs()
}

func TestStreamWriter(t *testing.T) {
	file := NewFile()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)

	// Test max characters in a cell.
	row := make([]interface{}, 1)
	row[0] = strings.Repeat("c", TotalCellChars+2)
	assert.NoError(t, streamWriter.SetRow("A1", row))

	// Test leading and ending space(s) character characters in a cell.
	row = make([]interface{}, 1)
	row[0] = " characters"
	assert.NoError(t, streamWriter.SetRow("A2", row))

	row = make([]interface{}, 1)
	row[0] = []byte("Word")
	assert.NoError(t, streamWriter.SetRow("A3", row))

	// Test set cell with style and rich text.
	styleID, err := file.NewStyle(&Style{Font: &Font{Color: "#777777"}})
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.SetRow("A4", []interface{}{
		Cell{StyleID: styleID},
		Cell{Formula: "SUM(A10,B10)", Value: " preserve space "},
	},
		RowOpts{Height: 45, StyleID: styleID}))
	assert.NoError(t, streamWriter.SetRow("A5", []interface{}{
		&Cell{StyleID: styleID, Value: "cell <>&'\""},
		&Cell{Formula: "SUM(A10,B10)"},
		[]RichTextRun{
			{Text: "Rich ", Font: &Font{Color: "2354e8"}},
			{Text: "Text", Font: &Font{Color: "e83723"}},
		},
	}))
	assert.NoError(t, streamWriter.SetRow("A6", []interface{}{time.Now()}))
	assert.NoError(t, streamWriter.SetRow("A7", nil, RowOpts{Height: 20, Hidden: true, StyleID: styleID}))
	assert.EqualError(t, streamWriter.SetRow("A8", nil, RowOpts{Height: MaxRowHeight + 1}), ErrMaxRowHeight.Error())

	for rowID := 10; rowID <= 51200; rowID++ {
		row := make([]interface{}, 50)
		for colID := 0; colID < 50; colID++ {
			row[colID] = rand.Intn(640000)
		}
		cell, _ := CoordinatesToCellName(1, rowID)
		assert.NoError(t, streamWriter.SetRow(cell, row))
	}

	assert.NoError(t, streamWriter.Flush())
	// Save spreadsheet by the given path.
	assert.NoError(t, file.SaveAs(filepath.Join("test", "TestStreamWriter.xlsx")))

	// Test set cell column overflow.
	assert.ErrorIs(t, streamWriter.SetRow("XFD51201", []interface{}{"A", "B", "C"}), ErrColumnNumber)
	assert.NoError(t, file.Close())

	// Test close temporary file error.
	file = NewFile()
	streamWriter, err = file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	for rowID := 10; rowID <= 25600; rowID++ {
		row := make([]interface{}, 50)
		for colID := 0; colID < 50; colID++ {
			row[colID] = rand.Intn(640000)
		}
		cell, _ := CoordinatesToCellName(1, rowID)
		assert.NoError(t, streamWriter.SetRow(cell, row))
	}
	assert.NoError(t, streamWriter.rawData.Close())
	assert.Error(t, streamWriter.Flush())

	streamWriter.rawData.tmp, err = os.CreateTemp(os.TempDir(), "excelize-")
	assert.NoError(t, err)
	_, err = streamWriter.rawData.Reader()
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.rawData.tmp.Close())
	assert.NoError(t, os.Remove(streamWriter.rawData.tmp.Name()))

	// Test create stream writer with unsupported charset.
	file = NewFile()
	file.Sheet.Delete("xl/worksheets/sheet1.xml")
	file.Pkg.Store("xl/worksheets/sheet1.xml", MacintoshCyrillicCharset)
	_, err = file.NewStreamWriter("Sheet1")
	assert.EqualError(t, err, "XML syntax error on line 1: invalid UTF-8")
	assert.NoError(t, file.Close())

	// Test read cell.
	file = NewFile()
	streamWriter, err = file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{Cell{StyleID: styleID, Value: "Data"}}))
	assert.NoError(t, streamWriter.Flush())
	cellValue, err := file.GetCellValue("Sheet1", "A1")
	assert.NoError(t, err)
	assert.Equal(t, "Data", cellValue)

	// Test stream reader for a worksheet with huge amounts of data.
	file, err = OpenFile(filepath.Join("test", "TestStreamWriter.xlsx"))
	assert.NoError(t, err)
	rows, err := file.Rows("Sheet1")
	assert.NoError(t, err)
	cells := 0
	for rows.Next() {
		row, err := rows.Columns()
		assert.NoError(t, err)
		cells += len(row)
	}
	assert.NoError(t, rows.Close())
	assert.Equal(t, 2559559, cells)
	// Save spreadsheet with password.
	assert.NoError(t, file.SaveAs(filepath.Join("test", "EncryptionTestStreamWriter.xlsx"), Options{Password: "password"}))
	assert.NoError(t, file.Close())
}

func TestStreamSetColWidth(t *testing.T) {
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.SetColWidth(3, 2, 20))
	assert.ErrorIs(t, streamWriter.SetColWidth(0, 3, 20), ErrColumnNumber)
	assert.ErrorIs(t, streamWriter.SetColWidth(MaxColumns+1, 3, 20), ErrColumnNumber)
	assert.EqualError(t, streamWriter.SetColWidth(1, 3, MaxColumnWidth+1), ErrColumnWidth.Error())
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{"A", "B", "C"}))
	assert.ErrorIs(t, streamWriter.SetColWidth(2, 3, 20), ErrStreamSetColWidth)
}

func TestStreamSetPanes(t *testing.T) {
	file, paneOpts := NewFile(), `{"freeze":true,"split":false,"x_split":1,"y_split":0,"top_left_cell":"B1","active_pane":"topRight","panes":[{"sqref":"K16","active_cell":"K16","pane":"topRight"}]}`
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.SetPanes(paneOpts))
	assert.EqualError(t, streamWriter.SetPanes(""), "unexpected end of JSON input")
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{"A", "B", "C"}))
	assert.ErrorIs(t, streamWriter.SetPanes(paneOpts), ErrStreamSetPanes)
}

func TestStreamTable(t *testing.T) {
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)

	// Write some rows. We want enough rows to force a temp file (>16MB).
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{"A", "B", "C"}))
	row := []interface{}{1, 2, 3}
	for r := 2; r < 10000; r++ {
		assert.NoError(t, streamWriter.SetRow(fmt.Sprintf("A%d", r), row))
	}

	// Write a table.
	assert.NoError(t, streamWriter.AddTable("A1", "C2", ""))
	assert.NoError(t, streamWriter.Flush())

	// Verify the table has names.
	var table xlsxTable
	val, ok := file.Pkg.Load("xl/tables/table1.xml")
	assert.True(t, ok)
	assert.NoError(t, xml.Unmarshal(val.([]byte), &table))
	assert.Equal(t, "A", table.TableColumns.TableColumn[0].Name)
	assert.Equal(t, "B", table.TableColumns.TableColumn[1].Name)
	assert.Equal(t, "C", table.TableColumns.TableColumn[2].Name)

	assert.NoError(t, streamWriter.AddTable("A1", "C1", ""))

	// Test add table with illegal options.
	assert.EqualError(t, streamWriter.AddTable("B26", "A21", `{x}`), "invalid character 'x' looking for beginning of object key string")
	// Test add table with illegal cell reference.
	assert.EqualError(t, streamWriter.AddTable("A", "B1", `{}`), newCellNameToCoordinatesError("A", newInvalidCellNameError("A")).Error())
	assert.EqualError(t, streamWriter.AddTable("A1", "B", `{}`), newCellNameToCoordinatesError("B", newInvalidCellNameError("B")).Error())
	// Test add table with unsupported charset content types.
	file.ContentTypes = nil
	file.Pkg.Store(defaultXMLPathContentTypes, MacintoshCyrillicCharset)
	assert.EqualError(t, streamWriter.AddTable("A1", "C2", ""), "XML syntax error on line 1: invalid UTF-8")
}

func TestStreamMergeCells(t *testing.T) {
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.MergeCell("A1", "D1"))
	// Test merge cells with illegal cell reference.
	assert.EqualError(t, streamWriter.MergeCell("A", "D1"), newCellNameToCoordinatesError("A", newInvalidCellNameError("A")).Error())
	assert.NoError(t, streamWriter.Flush())
	// Save spreadsheet by the given path.
	assert.NoError(t, file.SaveAs(filepath.Join("test", "TestStreamMergeCells.xlsx")))
}

func TestStreamInsertPageBreak(t *testing.T) {
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.InsertPageBreak("A1"))
	assert.NoError(t, streamWriter.Flush())
	// Save spreadsheet by the given path.
	assert.NoError(t, file.SaveAs(filepath.Join("test", "TestStreamInsertPageBreak.xlsx")))
}

func TestNewStreamWriter(t *testing.T) {
	// Test error exceptions
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	_, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	_, err = file.NewStreamWriter("SheetN")
	assert.EqualError(t, err, "sheet SheetN does not exist")
}

func TestStreamMarshalAttrs(t *testing.T) {
	var r *RowOpts
	attrs, err := r.marshalAttrs()
	assert.NoError(t, err)
	assert.Empty(t, attrs)
}

func TestStreamSetRow(t *testing.T) {
	// Test error exceptions.
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.EqualError(t, streamWriter.SetRow("A", []interface{}{}), newCellNameToCoordinatesError("A", newInvalidCellNameError("A")).Error())
	// Test set row with non-ascending row number.
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{}))
	assert.EqualError(t, streamWriter.SetRow("A1", []interface{}{}), newStreamSetRowError(1).Error())
	// Test set row with unsupported charset workbook.
	file.WorkBook = nil
	file.Pkg.Store(defaultXMLPathWorkbook, MacintoshCyrillicCharset)
	assert.EqualError(t, streamWriter.SetRow("A2", []interface{}{time.Now()}), "XML syntax error on line 1: invalid UTF-8")
}

func TestStreamSetRowNilValues(t *testing.T) {
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{nil, nil, Cell{Value: "foo"}}))
	streamWriter.Flush()
	ws, err := file.workSheetReader("Sheet1")
	assert.NoError(t, err)
	assert.NotEqual(t, ws.SheetData.Row[0].C[0].XMLName.Local, "c")
}

func TestStreamSetRowWithStyle(t *testing.T) {
	file := NewFile()
	defer func() {
		assert.NoError(t, file.Close())
	}()
	zeroStyleID := 0
	grayStyleID, err := file.NewStyle(&Style{Font: &Font{Color: "#777777"}})
	assert.NoError(t, err)
	blueStyleID, err := file.NewStyle(&Style{Font: &Font{Color: "#0000FF"}})
	assert.NoError(t, err)

	streamWriter, err := file.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	assert.NoError(t, streamWriter.SetRow("A1", []interface{}{
		"value1",
		Cell{Value: "value2"},
		&Cell{Value: "value2"},
		Cell{StyleID: blueStyleID, Value: "value3"},
		&Cell{StyleID: blueStyleID, Value: "value3"},
	}, RowOpts{StyleID: grayStyleID}))
	err = streamWriter.Flush()
	assert.NoError(t, err)

	ws, err := file.workSheetReader("Sheet1")
	assert.NoError(t, err)
	assert.Equal(t, grayStyleID, ws.SheetData.Row[0].C[0].S)
	assert.Equal(t, zeroStyleID, ws.SheetData.Row[0].C[1].S)
	assert.Equal(t, zeroStyleID, ws.SheetData.Row[0].C[2].S)
	assert.Equal(t, blueStyleID, ws.SheetData.Row[0].C[3].S)
	assert.Equal(t, blueStyleID, ws.SheetData.Row[0].C[4].S)
}

func TestStreamSetCellValFunc(t *testing.T) {
	f := NewFile()
	defer func() {
		assert.NoError(t, f.Close())
	}()
	sw, err := f.NewStreamWriter("Sheet1")
	assert.NoError(t, err)
	c := &xlsxC{}
	assert.NoError(t, sw.setCellValFunc(c, 128))
	assert.NoError(t, sw.setCellValFunc(c, int8(-128)))
	assert.NoError(t, sw.setCellValFunc(c, int16(-32768)))
	assert.NoError(t, sw.setCellValFunc(c, int32(-2147483648)))
	assert.NoError(t, sw.setCellValFunc(c, int64(-9223372036854775808)))
	assert.NoError(t, sw.setCellValFunc(c, uint(128)))
	assert.NoError(t, sw.setCellValFunc(c, uint8(255)))
	assert.NoError(t, sw.setCellValFunc(c, uint16(65535)))
	assert.NoError(t, sw.setCellValFunc(c, uint32(4294967295)))
	assert.NoError(t, sw.setCellValFunc(c, uint64(18446744073709551615)))
	assert.NoError(t, sw.setCellValFunc(c, float32(100.1588)))
	assert.NoError(t, sw.setCellValFunc(c, 100.1588))
	assert.NoError(t, sw.setCellValFunc(c, " Hello"))
	assert.NoError(t, sw.setCellValFunc(c, []byte(" Hello")))
	assert.NoError(t, sw.setCellValFunc(c, time.Now().UTC()))
	assert.NoError(t, sw.setCellValFunc(c, time.Duration(1e13)))
	assert.NoError(t, sw.setCellValFunc(c, true))
	assert.NoError(t, sw.setCellValFunc(c, nil))
	assert.NoError(t, sw.setCellValFunc(c, complex64(5+10i)))
}


text:
:host {
    font-family: Consolas, Arial, Helvetica, sans-serif;
    font-size: 0.8em;
}

.message {
    padding: 2px;
    height: 40px;
    background: lightgray;
}

.error {
    background: lightcoral;
}

.success {
    background: lightgreen;
}

button {
    margin: 3px;
}


text:
package com.jiabin.googleplay.base;

import android.app.Application;
import android.content.Context;
import android.os.Handler;

/**
 * @author Administrator
 * @version $Rev$
 * @time 2016/5/9 22:54
 * @des 全局,单例,用于存放一些全局的方法,属性
 * @updateAuthor GeekBin
 * @updateDate $Data$
 * @updateDes ${TODO}$
 */
public class MyApplication extends Application {

    private static Context mContext;

    /**
     * 得到上下文
     * @return
     */
    public static Context getContext() {
        return mContext;
    }

    /**
     * 得到主线程id
     * @return
     */
    public static long getMainThreadId() {
        return mMainThreadId;
    }

    /**
     * 得到主线程的Handler
     * @return
     */
    public static Handler getHandler() {
        return mHandler;
    }

    private static Handler mHandler;
    private static long mMainThreadId;

    @Override
    public void onCreate() {    //程序的入口方法
        /*-------------创建应用里面需要用到的一些共同属性------------*/
        //1.整个App的上下文
        mContext = getApplicationContext();

        //2.主线程Handler对象
        mHandler = new Handler();

        //3.应用程序的主线程id
        mMainThreadId = android.os.Process.myTid();

        /**
         * Tid:ThreadId--线程id
         * Pid:ProcessId--进程id
         * Uid:UserId --用户id
         */
        super.onCreate();
    }
}


text:
Date: 2019-02-22

## Status

Accepted

## Context

The issue motivating this decision, and any context that influences or constrains the decision.

The original author of go-bindata delete their account and then the repo was
recreated under a different owner. The dependency has shifted around enough that
we have lost faith in the intention of the maintainers

[more details here](https://twitter.com/francesc/status/961249107020001280?lang=en)

Also, some of the development use cases around go-bindata (like what is bundled into the code
during a test run or final build) made it hard to reason about.

## Decision

Use [Packr2](https://github.com/gobuffalo/packr/tree/master/v2) instead.

## Consequences

- Improved security, reduced risk of a potential bad actor owning go-bindata

- It improves developer experience

  If you use `go {build,install}`, it will load the files off disk

-	You can no longer use `go get ./...` to install bbl. If you install
  bosh-bootloader, via `go get ./...`, the build will fail since
  the dependencies (the terraform binary in terraform/binary\_dist/ and
  jumpbox-deployment and bosh-deployment in bosh/deployments/) do not exist yet.

  You need to manually add these.

- There is no longer a dev-shim and testing now can fake out the content that
  was previously provided by said shim

- Builds that want to actually bundle the source into bbl must use the packr2
  build tool


text:
package testing

import (
	"testing"

	"github.com/gophercloud/gophercloud/openstack/messaging/v2/messages"
	"github.com/gophercloud/gophercloud/pagination"
	th "github.com/gophercloud/gophercloud/testhelper"
	fake "github.com/gophercloud/gophercloud/testhelper/client"
)

func TestList(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleListSuccessfully(t)

	listOpts := messages.ListOpts{
		Limit: 1,
	}

	count := 0
	err := messages.List(fake.ServiceClient(), QueueName, listOpts).EachPage(func(page pagination.Page) (bool, error) {
		actual, err := messages.ExtractMessages(page)
		th.AssertNoErr(t, err)

		th.CheckDeepEquals(t, ExpectedMessagesSlice[count], actual)
		count++

		return true, nil
	})
	th.AssertNoErr(t, err)

	th.CheckEquals(t, 2, count)
}

func TestCreate(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleCreateSuccessfully(t)

	createOpts := messages.BatchCreateOpts{
		messages.CreateOpts{
			TTL:   300,
			Delay: 20,
			Body: map[string]interface{}{
				"event":     "BackupStarted",
				"backup_id": "c378813c-3f0b-11e2-ad92-7823d2b0f3ce",
			},
		},
		messages.CreateOpts{
			Body: map[string]interface{}{
				"event":         "BackupProgress",
				"current_bytes": "0",
				"total_bytes":   "99614720",
			},
		},
	}

	actual, err := messages.Create(fake.ServiceClient(), QueueName, createOpts).Extract()
	th.AssertNoErr(t, err)
	th.CheckDeepEquals(t, ExpectedResources, actual)
}

func TestGetMessages(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleGetMessagesSuccessfully(t)

	getMessagesOpts := messages.GetMessagesOpts{
		IDs: []string{"9988776655"},
	}

	actual, err := messages.GetMessages(fake.ServiceClient(), QueueName, getMessagesOpts).Extract()
	th.AssertNoErr(t, err)
	th.CheckDeepEquals(t, ExpectedMessagesSet, actual)
}

func TestGetMessage(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleGetSuccessfully(t)

	actual, err := messages.Get(fake.ServiceClient(), QueueName, MessageID).Extract()
	th.AssertNoErr(t, err)
	th.CheckDeepEquals(t, FirstMessage, actual)
}

func TestDeleteMessages(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleDeleteMessagesSuccessfully(t)

	deleteMessagesOpts := messages.DeleteMessagesOpts{
		IDs: []string{"9988776655"},
	}

	err := messages.DeleteMessages(fake.ServiceClient(), QueueName, deleteMessagesOpts).ExtractErr()
	th.AssertNoErr(t, err)
}

func TestPopMessages(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandlePopSuccessfully(t)

	popMessagesOpts := messages.PopMessagesOpts{
		Pop: 1,
	}

	actual, err := messages.PopMessages(fake.ServiceClient(), QueueName, popMessagesOpts).Extract()
	th.AssertNoErr(t, err)
	th.CheckDeepEquals(t, ExpectedPopMessage, actual)
}

func TestDeleteMessage(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleDeleteSuccessfully(t)

	deleteOpts := messages.DeleteOpts{
		ClaimID: "12345",
	}

	err := messages.Delete(fake.ServiceClient(), QueueName, MessageID, deleteOpts).ExtractErr()
	th.AssertNoErr(t, err)
}


text:
package sample

import "reg/t"

type sampler_dummy struct{ v t.Stuff }

func MakeDummySampler(v t.Stuff) Sampler {
	return &sampler_dummy{v}
}

func (s *sampler_dummy) Start(src <-chan t.TicksSteps, prod chan<- t.Sample) {
	for ts := range src {
		prod <- t.Sample{ts.Ticks, ts.Steps, s.v}
	}
}


text:
"""
taxi sim python code
======================

"""
__author__ = 'kissf lu'

import random
from collections import namedtuple
from queue import PriorityQueue
import time
import argparse
import logging as Log
Log.basicConfig(format='%(asctime)s %(message)s', level=Log.INFO)

DEFAULT_NUM_TAXIS = 3
DEFAULT_END_TIME = 180
SEARCH_DURATION = 5
TRIP_DURATION = 20
DEPARTURE_INTERVAL = 5

Event = namedtuple('Event', 'time car_id action')

# BEGIN TAXI_PROCESS
def taxi_process(id_pro: int, trips: int, start_time=0):
    """taxi process func"""
    time = yield Event(start_time, id_pro, 'go')
    for tr in range(trips):
        time = yield Event(time, id_pro, 'load')
        time = yield Event(time, id_pro, 'unload')
    yield Event(time, id_pro, 'back')

    # End taxi process
# END TAXI_PROCESS

# BEGIN TIME_GEN
def time_gen(action_type: str=None):
    """exponential dis time gen"""
    if action_type in ['go', 'unload']:
        interval = DEPARTURE_INTERVAL
    elif action_type is 'load':
        interval = TRIP_DURATION
    elif action_type is 'back':
        interval = 1
    else:
        raise ValueError(f'Unknown actions: {action_type}')
    return int(random.expovariate(1/interval)) + 1
# END TIME _GEN

# BEGIN TAXI_SIMULATOR
class TaxiSimulator(object):
    """"""
    def __init__(self, car_dict: dict=None):
        """

        :param pro_list:
        """
        self._q = PriorityQueue()
        self._car = car_dict if isinstance(car_dict, dict) else {}

    def run(self, end_time):
        Log.info(f'*** start simulation ***')
        sim_time = 0
        # RE_ACTIVATE PROCESS_TAXIS
        for _, car in sorted(self._car.items()):
            # activate car process
            event = next(car)
            self._q.put(event)

        while sim_time < end_time:
            # make sure _q is not empty else the thread of _q.get will be
            # locked untill _q not empty!
            if self._q.qsize() == 0:
                Log.info(f'*** end simulation normal {current_event} ***')
                break
            current_event = self._q.get()

            _time, id_car, pro_type = current_event
            Log.info(f"taxi: {id_car}{id_car*'  '} {current_event}")
            activate_car = self._car[id_car]
            sim_time = _time + time_gen(pro_type)
            try:
                event = activate_car.send(sim_time)
            except StopIteration:
                del self._car[id_car]
            else:
                self._q.put(event)

        Log.info(
            f"*** end of simulation: {self._q.qsize()} "
            f"events pending ***'")
# END TAXI SIMULATION

# main func for simulator
def main(
        end_time=DEFAULT_END_TIME, num_taxis = DEFAULT_NUM_TAXIS,
        seed=None
):
    if seed is not None:
        random.seed(seed)
    pro_dict = {i: taxi_process(
        id_pro=i, trips=(i+1)*2, start_time=i*DEPARTURE_INTERVAL)
                for i in range(num_taxis)}
    sim = TaxiSimulator(car_dict=pro_dict)
    sim.run(end_time=end_time)

if __name__ == '__main__':

    parse = argparse.ArgumentParser(
        description='Taxi fleet simulator'
    )
    parse.add_argument(
        '-e', '--end-time', type=int, default=DEFAULT_END_TIME,
        help=f'simulation end time; default={DEFAULT_END_TIME}'
    )
    parse.add_argument(
        '-t', '--taxis', type=int, default=DEFAULT_NUM_TAXIS,
        help=f'number of taxis; default={DEFAULT_NUM_TAXIS}'
    )
    parse.add_argument(
        '-s', '--seed', type=int, default=7,
        help=f'random generator seed (setting for test)'
    )
    args = parse.parse_args()
    main(args.end_time, args.taxis, args.seed)


text: Few useful scripts for working with AWS


text:
<!--
  ~ Copyright 2015 Persinity Inc.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.persinity.ndt</groupId>
        <artifactId>dmprod</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>haka-examples</artifactId>
    <packaging>jar</packaging>

    <name>haka-examples</name>
    <url>http://persinity.com</url>

    <profiles>
        <profile>
            <id>Cobertura</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>cobertura-maven-plugin</artifactId>
                        <version>2.7</version>
                        <configuration>
                            <check>
                                <haltOnFailure>true</haltOnFailure>
                                <!-- Project-wide thresholds -->
                                <!-- TODO fix line/branch rate -->
                                <totalLineRate>0</totalLineRate>
                                <!-- 50% comes from not covering the income assertions. The latter are trivial and may not be covered by designated tests.
                                     The income assertions either fail or pass, cutting the number of code branches by half.
                                     On the other hand if we skip some other path that starts after the income assertions, then this rate should catch it. -->
                                <totalBranchRate>0</totalBranchRate>
                            </check>
                            <formats>
                                <format>html</format>
                            </formats>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>verify</phase>
                                <goals>
                                    <goal>clean</goal>
                                    <!-- Generate reporting as part of the verify phase -->
                                    <goal>cobertura</goal>
                                    <goal>check</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <addMavenDescriptor>false</addMavenDescriptor>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <classpathLayoutType>custom</classpathLayoutType>
                            <customClasspathLayout>$${artifact.groupId}.$${artifact.artifactId}.$${artifact.extension}
                            </customClasspathLayout>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.5.5</version>
                <executions>
                    <execution>
                        <id>create-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <descriptors>
                                <descriptor>assembly.xml</descriptor>
                            </descriptors>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.persinity.ndt</groupId>
            <artifactId>haka</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.dnvriend</groupId>
            <artifactId>akka-persistence-inmemory_2.11</artifactId>
            <version>0.0.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
#include "util/u_memory.h"
#include "util/u_math.h"
#include "util/u_cpu_detect.h"
#include "util/u_format.h"
#include "util/u_string.h"
#include "util/u_format_s3tc.h"
#include "pipe/p_defines.h"
#include "pipe/p_screen.h"
#include "draw/draw_context.h"
#include "gallivm/lp_bld_type.h"

#include "os/os_time.h"
#include "lp_texture.h"
#include "lp_fence.h"
#include "lp_jit.h"
#include "lp_screen.h"
#include "lp_context.h"
#include "lp_debug.h"
#include "lp_public.h"
#include "lp_limits.h"
#include "lp_rast.h"

#include "state_tracker/sw_winsys.h"

#ifdef DEBUG
int LP_DEBUG = 0;

static const struct debug_named_value lp_debug_flags[] = {
   { "pipe",   DEBUG_PIPE, NULL },
   { "tgsi",   DEBUG_TGSI, NULL },
   { "tex",    DEBUG_TEX, NULL },
   { "setup",  DEBUG_SETUP, NULL },
   { "rast",   DEBUG_RAST, NULL },
   { "query",  DEBUG_QUERY, NULL },
   { "screen", DEBUG_SCREEN, NULL },
   { "counters", DEBUG_COUNTERS, NULL },
   { "scene", DEBUG_SCENE, NULL },
   { "fence", DEBUG_FENCE, NULL },
   { "mem", DEBUG_MEM, NULL },
   { "fs", DEBUG_FS, NULL },
   DEBUG_NAMED_VALUE_END
};
#endif

int LP_PERF = 0;
static const struct debug_named_value lp_perf_flags[] = {
   { "texmem",         PERF_TEX_MEM, NULL },
   { "no_mipmap",      PERF_NO_MIPMAPS, NULL },
   { "no_linear",      PERF_NO_LINEAR, NULL },
   { "no_mip_linear",  PERF_NO_MIP_LINEAR, NULL },
   { "no_tex",         PERF_NO_TEX, NULL },
   { "no_blend",       PERF_NO_BLEND, NULL },
   { "no_depth",       PERF_NO_DEPTH, NULL },
   { "no_alphatest",   PERF_NO_ALPHATEST, NULL },
   DEBUG_NAMED_VALUE_END
};

static const char *
llvmpipe_get_vendor(struct pipe_screen *screen)
{
   return "VMware, Inc.";
}

static const char *
llvmpipe_get_name(struct pipe_screen *screen)
{
   static char buf[100];
   util_snprintf(buf, sizeof(buf), "llvmpipe (LLVM %u.%u, %u bits)",
		 HAVE_LLVM >> 8, HAVE_LLVM & 0xff,
		 lp_native_vector_width );
   return buf;
}

static int
llvmpipe_get_param(struct pipe_screen *screen, enum pipe_cap param)
{
   switch (param) {
   case PIPE_CAP_MAX_COMBINED_SAMPLERS:
      return 2 * PIPE_MAX_SAMPLERS;  /* VS + FS samplers */
   case PIPE_CAP_NPOT_TEXTURES:
      return 1;
   case PIPE_CAP_TWO_SIDED_STENCIL:
      return 1;
   case PIPE_CAP_SM3:
      return 1;
   case PIPE_CAP_MAX_DUAL_SOURCE_RENDER_TARGETS:
      return 1;
   case PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS:
      return PIPE_MAX_SO_BUFFERS;
   case PIPE_CAP_ANISOTROPIC_FILTER:
      return 0;
   case PIPE_CAP_POINT_SPRITE:
      return 1;
   case PIPE_CAP_MAX_RENDER_TARGETS:
      return PIPE_MAX_COLOR_BUFS;
   case PIPE_CAP_OCCLUSION_QUERY:
      return 1;
   case PIPE_CAP_QUERY_TIME_ELAPSED:
      return 0;
   case PIPE_CAP_QUERY_TIMESTAMP:
      return 1;
   case PIPE_CAP_QUERY_PIPELINE_STATISTICS:
      return 0;
   case PIPE_CAP_TEXTURE_MIRROR_CLAMP:
      return 1;
   case PIPE_CAP_TEXTURE_SHADOW_MAP:
      return 1;
   case PIPE_CAP_TEXTURE_SWIZZLE:
      return 1;
   case PIPE_CAP_TEXTURE_BORDER_COLOR_QUIRK:
      return 0;
   case PIPE_CAP_MAX_TEXTURE_2D_LEVELS:
      return LP_MAX_TEXTURE_2D_LEVELS;
   case PIPE_CAP_MAX_TEXTURE_3D_LEVELS:
      return LP_MAX_TEXTURE_3D_LEVELS;
   case PIPE_CAP_MAX_TEXTURE_CUBE_LEVELS:
      return LP_MAX_TEXTURE_CUBE_LEVELS;
   case PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS:
      return LP_MAX_TEXTURE_ARRAY_LAYERS;
   case PIPE_CAP_BLEND_EQUATION_SEPARATE:
      return 1;
   case PIPE_CAP_INDEP_BLEND_ENABLE:
      return 1;
   case PIPE_CAP_INDEP_BLEND_FUNC:
      return 1;
   case PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT:
   case PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER:
   case PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER:
      return 1;
   case PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT:
      return 0;
   case PIPE_CAP_PRIMITIVE_RESTART:
      return 1;
   case PIPE_CAP_DEPTH_CLIP_DISABLE:
      return 0;
   case PIPE_CAP_SHADER_STENCIL_EXPORT:
      return 0;
   case PIPE_CAP_TGSI_INSTANCEID:
   case PIPE_CAP_VERTEX_ELEMENT_INSTANCE_DIVISOR:
      return 1;
   case PIPE_CAP_FRAGMENT_COLOR_CLAMPED:
      return 0;
   case PIPE_CAP_MIXED_COLORBUFFER_FORMATS:
      return 1;
   case PIPE_CAP_SEAMLESS_CUBE_MAP:
   case PIPE_CAP_SEAMLESS_CUBE_MAP_PER_TEXTURE:
      return 0;
   case PIPE_CAP_SCALED_RESOLVE:
      return 0;
   /* this is a lie could support arbitrary large offsets */
   case PIPE_CAP_MIN_TEXEL_OFFSET:
      return -8;
   case PIPE_CAP_MAX_TEXEL_OFFSET:
      return 7;
   case PIPE_CAP_CONDITIONAL_RENDER:
      return 1;
   case PIPE_CAP_TEXTURE_BARRIER:
      return 0;
   case PIPE_CAP_MAX_STREAM_OUTPUT_SEPARATE_COMPONENTS:
   case PIPE_CAP_MAX_STREAM_OUTPUT_INTERLEAVED_COMPONENTS:
      return 16*4;
   case PIPE_CAP_STREAM_OUTPUT_PAUSE_RESUME:
      return 1;
   case PIPE_CAP_TGSI_CAN_COMPACT_CONSTANTS:
      return 0;
   case PIPE_CAP_VERTEX_COLOR_UNCLAMPED:
   case PIPE_CAP_VERTEX_COLOR_CLAMPED:
      return 1;
   case PIPE_CAP_GLSL_FEATURE_LEVEL:
      return 140;
   case PIPE_CAP_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION:
      return 0;
   case PIPE_CAP_COMPUTE:
      return 0;
   case PIPE_CAP_USER_VERTEX_BUFFERS:
   case PIPE_CAP_USER_INDEX_BUFFERS:
      return 1;
   case PIPE_CAP_USER_CONSTANT_BUFFERS:
      return 0;
   case PIPE_CAP_VERTEX_BUFFER_OFFSET_4BYTE_ALIGNED_ONLY:
   case PIPE_CAP_VERTEX_BUFFER_STRIDE_4BYTE_ALIGNED_ONLY:
   case PIPE_CAP_VERTEX_ELEMENT_SRC_OFFSET_4BYTE_ALIGNED_ONLY:
   case PIPE_CAP_TGSI_TEXCOORD:
      return 0;

   case PIPE_CAP_CONSTANT_BUFFER_OFFSET_ALIGNMENT:
      return 16;
   case PIPE_CAP_START_INSTANCE:
   case PIPE_CAP_TEXTURE_MULTISAMPLE:
   case PIPE_CAP_MIN_MAP_BUFFER_ALIGNMENT:
   case PIPE_CAP_CUBE_MAP_ARRAY:
      return 0;
   case PIPE_CAP_TEXTURE_BUFFER_OBJECTS:
      return 1;
   case PIPE_CAP_MAX_TEXTURE_BUFFER_SIZE:
      return 65536;
   case PIPE_CAP_TEXTURE_BUFFER_OFFSET_ALIGNMENT:
      return 1;
   case PIPE_CAP_PREFER_BLIT_BASED_TEXTURE_TRANSFER:
      return 0;
   case PIPE_CAP_MAX_VIEWPORTS:
      return PIPE_MAX_VIEWPORTS;
   case PIPE_CAP_ENDIANNESS:
      return PIPE_ENDIAN_NATIVE;
   }
   /* should only get here on unhandled cases */
   debug_printf("Unexpected PIPE_CAP %d query\n", param);
   return 0;
}

static int
llvmpipe_get_shader_param(struct pipe_screen *screen, unsigned shader, enum pipe_shader_cap param)
{
   switch(shader)
   {
   case PIPE_SHADER_FRAGMENT:
      switch (param) {
      default:
         return gallivm_get_shader_param(param);
      }
   case PIPE_SHADER_VERTEX:
   case PIPE_SHADER_GEOMETRY:
      switch (param) {
      case PIPE_SHADER_CAP_MAX_TEXTURE_SAMPLERS:
         /* At this time, the draw module and llvmpipe driver only
          * support vertex shader texture lookups when LLVM is enabled in
          * the draw module.
          */
         if (debug_get_bool_option("DRAW_USE_LLVM", TRUE))
            return PIPE_MAX_SAMPLERS;
         else
            return 0;
      default:
         return draw_get_shader_param(shader, param);
      }
   default:
      return 0;
   }
}

static float
llvmpipe_get_paramf(struct pipe_screen *screen, enum pipe_capf param)
{
   switch (param) {
   case PIPE_CAPF_MAX_LINE_WIDTH:
      /* fall-through */
   case PIPE_CAPF_MAX_LINE_WIDTH_AA:
      return 255.0; /* arbitrary */
   case PIPE_CAPF_MAX_POINT_WIDTH:
      /* fall-through */
   case PIPE_CAPF_MAX_POINT_WIDTH_AA:
      return 255.0; /* arbitrary */
   case PIPE_CAPF_MAX_TEXTURE_ANISOTROPY:
      return 16.0; /* not actually signficant at this time */
   case PIPE_CAPF_MAX_TEXTURE_LOD_BIAS:
      return 16.0; /* arbitrary */
   case PIPE_CAPF_GUARD_BAND_LEFT:
   case PIPE_CAPF_GUARD_BAND_TOP:
   case PIPE_CAPF_GUARD_BAND_RIGHT:
   case PIPE_CAPF_GUARD_BAND_BOTTOM:
      return 0.0;
   }
   /* should only get here on unhandled cases */
   debug_printf("Unexpected PIPE_CAP %d query\n", param);
   return 0.0;
}

/**
 * Query format support for creating a texture, drawing surface, etc.
 * \param format  the format to test
 * \param type  one of PIPE_TEXTURE, PIPE_SURFACE
 */
static boolean
llvmpipe_is_format_supported( struct pipe_screen *_screen,
                              enum pipe_format format,
                              enum pipe_texture_target target,
                              unsigned sample_count,
                              unsigned bind)
{
   struct llvmpipe_screen *screen = llvmpipe_screen(_screen);
   struct sw_winsys *winsys = screen->winsys;
   const struct util_format_description *format_desc;

   format_desc = util_format_description(format);
   if (!format_desc)
      return FALSE;

   assert(target == PIPE_BUFFER ||
          target == PIPE_TEXTURE_1D ||
          target == PIPE_TEXTURE_1D_ARRAY ||
          target == PIPE_TEXTURE_2D ||
          target == PIPE_TEXTURE_2D_ARRAY ||
          target == PIPE_TEXTURE_RECT ||
          target == PIPE_TEXTURE_3D ||
          target == PIPE_TEXTURE_CUBE);

   if (sample_count > 1)
      return FALSE;

   if (bind & PIPE_BIND_RENDER_TARGET) {
      if (format_desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
         if (format_desc->nr_channels < 3)
            return FALSE;
      }
      else if (format_desc->colorspace != UTIL_FORMAT_COLORSPACE_RGB)
         return FALSE;

      if (format_desc->layout != UTIL_FORMAT_LAYOUT_PLAIN &&
          format != PIPE_FORMAT_R11G11B10_FLOAT)
         return FALSE;

      assert(format_desc->block.width == 1);
      assert(format_desc->block.height == 1);

      if (format_desc->is_mixed)
         return FALSE;

      if (!format_desc->is_array && !format_desc->is_bitmask &&
          format != PIPE_FORMAT_R11G11B10_FLOAT)
         return FALSE;

      /*
       * XXX refuse formats known to crash in generate_unswizzled_blend().
       * These include all 3-channel 24bit RGB8 variants, plus 48bit
       * (except those using floats) 3-channel RGB16 variants (the latter
       * seems to be more of a llvm bug though).
       * The mesa state tracker only seems to use these for SINT/UINT formats.
       */
      if (format_desc->is_array && format_desc->nr_channels == 3) {
         if (format_desc->block.bits == 24 || (format_desc->block.bits == 48 &&
               !util_format_is_float(format))) {
            return FALSE;
         }
      }
   }

   if (bind & PIPE_BIND_DISPLAY_TARGET) {
      if(!winsys->is_displaytarget_format_supported(winsys, bind, format))
         return FALSE;
   }

   if (bind & PIPE_BIND_DEPTH_STENCIL) {
      if (format_desc->layout != UTIL_FORMAT_LAYOUT_PLAIN)
         return FALSE;

      if (format_desc->colorspace != UTIL_FORMAT_COLORSPACE_ZS)
         return FALSE;

      /* TODO: Support stencil-only formats */
      if (format_desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_NONE) {
         return FALSE;
      }
   }

   if (format_desc->layout == UTIL_FORMAT_LAYOUT_S3TC) {
      return util_format_s3tc_enabled;
   }

   /*
    * Everything can be supported by u_format
    * (those without fetch_rgba_float might be not but shouldn't hit that)
    */

   return TRUE;
}

static void
llvmpipe_flush_frontbuffer(struct pipe_screen *_screen,
                           struct pipe_resource *resource,
                           unsigned level, unsigned layer,
                           void *context_private)
{
   struct llvmpipe_screen *screen = llvmpipe_screen(_screen);
   struct sw_winsys *winsys = screen->winsys;
   struct llvmpipe_resource *texture = llvmpipe_resource(resource);

   assert(texture->dt);
   if (texture->dt)
      winsys->displaytarget_display(winsys, texture->dt, context_private);
}

static void
llvmpipe_destroy_screen( struct pipe_screen *_screen )
{
   struct llvmpipe_screen *screen = llvmpipe_screen(_screen);
   struct sw_winsys *winsys = screen->winsys;

   if (screen->rast)
      lp_rast_destroy(screen->rast);

   lp_jit_screen_cleanup(screen);

   if(winsys->destroy)
      winsys->destroy(winsys);

   pipe_mutex_destroy(screen->rast_mutex);

   FREE(screen);
}

/**
 * Fence reference counting.
 */
static void
llvmpipe_fence_reference(struct pipe_screen *screen,
                         struct pipe_fence_handle **ptr,
                         struct pipe_fence_handle *fence)
{
   struct lp_fence **old = (struct lp_fence **) ptr;
   struct lp_fence *f = (struct lp_fence *) fence;

   lp_fence_reference(old, f);
}

/**
 * Has the fence been executed/finished?
 */
static boolean
llvmpipe_fence_signalled(struct pipe_screen *screen,
                         struct pipe_fence_handle *fence)
{
   struct lp_fence *f = (struct lp_fence *) fence;
   return lp_fence_signalled(f);
}

/**
 * Wait for the fence to finish.
 */
static boolean
llvmpipe_fence_finish(struct pipe_screen *screen,
                      struct pipe_fence_handle *fence_handle,
                      uint64_t timeout)
{
   struct lp_fence *f = (struct lp_fence *) fence_handle;

   lp_fence_wait(f);
   return TRUE;
}

static uint64_t
llvmpipe_get_timestamp(struct pipe_screen *_screen)
{
   return os_time_get_nano();
}

/**
 * Create a new pipe_screen object
 * Note: we're not presently subclassing pipe_screen (no llvmpipe_screen).
 */
struct pipe_screen *
llvmpipe_create_screen(struct sw_winsys *winsys)
{
   struct llvmpipe_screen *screen;

   util_cpu_detect();

#if defined(PIPE_ARCH_X86) && HAVE_LLVM < 0x0302
   /* require SSE2 due to LLVM PR6960. */
   if (!util_cpu_caps.has_sse2)
       return NULL;
#endif

#ifdef DEBUG
   LP_DEBUG = debug_get_flags_option("LP_DEBUG", lp_debug_flags, 0 );
#endif

   LP_PERF = debug_get_flags_option("LP_PERF", lp_perf_flags, 0 );

   screen = CALLOC_STRUCT(llvmpipe_screen);
   if (!screen)
      return NULL;

   screen->winsys = winsys;

   screen->base.destroy = llvmpipe_destroy_screen;

   screen->base.get_name = llvmpipe_get_name;
   screen->base.get_vendor = llvmpipe_get_vendor;
   screen->base.get_param = llvmpipe_get_param;
   screen->base.get_shader_param = llvmpipe_get_shader_param;
   screen->base.get_paramf = llvmpipe_get_paramf;
   screen->base.is_format_supported = llvmpipe_is_format_supported;

   screen->base.context_create = llvmpipe_create_context;
   screen->base.flush_frontbuffer = llvmpipe_flush_frontbuffer;
   screen->base.fence_reference = llvmpipe_fence_reference;
   screen->base.fence_signalled = llvmpipe_fence_signalled;
   screen->base.fence_finish = llvmpipe_fence_finish;

   screen->base.get_timestamp = llvmpipe_get_timestamp;

   llvmpipe_init_screen_resource_funcs(&screen->base);

   lp_jit_screen_init(screen);

   screen->num_threads = util_cpu_caps.nr_cpus > 1 ? util_cpu_caps.nr_cpus : 0;
#ifdef PIPE_SUBSYSTEM_EMBEDDED
   screen->num_threads = 0;
#endif
   screen->num_threads = debug_get_num_option("LP_NUM_THREADS", screen->num_threads);
   screen->num_threads = MIN2(screen->num_threads, LP_MAX_THREADS);

   screen->rast = lp_rast_create(screen->num_threads);
   if (!screen->rast) {
      lp_jit_screen_cleanup(screen);
      FREE(screen);
      return NULL;
   }
   pipe_mutex_init(screen->rast_mutex);

   util_format_s3tc_init();

   return &screen->base;
}


text:
  Saint-Lambert-et-Mont-de-Jeux est
       un village
       localisé dans le département des Ardennes en Champagne-Ardenne. On dénombrait 187 habitants en 2008.

Le nombre de logements, à Saint-Lambert-et-Mont-de-Jeux, se décomposait en 2011 en quatre appartements et 96 maisons soit
 un marché relativement équilibré.

À proximité de Saint-Lambert-et-Mont-de-Jeux sont situées les villes de
Chuffilly-Roche située à 5 km, 86 habitants,
Voncq à 5 km, 224 habitants,
Sainte-Vaubourg située à 4 km, 95 habitants,
Semuy localisée à 3 km, 97 habitants,
Attigny localisée à 3 km, 1 184 habitants,
Charbogne située à 1 km, 210 habitants,
 entre autres. De plus, Saint-Lambert-et-Mont-de-Jeux est située à seulement 17 km de Rethel.

Si vous pensez venir habiter à Saint-Lambert-et-Mont-de-Jeux, vous pourrez aisément trouver une maison à vendre.