content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from database.database import ma from models import KoeFavorite from .user_schema import UserSchema from .koe_schema import KoeSchema
[ 11748, 25064, 201, 198, 11748, 28686, 201, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 35514, 201, 198, 201, 198, ...
2.802326
86
import pickle import sys import numpy as np # Define the valid programs here if __name__ == '__main__': rollout_fn = sys.argv[1] parse_rollout(rollout_fn=rollout_fn)
[ 11748, 2298, 293, 198, 11748, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 2896, 500, 262, 4938, 4056, 994, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 38180, 62, 22184, 796, 2506...
2.588235
68
import unittest import pandas as pd import numpy as np import os import tempfile import shutil from signatureanalyzer.signatureanalyzer import run_spectra from signatureanalyzer.bnmf import ardnmf from signatureanalyzer.utils import file_loader SPECTRA_ARROW = "../../examples/example_luad_spectra_1.tsv" SPECTRA_WORD = "../../examples/example_luad_spectra_2.tsv" if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 4423, 346, 198, 198, 6738, 9877, 38200, 9107, 13, 12683, 1300, 38200, 9107, 1330, 10...
2.835616
146
from .python_utils import make_print_if_verbose
[ 6738, 764, 29412, 62, 26791, 1330, 787, 62, 4798, 62, 361, 62, 19011, 577, 628, 198 ]
3.125
16
""" RRFS-CMAQ File Reader """ import numpy as np import xarray as xr from numpy import concatenate from pandas import Series def open_mfdataset( fname, convert_to_ppb=True, mech="cb6r3_ae6_aq", var_list=None, fname_pm25=None, surf_only=False, **kwargs ): # Like WRF-chem add var list that just determines whether to calculate sums or not to speed this up. """Method to open RFFS-CMAQ dyn* netcdf files. Parameters ---------- fname : string or list fname is the path to the file or files. It will accept hot keys in strings as well. convert_to_ppb : boolean If true the units of the gas species will be converted to ppbv mech: str Mechanism to be used for calculating sums. Mechanisms supported: "cb6r3_ae6_aq" var_list: list List of variables to include in output. MELODIES-MONET only reads in variables need to plot in order to save on memory and simulation cost especially for vertical data. If None, will read in all model data and calculate all sums. fname_pm25: string or list Optional path to the file or files for precalculated PM2.5 sums. It will accept hot keys in strings as well. surf_only: boolean Whether to save only surface data to save on memory and computational cost (True) or not (False). Returns ------- xarray.DataSet RRFS-CMAQ model dataset in standard format for use in MELODIES-MONET """ # Get dictionary of summed species for the mechanism of choice. dict_sum = dict_species_sums(mech=mech) if var_list is not None: # Read in only a subset of variables and only do calculations if needed. var_list_orig = var_list.copy() # Keep track of the original list before changes. list_calc_sum = [] list_remove_extra = [] # list of variables to remove after the sum to save in memory. for var_sum in [ "PM25", "PM10", "noy_gas", "noy_aer", "nox", "pm25_cl", "pm25_ec", "pm25_ca", "pm25_na", "pm25_nh4", "pm25_no3", "pm25_so4", "pm25_om", ]: if var_sum in var_list: if var_sum == "PM25": var_list.extend(dict_sum["aitken"]) var_list.extend(dict_sum["accumulation"]) var_list.extend(dict_sum["coarse"]) # Keep track to remove these later too list_remove_extra.extend(dict_sum["aitken"]) list_remove_extra.extend(dict_sum["accumulation"]) list_remove_extra.extend(dict_sum["coarse"]) elif var_sum == "PM10": var_list.extend(dict_sum["aitken"]) var_list.extend(dict_sum["accumulation"]) var_list.extend(dict_sum["coarse"]) # Keep track to remove these later too list_remove_extra.extend(dict_sum["aitken"]) list_remove_extra.extend(dict_sum["accumulation"]) list_remove_extra.extend(dict_sum["coarse"]) else: var_list.extend(dict_sum[var_sum]) # Keep track to remove these later too list_remove_extra.extend(dict_sum[var_sum]) var_list.remove(var_sum) list_calc_sum.append(var_sum) # append the other needed species. var_list.append("lat") var_list.append("lon") var_list.append("phalf") var_list.append("tmp") var_list.append("pressfc") var_list.append("dpres") var_list.append("hgtsfc") var_list.append("delz") # Remove duplicates just in case: var_list = list(dict.fromkeys(var_list)) list_remove_extra = list(dict.fromkeys(list_remove_extra)) # Select only those elements in list_remove_extra that are not in var_list_orig list_remove_extra_only = list(set(list_remove_extra) - set(var_list_orig)) # If variables in pm25 files are included remove these as these are not in the main file # And will be added later. for pm25_var in [ "PM25_TOT", "PM25_TOT_NSOM", "PM25_EC", "PM25_NH4", "PM25_NO3", "PM25_SO4", "PM25_OC", "PM25_OM", ]: if pm25_var in var_list: var_list.remove(pm25_var) # open the dataset using xarray dset = xr.open_mfdataset(fname, concat_dim="time", combine="nested", **kwargs)[var_list] else: # Read in all variables and do all calculations. dset = xr.open_mfdataset(fname, concat_dim="time", combine="nested", **kwargs) list_calc_sum = [ "PM25", "PM10", "noy_gas", "noy_aer", "nox", "pm25_cl", "pm25_ec", "pm25_ca", "pm25_na", "pm25_nh4", "pm25_no3", "pm25_so4", "pm25_om", ] if fname_pm25 is not None: # Add the processed pm2.5 species. dset_pm25 = xr.open_mfdataset(fname_pm25, concat_dim="time", combine="nested", **kwargs) dset_pm25 = dset_pm25.drop( labels=["lat", "lon", "pfull"] ) # Drop duplicate variables so can merge. # Slight differences in pfull value between the files, but I assume that these still represent the # same pressure levels from the model dynf* files. # Attributes are formatted differently in pm25 file so remove attributes and use those from dynf* files. dset_pm25.attrs = {} dset = dset.merge(dset_pm25) # Standardize some variable names dset = dset.rename( { "grid_yt": "y", "grid_xt": "x", "pfull": "z", "phalf": "z_i", # Interface pressure levels "lon": "longitude", "lat": "latitude", "tmp": "temperature_k", # standard temperature (kelvin) "pressfc": "surfpres_pa", "dpres": "dp_pa", # Change names so standard surfpres_pa and dp_pa "hgtsfc": "surfalt_m", "delz": "dz_m", } ) # Optional, but when available include altitude info # Calculate pressure. This has to go before sorting because ak and bk # are not sorted as they are in attributes dset["pres_pa_mid"] = _calc_pressure(dset) # Adjust pressure levels for all models such that the surface is first. dset = dset.sortby("z", ascending=False) dset = dset.sortby("z_i", ascending=False) # Note this altitude calcs needs to always go after resorting. # Altitude calculations are all optional, but for each model add values that are easy to calculate. dset["alt_msl_m_full"] = _calc_hgt(dset) dset["dz_m"] = dset["dz_m"] * -1.0 # Change to positive values. # Set coordinates dset = dset.reset_index( ["x", "y", "z", "z_i"], drop=True ) # For now drop z_i no variables use it. dset["latitude"] = dset["latitude"].isel(time=0) dset["longitude"] = dset["longitude"].isel(time=0) dset = dset.reset_coords() dset = dset.set_coords(["latitude", "longitude"]) # These sums and units are quite expensive and memory intensive, # so add option to shrink dataset to just surface when needed if surf_only: dset = dset.isel(z=0).expand_dims("z", axis=1) # Need to adjust units before summing for aerosols # convert all gas species to ppbv if convert_to_ppb: for i in dset.variables: if "units" in dset[i].attrs: if "ppmv" in dset[i].attrs["units"]: dset[i] *= 1000.0 dset[i].attrs["units"] = "ppbv" # convert "ug/kg to ug/m3" for i in dset.variables: if "units" in dset[i].attrs: if "ug/kg" in dset[i].attrs["units"]: # ug/kg -> ug/m3 using dry air density dset[i] = dset[i] * dset["pres_pa_mid"] / dset["temperature_k"] / 287.05535 dset[i].attrs["units"] = r"$\mu g m^{-3}$" # add lazy diagnostic variables # Note that because there are so many species to sum. Summing the aerosols is slowing down the code. if "PM25" in list_calc_sum: dset = add_lazy_pm25(dset, dict_sum) if "PM10" in list_calc_sum: dset = add_lazy_pm10(dset, dict_sum) if "noy_gas" in list_calc_sum: dset = add_lazy_noy_g(dset, dict_sum) if "noy_aer" in list_calc_sum: dset = add_lazy_noy_a(dset, dict_sum) if "nox" in list_calc_sum: dset = add_lazy_nox(dset, dict_sum) if "pm25_cl" in list_calc_sum: dset = add_lazy_cl_pm25(dset, dict_sum) if "pm25_ec" in list_calc_sum: dset = add_lazy_ec_pm25(dset, dict_sum) if "pm25_ca" in list_calc_sum: dset = add_lazy_ca_pm25(dset, dict_sum) if "pm25_na" in list_calc_sum: dset = add_lazy_na_pm25(dset, dict_sum) if "pm25_nh4" in list_calc_sum: dset = add_lazy_nh4_pm25(dset, dict_sum) if "pm25_no3" in list_calc_sum: dset = add_lazy_no3_pm25(dset, dict_sum) if "pm25_so4" in list_calc_sum: dset = add_lazy_so4_pm25(dset, dict_sum) if "pm25_om" in list_calc_sum: dset = add_lazy_om_pm25(dset, dict_sum) # Change the times to pandas format dset["time"] = dset.indexes["time"].to_datetimeindex(unsafe=True) # Turn off warning for now. This is just because the model is in julian time # Drop extra variables that were part of sum, but are not in original var_list # to save memory and computational time. # This is only revevant if var_list is provided if var_list is not None: if bool(list_remove_extra_only): # confirm list not empty dset = dset.drop_vars(list_remove_extra_only) return dset def _get_keys(d): """Calculates keys Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- list list of keys """ keys = Series([i for i in d.data_vars.keys()]) return keys def add_lazy_pm25(d, dict_sum): """Calculates PM2.5 sum. 20% of coarse mode is included in PM2.5 sum. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new PM2.5 calculation """ keys = _get_keys(d) allvars = Series( concatenate([dict_sum["aitken"], dict_sum["accumulation"], dict_sum["coarse"]]) ) weights = Series( concatenate( [ np.ones(len(dict_sum["aitken"])), np.ones(len(dict_sum["accumulation"])), np.full(len(dict_sum["coarse"]), 0.2), ] ) ) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] newweights = weights.loc[index] d["PM25"] = add_multiple_lazy2(d, newkeys, weights=newweights) d["PM25"] = d["PM25"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "PM2.5", "long_name": "PM2.5 calculated by MONET assuming coarse mode 20%", } ) return d def add_lazy_pm10(d, dict_sum): """Calculates PM10 sum. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new PM10 calculation """ keys = _get_keys(d) allvars = Series( concatenate([dict_sum["aitken"], dict_sum["accumulation"], dict_sum["coarse"]]) ) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] d["PM10"] = add_multiple_lazy2(d, newkeys) d["PM10"] = d["PM10"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "PM10", "long_name": "Particulate Matter < 10 microns", } ) return d def add_lazy_noy_g(d, dict_sum): """Calculates NOy gas Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new NOy gas calculation """ keys = _get_keys(d) allvars = Series(dict_sum["noy_gas"]) weights = Series(dict_sum["noy_gas_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] newweights = weights.loc[index] d["noy_gas"] = add_multiple_lazy2(d, newkeys, weights=newweights) d["noy_gas"] = d["noy_gas"].assign_attrs({"name": "noy_gas", "long_name": "NOy gases"}) return d def add_lazy_noy_a(d, dict_sum): """Calculates NOy aerosol Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new NOy aerosol calculation """ keys = _get_keys(d) allvars = Series(dict_sum["noy_aer"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] d["noy_aer"] = add_multiple_lazy2(d, newkeys) d["noy_aer"] = d["noy_aer"].assign_attrs( {"units": r"$\mu g m^{-3}$", "name": "noy_aer", "long_name": "NOy aerosol"} ) return d def add_lazy_nox(d, dict_sum): """Calculates NOx Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new NOx calculation """ keys = _get_keys(d) allvars = Series(dict_sum["nox"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] d["nox"] = add_multiple_lazy2(d, newkeys) d["nox"] = d["nox"].assign_attrs({"name": "nox", "long_name": "nox"}) return d def add_lazy_cl_pm25(d, dict_sum): """Calculates sum of particulate Cl. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new CLf calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_cl"]) weights = Series(dict_sum["pm25_cl_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_cl"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_cl"] = d["pm25_cl"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_cl", "long_name": "PM2.5 CL assuming coarse mode 20%", } ) return d def add_lazy_ec_pm25(d, dict_sum): """Calculates sum of particulate EC. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new EC calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_ec"]) weights = Series(dict_sum["pm25_ec_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_ec"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_ec"] = d["pm25_ec"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_ec", "long_name": "PM2.5 EC assuming coarse mode 20%", } ) return d def add_lazy_ca_pm25(d, dict_sum): """Calculates sum of particulate CA. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new CA calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_ca"]) weights = Series(dict_sum["pm25_ca_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_ca"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_ca"] = d["pm25_ca"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_ca", "long_name": "PM2.5 CA assuming coarse mode 20%", } ) return d def add_lazy_na_pm25(d, dict_sum): """Calculates sum of particulate NA. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new NA calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_na"]) weights = Series(dict_sum["pm25_na_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_na"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_na"] = d["pm25_na"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_na", "long_name": "PM2.5 NA assuming coarse mode 20%", } ) return d def add_lazy_nh4_pm25(d, dict_sum): """Calculates sum of particulate NH4. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new NH4 calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_nh4"]) weights = Series(dict_sum["pm25_nh4_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_nh4"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_nh4"] = d["pm25_nh4"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_nh4", "long_name": "PM2.5 NH4 assuming coarse mode 20%", } ) return d def add_lazy_no3_pm25(d, dict_sum): """Calculates sum of particulate NO3. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new NO3 calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_no3"]) weights = Series(dict_sum["pm25_no3_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_no3"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_no3"] = d["pm25_no3"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_no3", "long_name": "PM2.5 NO3 assuming coarse mode 20%", } ) return d def add_lazy_so4_pm25(d, dict_sum): """Calculates sum of particulate SO4. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new SO4 calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_so4"]) weights = Series(dict_sum["pm25_so4_weight"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] neww = weights.loc[index] d["pm25_so4"] = add_multiple_lazy2(d, newkeys, weights=neww) d["pm25_so4"] = d["pm25_so4"].assign_attrs( { "units": r"$\mu g m^{-3}$", "name": "pm25_so4", "long_name": "PM2.5 SO4 assuming coarse mode 20%", } ) return d def add_lazy_om_pm25(d, dict_sum): """Calculates sum of particulate OM. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.Dataset RRFS-CMAQ model data including new OM calculation """ keys = _get_keys(d) allvars = Series(dict_sum["pm25_om"]) index = allvars.isin(keys) if can_do(index): newkeys = allvars.loc[index] d["pm25_om"] = add_multiple_lazy2(d, newkeys) d["pm25_om"] = d["pm25_om"].assign_attrs( {"units": r"$\mu g m^{-3}$", "name": "pm25_om", "long_name": "PM2.5 OM"} ) return d def add_multiple_lazy(dset, variables, weights=None): """Sums variables Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data variables : series series of variables variables : series series of weights to apply to each variable during the sum Returns ------- xarray.Dataarray Weighted sum of all specified variables """ from numpy import ones if weights is None: weights = ones(len(variables)) else: weights = weights.values variables = variables.values new = dset[variables[0]].copy() * weights[0] for i, j in zip(variables[1:], weights[1:]): new = new + dset[i] * j return new def add_multiple_lazy2(dset, variables, weights=None): """Sums variables. This is similar to add_multiple_lazy, but is a little faster. Parameters ---------- d : xarray.Dataset RRFS-CMAQ model data variables : series series of variables variables : series series of weights to apply to each variable during the sum Returns ------- xarray.Dataarray Weighted sum of all specified variables """ dset2 = dset[variables.values] if weights is not None: for i, j in zip(variables.values, weights.values): dset2[i] = dset2[i] * j new = dset2.to_array().sum("variable") return new def _predefined_mapping_tables(dset): """Predefined mapping tables for different observational parings used when combining data. Returns ------- dictionary dictionary defining default mapping tables """ to_improve = {} to_nadp = {} to_aqs = { "OZONE": ["o3"], "PM2.5": ["PM25"], "CO": ["co"], "NOY": ["NOy"], "NOX": ["NOx"], "SO2": ["so2"], "NO": ["no"], "NO2": ["no2"], } to_airnow = { "OZONE": ["o3"], "PM2.5": ["PM25"], "CO": ["co"], "NOY": ["NOy"], "NOX": ["NOx"], "SO2": ["so2"], "NO": ["no"], "NO2": ["no2"], } to_crn = {} to_aeronet = {} to_cems = {} mapping_tables = { "improve": to_improve, "aqs": to_aqs, "airnow": to_airnow, "crn": to_crn, "cems": to_cems, "nadp": to_nadp, "aeronet": to_aeronet, } dset = dset.assign_attrs({"mapping_tables": mapping_tables}) return dset # For the different mechanisms, just update these arrays as needed. def dict_species_sums(mech): """Predefined mapping tables for different observational parings used when combining data. Parameters ---------- mech : string mechanism name Returns ------- dictionary dictionary defining the variables to sum based on the specified mechanism """ if mech == "cb6r3_ae6_aq": sum_dict = {} # Arrays for different gasses and pm groupings sum_dict.update( { "accumulation": [ "aso4j", "ano3j", "anh4j", "anaj", "aclj", "aecj", "aothrj", "afej", "asij", "atij", "acaj", "amgj", "amnj", "aalj", "akj", "alvpo1j", "asvpo1j", "asvpo2j", "asvpo3j", "aivpo1j", "axyl1j", "axyl2j", "axyl3j", "atol1j", "atol2j", "atol3j", "abnz1j", "abnz2j", "abnz3j", "aiso1j", "aiso2j", "aiso3j", "atrp1j", "atrp2j", "asqtj", "aalk1j", "aalk2j", "apah1j", "apah2j", "apah3j", "aorgcj", "aolgbj", "aolgaj", "alvoo1j", "alvoo2j", "asvoo1j", "asvoo2j", "asvoo3j", "apcsoj", ] } ) sum_dict.update( { "accumulation_wopc": [ "aso4j", "ano3j", "anh4j", "anaj", "aclj", "aecj", "aothrj", "afej", "asij", "atij", "acaj", "amgj", "amnj", "aalj", "akj", "alvpo1j", "asvpo1j", "asvpo2j", "asvpo3j", "aivpo1j", "axyl1j", "axyl2j", "axyl3j", "atol1j", "atol2j", "atol3j", "abnz1j", "abnz2j", "abnz3j", "aiso1j", "aiso2j", "aiso3j", "atrp1j", "atrp2j", "asqtj", "aalk1j", "aalk2j", "apah1j", "apah2j", "apah3j", "aorgcj", "aolgbj", "aolgaj", "alvoo1j", "alvoo2j", "asvoo1j", "asvoo2j", "asvoo3j", ] } ) sum_dict.update( { "aitken": [ "aso4i", "ano3i", "anh4i", "anai", "acli", "aeci", "aothri", "alvpo1i", "asvpo1i", "asvpo2i", "alvoo1i", "alvoo2i", "asvoo1i", "asvoo2i", ] } ) sum_dict.update( {"coarse": ["asoil", "acors", "aseacat", "aclk", "aso4k", "ano3k", "anh4k"]} ) sum_dict.update( { "noy_gas": [ "no", "no2", "no3", "n2o5", "hono", "hno3", "pna", "cron", "clno2", "pan", "panx", "opan", "ntr1", "ntr2", "intr", ] } ) sum_dict.update({"noy_gas_weight": [1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}) sum_dict.update( {"noy_aer": ["ano3i", "ano3j", "ano3k"]} ) # Need to confirm here if there is a size cutoff for noy obs? sum_dict.update({"nox": ["no", "no2"]}) sum_dict.update({"pm25_cl": ["acli", "aclj", "aclk"]}) sum_dict.update({"pm25_cl_weight": [1, 1, 0.2]}) sum_dict.update({"pm25_ec": ["aeci", "aecj"]}) sum_dict.update({"pm25_ec_weight": [1, 1]}) sum_dict.update({"pm25_na": ["anai", "anaj", "aseacat", "asoil", "acors"]}) sum_dict.update({"pm25_na_weight": [1, 1, 0.2 * 0.8373, 0.2 * 0.0626, 0.2 * 0.0023]}) sum_dict.update({"pm25_ca": ["acaj", "aseacat", "asoil", "acors"]}) sum_dict.update({"pm25_ca_weight": [1, 0.2 * 0.0320, 0.2 * 0.0838, 0.2 * 0.0562]}) sum_dict.update({"pm25_nh4": ["anh4i", "anh4j", "anh4k"]}) sum_dict.update({"pm25_nh4_weight": [1, 1, 0.2]}) sum_dict.update({"pm25_no3": ["ano3i", "ano3j", "ano3k"]}) sum_dict.update({"pm25_no3_weight": [1, 1, 0.2]}) sum_dict.update({"pm25_so4": ["aso4i", "aso4j", "aso4k"]}) sum_dict.update({"pm25_so4_weight": [1, 1, 0.2]}) sum_dict.update( { "pm25_om": [ "alvpo1i", "asvpo1i", "asvpo2i", "alvoo1i", "alvoo2i", "asvoo1i", "asvoo2i", "alvpo1j", "asvpo1j", "asvpo2j", "asvpo3j", "aivpo1j", "axyl1j", "axyl2j", "axyl3j", "atol1j", "atol2j", "atol3j", "abnz1j", "abnz2j", "abnz3j", "aiso1j", "aiso2j", "aiso3j", "atrp1j", "atrp2j", "asqtj", "aalk1j", "aalk2j", "apah1j", "apah2j", "apah3j", "aorgcj", "aolgbj", "aolgaj", "alvoo1j", "alvoo2j", "asvoo1j", "asvoo2j", "asvoo3j", "apcsoj", ] } ) else: raise NotImplementedError( "Mechanism not supported, update _rrfs_cmaq_mm.py file in MONETIO" ) return sum_dict def _calc_hgt(f): """Calculates the geopotential height in m from the variables hgtsfc and delz. Note: To use this function the delz value needs to go from surface to top of atmosphere in vertical. Because we are adding the height of each grid box these are really grid top values Parameters ---------- f : xarray.Dataset RRFS-CMAQ model data Returns ------- xr.DataArray Geoptential height with attributes. """ sfc = f.surfalt_m.load() dz = f.dz_m.load() * -1.0 # These are negative in RRFS-CMAQ, but you resorted and are adding from the surface, # so make them positive. dz[:, 0, :, :] = dz[:, 0, :, :] + sfc # Add the surface altitude to the first model level only z = dz.rolling(z=len(f.z), min_periods=1).sum() z.name = "alt_msl_m_full" z.attrs["long_name"] = "Altitude MSL Full Layer in Meters" z.attrs["units"] = "m" return z def _calc_pressure(dset): """Calculate the mid-layer pressure in Pa from surface pressure and ak and bk constants. Interface pressures are calculated by: phalf(k) = a(k) + surfpres * b(k) Mid layer pressures are calculated by: pfull(k) = (phalf(k+1)-phalf(k))/log(phalf(k+1)/phalf(k)) Parameters ---------- dset : xarray.Dataset RRFS-CMAQ model data Returns ------- xarray.DataArray Mid-layer pressure with attributes. """ pres = dset.dp_pa.copy().load() # Have to load into memory here so can assign levels. srfpres = dset.surfpres_pa.copy().load() for k in range(len(dset.z)): pres_2 = dset.ak[k + 1] + srfpres * dset.bk[k + 1] pres_1 = dset.ak[k] + srfpres * dset.bk[k] pres[:, k, :, :] = (pres_2 - pres_1) / np.log(pres_2 / pres_1) pres.name = "pres_pa_mid" pres.attrs["units"] = "pa" pres.attrs["long_name"] = "Pressure Mid Layer in Pa" return pres
[ 37811, 26067, 10652, 12, 34, 5673, 48, 9220, 25342, 37227, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2124, 18747, 355, 2124, 81, 198, 6738, 299, 32152, 1330, 1673, 36686, 378, 198, 6738, 19798, 292, 1330, 7171, 628, 198, 198, 4299...
1.815259
17,917
load("@com_github_atlassian_bazel_tools//multirun:def.bzl", "command") load("@bazel_skylib//lib:shell.bzl", "shell") # This macro expects target directory for the file as an additional command line argument.
[ 2220, 7203, 31, 785, 62, 12567, 62, 25864, 46091, 62, 65, 41319, 62, 31391, 1003, 16680, 343, 403, 25, 4299, 13, 65, 48274, 1600, 366, 21812, 4943, 198, 2220, 7203, 31, 65, 41319, 62, 15688, 8019, 1003, 8019, 25, 29149, 13, 65, 4827...
3.166667
66
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** Astronomical Observatory, Ghent University ** # ***************************************************************** ## \package pts.magic.catalog.catalog Contains the GalacticCatalog and StellarCatalog classes. # ----------------------------------------------------------------- # Ensure Python 3 functionality from __future__ import absolute_import, division, print_function # Import the relevant PTS classes and modules from ..tools import catalogs from ...core.tools import introspection, tables from ...core.tools import filesystem as fs # ----------------------------------------------------------------- catalogs_user_path = fs.join(introspection.pts_user_dir, "catalogs") # ----------------------------------------------------------------- # ----------------------------------------------------------------- # -----------------------------------------------------------------
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 2, 41906, 17174, 9, 198, 2, 12429, 220, 220, 220, 220, 220, 220, 20907, 1377, 11361, 16984, 15813, 329, 1762, 351, 14277, ...
4.831858
226
from dataclasses import dataclass from typing import Iterable import torch from torchmetrics import ConfusionMatrix from collections import defaultdict argmax = lambda l: l.index(max(l)) BIRAD_MAP = ['2', '3', '4', '5'] _lbm()
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 40806, 540, 198, 198, 11748, 28034, 198, 6738, 28034, 4164, 10466, 1330, 7326, 4241, 46912, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 853, 9806, 796, 37456, 300,...
3.038961
77
# # dporules.py # # Author(s): # Matteo Spallanzani <spmatteo@iis.ee.ethz.ch> # # Copyright (c) 2020-2021 ETH Zurich. # # 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. # import networkx as nx from collections import OrderedDict import itertools import math import torch import torch.nn as nn import quantlib.editing.graphs as qg from quantlib.editing.graphs.grrules.dporules import DPORule from quantlib.editing.graphs.grrules import Seeker from quantlib.editing.graphs.graphs.nodes import Bipartite, __NODE_ID_FORMAT__, PyTorchNode import quantlib.algorithms as qa from .folding import foldsteinqconvbnste, foldconvbnste, foldsteinqconvbn __all__ = [ 'FoldSTEINQConvBNSTETypeARule', 'FoldSTEINQConvBNSTETypeBRule', 'FoldConvBNSTERule', 'FoldSTEINQConvBNRule', ]
[ 2, 220, 198, 2, 288, 1819, 5028, 13, 9078, 198, 2, 220, 198, 2, 6434, 7, 82, 2599, 198, 2, 38789, 78, 1338, 439, 35410, 3216, 1279, 2777, 6759, 660, 78, 31, 72, 271, 13, 1453, 13, 2788, 89, 13, 354, 29, 198, 2, 220, 198, 2, ...
2.942922
438
# -*- coding: utf-8 -*- # System imports import json # Third-party imports import falcon from news_api.endpoints.vespaSearcher import vespaSearch from news_api.endpoints.top_entities import getTopNewEntities from news_api.endpoints.top_clusters import getTopNewCluster # Local imports # from news_api import settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 4482, 17944, 198, 11748, 33918, 198, 198, 2, 10467, 12, 10608, 17944, 198, 11748, 24215, 1102, 198, 6738, 1705, 62, 15042, 13, 437, 13033, 13, 1158, 8957, 50, ...
3.135922
103
#9-Faa um programa que leia um nmero indeterminado de notas. Aps esta entrada de dados, faa seguinte: #. Mostre a quantidade de notas que foram lidas. #. Exiba todas as notas na ordem em que foram informadas. #. Calcule e mostre a mdia das notas. #. Calcule e mostre a quantidade de notas acima da mdia calculada. list=[] acima_media=[] notas=float(input("Informe suas notas(-1 para sair\n")) while(notas>=0): list.append(notas) notas=float(input("Informe suas notas(-1 para sair\n")) media=sum(list)/len(list) for i, word in enumerate(list): if word>media: acima_media+=[word] soma=len(acima_media) print('na posio',i,'foi digitado o nmero ',word) print(f' A quantidades de notas que foram informados: {len(list)}') print() print('=>'*30) print(f'A mdia das notas foi {media}') print(f'{soma}') print(acima_media)
[ 2, 24, 12, 37, 7252, 23781, 1430, 64, 8358, 443, 544, 23781, 299, 647, 78, 773, 13221, 4533, 390, 407, 292, 13, 317, 862, 1556, 64, 24481, 4763, 390, 9955, 418, 11, 277, 7252, 384, 5162, 600, 68, 25, 198, 2, 13, 4042, 260, 257, ...
2.368715
358
from fractions import gcd def smallestDiv(): """Finds smallest number that is evenly divisible from 1 through 20""" return reduce(lambda x,y: lcm(x,y), range(1,21)) if __name__ == '__main__': print smallestDiv()
[ 6738, 49876, 1330, 308, 10210, 198, 198, 4299, 18197, 24095, 33529, 198, 197, 37811, 16742, 82, 18197, 1271, 326, 318, 21894, 2659, 12843, 422, 352, 832, 1160, 37811, 198, 197, 7783, 4646, 7, 50033, 2124, 11, 88, 25, 300, 11215, 7, 87...
3.1
70
import argparse import csv import glob import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set() shapes = ['TriangPrismIsosc', 'parallelepiped', 'sphere', 'wire'] if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 269, 21370, 198, 11748, 15095, 198, 11748, 28686, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 3...
2.663265
98
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Keith Yang' __email__ = 'yang@keitheis.org' __version__ = '0.1.0' from pyramid.settings import asbool from .bootstrap import BootstrapFactory
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 705, 46868, 10998, 6, 198, 834, 12888, 834, 796, 705, 17859, 31, 365, 31470, 271, 13, 2398,...
2.653846
78
#!/bin/python3 import math import os import random import re import sys def print_singly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) # Complete the mergeLists function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') tests = int(input()) for tests_itr in range(tests): llist1_count = int(input()) llist1 = SinglyLinkedList() for _ in range(llist1_count): llist1_item = int(input()) llist1.insert_node(llist1_item) llist2_count = int(input()) llist2 = SinglyLinkedList() for _ in range(llist2_count): llist2_item = int(input()) llist2.insert_node(llist2_item) llist3 = mergeLists(llist1.head, llist2.head) print_singly_linked_list(llist3, ' ', fptr) fptr.write('\n') fptr.close()
[ 2, 48443, 8800, 14, 29412, 18, 198, 198, 11748, 10688, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 302, 198, 11748, 25064, 198, 198, 4299, 3601, 62, 82, 4420, 62, 25614, 62, 4868, 7, 17440, 11, 41767, 11, 277, 20692, 2599, 198, ...
2.055028
527
from quo import Console from quo.pretty import Pretty from quo.panel import Panel DATA = "My name is Quo" console = Console() for w in range(130): console.echo(Panel(Pretty(DATA), width=w))
[ 6738, 18658, 1330, 24371, 198, 6738, 18658, 13, 37784, 1330, 20090, 198, 6738, 18658, 13, 35330, 1330, 18810, 628, 198, 26947, 796, 366, 3666, 1438, 318, 2264, 78, 1, 628, 198, 198, 41947, 796, 24371, 3419, 198, 1640, 266, 287, 2837, ...
3.15873
63
#-*- coding: utf-8 -*- from django.conf import settings WYSIHTML5_EDITOR = { # Give the editor a name, the name will also be set as class # name on the iframe and on the iframe's body 'name': 'null', # Whether the editor should look like the textarea (by adopting styles) 'style': 'true', # Id of the toolbar element, pass false if you don't want # any toolbar logic 'toolbar': 'null', # Whether urls, entered by the user should automatically become # clickable-links 'autoLink': 'true', # Object which includes parser rules (set this to # examples/rules/spec.json or your own spec, otherwise only span # tags are allowed!) 'parserRules': 'wysihtml5ParserRules', # Parser method to use when the user inserts content via copy & paste 'parser': 'wysihtml5.dom.parse || Prototype.K', # Class name which should be set on the contentEditable element in # the created sandbox iframe, can be styled via the 'stylesheets' option 'composerClassName': '"wysihtml5-editor"', # Class name to add to the body when the wysihtml5 editor is supported 'bodyClassName': '"wysihtml5-supported"', # By default wysihtml5 will insert <br> for line breaks, set this to # false to use <p> 'useLineBreaks': 'true', # Array (or single string) of stylesheet urls to be loaded in the # editor's iframe 'stylesheets': '["%s"]' % (settings.STATIC_URL + "wysihtml5/css/stylesheet.css"), # Placeholder text to use, defaults to the placeholder attribute # on the textarea element 'placeholderText': 'null', # Whether the composer should allow the user to manually resize # images, tables etc. 'allowObjectResizing': 'true', # Whether the rich text editor should be rendered on touch devices # (wysihtml5 >= 0.3.0 comes with basic support for iOS 5) 'supportTouchDevices': 'true' } WYSIHTML5_TOOLBAR = { "formatBlockHeader": { "active": True, "command_name": "formatBlock", "render_icon": "wysihtml5.widgets.render_formatBlockHeader_icon" }, "formatBlockParagraph": { "active": True, "command_name": "formatBlock", "render_icon": "wysihtml5.widgets.render_formatBlockParagraph_icon" }, "bold": { "active": True, "command_name": "bold", "render_icon": "wysihtml5.widgets.render_bold_icon" }, "italic": { "active": True, "command_name": "italic", "render_icon": "wysihtml5.widgets.render_italic_icon" }, "underline": { "active": True, "command_name": "underline", "render_icon": "wysihtml5.widgets.render_underline_icon" }, "justifyLeft": { "active": True, "command_name": "justifyLeft", "render_icon": "wysihtml5.widgets.render_justifyLeft_icon" }, "justifyCenter": { "active": True, "command_name": "justifyCenter", "render_icon": "wysihtml5.widgets.render_justifyCenter_icon" }, "justifyRight": { "active": True, "command_name": "justifyRight", "render_icon": "wysihtml5.widgets.render_justifyRight_icon" }, "insertOrderedList": { "active": True, "command_name": "insertOrderedList", "render_icon": "wysihtml5.widgets.render_insertOrderedList_icon" }, "insertUnorderedList": { "active": True, "command_name": "insertUnorderedList", "render_icon": "wysihtml5.widgets.render_insertUnorderedList_icon" }, "insertImage": { "active": True, "command_name": "insertImage", "render_icon": "wysihtml5.widgets.render_insertImage_icon", "render_dialog": "wysihtml5.widgets.render_insertImage_dialog" }, "createLink": { "active": True, "command_name": "createLink", "render_icon": "wysihtml5.widgets.render_createLink_icon", "render_dialog": "wysihtml5.widgets.render_createLink_dialog" }, "insertHTML": { "active": True, "command_name": "insertHTML", "command_value": "<blockquote>quote</blockquote>", "render_icon": "wysihtml5.widgets.render_insertHTML_icon" }, "foreColor": { "active": True, "command_name": "foreColor", "render_icon": "wysihtml5.widgets.render_foreColor_icon" }, "changeView": { "active": True, "command_name": "change_view", "render_icon": "wysihtml5.widgets.render_changeView_icon" }, } # This is necessary to protect the field of content in cases where # the user disables JavaScript in the browser, so that Wysihtml5 can't # do the filter job. WYSIHTML5_ALLOWED_TAGS = ('h1 h2 h3 h4 h5 h6 div p b i u' ' ul ol li span img a blockquote')
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 198, 54, 56, 11584, 28656, 20, 62, 24706, 1581, 796, 1391, 198, 220, 220, 220, 1303, 13786, 262, 5464, 257, 1438, 1...
2.378061
2,042
from protocols import reports_3_0_0 as participant_old from protocols import participant_1_0_0 from protocols.migration import BaseMigration
[ 6738, 19565, 1330, 3136, 62, 18, 62, 15, 62, 15, 355, 18399, 62, 727, 198, 6738, 19565, 1330, 18399, 62, 16, 62, 15, 62, 15, 198, 6738, 19565, 13, 76, 4254, 1330, 7308, 44, 4254, 628 ]
3.944444
36
from builtins import object from datetime import timedelta import factory from django.utils.timezone import now from bluebottle.pages.models import Page from .accounts import BlueBottleUserFactory
[ 6738, 3170, 1040, 1330, 2134, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 11748, 8860, 198, 6738, 42625, 14208, 13, 26791, 13, 2435, 11340, 1330, 783, 198, 198, 6738, 4171, 10985, 293, 13, 31126, 13, 27530, 1330, 7873, 198, 673...
3.921569
51
# Copyright The IETF Trust 2020, All Rights Reserved # -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-01-17 12:32 from django.db import migrations def create_or_delete_ipr_doc_events(apps, delete=False): """Create or delete DocEvents for IprEvents Mostly duplicates IprEvent.create_doc_events(). This is necessary because model methods, including custom save() methods, are not available to migrations. """ IprEvent = apps.get_model('ipr', 'IprEvent') DocEvent = apps.get_model('doc', 'DocEvent') # Map from self.type_id to DocEvent.EVENT_TYPES for types that # should be logged as DocEvents event_type_map = { 'posted': 'posted_related_ipr', 'removed': 'removed_related_ipr', } for ipr_event in IprEvent.objects.filter(type_id__in=event_type_map): related_docs = set() # related docs, no duplicates for alias in ipr_event.disclosure.docs.all(): related_docs.update(alias.docs.all()) for doc in related_docs: kwargs = dict( type=event_type_map[ipr_event.type_id], time=ipr_event.time, by=ipr_event.by, doc=doc, rev='', desc='%s related IPR disclosure: <b>%s</b>' % (ipr_event.type.name, ipr_event.disclosure.title), ) events = DocEvent.objects.filter(**kwargs) # get existing events if delete: events.delete() elif len(events) == 0: DocEvent.objects.create(**kwargs) # create if did not exist def forward(apps, schema_editor): """Create a DocEvent for each 'posted' or 'removed' IprEvent""" create_or_delete_ipr_doc_events(apps, delete=False) def reverse(apps, schema_editor): """Delete DocEvents that would be created by the forward migration This removes data, but only data that can be regenerated by running the forward migration. """ create_or_delete_ipr_doc_events(apps, delete=True)
[ 2, 15069, 383, 314, 22274, 9870, 12131, 11, 1439, 6923, 33876, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1983, 319, 12131, 12, 486, 12, 1558, 1105, 25, 2624, ...
2.256959
934
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 23:52:04 2020 @author: Madhur Gupta """ from __future__ import print_function import cv2 import argparse ap=argparse.ArgumentParser() ap.add_argument('-i','--image',required=True,help='path to image') args=vars(ap.parse_args()) image=cv2.imread(args['image']) cv2.imshow("Original", image) #setting 0,0 as red pixel (b,g,r)=image[0,0] print("Pixel at (0, 0) - Red: {}, Green: {}, Blue: {}".format(r,g, b)) image[0, 0] = (0, 0, 255) (b, g, r) = image[0, 0] print("Pixel at (0, 0) - Red: {}, Green: {}, Blue: {}".format(r,g, b)) #setting the corner of image as green corner=image[0:100,0:100] cv2.imshow('corner',corner) image[0:100,0:100]=(0,255,0) cv2.imshow('Updated',image) cv2.waitKey(0)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 30030, 4280, 1315, 2242, 25, 4309, 25, 3023, 12131, 201, 198, 201, 198, 31, 9800, 25, 4627, 48349, 42095, 201, 198, 37811, 201, 198, ...
2.182825
361
# -*- coding: utf-8 -*- """ ACLReader test cases """ import unittest from kazoo.security import ACL, Id from zk_shell.acl import ACLReader
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 17382, 33634, 1332, 2663, 37227, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 479, 1031, 2238, 13, 12961, 1330, 17382, 11, 5121, 198, 198, 6738, 1976, 74,...
2.769231
52
"""Base validators.""" import re from dictator.errors import ValidationError from dictator.validators import Validator from typing import Type, Callable, Any, Tuple, Union HEX_REGEX = re.compile(r"^(0x)?([0-9A-Fa-f]+)$") BIN_REGEX = re.compile(r"^(0b)?([0-1]+)$") def _validate_integer(_value: Any, **kwargs: Any) -> int: """Validate integer value. Parameters ---------- _value Some value kwargs Other metadata """ if isinstance(_value, str): # try converting h = HEX_REGEX.match(_value) b = BIN_REGEX.match(_value) if h is not None: if h.group(1) is None and b is not None: # is actually binary return int(h.group(2), 2) return int(h.group(2), 16) raise ValidationError("cannot validate as integer") elif isinstance(_value, bool): raise ValidationError("cannot validate as integer, got boolean") elif isinstance(_value, int): return _value raise ValidationError("cannot validate as integer") validate_string = ValidatorFactory(ValidateType(str)) validate_list = ValidatorFactory(ValidateType(tuple, list)) validate_dict = ValidatorFactory(ValidateType(dict)) validate_boolean = ValidatorFactory(ValidateType(bool)) validate_float = ValidatorFactory(ValidateType(float)) validate_integer = ValidatorFactory(_validate_integer) validate_string_pre = ValidatorFactory(ValidateType(str), after_fn=False) validate_list_pre = ValidatorFactory(ValidateType(tuple, list), after_fn=False) validate_dict_pre = ValidatorFactory(ValidateType(dict), after_fn=False) validate_boolean_pre = ValidatorFactory(ValidateType(bool), after_fn=False) validate_float_pre = ValidatorFactory(ValidateType(float), after_fn=False) validate_integer_pre = ValidatorFactory(_validate_integer, after_fn=False) def validate_null(_value: Any, **kwargs: Any) -> None: """Validate null value. Parameters --------- _value Some value kwargs Other metadata """ if _value is not None: raise ValidationError("value is not null") return _value DEFAULT_VALIDATOR_BY_TYPE = { int: validate_integer, str: validate_string, list: validate_list, dict: validate_dict, bool: validate_boolean, float: validate_float, }
[ 37811, 14881, 4938, 2024, 526, 15931, 198, 198, 11748, 302, 198, 6738, 26671, 13, 48277, 1330, 3254, 24765, 12331, 198, 6738, 26671, 13, 12102, 2024, 1330, 48951, 1352, 198, 6738, 19720, 1330, 5994, 11, 4889, 540, 11, 4377, 11, 309, 292...
2.616592
892
from .ReportParser import ReportParser
[ 6738, 764, 19100, 46677, 1330, 6358, 46677, 628 ]
5
8
import torch.nn as nn import torch """ # use this one when not doing multi-task learning as a baseline class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, nlayers=2): super(EncoderRNN, self).__init__() self.nlayers = nlayers self.hidden_size = hidden_size self.embedding = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, nlayers) def forward(self, input, hidden): embedded = self.embedding(input).view(1, 1, -1) output = embedded output, hidden = self.gru(output, hidden) return output, hidden def initHidden(self, bsz): return torch.zeros(self.nlayers, bsz, self.hidden_size, device='gpu') """
[ 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 628, 198, 198, 37811, 198, 2, 779, 428, 530, 618, 407, 1804, 5021, 12, 35943, 4673, 355, 257, 14805, 198, 4871, 14711, 12342, 49, 6144, 7, 20471, 13, 26796, 2599, 198, 220, 2...
2.417476
309
import torch import torch.nn as nn from torch.optim.lr_scheduler import CosineAnnealingLR, CosineAnnealingWarmRestarts import itertools import matplotlib.pyplot as plt initial_lr = 0.1 net_1 = model() optimizer_1 = torch.optim.Adam(net_1.parameters(), lr=initial_lr) scheduler_1 = CosineAnnealingWarmRestarts(optimizer_1, T_0=1) print("", optimizer_1.defaults['lr']) lr_list = [] # lr for epoch in range(0, 6): # train for i in range(int(30000/32)): optimizer_1.zero_grad() optimizer_1.step() print("%depoch%f" % (epoch, optimizer_1.param_groups[0]['lr'])) lr_list.append(optimizer_1.param_groups[0]['lr']) scheduler_1.step((epoch+i+1)/int(30000/32)) # lr plt.plot(lr_list) plt.xlabel("epoch") plt.ylabel("lr") plt.title("learning rate's curve changes as epoch goes on!") plt.show()
[ 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 40085, 13, 14050, 62, 1416, 704, 18173, 1330, 10437, 500, 43227, 4272, 35972, 11, 10437, 500, 43227, 4272, 54, 1670, 19452, 5889, 198, 11748, 340, 861,...
2.227154
383
from django.urls import path from .views import events_calendar, calendar_event_detail, past_competitions app_name = 'events_calendar' urlpatterns = [ path('past_competitions/', past_competitions, name='past_competitions'), path('<int:year>/<int:month>/<int:day>/<int:hour>/<slug:event>/', calendar_event_detail, name='calendar_event_detail'), path('<int:days>', events_calendar, name='events_calendar'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 33571, 1330, 2995, 62, 9948, 9239, 11, 11845, 62, 15596, 62, 49170, 11, 1613, 62, 5589, 316, 1756, 628, 198, 1324, 62, 3672, 796, 705, 31534, 62, 9948, 9239, 6, 198,...
2.618182
165
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pdb import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from trading_gym.utils.data.toy import create_toy_data from trading_gym.envs.portfolio_gym.portfolio_gym import PortfolioTradingGym order_book_id_number = 100 toy_data = create_toy_data(order_book_ids_number=order_book_id_number, feature_number=10, start="2019-05-01", end="2019-12-12", frequency="D") env = PortfolioTradingGym(data_df=toy_data, sequence_window=1, add_cash=False) state = env.reset() while True: next_state, reward, done, info = env.step(action=None) label = info["one_step_fwd_returns"] print(state) print(label) # regressor = LinearRegression() regressor.fit(state.values, label.values) #display and store print(regressor.coef_) env.experience_buffer["coef"].append(regressor.coef_) # if done: break else: state = next_state # factor_returns = pd.DataFrame(np.array(env.experience_buffer["coef"]), index=env.experience_buffer["dt"], columns=toy_data.columns[:-1]) cum_factor_returns = (factor_returns +1).cumprod() cum_factor_returns.plot(title="Cumulative Factor Return",linewidth=2.2)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 279, 9945, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720,...
2.49697
495
"""session speaker Revision ID: 6f98e24760d Revises: 58588eba8cb8 Create Date: 2013-11-22 17:28:47.751025 """ # revision identifiers, used by Alembic. revision = '6f98e24760d' down_revision = '58588eba8cb8' from alembic import op import sqlalchemy as sa
[ 37811, 29891, 10834, 198, 198, 18009, 1166, 4522, 25, 718, 69, 4089, 68, 23753, 1899, 67, 198, 18009, 2696, 25, 7618, 39118, 1765, 64, 23, 21101, 23, 198, 16447, 7536, 25, 2211, 12, 1157, 12, 1828, 1596, 25, 2078, 25, 2857, 13, 2425...
2.47619
105
#!/usr/bin/python """ this is the code to accompany the Lesson 3 (decision tree) mini-project use an DT to identify emails from the Enron corpus by their authors Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess from sklearn import tree from sklearn.metrics import accuracy_score import time ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() clf = tree.DecisionTreeClassifier(min_samples_split = 40) clf = clf.fit(features_train, labels_train) prediction = clf.predict(features_test) accuracy = accuracy_score(prediction, labels_test) print("Accuracy: %.6f" % accuracy) print("Feature length: %d" % len(features_train[0])) ######################################################### ### your code goes here ### #########################################################
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 37811, 220, 198, 220, 220, 220, 428, 318, 262, 2438, 284, 13873, 262, 12892, 261, 513, 357, 12501, 1166, 5509, 8, 9927, 12, 16302, 628, 220, 220, 220, 779, 281, 24311, 284, 5911, 7237,...
3.561688
308
''' mode: python; py-indent-offset: 4; tab-width: 4; coding: utf-8 Copyright (C) 2020 Airbus SAS ''' import unittest import time import numpy as np import pandas as pd from sos_trades_core.execution_engine.execution_engine import ExecutionEngine from climateeconomics.sos_processes.iam.witness.witness_dev.usecase_witness import Study as Study_open if '__main__' == __name__: t0 = time.time() cls = TestGlobalEnergyValues() cls.setUp() cls.test_03_check_net_production_values() print(f'Time : {time.time() - t0} s')
[ 7061, 6, 198, 14171, 25, 21015, 26, 12972, 12, 521, 298, 12, 28968, 25, 604, 26, 7400, 12, 10394, 25, 604, 26, 19617, 25, 3384, 69, 12, 23, 198, 15269, 357, 34, 8, 12131, 39173, 35516, 198, 7061, 6, 198, 11748, 555, 715, 395, 19...
2.655172
203
import os import csv import h5py import numpy as np from neuron import h from .sim_module import SimulatorMod from bmtk.simulator.bionet.biocell import BioCell from bmtk.simulator.bionet.io_tools import io from bmtk.simulator.bionet.pointprocesscell import PointProcessCell pc = h.ParallelContext() MPI_RANK = int(pc.id()) N_HOSTS = int(pc.nhost())
[ 11748, 28686, 198, 11748, 269, 21370, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 43164, 1330, 289, 198, 198, 6738, 764, 14323, 62, 21412, 1330, 13942, 5841, 198, 6738, 275, 16762, 74, 13, 14323, 8927, 13, ...
2.765625
128
import time client_msg_type = 689 reserved_data_field = 0
[ 11748, 640, 198, 198, 16366, 62, 19662, 62, 4906, 796, 718, 4531, 198, 411, 8520, 62, 7890, 62, 3245, 796, 657, 628, 628, 628, 628, 628 ]
2.615385
26
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # # ------------------------------------------------------------- from .mapper import Mapper
[ 2, 20368, 1783, 32501, 198, 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, ...
4.4
215
from .home import Steg __all__ = ['Steg',]
[ 6738, 764, 11195, 1330, 520, 1533, 198, 198, 834, 439, 834, 796, 37250, 7447, 70, 3256, 60 ]
2.529412
17
import ctypes from ctypes import wintypes, windll import win32api import win32con import win32gui # PUL = ctypes.POINTER(ctypes.c_ulong) PUL = ctypes.c_void_p # HookProc = ctypes.WINFUNCTYPE( wintypes.LPARAM, ctypes.c_int32, wintypes.WPARAM, ctypes.POINTER(KeyBdMsg)) # SendInput = windll.user32.SendInput SendInput.argtypes = ( wintypes.UINT, ctypes.POINTER(Input), ctypes.c_int) # GetMessage = windll.user32.GetMessageA GetMessage.argtypes = ( wintypes.MSG, wintypes.HWND, wintypes.UINT, wintypes.UINT) # SetWindowsHookEx = windll.user32.SetWindowsHookExA SetWindowsHookEx.argtypes = ( ctypes.c_int, HookProc, wintypes.HINSTANCE, wintypes.DWORD) # UnhookWindowsHookEx = windll.user32.UnhookWindowsHookEx UnhookWindowsHookEx.argtypes = ( wintypes.HHOOK,) # CallNextHookEx = windll.user32.CallNextHookEx CallNextHookEx.argtypes = ( wintypes.HHOOK, ctypes.c_int, wintypes.WPARAM, KeyBdMsg) GetAsyncKeyState = windll.user32.GetAsyncKeyState GetAsyncKeyState.argtypes = ( ctypes.c_int, ) GetMessageExtraInfo = windll.user32.GetMessageExtraInfo SetMessageExtraInfo = windll.user32.SetMessageExtraInfo SetMessageExtraInfo.argtypes = ( wintypes.LPARAM, ) def send_kb_event(v_key, is_pressed): """ dwExtraInfo228 :param v_key: :param is_pressed: :return: """ extra = 228 li = InputUnion() flag = KeyBdInput.KEYUP if not is_pressed else 0 li.ki = KeyBdInput(v_key, 0x48, flag, 0, extra) input = Input(Input.KEYBOARD, li) return SendInput(1, ctypes.pointer(input), ctypes.sizeof(input))
[ 11748, 269, 19199, 198, 6738, 269, 19199, 1330, 266, 600, 9497, 11, 2344, 297, 198, 198, 11748, 1592, 2624, 15042, 198, 11748, 1592, 2624, 1102, 198, 11748, 1592, 2624, 48317, 198, 198, 2, 350, 6239, 796, 269, 19199, 13, 16402, 41358, ...
2.277008
722
from django.shortcuts import render import numpy as np
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 11748, 299, 32152, 355, 45941, 628, 628 ]
3.625
16
from django.db import models from django.contrib.auth.models import AbstractBaseUser
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 201, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 14881, 12982, 201, 198, 201, 198, 201, 198 ]
3.137931
29
from .validators import Validator, BaseRule __all__ = ('Validator', 'BaseRule',)
[ 6738, 764, 12102, 2024, 1330, 48951, 1352, 11, 7308, 31929, 628, 198, 834, 439, 834, 796, 19203, 47139, 1352, 3256, 705, 14881, 31929, 3256, 8, 198 ]
3.192308
26
#! /usr/bin/env python """ Compare bruker read_pdata to read. """ import nmrglue as ng import matplotlib.pyplot as plt # read in the data data_dir = "data/bruker_exp/1/pdata/1" # From pre-procced data. dic, data = ng.bruker.read_pdata(data_dir, scale_data=True) udic = ng.bruker.guess_udic(dic, data) uc = ng.fileiobase.uc_from_udic(udic) ppm_scale = uc.ppm_scale() # From FID dic1, data1 = ng.bruker.read(data_dir) # remove the digital filter, this data is from an analog spectrometer. # data = ng.bruker.remove_digital_filter(dic, data) # process the spectrum data1 = ng.proc_base.ls(data1, 1) # left shift data1 = ng.proc_base.gm(data1, g2=1/2.8e3) # To match proc data... data1 = ng.proc_base.zf_size(data1, 1024*32) # zero fill data1 = ng.proc_base.fft_positive(data1) # FT data1 = ng.proc_base.ps(data1, p0=93) # phase is 180 off Bruker data1 = ng.proc_base.di(data1) # discard udic1 = ng.bruker.guess_udic(dic1, data1) uc1 = ng.fileiobase.uc_from_udic(udic1) ppm_scale1 = uc1.ppm_scale() # plot the spectrum fig = plt.figure() plt.hold(True) plt.plot(ppm_scale, data) plt.plot(ppm_scale1, data1) plt.hold(False) plt.xlim([50, -50]) plt.xlabel('Carbon Chemical shift (ppm from neat TMS)') plt.title('bruker.read_pdata vs bruker.read, note ppm axis') plt.show()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 41488, 18145, 6122, 1100, 62, 79, 7890, 284, 1100, 13, 198, 37811, 198, 198, 11748, 28642, 81, 4743, 518, 355, 23370, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355,...
2.207358
598
import io import os import unittest import boto3 from botocore.response import StreamingBody from botocore.stub import Stubber from functions.posts_get.posts_get_logic import posts_get_logic
[ 11748, 33245, 198, 11748, 28686, 198, 11748, 555, 715, 395, 198, 198, 11748, 275, 2069, 18, 198, 6738, 10214, 420, 382, 13, 26209, 1330, 43124, 25842, 198, 6738, 10214, 420, 382, 13, 301, 549, 1330, 41135, 527, 198, 198, 6738, 5499, 1...
3.233333
60
from typing import Union, List import copy import math import numpy as np """ Principles: - geometry objects are defined by the minimum required information - Points are made of coordinates (floats), everything else is based on Points except for Vectors """ def move(obj: Union[Point, Line, Rectangle, Box, Face], vector: Vector, inplace=False): if isinstance(obj, Point): return obj + vector else: if inplace: new_obj = obj else: new_obj = copy.deepcopy(obj) for param, val in new_obj.__dict__.items(): if isinstance(val, (Point, Line, Rectangle, Box, Face)): # love recursion new_obj.__dict__[param] = move(val, vector) elif isinstance(val, list): new_obj.__dict__[param] = [move(p, vector) for p in val] return new_obj def rotate_xy(obj: Union[Point, Line, Rectangle, Box, Face], angle: float, center: Point = Point(0, 0, 0), inplace=False): """ Rotate objects in the xy plane (around z axis) :param obj: object to rotate :param angle: angle to rotate with :param center: center to rotate around :param inplace: set True to modify the object instance itself :return: rotated object """ if isinstance(obj, Point): # move point to origin obj_origin = move(obj, Point(0, 0, 0) - center) # apply rotation around origin new_point = Point( x=obj_origin.x * math.cos(math.radians(angle)) - obj_origin.y * math.sin(math.radians(angle)), y=obj_origin.x * math.sin(math.radians(angle)) + obj_origin.y * math.cos(math.radians(angle)), z=obj_origin.z ) # move back return move(new_point, center - Point(0, 0, 0)) else: if inplace: new_obj = obj else: new_obj = copy.deepcopy(obj) for param, val in new_obj.__dict__.items(): if isinstance(val, (Point, Line, Rectangle, Box, Face)): # love recursion new_obj.__dict__[param] = rotate_xy(val, angle, center) elif isinstance(val, list): new_obj.__dict__[param] = [rotate_xy(p, angle, center) for p in val] return new_obj
[ 6738, 19720, 1330, 4479, 11, 7343, 198, 11748, 4866, 198, 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 628, 198, 37811, 198, 47231, 6418, 25, 198, 198, 12, 22939, 5563, 389, 5447, 416, 262, 5288, 2672, 1321, 198, 12, 11045, 389, ...
2.272817
1,008
import os, logging if not os.path.exists('config'): os.mkdir('config') log = logging.getLogger('danmu') log.setLevel(logging.DEBUG) fileHandler = logging.FileHandler(os.path.join('config', 'run.log'), encoding = 'utf8') fileHandler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)-17s <%(message)s> %(levelname)s %(filename)s[%(lineno)d]', datefmt='%Y%m%d %H:%M:%S') fileHandler.setFormatter(formatter) log.addHandler(fileHandler) if __name__ == '__main__': log.debug('This is debug') log.info('This is info')
[ 11748, 28686, 11, 18931, 201, 198, 201, 198, 361, 407, 28686, 13, 6978, 13, 1069, 1023, 10786, 11250, 6, 2599, 28686, 13, 28015, 15908, 10786, 11250, 11537, 201, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 10786, 25604, 30300, 11537, ...
2.449339
227
import multiprocessing import time import gym import gym3 import numpy as np from gym.vector import make as make_vec_env from procgen import ProcgenGym3Env population_size = 112 number_env_steps = 1000 if __name__ == "__main__": main()
[ 11748, 18540, 305, 919, 278, 198, 11748, 640, 198, 198, 11748, 11550, 198, 11748, 11550, 18, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 11550, 13, 31364, 1330, 787, 355, 787, 62, 35138, 62, 24330, 198, 6738, 13834, 5235, 1330, 31345...
2.964286
84
import time import typing
[ 11748, 640, 198, 11748, 19720, 628, 628 ]
4.142857
7
# adapted from https://sites.google.com/site/mikescoderama/Home/0-1-knapsack-problem-in-p W = 10 v = [9, 14, 16, 30] w = [2, 3, 4, 6] print(zeroOneKnapsack(v, w, W))
[ 198, 2, 16573, 422, 220, 3740, 1378, 49315, 13, 13297, 13, 785, 14, 15654, 14, 76, 1134, 3798, 12342, 1689, 14, 16060, 14, 15, 12, 16, 12, 15418, 1686, 441, 12, 45573, 12, 259, 12, 79, 198, 198, 54, 796, 838, 198, 85, 796, 685, ...
2.023256
86
# Generated by Django 3.0.2 on 2020-10-08 22:36 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 17, 319, 12131, 12, 940, 12, 2919, 2534, 25, 2623, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import os import sys import django sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings") django.setup() from django.contrib.auth.models import User # noqa: E402 from museum_site.models import * # noqa: E402 if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 42625, 14208, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 3...
2.578947
133
import matplotlib.pylab as plt import numpy as np plt.figure() axes=plt.gca() y= np.random.randn(9) col_labels=['col1','col2','col3'] row_labels=['row1','row2','row3'] table_vals=[[11,12,13],[21,22,23],[28,29,30]] row_colors=['red','gold','green'] the_table = plt.table(cellText=table_vals, colWidths = [0.1]*3, rowLabels=row_labels, colLabels=col_labels, rowColours=row_colors, loc='upper right') plt.text(12,3.4,'Table Title',size=8) plt.plot(y) plt.show()
[ 11748, 2603, 29487, 8019, 13, 79, 2645, 397, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 489, 83, 13, 26875, 3419, 198, 897, 274, 28, 489, 83, 13, 70, 6888, 3419, 198, 88, 28, 45941, 13, 25120, 13, 25192, 77, 7, ...
1.825083
303
import re import os def extract(regularE : str, init : str, stop : str, string : str): """ regularE: RE to catch string init: First string to replace stop: Last string to replace string: String to apply the RE With a regular expression and init and stop to replace, gets a substring from string argument and returns it. """ return re.findall(regularE, string)[0]\ .replace(init, "")\ .replace(stop, "") def get_term_clock_pid(): """ return: int with the PID of term_clock; -1 if process doesn't exist. Extracts the PID of term_clock process with systemctl. """ # sputnikDriver prints in their own console all the PIDs of its subprocesses ret = os.popen("systemctl status sputnikDriver.service").read() if ret == "": return -1 return int(extract(r"term_clock .+ PID", "term_clock ", " PID", ret)) def check_alive(): """ return: True if java process is running; False otherwise Check if a java process in sputnikDriver (i.e. the Minecraft Server) is running """ ret = os.popen("systemctl status sputnikDriver.service").read() return "java" in ret
[ 11748, 302, 198, 11748, 28686, 628, 198, 4299, 7925, 7, 16338, 36, 1058, 965, 11, 2315, 1058, 965, 11, 2245, 1058, 965, 11, 4731, 1058, 965, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 220, 220, 220, 220, 3218, 36, 25, 22...
2.541414
495
#!/usr/env/python3 # coding=utf-8 # # Generate Steamguard OTP with the shared secret passed as an argument # Ganesh Velu import hmac import base64 import hashlib import codecs import time import sys STEAM_DECODE_CHARS = ['2', '3', '4', '5', '6', '7', '8', '9', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y'] if __name__ == '__main__': print(get_authentication_code(sys.argv[1]), end='')
[ 2, 48443, 14629, 14, 24330, 14, 29412, 18, 198, 2, 19617, 28, 40477, 12, 23, 198, 2, 198, 2, 2980, 378, 9094, 14864, 440, 7250, 351, 262, 4888, 3200, 3804, 355, 281, 4578, 198, 2, 23207, 5069, 17378, 84, 220, 198, 198, 11748, 289,...
1.980315
254
""" """
[ 37811, 198, 198, 37811, 198 ]
1.8
5
"""Handle rendering of the Energy Power Meter widget.""" from apps.widgets.resource_goal import resource_goal def supply(request, page_name): """Return the view_objects content, which in this case is empty.""" _ = page_name team = request.user.get_profile().team if team: interval = resource_goal.team_goal_settings(team, "energy").realtime_meter_interval else: interval = None width = 300 height = 100 return {"interval": interval, "width": width, "height": height }
[ 37811, 37508, 14837, 286, 262, 6682, 4333, 46423, 26295, 526, 15931, 198, 6738, 6725, 13, 28029, 11407, 13, 31092, 62, 35231, 1330, 8271, 62, 35231, 628, 198, 4299, 5127, 7, 25927, 11, 2443, 62, 3672, 2599, 198, 220, 220, 220, 37227, ...
2.673077
208
import argparse import json from authlib.jose import JsonWebKey from cryptography.hazmat.primitives import serialization def generate_key_pair(filename, kid=None): """ 'kid' will default to the jwk thumbprint if not set explicitly. Reference: https://tools.ietf.org/html/rfc7638 """ options = {} if kid: options["kid"] = kid jwk = JsonWebKey.generate_key("RSA", 2048, is_private=True, options=options) print(("Writing public key to %s.jwk" % filename)) with open("%s.jwk" % filename, mode="w") as f: f.truncate(0) f.write(jwk.as_json()) print(("Writing key ID to %s.kid" % filename)) with open("%s.kid" % filename, mode="w") as f: f.truncate(0) f.write(jwk.as_dict()["kid"]) print(("Writing private key to %s.pem" % filename)) with open("%s.pem" % filename, mode="wb") as f: f.truncate(0) f.write( jwk.get_private_key().private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) ) parser = argparse.ArgumentParser(description="Generates a key pair into files") parser.add_argument("filename", help="The filename prefix for the generated key files") args = parser.parse_args() generate_key_pair(args.filename)
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 198, 6738, 6284, 8019, 13, 73, 577, 1330, 449, 1559, 13908, 9218, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 1330, 11389, 1634, 628, 198, 4299, 7716, 62, 2539, 62, 24874, 7, 343...
2.427586
580
### # Copyright (c) 2019-present, IBM Research # Licensed under The MIT License [see LICENSE for details] ### from collections import defaultdict from hkpy.hkpyo.model import HKOContext, HKOContextManager, HKOConcept, HKOSubConceptAxiom, HKOConjunctionExpression, \ HKODisjunctionExpression, HKOConceptAssertion, HKOIndividual, HKOPropertyAssertion, HKOLiteral, Union, HKOAxiom, \ HKOAssertion, HKOProperty
[ 21017, 198, 2, 15069, 357, 66, 8, 13130, 12, 25579, 11, 19764, 4992, 198, 2, 49962, 739, 383, 17168, 13789, 685, 3826, 38559, 24290, 329, 3307, 60, 198, 21017, 198, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 6738, 289, 74, 9078, ...
3.007194
139
from django.contrib import admin from .models import Account, Product, Drink, Topping, Order admin.site.register(Account) admin.site.register(Product) admin.site.register(Drink) admin.site.register(Topping) admin.site.register(Order)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 10781, 11, 8721, 11, 32906, 11, 1675, 2105, 11, 8284, 628, 198, 28482, 13, 15654, 13, 30238, 7, 30116, 8, 198, 28482, 13, 15654, 13, 30238, 7, 15667, ...
3.246575
73
from __future__ import absolute_import from influxdb_client.client.influxdb_client import InfluxDBClient
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 25065, 9945, 62, 16366, 13, 16366, 13, 10745, 22564, 9945, 62, 16366, 1330, 4806, 22564, 11012, 11792, 198 ]
3.655172
29
from django.contrib.auth.models import User from django import forms from .models import UserProfile
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 11787, 37046, 628, 198, 220, 628, 198 ]
3.566667
30
import sys import numpy as np import os import requests import json import logging from json import JSONEncoder from keras.models import model_from_json sys.path.append('..') from preprocessing.InputHelper import InputHelper from model.lstm import rmse from model.lstm import buildModel from keras.preprocessing.sequence import pad_sequences sys.path.append('..') ''' This is a stand-alone test for the python API service. It doesn't use Flask. ''' OPTIMIZER = 'rmsprop' NUM_CLASSES = 0 MAXLEN = 50 SAVED_MODEL_FILE = '../../saved_models/model.h5' PUBMED_DIM = 200 VAL_DIMENSIONS = 5 TF_SERVING_HOSTNAME = os.environ.get("TF_SERVING_HOSTNAME", "") TF_SERVING_PORT = os.environ.get("TF_SERVING_PORT", "") USES_TF_SERVING = TF_SERVING_HOSTNAME != "" and TF_SERVING_PORT != "" def get_model_json(saved_model): print("Loading model from file {}".format(saved_model)) json_file = open(saved_model, 'r') json_str = json_file.read() json_file.close() return json_str def predict_outcome(inpH, model, test_instance_str): x = inpH.tokenizer.texts_to_sequences([test_instance_str]) x = pad_sequences(x, padding='post', maxlen=MAXLEN) y_preds = model.predict(x, steps=1) return y_preds[0] def predict_regression_outcome(model, model_name, test_input_batch): y_preds = predict_outcome_local_or_api(model, model_name, test_input_batch) return y_preds[:,0] def predict_confidence(model, model_name, test_input_batch): y_preds = predict_outcome_local_or_api(model, model_name, test_input_batch) return np.max(y_preds, axis=1) def predict_outcome_local_or_api(model, model_name, test_input_batch): if USES_TF_SERVING: return call_tf_serving_predict(model_name, test_input_batch) else: # in this case, "model" is the actual keras model return predict_outcome_with_dynamic_vocabchange(model, test_input_batch) def predict_outcome_with_dynamic_vocabchange(model, test_input_batch): x_test = test_input_batch print("x_test = {}".format(x_test)) y_preds = model.predict_on_batch(x_test) print('y_preds = {}'.format(y_preds)) return y_preds def call_tf_serving_predict(model_name, test_input_batch): x_test = test_input_batch logging.debug("x_test = {}".format(x_test)) url = get_tf_serving_predict_endpoint(model_name) # batched instances instances = x_test json_post_body = json.dumps({"instances": instances}, cls=NumpyArrayEncoder) r = requests.post(url, json_post_body) logging.info(f"Response from {url}") logging.info(r.text) response = r.json() return np.array(response["predictions"]) def get_tf_serving_predict_endpoint(model_name): return "http://" + TF_SERVING_HOSTNAME + ":" + TF_SERVING_PORT + "/" \ + "v1/models/" + model_name + ":predict" def init_embedding(embfile): inpH = InputHelper() print("converting words to ids...") inpH.convertWordsToIds(embfile) print("vocab size = {}".format(inpH.vocab_size)) inpH.loadW2V(embfile) return inpH # Replace a node if the form C:<x>:0.1 with C:<x>:0.2 (the closest value with the same attrib-id in our vocabulary) if __name__ == "__main__": main(sys.argv[1:])
[ 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 18931, 198, 6738, 33918, 1330, 19449, 27195, 12342, 198, 6738, 41927, 292, 13, 27530, 1330, 2746, 62, 6738, 62, 17752, 1...
2.495356
1,292
from manhattan.manage import config from manhattan.nav import Nav, NavItem from blueprints.accounts.manage import blueprint from blueprints.accounts.models import Account __all__ = ['AccountConfig']
[ 6738, 582, 12904, 13, 805, 496, 1330, 4566, 198, 6738, 582, 12904, 13, 28341, 1330, 13244, 11, 13244, 7449, 198, 198, 6738, 4171, 17190, 13, 23317, 82, 13, 805, 496, 1330, 30881, 198, 6738, 4171, 17190, 13, 23317, 82, 13, 27530, 1330,...
3.740741
54
from aiohttp import ClientConnectionError from wsrpc_aiohttp.testing import BaseTestCase, async_timeout
[ 6738, 257, 952, 4023, 1330, 20985, 32048, 12331, 198, 6738, 266, 27891, 14751, 62, 64, 952, 4023, 13, 33407, 1330, 7308, 14402, 20448, 11, 30351, 62, 48678, 628 ]
3.75
28
import logging import logging.config import os LOG_DIR = os.path.dirname(os.path.abspath(__file__)) log_config = { 'version': 1, 'formatters': { 'verbose': { 'class': 'logging.Formatter', 'format': '%(asctime)s [%(name)s] %(levelname)-8s %(pathname)s:%(lineno)d - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', 'style': '%' }, 'simple': { 'class': 'logging.Formatter', 'format': '%(asctime)s %(levelname)-8s - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', 'style': '%' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'simple' }, 'octopus': { 'class': 'logging.FileHandler', 'level': 'INFO', 'filename': os.path.join(LOG_DIR, 'octopus.log'), 'mode': 'a', 'formatter': 'verbose', 'encoding': 'utf-8' }, 'surveillance': { 'class': 'logging.FileHandler', 'level': 'INFO', 'filename': os.path.join(LOG_DIR, 'surveillance.log'), 'mode': 'a', 'formatter': 'verbose', 'encoding': 'utf-8' }, 'file': { 'class': 'logging.FileHandler', 'level': 'INFO', 'filename': 'app.log', 'mode': 'a', 'formatter': 'verbose', 'encoding': 'utf-8' }, 'rotate_file': { 'class': 'logging.handlers.RotatingFileHandler', 'level': 'INFO', 'filename': 'app.log', 'mode': 'a', 'formatter': 'verbose', 'maxBytes': 10485760, 'backupCount': 3, 'encoding': 'utf-8' } }, 'loggers': { 'Octopus': { 'handlers': ['octopus'] }, 'Surveillance': { 'handlers': ['surveillance'] } }, 'root': { 'level': 'INFO', 'handlers': ['console'] } } # propagate default is true,so message is propagated its parent's logger until root # e.x. Octopus flush message to file, and progagate message to root logger, and flush to console logging.config.dictConfig(log_config)
[ 11748, 18931, 198, 11748, 18931, 13, 11250, 198, 11748, 28686, 198, 198, 25294, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 4008, 198, 6404, 62, 11250, 796, 1391, 198, 2...
1.816406
1,280
#!/usr/bin/env python import os import platform from glob import glob import utils.appconfig as appconfig # GLOBAL CONSTANTS # --- File Structure Constants --- BASE_DIRS = { 'delivery': [ 'CritiqueArchive' ], 'docs': [], 'frames': [], 'library': [ 'models', 'templates', 'sound', 'texture' ], 'publish': [], 'source': [ 'plates', 'reference' ], 'working': [ 'scenes', 'assets' ]} PROD_DIRS = [ 'scenes', 'publish' ] STAGE_DIRS = appconfig.get_config_value('law', 'stages') FRAME_DIRS = [ 'cg', 'comp', 'edit', 'elements', 'plates' ] # GLOBAL FUNCTIONS # SET SHOW ENV VARIABLE # SET SEQ ENV VARIABLE # SET SHOT ENV VARIABLE if __name__ == '__main__': print serverDir()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 3859, 198, 6738, 15095, 1330, 15095, 198, 198, 11748, 3384, 4487, 13, 1324, 11250, 355, 598, 11250, 628, 198, 2, 10188, 9864, 1847, 7102, 2257, 1565, 4694,...
1.733558
593
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors. # # 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. # Lint as: python3 """THUNews""" import csv import ctypes import os import datasets csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2)) _CITATION = """\ @misc{xujianhua, title={page xxx}, author={Xiang Zhang and Junbo Zhao and Yann LeCun}, year={2015}, eprint={1509.01626}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ _DESCRIPTION = """\ THUCTC(THU Chinese Text Classification)\ THUCTCbigramChi-squaretfidf LibSVMLibLinearTHUCTC """ _DATA_URL = "http://127.0.0.1/thuc_news.zip" _CLS = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 12131, 383, 309, 22854, 37535, 16092, 292, 1039, 46665, 290, 262, 12905, 2667, 32388, 16092, 292, 1039, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 35...
2.869767
430
from lib.interface import cabecalho
[ 6738, 9195, 13, 39994, 1330, 16212, 721, 282, 8873, 220, 628, 198 ]
3.25
12
from graph import Graph matrix = [] with open('p083_matrix.txt') as file: for line in file.readlines(): currentline = [int(n) for n in line.split(',')] matrix.append(currentline) numGraph = Graph() # add each node first for i in range(len(matrix)): for j in range(len(matrix[i])): numGraph.addNode((i, j)) # then map edges for i in range(len(matrix)): for j in range(len(matrix[i])): if i == 0 and j == 0: numGraph.addEdge((i, j), (i + 1, j), matrix[i + 1][j]) numGraph.addEdge((i, j), (i, j + 1), matrix[i][j + 1]) elif i == 0 and j == len(matrix[i]) - 1: numGraph.addEdge((i, j), (i + 1, j), matrix[i + 1][j]) numGraph.addEdge((i, j), (i, j - 1), matrix[i][j - 1]) elif i == len(matrix) - 1 and j == 0: numGraph.addEdge((i, j), (i, j + 1), matrix[i][j + 1]) numGraph.addEdge((i, j), (i - 1, j), matrix[i - 1][j]) elif i == len(matrix) - 1 and j == len(matrix[i]) - 1: numGraph.addEdge((i, j), (i - 1, j), matrix[i - 1][j]) numGraph.addEdge((i, j), (i, j - 1), matrix[i][j - 1]) elif i == 0: numGraph.addEdge((i, j), (i + 1, j), matrix[i + 1][j]) numGraph.addEdge((i, j), (i, j + 1), matrix[i][j + 1]) numGraph.addEdge((i, j), (i, j - 1), matrix[i][j - 1]) elif i == len(matrix) - 1: numGraph.addEdge((i, j), (i, j + 1), matrix[i][j + 1]) numGraph.addEdge((i, j), (i - 1, j), matrix[i - 1][j]) numGraph.addEdge((i, j), (i, j - 1), matrix[i][j - 1]) elif j == 0: numGraph.addEdge((i, j), (i + 1, j), matrix[i + 1][j]) numGraph.addEdge((i, j), (i, j + 1), matrix[i][j + 1]) numGraph.addEdge((i, j), (i - 1, j), matrix[i - 1][j]) elif j == len(matrix[i]) - 1: numGraph.addEdge((i, j), (i + 1, j), matrix[i + 1][j]) numGraph.addEdge((i, j), (i - 1, j), matrix[i - 1][j]) numGraph.addEdge((i, j), (i, j - 1), matrix[i][j - 1]) else: numGraph.addEdge((i, j), (i + 1, j), matrix[i + 1][j]) numGraph.addEdge((i, j), (i, j + 1), matrix[i][j + 1]) numGraph.addEdge((i, j), (i - 1, j), matrix[i - 1][j]) numGraph.addEdge((i, j), (i, j - 1), matrix[i][j - 1]) endCoordinates = (len(matrix) - 1, len(matrix[0]) - 1) shortestPathMap = numGraph.aStarSearch((0, 0), endCoordinates) shortestPath = numGraph.outputPath(shortestPathMap, (0, 0), endCoordinates) print(sum([matrix[c[0]][c[1]] for c in shortestPath]))
[ 6738, 4823, 1330, 29681, 198, 198, 6759, 8609, 796, 17635, 198, 198, 4480, 1280, 10786, 79, 48290, 62, 6759, 8609, 13, 14116, 11537, 355, 2393, 25, 198, 220, 220, 220, 329, 1627, 287, 2393, 13, 961, 6615, 33529, 198, 220, 220, 220, ...
1.929464
1,361
from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, redirect, get_object_or_404 from designs import models as design_models from feet import models as foot_models from products import models as product_models from .models import Cart, CartItem # def add_cart(request, pk, design_pk): """ """ product = product_models.Product.objects.get(pk=pk) # try: cart = Cart.objects.get(session_key=_session_key(request)) # except Cart.DoesNotExist: if request.user.is_authenticated: cart = Cart.objects.create( session_key=_session_key(request), user_id=request.user.pk ) cart.save() else: cart = Cart.objects.create(session_key=_session_key(request)) cart.save() # try: cart_item = CartItem.objects.get(product=product, cart=cart, design=design_pk) # if ( cart_item.length_left != request.session["length_left"] or cart_item.length_right != request.session["length_right"] or cart_item.width_left != request.session["width_left"] or cart_item.width_right != request.session["width_right"] ): cart_item.length_left = request.session["length_left"] cart_item.length_right = request.session["length_right"] cart_item.width_left = request.session["width_left"] cart_item.width_right = request.session["width_right"] # else: cart_item.quantity += 1 cart_item.save() # except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, design=design_models.Design.objects.get(pk=design_pk), length_left=request.session["length_left"], length_right=request.session["length_right"], width_left=request.session["width_left"], width_right=request.session["width_right"], quantity=1, cart=cart, ) cart_item.save() return redirect("carts:cart") def cart_display(request, amount=0, counter=0, cart_items=None): """ """ # try: cart = Cart.objects.get(session_key=_session_key(request)) cart_items = CartItem.objects.filter(cart=cart) for cart_item in cart_items: amount += cart_item.product.price * cart_item.quantity counter += cart_item.quantity # except ObjectDoesNotExist: pass return render( request, "carts/cart.html", {"cart_items": cart_items, "amount": amount, "counter": counter}, ) def remove_item(request, pk, design_pk): """ """ # cart = Cart.objects.get(session_key=_session_key(request)) product = get_object_or_404(product_models.Product, pk=pk) cart_item = CartItem.objects.get(product=product, cart=cart, design=design_pk) # 1 if cart_item.quantity > 1: cart_item.quantity -= 1 cart_item.save() # 1 else: cart_item.delete() return redirect("carts:cart") def delete_cartitem(request, pk, design_pk): """ """ # cart = Cart.objects.get(session_key=_session_key(request)) product = get_object_or_404(product_models.Product, pk=pk) cart_item = CartItem.objects.get(product=product, cart=cart, design=design_pk) cart_item.delete() return redirect("carts:cart")
[ 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 9824, 1330, 4981, 355, 1486, 62, 2...
2.280263
1,520
""" Script to deploy a website to the server by ftp. - Compares local directory with remote directory - Updates modified files - Adds new files - Optionally, removes deleted files from remote Requires: python 3.3+ Due to use of ftplib.mlsd() The MIT License (MIT) Copyright (c) 2015 James Benson """ """ TODO: FTP response codes to look out for: - 502 unknown command - 550 empty directory - 451 can't remove directory Good ones: - 226 transfer complete """ asciiExt = ['coffee', 'css', 'erb', 'haml', 'handlebars', 'hb', 'htm', 'html', 'js', 'less', 'markdown', 'md', 'ms', 'mustache', 'php', 'rb', 'sass', 'scss', 'slim', 'txt', 'xhtml', 'xml']; deleteIgnoreFiles = ["/.ftpquota"]; deleteIgnoreDirs = ["/cgi-bin"]; remoteSep = "/"; dLogName = "debug.txt"; STOR_AUTO = 0; STOR_BINARY = 1; STOR_ASCII = 2; UPLOAD_OVERWRITE = 0; UPLOAD_MODIFIED = 1; ######################### SETUP ########################## remoteHost = "127.0.0.1"; remoteUser = "Benson"; remotePassword = "benson"; localPath = "D:\\test\\ftp"; remotePath = "/"; ### OPTIONS ### verbose = True; remoteTLS = False; # SSL/TLS doesn't work invalid certificate error remoteDelete = True; remoteIgnoreHidden = False; # TODO: Implement hidden. storMode = STOR_BINARY; # only binary currently works uploadMode = UPLOAD_MODIFIED; debug = True; ########################################################## import os; from datetime import datetime, timedelta; from ftplib import FTP, FTP_TLS, error_reply, error_temp, error_perm, error_proto, all_errors; if remoteTLS: import ssl; ftp = None; dLog = None; # === FTP Functions === def stor(dirpath, file): """Store the file obj to the dirpath of server.""" ext = (os.path.splitext(file.name())[1]).lstrip('.'); storpath = remoteJoin(dirpath, file.name()); try: if (storMode == STOR_ASCII) or (storMode == STOR_AUTO and ext in asciiExt): # Store in ASCII mode if verbose: print("[asc] ", end=""); ftp.storlines("STOR %s" % storpath, open(file.path)); else: # Store in binary mode if verbose: print("[bin] ", end=""); ftp.storbinary("STOR %s" % storpath, open(file.path, "rb")); setModified(dirpath, file); if verbose: print("Uploaded: %s -> %s" % (file.path, storpath)); except OSError as oserror: print("Failed Upload: %s\n %s" % (file.path, oserror)); def setModified(dirpath, file): """Attempts to set the modified time with MFMT.""" ftp.voidcmd("MFMT %s %s" % (file.getModified(), remoteJoin(dirpath, file.name()))); def rm(dirpath, file): """Delete the file at the path from the server.""" p = remoteJoin(dirpath, file.name()); _rm(p); if verbose: print("Deleted: %s" % p); def _rmDir(dirpath): """Delete directory with name from the current working directory. Only deletes empty directories.""" ftp.rmd(dirpath); # TODO: What if fails to delete? def _rmDirR(dirpath): """Remove the directory at dirpath and its contents (recursive).""" try: dirs, files = listRemote(dirpath); for f in files: _rm(f.path); for d in dirs: _rmDirR(d.path); _rmDir(d.path); except: raise error_temp("451 Can't remove directory"); # === End FTP Functions === # === Traversal Functions === # === End Traversal Functions === # === Structures === # === End Structures === def compareFiles(localList, remoteList, checkDeleted = True): """Compares localList with remoteList gets the tuple containing File objects: (new, modified, unmodified, deleted) new: Files that are in localList but not in remoteList. modified: Files that are newer in localList than remoteList. unmodified: Files that are the same in both lists. deleted: Files that are in the remoteList but not in localList. *newer is defined by the file's date modified attribute. New, Modified and Unmodified will contain local files objects that need to be uploaded to the remote location. Deleted will contain remote file objects that need to be deleted from the remote location.""" new = []; modified = []; unmodified = []; deleted = []; dprint("COMPARE FILES"); for lfile in localList: dprint("LOCAL: %s - %s" % (lfile.path, lfile.modified)); existsInRemote = False; for rfile in remoteList: if lfile == rfile: dprint("REMOTE: %s - %s" % (rfile.path, rfile.modified)); existsInRemote = True; if uploadMode == UPLOAD_OVERWRITE or lfile > rfile: dprint("Upload Mode: %s | Modified: lfile > rfile" % uploadMode); modified.append(lfile); else: dprint("Not Modified: lfile <= rfile"); unmodified.append(lfile); break; if not existsInRemote: dprint("New local file"); new.append(lfile); dprint("--------------------------------------"); # Check for deleted files if checkDeleted: dprint("CHECK FOR DELETED FILES"); for rfile in remoteList: existsInLocal = False; for lfile in localList: if rfile == lfile: existsInLocal = True; break; if not existsInLocal and not rfile.path in deleteIgnoreFiles: dprint("DELETED: %s" % rfile.path); deleted.append(rfile); dprint("--------------------------------------"); return (new, modified, unmodified, deleted); def compareDirs(localList, remoteList, checkDeleted = True): """Compares localList with remoteList gets the tuple containing string names of the directories: (new, existing, deleted) new: Directories that are in localList but not in remoteList. existing: Directories that are in both lists. deleted: Directories that are in the remoteList but not in localList. localList - list of strings of the directory names in the local location. remoteList - list of strings of the directory name in the remote location.""" new = []; existing = []; deleted = []; dprint("COMPARE DIRECTORIES"); for ldir in localList: dprint("LOCAL DIR: %s"%ldir.path); existsInRemote = False; for rdir in remoteList: if ldir == rdir: dprint("REMOTE DIR: %s"%rdir.path); dprint("Exists On Local and Remote"); existsInRemote = True; existing.append(ldir) break; if not existsInRemote: dprint("New Local Directory"); new.append(ldir); # Check for deleted directories if checkDeleted: dprint("CHECK FOR DELETED DIRECTORIES"); for rdir in remoteList: existsInLocal = False; for ldir in localList: if rdir == ldir: existsInLocal = True; break; if not existsInLocal and not rdir.path in deleteIgnoreDirs: dprint("DELETED: %s" % rdir.path); deleted.append(rdir); dprint("--------------------------------------"); return (new, existing, deleted); def dprint(line, end="\n"): global dLog; if debug: if dLog == None: if os.path.exists(dLogName): os.remove(dLogName); dLog = open(dLogName, "w") dLog.write(line + end); if __name__ == "__main__": main();
[ 37811, 198, 220, 220, 220, 12327, 284, 6061, 257, 3052, 284, 262, 4382, 416, 10117, 79, 13, 628, 220, 220, 220, 220, 220, 220, 220, 532, 3082, 3565, 1957, 8619, 351, 6569, 8619, 198, 220, 220, 220, 220, 220, 220, 220, 532, 28090, ...
2.399564
3,211
""" Author : Robin Singh Programs List: 1.Queue 2.Circular Queue 3.Double Ended Queue """ import inspect
[ 37811, 198, 13838, 1058, 12325, 14403, 198, 15167, 82, 7343, 25, 198, 16, 13, 34991, 220, 198, 17, 13, 31560, 934, 4670, 518, 198, 18, 13, 25628, 47624, 4670, 518, 198, 37811, 198, 198, 11748, 10104, 628, 628 ]
2.894737
38
from wataru.commands.models.base import CommandBase from wataru.logging import getLogger import wataru.rules.models as rmodels import os import sys logger = getLogger(__name__)
[ 6738, 4383, 11493, 13, 9503, 1746, 13, 27530, 13, 8692, 1330, 9455, 14881, 198, 6738, 4383, 11493, 13, 6404, 2667, 1330, 651, 11187, 1362, 198, 11748, 4383, 11493, 13, 38785, 13, 27530, 355, 374, 27530, 198, 198, 11748, 28686, 198, 1174...
3.214286
56
# A Sensation which creates a Polyline of 35 points of the finger joints, along which a Circle Path is animated. from pysensationcore import * import sensation_helpers as sh import HandOperations # We will use the joint positions of the fingers to animate a Circle along a PolylinePath fingers = ["thumb", "indexFinger", "middleFinger", "ringFinger", "pinkyFinger"] bones = ["metacarpal", "proximal", "intermediate", "distal", "intermediate","proximal","metacarpal"] jointKeyFrames = [] # Create a Polyline Path for each Animation Step animPath = createInstance("PolylinePath", "PolylinePathInstance") # Create inputs for each of the Bone joints for finger in fingers: for bone in bones: jointInputName = "%s_%s_position" % (finger, bone) jointKeyFrames+=[jointInputName] # The number of Key frames numPoints = len(jointKeyFrames) points = sh.createList(numPoints) # Connect the points list for our Polylinepath to the animation path connect(points["output"], animPath.points) translateAlongPath = createInstance("TranslateAlongPath", "translateAlongPath") connect(Constant((1,0,0)), translateAlongPath.direction) connect(animPath.out, translateAlongPath.animationPath) # The Object Path (a circle) Will trace along the animation Path # On top of its translation along the path, we apply a rotation transform, # to match the orientation of the Palm circlePath = createInstance("CirclePath", "objectPath") orientToPalmInstance = createInstance("OrientPathToPalm", "orientToPalm") # Object Path -> OrientPathToPalm -> TranslateAlongPath connect(circlePath.out, orientToPalmInstance.path) connect(orientToPalmInstance.out, translateAlongPath.objectPath) topLevelInputs = {} for n in range(0,numPoints): topLevelInputs[(jointKeyFrames[n], points["inputs"][n])] = (0,0,0) topLevelInputs[("t", translateAlongPath.t)] = (0, 0, 0) topLevelInputs[("duration", translateAlongPath.duration)] = (2.5,0,0) topLevelInputs[("dotSize", circlePath.radius)] = (0.01, 0, 0) topLevelInputs[("palm_direction", orientToPalmInstance.palm_direction)] = (0, 0, 0) topLevelInputs[("palm_normal", orientToPalmInstance.palm_normal)] = (0, 0, 0) fingerScan = sh.createSensationFromPath("Finger Trace", topLevelInputs, output = translateAlongPath.out, drawFrequency = 120, renderMode=sh.RenderMode.Loop, definedInVirtualSpace = True ) # Hide the non-vital inputs... visibleInputs = ("duration", "dotSize") for topLevelInput in topLevelInputs.keys(): inputName = topLevelInput[0] if inputName not in visibleInputs: setMetaData(getattr(fingerScan, inputName), "Input-Visibility", False) setMetaData(fingerScan.duration, "Type", "Scalar") setMetaData(fingerScan.dotSize, "Type", "Scalar")
[ 2, 317, 14173, 341, 543, 8075, 257, 12280, 1370, 286, 3439, 2173, 286, 262, 7660, 24039, 11, 1863, 543, 257, 16291, 10644, 318, 15108, 13, 198, 6738, 279, 893, 25742, 7295, 1330, 1635, 198, 11748, 18098, 62, 16794, 364, 355, 427, 198,...
2.756859
1,057
"""Extract inception_v3_feats from videos for Youtube-8M feature extractor.""" import os import torch import init_path import misc.config as cfg from misc.utils import (concat_feat_var, get_dataloader, make_cuda, make_variable) from models import inception_v3 if __name__ == '__main__': # init models and data loader model = make_cuda(inception_v3(pretrained=True, transform_input=True, extract_feat=True)) model.eval() # get vid list video_list = os.listdir(cfg.video_root) video_list = [v for v in video_list if os.path.splitext(v)[1] in cfg.video_ext] # extract features by inception_v3 for idx, video_file in enumerate(video_list): vid = os.path.splitext(video_file)[0] filepath = os.path.join(cfg.video_root, video_file) if os.path.exists(cfg.inception_v3_feats_path.format(vid)): print("skip {}".format(vid)) else: print("processing {}".format(vid)) # data loader for frames in single video data_loader = get_dataloader(dataset="VideoFrame", path=filepath, num_frames=cfg.num_frames, batch_size=cfg.batch_size) # extract features by inception_v3 feats = None for step, frames in enumerate(data_loader): print("--> extract features [{}/{}]".format(step + 1, len(data_loader))) feat = model(make_variable(frames)) feats = concat_feat_var(feats, feat.data.cpu()) print("--> save feats to {}" .format(cfg.inception_v3_feats_path.format(vid))) torch.save(feats, cfg.inception_v3_feats_path.format(vid)) # print("--> delete original video file: {}".format(filepath)) # os.remove(filepath)
[ 37811, 11627, 974, 30839, 62, 85, 18, 62, 5036, 1381, 422, 5861, 329, 27431, 12, 23, 44, 3895, 7925, 273, 526, 15931, 198, 198, 11748, 28686, 198, 198, 11748, 28034, 198, 198, 11748, 2315, 62, 6978, 198, 11748, 12747, 13, 11250, 355, ...
1.947818
1,054
from collections import deque from ..utils.collections import DictLike from ..matcher.core import ReteNet from ..matcher.actions import make_node_token, make_edge_token, make_attr_token from .sampler import NextReactionMethod
[ 6738, 17268, 1330, 390, 4188, 220, 198, 6738, 11485, 26791, 13, 4033, 26448, 1330, 360, 713, 7594, 198, 6738, 11485, 6759, 2044, 13, 7295, 1330, 4990, 68, 7934, 198, 6738, 11485, 6759, 2044, 13, 4658, 1330, 787, 62, 17440, 62, 30001, ...
3.5
66
### performing function similar to --snapcheck option in command line ###### from jnpr.jsnapy import SnapAdmin from pprint import pprint from jnpr.junos import Device js = SnapAdmin() config_file = "/etc/jsnapy/testfiles/config_single_snapcheck.yml" snapvalue = js.snapcheck(config_file, "snap") for snapcheck in snapvalue: print "\n -----------snapcheck----------" print "Tested on", snapcheck.device print "Final result: ", snapcheck.result print "Total passed: ", snapcheck.no_passed print "Total failed:", snapcheck.no_failed pprint(dict(snapcheck.test_details))
[ 21017, 9489, 2163, 2092, 284, 1377, 45380, 9122, 3038, 287, 3141, 1627, 46424, 2, 198, 6738, 474, 77, 1050, 13, 8457, 77, 12826, 1330, 16026, 46787, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 474, 77, 1050, 13, 29741, 418, 1330...
3.09375
192
from typing import * if __name__ == "__main__": so = Solution() print(so.numberOfSteps(123))
[ 6738, 19720, 1330, 1635, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 523, 796, 28186, 3419, 198, 220, 220, 220, 3601, 7, 568, 13, 17618, 5189, 8600, 82, 7, 10163, 4008 ]
2.575
40
import Tkinter as tk from PIL import Image, ImageTk import aggdraw window = tk.Tk() label = tk.Label(window) label.pack() # schedule changing images import itertools, random, time # Begin # img = aggdraw.Draw("RGBA", (1000,600), random_n(0,222,n=3) ) import geovis sf = geovis.shapefile_fork.Reader("D:/Test Data/cshapes/cshapes.shp") for shape in sf.iterShapes(): if shape.__geo_interface__["type"] == "Polygon": flatcoords = [xory+350 for xy in shape.__geo_interface__["coordinates"][0] for xory in xy] draw_polygon(img, flatcoords) update(img) window.mainloop()
[ 198, 11748, 309, 74, 3849, 355, 256, 74, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 51, 74, 198, 11748, 4194, 19334, 198, 198, 17497, 796, 256, 74, 13, 51, 74, 3419, 198, 18242, 796, 256, 74, 13, 33986, 7, 17497, 8, 198, 18242, ...
2.465021
243
from utils import utils if __name__ == "__main__": day = 10 data = utils.get_ints_from_file(f"data/aoc{day}_data.txt") data = sorted(data) data = [0] + data + [data[-1]+3] print(f"Part 1 solution: {part_1(data)}") print(f"Part 2 solution: {part_2(data)}")
[ 6738, 3384, 4487, 1330, 3384, 4487, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1110, 796, 838, 198, 220, 220, 220, 1366, 796, 3384, 4487, 13, 1136, 62, 29503, 62, 6738, 62, 7753, 7, 69, ...
2.222222
126
""" @author: Alexander Studier-Fischer, Jan Odenthal, Berkin Oezdemir, Isabella Camplisson, University of Heidelberg """ from HyperGuiModules import * import logging import os #logging.basicConfig(level=logging.DEBUG) xSize=None ySize=None if __name__ == '__main__': main()
[ 37811, 198, 31, 9800, 25, 10009, 3604, 959, 12, 37, 24645, 11, 2365, 10529, 34728, 11, 4312, 5116, 440, 8471, 9536, 343, 11, 1148, 43653, 7298, 489, 30927, 11, 2059, 286, 679, 5943, 3900, 198, 37811, 198, 198, 6738, 15079, 8205, 72, ...
2.813725
102
# Free the prisoner, defeat the guard and grab the gem. hero.moveRight() # Free Patrick from behind the "Weak Door". hero.attack("Weak Door") hero.moveRight(2) # Defeat the guard, named "Two". # Get the gem. hero.moveRight() hero.moveDown(3)
[ 2, 3232, 262, 17234, 11, 7433, 262, 4860, 290, 5552, 262, 16840, 13, 198, 11718, 13, 21084, 11028, 3419, 198, 2, 3232, 9925, 422, 2157, 262, 366, 44898, 19821, 1911, 198, 11718, 13, 20358, 7203, 44898, 19821, 4943, 198, 11718, 13, 210...
3.171053
76
# -*- coding: utf-8 -*- # import libraries import os from PIL import Image import nltk import numpy as np import matplotlib.pyplot as plt import random from scipy.ndimage import gaussian_gradient_magnitude from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS # import mask image. Search for stencil image for better results mask = np.array(Image.open("darthvader01.png")) # define function for grayscale coloring # Load and text and decode text = open(('conti_just_body.txt'), "rb").read().decode('UTF-8', errors='replace') # Load stopwords for EN language from nlkt stopwords = nltk.corpus.stopwords.words('english') # Create Worldcloud wc = WordCloud(max_words=100000, width=1596, height=584, stopwords=stopwords, mask=mask).generate(text) # Recolor our Wordcloud plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3), interpolation="bilinear") # Save worldcloud file wc.to_file("CONTI_Darth.png")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 1330, 12782, 220, 198, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 11748, 299, 2528, 74, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603,...
2.86747
332
# -*- coding: utf-8 -*- """ Created on Thu Oct 26 08:19:16 2017 @author: 0 """ from scipy.misc import imresize from scipy.signal import convolve,convolve2d import scipy from PIL import Image import cv2 import numpy as np img = cv2.imread("C://Users/0/Downloads/basketball1.png",0) img2 = cv2.imread("C://Users/0/Downloads/basketball2.png",0) #cv2.imshow('img',img) #cv2.imshow('img2',img2) k=(3,3) print img img = cv2.GaussianBlur(img, k, 1.5) img2 = cv2.GaussianBlur(img2, k, 1.5) cv2.imshow('img3',img) #cv2.waitKey(10000) cv2.destroyAllWindows() imga=np.matrix(img) imga2=np.matrix(img2) #print imga #img=Image.fromarray(imga) #img.show() height,width = imga.shape #for x in range img(x,0): print imga.shape print height ,width # print x #for y in height: # for x in width: # print '0' #for y in range(height): print imga #imga[0,1]=imga[0,1]+1 #print imga print fx(1,0),fy(0,4) imga=imresize(imga,(240,320)) imga2=imresize(imga2,(240,320)) print imga,imga.shape,imga2,imga2.shape u=np.zeros([240,320]) v=np.zeros([240,320]) w2=30 w=15 #for i in range(w2): # for y in range(w2): # # # print matrix #matrix=np.zeros([w2,w2]) # #for x in range(w,240-w): # # for y in range(w,320-w): # c=0 ## matrix[w,w]=x # print x,y #print matrix #def conv2(x, y, mode='same'): # return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 2) #print convolve2d(imga2,matrix,'valid') ''' ft = scipy.signal.convolve2d(imga, 0.25 * np.ones((2,2))) + \ scipy.signal.convolve2d(imga2, -0.25 * np.ones((2,2))) #print ft fx,fy=np.gradient(cv2.GaussianBlur(img, k, 1.5)) fx = fx[0:478, 0:638] fy = fy[0:478, 0:638] ft = ft[0:478, 0:638] #print fx,fy,ft ''' ''' for i in range(w+1,480-w): for j in range(w+1,640-w): Ix = fx[i-w:i+w, j-w:j+w] Iy = fy[i-w:i+w, j-w:j+w] It = ft[i-w:i+w, j-w:j+w] A = [Ix,Iy] print fx,fy,ft ''' #C=A.T*-It #print C #print curFx,curFy,curFt,U[0],U[1]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 2556, 2608, 8487, 25, 1129, 25, 1433, 2177, 198, 198, 31, 9800, 25, 657, 198, 37811, 198, 6738, 629, 541, 88, 13, 44374, 1330, 545, 411,...
1.872624
1,052
#!usr/bin/env python3 #import dependecies import sqlite3 import csv #connect to test_data conn = sqlite3.connect('test_data.db') #create a cursor c = conn.cursor() c.execute("DROP TABLE test_data") #create a test_data table c.execute("""CREATE TABLE test_data(age integer, sex text, bmi real, children integer, smoker text, region text)""") #get test_data file get_file = open('test_data.csv') #read test_data file read_file = csv.reader(get_file) c.executemany("INSERT INTO test_data VALUES (?, ?, ?, ?, ?, ?,?)", read_file) conn.commit() conn.close()
[ 2, 0, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 11748, 4745, 721, 444, 198, 11748, 44161, 578, 18, 198, 11748, 269, 21370, 198, 198, 2, 8443, 284, 1332, 62, 7890, 198, 37043, 796, 44161, 578, 18, 13, 8443, 10786, 9288, 6...
1.914948
388
from swift_cloud_py.entities.control_output.fixed_time_schedule import FixedTimeSchedule from swift_cloud_py.entities.intersection.intersection import Intersection from swift_cloud_py.validate_safety_restrictions.validate_bounds import validate_bounds from swift_cloud_py.validate_safety_restrictions.validate_completeness import validate_completeness from swift_cloud_py.validate_safety_restrictions.validate_conflicts import validate_conflicts from swift_cloud_py.validate_safety_restrictions.validate_fixed_orders import validate_fixed_orders from swift_cloud_py.validate_safety_restrictions.validate_other_sg_relations import validate_other_sg_relations def validate_safety_restrictions(intersection: Intersection, fixed_time_schedule: FixedTimeSchedule, tolerance: float = 10**(-2)) -> None: """ Check if the fixed-time schedule satisfies the safety restrictions such as bounds on greenyellow times and bounds on red times. :param intersection: intersection object (this object also contains safety restrictions that a fixed-time schedule should satisfy) :param fixed_time_schedule: the schedule that we would like to validate :param tolerance: tolerance in seconds for violating safety restrictions This method raises a SafetyViolation-exception if the safety restrictions are not satisfied. """ validate_bounds(intersection=intersection, fts=fixed_time_schedule, tolerance=tolerance) validate_conflicts(intersection=intersection, fts=fixed_time_schedule, tolerance=tolerance) validate_other_sg_relations(intersection=intersection, fts=fixed_time_schedule, tolerance=tolerance) validate_completeness(intersection=intersection, fts=fixed_time_schedule) validate_fixed_orders(intersection=intersection, fts=fixed_time_schedule)
[ 6738, 14622, 62, 17721, 62, 9078, 13, 298, 871, 13, 13716, 62, 22915, 13, 34021, 62, 2435, 62, 15952, 5950, 1330, 10832, 7575, 27054, 5950, 198, 6738, 14622, 62, 17721, 62, 9078, 13, 298, 871, 13, 3849, 5458, 13, 3849, 5458, 1330, 4...
3.384045
539
from timingsignal import TimingSignal from brick_characterizer.CharBase import CharBase
[ 6738, 4628, 654, 570, 282, 1330, 5045, 278, 11712, 282, 198, 6738, 17214, 62, 22769, 7509, 13, 12441, 14881, 1330, 3178, 14881, 628 ]
3.869565
23
from .str2num import str2num __all__ = [ 'str2num' ]
[ 6738, 764, 2536, 17, 22510, 1330, 965, 17, 22510, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 2536, 17, 22510, 6, 198, 60, 198 ]
2.071429
28
import sys # First: to understand the uses of "format" below, read these: # Format String Syntax https://docs.python.org/2/library/string.html#formatstrings # Format Specification Mini-Language https://docs.python.org/2/library/string.html#formatspec # In Python 2, there are two integer types: int, long. # int is the underlying platform's signed integer type, # either 32 or 64 bit, depending on the platform. print "2^31 - 1 = {0:20} = {0:17x} ".format((1 << 31) - 1) print "2^63 - 1 = {0:20} = {0:17x} ".format((1 << 63) - 1) # sys.maxint gives the maximum value of int. It is 2^31-1 or 2^63-1. maxint = sys.maxint print " max int = {0:20} = {0:17x} {1}".format(maxint, type(maxint)) # There is no sys.minint, but it's simply -sys.maxint-1 as said in Python documentation # http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex minint = -maxint - 1 print " min int = {0:20} = {0:17x} {1}".format(minint, type(minint)) print # long is an integer type with unlimited range. Python automatically # switches over from int to long whenever there is overflow. # That's why, there is no sys.maxlong. # Python 3 even gets rid of sys.maxint, because it has just single # integer type: int. It actually behaves like 2's long i.e. has unlimited range. # 3 has sys.maxsize, which loosely relates to 2's sys.maxint. # http://docs.python.org/3.3/whatsnew/3.0.html#integers # http://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex # Let's test the automatic switchover from int to long # On 64-bit platform, the switchover point is between 2^63-1 and 2^63. for r in [ range(1, 22), range(28, 37), range(53, 69), range(88, 100), range(123, 131) ]: for i in r: # make 2^i - 1, without spilling beyond i bits. n = (((1 << (i-1)) - 1) << 1) + 1 # i is formatted as left-aligned ('<'), width 3. # n is formatted as hex ('x') with 0x prefix ('#'), width 35. print "2**{0:<3} - 1 = {1:#35x} {2}".format(i, n, type(n)) print " + 1 = {1:#35x} {2}".format(i, n+1, type(n+1)) print "..." print print -1 print -1 & 0xFF print -1 & 0xFFF
[ 11748, 25064, 198, 198, 2, 3274, 25, 284, 1833, 262, 3544, 286, 366, 18982, 1, 2174, 11, 1100, 777, 25, 198, 2, 220, 220, 18980, 10903, 26375, 897, 3740, 1378, 31628, 13, 29412, 13, 2398, 14, 17, 14, 32016, 14, 8841, 13, 6494, 2, ...
2.618357
828
import os from sendDetailedEmail.email import MailAttachment if __name__=="__main__": clientEmail = input("input a valid client email ID: ") sendMail(clientEmail)
[ 11748, 28686, 198, 6738, 3758, 32080, 15333, 13, 12888, 1330, 11099, 8086, 15520, 198, 198, 361, 11593, 3672, 834, 855, 1, 834, 12417, 834, 1298, 198, 220, 220, 220, 5456, 15333, 796, 5128, 7203, 15414, 257, 4938, 5456, 3053, 4522, 25, ...
3.185185
54
from contextlib import contextmanager import pathlib import sys from typing import Union, List from .import_hook import PyFinder, PyHTTPFinder # Singleton instance of PyFinder pyfinder: PyFinder = None def _update_syspath(path: str): """ Append `path` to sys.path so that files in path can be imported """ path = pathlib.Path(path).resolve().as_posix() if path not in sys.path: sys.path.append(path) def register_hook( base_url: Union[str, List[str]], download_path: str = "", modules: List[str] = None, update_syspath: bool = True, ): """ Register import hook to sys.meta_path. Args: base_url (str or List[str]): URL(s) where the directory containing Python packages is served through HTTP/S download_path (str): the path in virtual file system where Python packages will be downloaded, default is current working directory modules (List[str]): a list, with the names of the root modules/packages that can be imported from the given URL update_syspath (bool): whether to add ``download_path`` to `sys.path` **Notes on** ``module`` **parameter**: If this parameter is not specified, import statement will try to search a module everytime when the module is not found in local filesystem. This means every FAILED import statement will result in multiple 404 HTTP errors. So when you have fixed modules, using modules parameter to whitelist downloadable modules in recommended. """ global pyfinder if pyfinder is not None and pyfinder._registered(): raise RuntimeError( "import hook is already registered, if you want to register a new hook, unregister the existing hook with unregister_hook() first" ) pyfinder = PyHTTPFinder(base_url, download_path, modules) pyfinder.register() if update_syspath: _update_syspath(download_path) return pyfinder def unregister_hook(): """ Unregister import hook from sys.meta_path. After calling this method, new external modules cannot be downloaded and imported, while previously imported modules can be keep available. """ global pyfinder if pyfinder is not None: pyfinder.unregister() pyfinder = None def add_module(module: Union[str, List[str]]): """ Add new module(s) that can be imported from URL. Args: module (str or List[str]): modules/packages that can be imported from the URL """ global pyfinder if pyfinder is None or (not pyfinder._registered()): raise RuntimeError("import hook is not registered") pyfinder.add_module(module) def available_modules(): """ Get the list of modules that can be imported from the URL. """ global pyfinder if pyfinder is None or (not pyfinder._registered()): raise RuntimeError("import hook is not registered") return pyfinder.available_modules()
[ 6738, 4732, 8019, 1330, 4732, 37153, 198, 11748, 3108, 8019, 198, 11748, 25064, 198, 6738, 19720, 1330, 4479, 11, 7343, 198, 6738, 764, 11748, 62, 25480, 1330, 9485, 37, 5540, 11, 9485, 40717, 37, 5540, 198, 198, 2, 5573, 10565, 4554, ...
3.100423
946
#!/usr/bin/env python3 import uuid import click from rastervision.rv_config import RVConfig if __name__ == '__main__': batch_submit()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 334, 27112, 198, 198, 11748, 3904, 198, 198, 6738, 374, 1603, 10178, 13, 81, 85, 62, 11250, 1330, 31367, 16934, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, ...
2.685185
54
from fastapi import APIRouter from models.item_model import Payload from service import item_service router = APIRouter()
[ 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 198, 198, 6738, 4981, 13, 9186, 62, 19849, 1330, 7119, 2220, 198, 6738, 2139, 1330, 2378, 62, 15271, 198, 198, 472, 353, 796, 3486, 4663, 39605, 3419, 198 ]
3.472222
36
""" Docker Configurator http://www.github.com/EnigmaCurry/docker-configurator This tool creates self-configuring docker containers given a single YAML file. Run this script before your main docker CMD. It will write fresh config files on every startup of the container, based off of Mako templates embedded in the docker image, as well as values specified in a YAML file provided in a mounted volume. The idea of this is that container configuration is kind of hard because everyone does it differently. This creates a standard way of doing it for containers that I write. A single file to configure everything. See the included example project: `docker_configurator_example` --------------------------------------------------------------------------- Copyright (c) 2019 PlenusPyramis Copyright (c) 2015 Ryan McGuire Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import yaml from mako.template import Template from mako.lookup import TemplateLookup from mako import exceptions as mako_exceptions import logging import argparse import os import shutil import collections logging.basicConfig(level=logging.INFO) logger=logging.getLogger("docker_configurator") __version__ = "v0.9.0" def deep_merge(*dicts): """ Non-destructive deep-merge of multiple dictionary-like objects >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1', 'recipe':['one','two'] } } } >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5', 'recipe':['three'] } } } >>> c = deep_merge(a, b) >>> a == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1', 'recipe':['one','two'] } } } True >>> b == { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5', 'recipe':['three'] } } } True >>> c == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5', 'recipe':['three'] } } } True >>> c == deep_merge(a, b, c) True """ # Wrap the merge function so that it is no longer destructive of its destination: final = {} for d in dicts: merge(d, final) return final if __name__ == "__main__": main()
[ 37811, 198, 35, 12721, 17056, 333, 1352, 198, 4023, 1378, 2503, 13, 12567, 13, 785, 14, 4834, 13495, 34, 16682, 14, 45986, 12, 11250, 333, 1352, 628, 198, 1212, 2891, 8075, 2116, 12, 11250, 870, 36253, 16472, 1813, 257, 2060, 198, 56,...
3.255252
952
from datetime import date import boundaries boundaries.register('federal-electoral-districts', # The slug of the boundary set # The name of the boundary set for display. name='Federal electoral districts', # Generic singular name for a boundary from this set. Optional if the # boundary set's name ends in "s". singular='Federal electoral district', # If this were omitted, the same value would be generated # Geographic extents which the boundary set encompasses domain='Canada', # Path to the shapefile directory. Relative to the current file, so if this file # is in the same directory as the shapefile -- usually the case -- you can omit # this parameter. file='', # Last time the source was updated or checked for new data last_updated=date(1970, 1, 1), # A function that's passed the feature and should return a name string # The boundaries model provides some simple function factories for this. name_func=boundaries.clean_attr('FEDENAME'), # Function to extract a feature's "external_id" property id_func=boundaries.attr('FEDUID'), # Function to provide the slug (URL component) of the boundary # If not provided, uses the name to generate the slug; this is usually # what you want. #slug_func=boundaries.attr('FEDUID'), # Function that returns true/false to determine whether a given feature should be included # By default, all features are included. #is_valid_func=lambda f: True, # Authority that is responsible for the accuracy of this data authority='H.R.M. Queen Elizabeth II', # A URL to the source of this data source_url='http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/bound-limit-eng.cfm', # A URL to the license for this data licence_url='http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/license-eng.cfm?lang=_e&year=11&type=fed000a&format=a', # A URL to the data file, e.g. a ZIP archive data_url='http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/files-fichiers/gfed000a11a_e.zip', # Notes identifying any pecularities about the data, such as columns that # were deleted or files which were merged notes='', # Encoding of the text fields in the shapefile, e.g. 'utf-8'. Default: 'ascii' encoding='iso-8859-1', # Used only by the represent-maps app -- if you're not using that, ignore label_point_func. # A function from a feature object to a Point where to display a label for feature on a map. #label_point_func = lambda feature: None, )
[ 6738, 4818, 8079, 1330, 3128, 198, 198, 11748, 13215, 198, 198, 7784, 3166, 13, 30238, 10786, 69, 2110, 12, 9509, 6864, 12, 17080, 2012, 82, 3256, 1303, 383, 31065, 286, 262, 18645, 900, 198, 220, 220, 220, 1303, 383, 1438, 286, 262, ...
3.165441
816
# # from .subscriber import Subscriber from .logger import Logger from .constants import Constants from .events import Events # import json
[ 2, 198, 2, 198, 6738, 764, 7266, 1416, 24735, 1330, 3834, 1416, 24735, 198, 6738, 764, 6404, 1362, 1330, 5972, 1362, 198, 6738, 764, 9979, 1187, 1330, 4757, 1187, 198, 6738, 764, 31534, 1330, 18715, 198, 198, 2, 198, 11748, 33918, 198...
3.357143
42
''' Authentication methods for cs166 final project. ''' import random, hashlib from .db import retrieve_accounts lower_case = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] upper_case = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] special = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '?', '[', ']', '{', '}', ':', ';', '"', '/', '.', ',', '<', '>'] def authenticate(username, password): ''' Authenticates user upon login ''' # retrieves users from database users = retrieve_accounts() stored_username = '' stored_password = '' # finds user in records for user in users: if user[0] == username: stored_username = user[0] stored_password = user[1] # if user is not found, false if (stored_username == '' or stored_password == ''): return False # retrieves salt and stored password from pw string salt_length = 40 salt = stored_password[:salt_length] stored_hash = stored_password[salt_length:] # compares inputted password with hash and returns result hashable = salt + password hashable = hashable.encode('utf-8') this_hash = hashlib.sha1(hashable).hexdigest() return this_hash == stored_hash def verify_new_account(username, password): ''' Method used to determine if new account credentials are valid Parameters: username (str) : username entered by user password (str) : password entered by user Returns: status (bool) : status of if the new credentials are good or not ''' global lower_case, upper_case, nums, special # retrieves all users from db and makes a list of all usernames users = retrieve_accounts() taken_usernames = [] for accounts in users: taken_usernames.append(accounts[0]) # status of whether or not password contains the requirements requirement_one = len(password) >= 8 requirement_two = len(password) <= 25 requirement_three = username not in taken_usernames requirement_lower = False requierment_upper = False requirement_nums = False requirement_special = False for char in password: if char in lower_case: requirement_lower = True if char in upper_case: requierment_upper = True if char in nums: requirement_nums = True if char in special: requirement_special = True # SQL injection prevention for char in username: if char in special: return False status = False if (requirement_one and requirement_two and requirement_three and requirement_lower and requierment_upper and requirement_nums and requirement_special): status = True return status def random_password(): ''' Function to return randomly generated password Returns: password (str) : randomly generated password ''' global lower_case, upper_case, nums, special chars = [lower_case, upper_case, nums, special] password_length = random.randint(12, 16) password = '' for i in range(password_length): lib = chars[random.randint(0, 3)] char = lib[random.randint(0, len(lib) - 1)] password += char return password
[ 7061, 6, 628, 220, 220, 220, 48191, 5050, 329, 50115, 23055, 2457, 1628, 13, 198, 198, 7061, 6, 198, 198, 11748, 4738, 11, 12234, 8019, 198, 6738, 764, 9945, 1330, 19818, 62, 23317, 82, 198, 198, 21037, 62, 7442, 796, 37250, 64, 325...
2.515901
1,415
# coding: utf-8 """ @author: csy @license: (C) Copyright 2017-2018 @contact: wyzycao@gmail.com @time: 2018/11/22 @desc: """ import unittest from orm.data_base import Database
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 198, 31, 9800, 25, 269, 1837, 198, 31, 43085, 25, 357, 34, 8, 15069, 2177, 12, 7908, 198, 31, 32057, 25, 266, 88, 7357, 66, 5488, 31, 14816, 13, 785, 198, 31, 2435, 25, 2864, 14, 115...
2.492958
71
import distutils from setuptools import setup try: from kervi.platforms.windows.version import VERSION except: VERSION = "0.0" try: distutils.dir_util.remove_tree("dist") except: pass setup( name='kervi-hal-win', version=VERSION, packages=[ "kervi/platforms/windows", ], install_requires=[ 'psutil', 'inputs' ], )
[ 11748, 1233, 26791, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 479, 712, 72, 13, 24254, 82, 13, 28457, 13, 9641, 1330, 44156, 2849, 198, 16341, 25, 198, 220, 220, 220, 44156, 2849, 796, 3...
2.22807
171
import argparse import materia as mtr import dask.distributed if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--qcenv", type=str) parser.add_argument("--scratch", type=str) parser.add_argument("--dask_scratch", type=str) parser.add_argument("--num_evals", type=int) args = parser.parse_args() m = mtr.Molecule("benzene") qchem = mtr.QChem(qcenv=args.qcenv, scratch_dir=args.scratch) io = mtr.IO("gs.in", "gs.out", "minimize_koopman_error") min_ke = qchem.minimize_koopman_error(io, name="min_ke") min_ke.requires(molecule=m, num_evals=args.num_evals) wf = mtr.Workflow(min_ke) cluster = dask.distributed.LocalCluster() with dask.config.set(temporary_directory=args.dask_scratch): with dask.distributed.Client(cluster) as client: print(wf.compute()["min_ke"])
[ 11748, 1822, 29572, 198, 11748, 26910, 544, 355, 285, 2213, 198, 11748, 288, 2093, 13, 17080, 6169, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677, ...
2.338667
375
# -*- coding: utf-8 -*- """Top-level package for simple.""" __author__ = """John Bridstrup""" __email__ = 'john.bridstrup@gmail.com' __version__ = '0.1.8' # import Data # import data_analysis # import kernels # import KMC # import running # import simple # import simulations # import statevector
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 9126, 12, 5715, 5301, 329, 2829, 526, 15931, 198, 198, 834, 9800, 834, 796, 37227, 7554, 28320, 301, 12618, 37811, 198, 834, 12888, 834, 796, 705, 30686, 13,...
2.941176
102
# from traceback import TracebackException from django.contrib.auth.forms import UserCreationForm # from django.contrib.auth.models import User from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.postgres.search import SearchVector from django.core import serializers from django.http import JsonResponse from django.views import View # import os # from django.contrib.sites.shortcuts import get_current_site # from django.utils.encoding import force_bytes # from django.utils.encoding import force_text # from django.utils.http import urlsafe_base64_encode # from django.utils.http import urlsafe_base64_decode # from django.template.loader import render_to_string from django.http import HttpResponse import django_filters.rest_framework from django.shortcuts import render, redirect from .forms import ProfilePhotoForm, PhotoForm, SignUpForm, ProfileForm, ItemForm, SearchForm from .models import User, Profile, Item, Category, Item_Image, Favorite_item from ebazar import settings from .serializers import ( CategorySerializer, ItemSerializer, UserSerializer, Item_ImageSerializer,) from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets, status # import django_filters.rest_framework from rest_framework.generics import ( DestroyAPIView, ListAPIView, UpdateAPIView, RetrieveAPIView, CreateAPIView ) from rest_framework.views import APIView import shutil import os import datetime import json # print console logs log_prefix = '['+datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S")+']' log_end = '********' log_date = datetime.datetime.now().strftime("%d-%m-%y_%H:%M") # redirect to create user (url(r'^$')) # create user with min information def show_item(request, item_id): user = request.user exist = 1 # if user and request.method == "GET": # favs = Favorite_item.objects.filter(user=user) # # for fav in favs: # if fav.item_id == int(item_id): # print(fav.item_id) # exist = 1 # else: # exist = 0 item = Item.objects.filter(id=item_id)[0] item_images = Item_Image.objects.filter() return render(request, 'emarket/item_detail.html', {'item': item, 'pics': item_images, 'exist': exist}) # @login_required # def add_to_fav(request): # return redirect('home') def show_category(request, cat_id): cat = Category.objects.get(id=cat_id) items = Item.objects.filter(category=cat) pics = Item_Image.objects.all() if items: paginator = Paginator(items, 9) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) return render(request, 'emarket/show_category.html', {'cat':cat, 'items':items, 'pics':pics}) def home(request): cats = Category.objects.all() # item_pic = {} items = Item.objects.order_by('-price')[0:9] item_images = Item_Image.objects.filter() # print(item_images) # print(items) # print(categories) return render(request, 'emarket/home.html', {'cats': cats, 'items': items, 'pics': item_images, }) def search(request, search_word=None): message = 'hli golar:' pics = Item_Image.objects.all() items = Item.objects.all() form = SearchForm if request.method == 'POST': form = SearchForm(request.POST) search_word = request.POST.get('search') location = request.POST.get('location') user = request.POST.get('user') if location and user: items = Item.objects.filter(name__icontains=search_word).filter(user=user).filter(location=location) elif user: items = Item.objects.filter(name__icontains=search_word).filter(user=user) elif location: items = Item.objects.filter(name__icontains=search_word).filter(location=location) else: items = Item.objects.filter(name__icontains=search_word) if items: message = 'Netijeler:' else: message = 'Hi zat ok' items = None if items: paginator = Paginator(items, 18) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) return render(request, 'emarket/expo.html', {'items': items, 'pics': pics, 'ms': message, 's_word': search_word, 'form':form}) class UserCreate(APIView): # api for item # api for category
[ 2, 422, 12854, 1891, 1330, 34912, 1891, 16922, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 11787, 12443, 341, 8479, 198, 2, 422, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 4...
2.456023
2,092
import discord import utils import inspect from discord.ext import commands from io import StringIO
[ 11748, 36446, 198, 11748, 3384, 4487, 198, 11748, 10104, 198, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 33245, 1330, 10903, 9399, 628, 198 ]
4.12
25