id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3327812
from sqlalchemy import Boolean, Column, LargeBinary, Integer, String from sqlalchemy.orm import relationship from database_schemas.base import Base class UserEntry(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, autoincrement=True) username = Column(String, unique=True, index=True) email = Column(String, unique=True, index=True) hashed_password = Column(LargeBinary) is_active = Column(Boolean, default=True) rooms = relationship("RoomEntry", secondary="participants", back_populates="users")
StarcoderdataPython
4828424
import numpy as np import pandas as pd import os from urbansim_defaults import datasources from urbansim_defaults import utils from urbansim.utils import misc import orca from utils import geom_id_to_parcel_id, parcel_id_to_geom_id from utils import nearest_neighbor ##################### # TABLES AND INJECTABLES ##################### @orca.injectable('year') def year(): try: return orca.get_injectable("iter_var") except: pass # if we're not running simulation, return base year return 2014 @orca.injectable() def initial_year(): return 2010 @orca.injectable() def final_year(): return 2040 @orca.injectable('store', cache=True) def hdfstore(settings): return pd.HDFStore( os.path.join(misc.data_dir(), settings["store"])) @orca.injectable(cache=True) def low_income(settings): return int(settings["low_income_for_hlcm"]) @orca.injectable("limits_settings", cache=True) def limits_settings(settings, scenario): d = settings['development_limits'] if scenario in d.keys(): print "Using limits for scenario: %s" % scenario return d[scenario] if "default" in d.keys(): print "Using default limits" return d["default"] # assume there's no scenario-based limits and the dict is the limits return d @orca.injectable(cache=True) def inclusionary_housing_settings(settings, scenario): s = settings['inclusionary_housing_settings'] if scenario in s.keys(): print "Using inclusionary settings for scenario: %s" % scenario s = s[scenario] elif "default" in s.keys(): print "Using default inclusionary settings" s = s["default"] d = {} for item in s: print "Setting inclusionary rates for %d cities to %.2f" %\ (len(item["values"]), item["amount"]) # this is a list of inclusionary rates and the cities they apply # to - need to turn it in a map of city names to rates for juris in item["values"]: d[juris] = item["amount"] return d @orca.injectable('building_sqft_per_job', cache=True) def building_sqft_per_job(settings): return settings['building_sqft_per_job'] # key locations in the Bay Area for use as attractions in the models @orca.table('landmarks', cache=True) def landmarks(): return pd.read_csv(os.path.join(misc.data_dir(), 'landmarks.csv'), index_col="name") @orca.table('jobs', cache=True) def jobs(store): if 'jobs_urbansim_allocated' not in store: # if jobs allocation hasn't been done, then do it # (this should only happen once) orca.run(["allocate_jobs"]) return store['jobs_urbansim_allocated'] # the way this works is there is an orca step to do jobs allocation, which # reads base year totals and creates jobs and allocates them to buildings, # and writes it back to the h5. then the actual jobs table above just reads # the auto-allocated version from the h5. was hoping to just do allocation # on the fly but it takes about 4 minutes so way to long to do on the fly @orca.step('allocate_jobs') def jobs(store, baseyear_taz_controls, settings, parcels): # this isn't pretty, but can't use orca table because there would # be a circular dependenct - I mean jobs dependent on buildings and # buildings on jobs, so we have to grab from the store directly buildings = store['buildings'] buildings["non_residential_sqft"][ buildings.building_type_id.isin([15, 16])] = 0 buildings["building_sqft"][buildings.building_type_id.isin([15, 16])] = 0 buildings["zone_id"] = misc.reindex(parcels.zone_id, buildings.parcel_id) # we need to do a new assignment from the controls to the buildings # first disaggregate the job totals sector_map = settings["naics_to_empsix"] jobs = [] for taz, row in baseyear_taz_controls.local.iterrows(): for sector_col, num in row.iteritems(): # not a sector total if not sector_col.startswith("emp_sec"): continue # get integer sector id sector_id = int(''.join(c for c in sector_col if c.isdigit())) sector_name = sector_map[sector_id] jobs += [[sector_id, sector_name, taz, -1]] * int(num) # df is now the df = pd.DataFrame(jobs, columns=[ 'sector_id', 'empsix', 'taz', 'building_id']) # just do random assignment weighted by job spaces - we'll then # fill in the job_spaces if overfilled in the next step (code # has existed in urbansim for a while) for taz, cnt in df.groupby('taz').size().iteritems(): potential_add_locations = buildings.non_residential_sqft[ (buildings.zone_id == taz) & (buildings.non_residential_sqft > 0)] if len(potential_add_locations) == 0: # if no non-res buildings, put jobs in res buildings potential_add_locations = buildings.building_sqft[ buildings.zone_id == taz] weights = potential_add_locations / potential_add_locations.sum() print taz, len(potential_add_locations),\ potential_add_locations.sum(), cnt buildings_ids = potential_add_locations.sample( cnt, replace=True, weights=weights) df["building_id"][df.taz == taz] = buildings_ids.index.values s = buildings.zone_id.loc[df.building_id].value_counts() t = baseyear_taz_controls.emp_tot - s # assert we matched the totals exactly assert t.sum() == 0 # this is some exploratory diagnostics comparing the job controls to # the buildings table - in other words, comparing non-residential space # to the number of jobs ''' old_jobs = store['jobs'] old_jobs_cnt = old_jobs.groupby('taz').si ze() emp_tot = baseyear_taz_controls.emp_tot print buildings.job_spaces.groupby(buildings.building_type_id).sum() supply = buildings.job_spaces.groupby(buildings.zone_id).sum() non_residential_sqft = buildings.non_residential_sqft.\ groupby(buildings.zone_id).sum() s = (supply-emp_tot).order() df = pd.DataFrame({ "job_spaces": supply, "jobs": emp_tot, "non_residential_sqft": non_residential_sqft }, index=s.index) df["vacant_spaces"] = supply-emp_tot df["vacancy_rate"] = df.vacant_spaces/supply.astype('float') df["old_jobs"] = old_jobs_cnt df["old_vacant_spaces"] = supply-old_jobs_cnt df["old_vacancy_rate"] = df.old_vacant_spaces/supply.astype('float') df["sqft_per_job"] = df.non_residential_sqft / df.jobs df["old_sqft_per_job"] = df.non_residential_sqft / df.old_jobs df.index.name = "zone_id" print df[["jobs", "old_jobs", "job_spaces", "non_residential_sqft"]].corr() df.sort("sqft_per_job").to_csv("job_demand.csv") ''' store['jobs_urbansim_allocated'] = df @orca.table(cache=True) def baseyear_taz_controls(): return pd.read_csv(os.path.join("data", "baseyear_taz_controls.csv"), index_col="taz1454") @orca.table(cache=True) def base_year_summary_taz(): return pd.read_csv(os.path.join('data', 'baseyear_taz_summaries_2010.csv'), index_col="zone_id") # the estimation data is not in the buildings table - they are the same @orca.table('homesales', cache=True) def homesales(store): # we need to read directly from the store here. Why? The buildings # table itself drops a bunch of columns we need - most notably the # redfin_sales_price column. Why? Because the developer model will # append rows (new buildings) to the buildings table and we don't want # the developer model to know about redfin_sales_price (which is # meaningless for forecast buildings) df = store['buildings'] df = df.dropna(subset=["redfin_sale_price"]) df["price_per_sqft"] = df.eval('redfin_sale_price / sqft_per_unit') df = df.query("sqft_per_unit > 200") df = df.dropna(subset=["price_per_sqft"]) return df # non-residential rent data @orca.table('costar', cache=True) def costar(store, parcels): df = pd.read_csv(os.path.join(misc.data_dir(), '2015_08_29_costar.csv')) df["PropertyType"] = df.PropertyType.replace("General Retail", "Retail") df = df[df.PropertyType.isin(["Office", "Retail", "Industrial"])] df["costar_rent"] = df["Average Weighted Rent"].astype('float') df["year_built"] = df["Year Built"].fillna(1980) df = df.dropna(subset=["costar_rent", "Latitude", "Longitude"]) # now assign parcel id df["parcel_id"] = nearest_neighbor( parcels.to_frame(['x', 'y']).dropna(subset=['x', 'y']), df[['Longitude', 'Latitude']] ) return df @orca.table(cache=True) def zoning_lookup(): df = pd.read_csv(os.path.join(misc.data_dir(), "zoning_lookup.csv")) # this part is a bit strange - we do string matching on the names of zoning # in order ot link parcels and zoning and some of the strings have small # differences, so we copy the row and have different strings for the same # lookup row. for now we drop duplicates of the id field in order to run # in urbansim (all the attributes of rows that share an id are the same - # only the name is different) df = df.drop_duplicates(subset='id').set_index('id') return df @orca.table('zoning_table_city_lookup', cache=True) def zoning_table_city_lookup(): df = pd.read_csv(os.path.join(misc.data_dir(), "zoning_table_city_lookup.csv"), index_col="juris") return df # zoning for use in the "baseline" scenario # comes in the hdf5 @orca.table('zoning_baseline', cache=True) def zoning_baseline(parcels, zoning_lookup, settings): df = pd.read_csv(os.path.join(misc.data_dir(), "2015_12_21_zoning_parcels.csv"), index_col="geom_id") df = pd.merge(df, zoning_lookup.to_frame(), left_on="zoning_id", right_index=True) df = geom_id_to_parcel_id(df, parcels) d = {k: "type%d" % v for k, v in settings["building_type_map2"].items()} df.columns = [d.get(x, x) for x in df.columns] return df @orca.table('zoning_scenario', cache=True) def zoning_scenario(parcels_geography, scenario, settings): scenario_zoning = pd.read_csv( os.path.join(misc.data_dir(), 'zoning_mods_%s.csv' % scenario), dtype={'jurisdiction': 'str'}) d = {k: "type%d" % v for k, v in settings["building_type_map2"].items()} for k, v in d.items(): scenario_zoning['add-'+v] = scenario_zoning.add_bldg.str.contains(k) for k, v in d.items(): scenario_zoning['drop-'+v] = scenario_zoning.drop_bldg.\ astype(str).str.contains(k) return pd.merge(parcels_geography.to_frame().reset_index(), scenario_zoning, on=['zoningmodcat'], how='left').set_index('parcel_id') # this is really bizarre, but the parcel table I have right now has empty # zone_ids for a few parcels. Not enough to worry about so just filling with # the mode @orca.table('parcels', cache=True) def parcels(store): df = store['parcels'] df["zone_id"] = df.zone_id.replace(0, 1) cfg = { "fill_nas": { "zone_id": { "how": "mode", "type": "int" }, "shape_area": { "how": "median", "type": "float" } } } df = utils.table_reprocess(cfg, df) # have to do it this way because otherwise it's a circular reference sdem = pd.read_csv(os.path.join(misc.data_dir(), "development_projects.csv")) # mark parcels that are going to be developed by the sdem df["sdem"] = df.geom_id.isin(sdem.geom_id).astype('int') return df @orca.table('parcels_zoning_calculations', cache=True) def parcels_zoning_calculations(parcels): return pd.DataFrame(data=parcels.to_frame( columns=['geom_id', 'total_residential_units']), index=parcels.index) @orca.table('taz') def taz(zones): return zones @orca.table(cache=True) def parcel_rejections(): url = "https://forecast-feedback.firebaseio.com/parcelResults.json" return pd.read_json(url, orient="index").set_index("geomId") @orca.table(cache=True) def parcels_geography(parcels): df = pd.read_csv(os.path.join(misc.data_dir(), "02_01_2016_parcels_geography.csv"), index_col="geom_id", dtype={'jurisdiction': 'str'}) df = geom_id_to_parcel_id(df, parcels) juris_name = pd.read_csv(os.path.join(misc.data_dir(), "census_id_to_name.csv"), index_col="census_id").name10 df["juris_name"] = df.jurisdiction_id.map(juris_name) df["pda_id"] = df.pda_id.str.lower() return df @orca.table(cache=True) def manual_edits(): return pd.read_csv(os.path.join(misc.data_dir(), "manual_edits.csv")) def reprocess_dev_projects(df): # if dev projects with the same parcel id have more than one build # record, we change the later ones to add records - we don't want to # constantly be redeveloping projects, but it's a common error for users # to make in their development project configuration df = df.sort_values(["geom_id", "year_built"]) prev_geom_id = None for index, rec in df.iterrows(): if rec.geom_id == prev_geom_id: df.loc[index, "action"] = "add" prev_geom_id = rec.geom_id return df @orca.table(cache=True) def demolish_events(parcels, settings, scenario): df = pd.read_csv(os.path.join(misc.data_dir(), "development_projects.csv")) df = reprocess_dev_projects(df) # this filters project by scenario if scenario in df: # df[scenario] is 1s and 0s indicating whether to include it df = df[df[scenario].astype('bool')] # keep demolish and build records df = df[df.action.isin(["demolish", "build"])] df = df.dropna(subset=['geom_id']) df = df.set_index("geom_id") df = geom_id_to_parcel_id(df, parcels).reset_index() # use parcel id return df @orca.table(cache=True) def development_projects(parcels, settings, scenario): df = pd.read_csv(os.path.join(misc.data_dir(), "development_projects.csv")) df = reprocess_dev_projects(df) df = df[df.action.isin(["add", "build"])] # this filters project by scenario colname = "scen%s" % scenario # df[colname] is 1s and 0s indicating whether to include it # this used to be an optional filter but now I'm going to require it so # that we don't accidentally include all the development projects since # we've started using scenario-based dev projects pretty extensively df = df[df[colname].astype('bool')] df = df.dropna(subset=['geom_id']) for fld in ['residential_sqft', 'residential_price', 'non_residential_price']: df[fld] = 0 df["redfin_sale_year"] = 2012 # hedonic doesn't tolerate nans df["stories"] = df.stories.fillna(1) df["building_sqft"] = df.building_sqft.fillna(0) df["non_residential_sqft"] = df.non_residential_sqft.fillna(0) df["building_type"] = df.building_type.replace("HP", "OF") df["building_type"] = df.building_type.replace("GV", "OF") df["building_type"] = df.building_type.replace("SC", "OF") df["building_type_id"] = \ df.building_type.map(settings["building_type_map2"]) df = df.dropna(subset=["geom_id"]) # need a geom_id to link to parcel_id df = df.dropna(subset=["year_built"]) # need a year built to get built df["geom_id"] = df.geom_id.astype("int") df = df.query('residential_units != "rent"') df["residential_units"] = df.residential_units.fillna(0).astype("int") geom_id = df.geom_id df = df.set_index("geom_id") df = geom_id_to_parcel_id(df, parcels).reset_index() # use parcel id df["geom_id"] = geom_id.values # add it back again cause it goes away # we don't predict prices for schools and hotels right now df = df.query("building_type_id <= 4 or building_type_id >= 7") df["deed_restricted_units"] = 0 print "Describe of development projects" print df[orca.get_table('buildings').local_columns].describe() return df @orca.table('households', cache=True) def households(store, settings): # start with households from urbansim_defaults df = datasources.households(store, settings) # need to keep track of base year income quartiles for use in the # transition model - even caching doesn't work because when you add # rows via the transitioning, you automatically clear the cache! # this is pretty nasty and unfortunate df["base_income_quartile"] = pd.Series(pd.qcut(df.income, 4, labels=False), index=df.index).add(1) df["base_income_octile"] = pd.Series(pd.qcut(df.income, 8, labels=False), index=df.index).add(1) return df @orca.table('buildings', cache=True) def buildings(store, parcels, households, jobs, building_sqft_per_job, settings, manual_edits): # start with buildings from urbansim_defaults df = datasources.buildings(store, households, jobs, building_sqft_per_job, settings) df = df.drop(['development_type_id', 'improvement_value', 'sqft_per_unit', 'nonres_rent_per_sqft', 'res_price_per_sqft', 'redfin_sale_price', 'redfin_home_type', 'costar_property_type', 'costar_rent'], axis=1) edits = manual_edits.local edits = edits[edits.table == 'buildings'] for index, row, col, val in \ edits[["id", "attribute", "new_value"]].itertuples(): df.set_value(row, col, val) # set the vacancy rate in each building to 5% for testing purposes df["residential_units"] = df.residential_units.fillna(0) # for some reason nonres can be more than total sqft df["building_sqft"] = pd.DataFrame({ "one": df.building_sqft, "two": df.residential_sqft + df.non_residential_sqft}).max(axis=1) # keeps parking lots from getting redeveloped df["building_sqft"][df.building_type_id.isin([15, 16])] = 0 df["non_residential_sqft"][df.building_type_id.isin([15, 16])] = 0 # don't know what a 0 building type id, set to office df["building_type_id"] = df.building_type_id.replace(0, 4) # we should only be using the "buildings" table during simulation, and in # simulation we want to normalize the prices to 2012 style prices df["redfin_sale_year"] = 2012 # hope we get more data on this soon df["deed_restricted_units"] = 0 zone_ids = misc.reindex(parcels.zone_id, df.parcel_id).\ reindex(df.index).fillna(-1) # sample deed restricted units to match current deed restricted unit # zone totals for taz, row in pd.read_csv('data/deed_restricted_zone_totals.csv', index_col='taz_key').iterrows(): cnt = row["units"] if cnt <= 0: continue potential_add_locations = df.residential_units[ (zone_ids == taz) & (df.residential_units > 0)] assert len(potential_add_locations) > 0 weights = potential_add_locations / potential_add_locations.sum() buildings_ids = potential_add_locations.sample( cnt, replace=True, weights=weights) units = pd.Series(buildings_ids.index.values).value_counts() df.loc[units.index, "deed_restricted_units"] += units.values print "Total deed restricted units after random selection: %d" % \ df.deed_restricted_units.sum() df["deed_restricted_units"] = \ df[["deed_restricted_units", "residential_units"]].min(axis=1) print "Total deed restricted units after truncating to res units: %d" % \ df.deed_restricted_units.sum() return df @orca.table('household_controls_unstacked', cache=True) def household_controls_unstacked(): df = pd.read_csv(os.path.join(misc.data_dir(), "household_controls.csv")) return df.set_index('year') # the following overrides household_controls table defined in urbansim_defaults @orca.table('household_controls', cache=True) def household_controls(household_controls_unstacked): df = household_controls_unstacked.to_frame() # rename to match legacy table df.columns = [1, 2, 3, 4] # stack and fill in columns df = df.stack().reset_index().set_index('year') # rename to match legacy table df.columns = ['base_income_quartile', 'total_number_of_households'] return df @orca.table('employment_controls_unstacked', cache=True) def employment_controls_unstacked(): df = pd.read_csv(os.path.join(misc.data_dir(), "employment_controls.csv")) return df.set_index('year') # the following overrides employment_controls # table defined in urbansim_defaults @orca.table('employment_controls', cache=True) def employment_controls(employment_controls_unstacked): df = employment_controls_unstacked.to_frame() # rename to match legacy table df.columns = [1, 2, 3, 4, 5, 6] # stack and fill in columns df = df.stack().reset_index().set_index('year') # rename to match legacy table df.columns = ['empsix_id', 'number_of_jobs'] return df @orca.table('zone_forecast_inputs', cache=True) def zone_forecast_inputs(): return pd.read_csv(os.path.join(misc.data_dir(), "zone_forecast_inputs.csv"), index_col="zone_id") # this is the set of categories by zone of sending and receiving zones # in terms of vmt fees @orca.table("vmt_fee_categories", cache=True) def vmt_fee_categories(): return pd.read_csv(os.path.join(misc.data_dir(), "vmt_fee_zonecats.csv"), index_col="taz") @orca.table('taz_geography', cache=True) def taz_geography(): tg = pd.read_csv(os.path.join(misc.data_dir(), "taz_geography.csv"), index_col="zone") sr = pd.read_csv(os.path.join(misc.data_dir(), "superdistricts.csv"), index_col="number") tg["subregion_id"] = sr.subregion.loc[tg.superdistrict].values tg["subregion"] = tg.subregion_id.map({ 1: "Core", 2: "Urban", 3: "Suburban", 4: "Rural" }) return tg # these are shapes - "zones" in the bay area @orca.table('zones', cache=True) def zones(store): df = store['zones'] df = df.sort_index() return df # this specifies the relationships between tables orca.broadcast('parcels_geography', 'buildings', cast_index=True, onto_on='parcel_id') orca.broadcast('tmnodes', 'buildings', cast_index=True, onto_on='tmnode_id') orca.broadcast('parcels', 'homesales', cast_index=True, onto_on='parcel_id') orca.broadcast('nodes', 'homesales', cast_index=True, onto_on='node_id') orca.broadcast('tmnodes', 'homesales', cast_index=True, onto_on='tmnode_id') orca.broadcast('nodes', 'costar', cast_index=True, onto_on='node_id') orca.broadcast('tmnodes', 'costar', cast_index=True, onto_on='tmnode_id') orca.broadcast('logsums', 'homesales', cast_index=True, onto_on='zone_id') orca.broadcast('logsums', 'costar', cast_index=True, onto_on='zone_id') orca.broadcast('taz_geography', 'parcels', cast_index=True, onto_on='zone_id')
StarcoderdataPython
158220
# Generated by Django 3.1.2 on 2020-10-12 20:33 import ckeditor.fields from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=100)), ('publicado', models.DateTimeField(default=django.utils.timezone.now)), ('criado', models.DateTimeField(auto_now_add=True)), ], options={ 'verbose_name': 'Categoria', 'verbose_name_plural': 'Categorias', 'ordering': ['-criado'], }, ), migrations.AlterModelOptions( name='post', options={'ordering': ('-publicado',)}, ), migrations.AddField( model_name='post', name='alterado', field=models.DateTimeField(auto_now=True), ), migrations.AddField( model_name='post', name='criado', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='post', name='imagem', field=models.ImageField(blank=True, null=True, upload_to='blog'), ), migrations.AddField( model_name='post', name='publicado', field=models.DateTimeField(default=django.utils.timezone.now), ), migrations.AddField( model_name='post', name='status', field=models.CharField(choices=[('rascunho', 'Rascunho'), ('publicado', 'Publicado')], default='rascunho', max_length=10), ), migrations.AlterField( model_name='post', name='conteudo', field=ckeditor.fields.RichTextField(verbose_name='Conteúdo'), ), migrations.AlterField( model_name='post', name='titulo', field=models.CharField(max_length=250, verbose_name='Título'), ), migrations.AddField( model_name='post', name='categoria', field=models.ManyToManyField(related_name='get_posts', to='blog.Category'), ), ]
StarcoderdataPython
3320947
import numpy as np import matplotlib.pyplot as plt from ftocp import FTOCP from map import MAP from riccati_sols import double_integrator_params from unicycle import Unicycle import signal import time import traceback # allow Ctrl-C to work despite plotting signal.signal(signal.SIGINT, signal.SIG_DFL) # ============================================================================================== # USER DEFINED PARAMETERS # ============================================================================================== # set the noise level w = 0.2 enable_perturbations = True gamma = 1.9 # choose the Q and R for the low level controller design Q = np.eye(4) Q[2,2] = 2 # increased weights on vel Q[3,3] = 2 R = np.eye(2) P, Vmax, d_tighten, K = double_integrator_params(w, gamma, Q, R) print("USING D_tighten = ", d_tighten) robot_params = {"d": d_tighten, "w": w, "P": P, "Vmax": Vmax, "K_feedback": K, "velMax" : 2.0} # choose MPC timestep and horizon dt_mpc = 0.5 N = 25 # how long to simulate for SIMULATE_T = N*dt_mpc # seconds # this is the timestep for simulation/integration dt_uni = 0.005 # dimension of state and control inputs nx =4 nu= 2 # choose the cost for the MPC solution Q = 0.5*np.eye(nx) R = 10*np.eye(nu) Qf = 20*N*np.eye(nx) # set the start and goal x0 = np.array([2, 2.,0.0,0.5]) # Position and velocity theta_0 = np.arctan2(x0[3],x0[2]) # initial heading angle goal = np.array([13.0, 2.0, 0.0, 0.0]) # construct the environment, recList = [] # Each rec = [ x, y, width, height ] recList.append([ 0, 0, 5, 7.5]) recList.append([10, 0, 5, 7.5]) recList.append([ 0,7.5, 15, 7.5]) mapEnv = MAP(recList, printLevel = 0) # construct a tightened environment recListTight = [] recListTight.append([ 0, 0, 5-d_tighten, 7.5+d_tighten]) # Each rec = [ x, y, width, height ] recListTight.append([10+d_tighten, 0, 5-d_tighten, 7.5+d_tighten]) recListTight.append([ 0,7.5+d_tighten, 15, 7.5-d_tighten]) mapTight = MAP(recListTight, printLevel=0) plt.figure() mapEnv.plotMap() mapTight.plotMap(linestyle='dashed') plt.scatter(x0[0], x0[1], marker='o') plt.scatter(goal[0], goal[1], marker='o') plt.savefig("figs/regions.eps") plt.savefig("figs/regions.png") # ============================================================================================== # discrete time double integrator A = np.array([[1, 0, dt_mpc, 0], [0, 1, 0, dt_mpc], [0, 0, 1, 0], [0, 0, 0, 1]]) B = np.array([[ dt_mpc**2/2, 0], [ 0, dt_mpc**2/2], [dt_mpc, 0], [ 0, dt_mpc]]) ## discrete matrices for unicycle interp of lin_sys A_di = np.array([[1, 0, dt_uni, 0], [0, 1, 0, dt_uni], [0, 0, 1, 0], [0, 0, 0, 1]]) B_di = np.array([[ dt_uni**2/2, 0], [ 0, dt_uni**2/2], [dt_uni, 0], [ 0, dt_uni]]) ##### Initialize Unicycle robot = Unicycle(x0[0],x0[1],theta_0, robot_params) robot.controls_v.append( np.linalg.norm(x0[2:4])) robot.controls_w.append( 0 ) robot.controls_v_perturbed.append( np.linalg.norm(x0[2:4])) robot.controls_w_perturbed.append( 0 ) ###### INTIALISE THE FTOCP PROBLEM ftocp = FTOCP(N, goal, A, B, Q, R, Qf, mapTight.bVecList, robot_params, printLevel = 0, mpcTimestep=dt_mpc, amax=0.5) ftocp.build() def replanMPC(robot, ftocp): s_time = time.time() # use the last applied velocity as the estimate for the double integrator state vx = robot.controls_v[-1]*np.cos(robot.X[2]) vy = robot.controls_v[-1]*np.sin(robot.X[2]) # create the estimated double integrator state x0 = np.array([robot.X[0], robot.X[1], vx, vy ]) s_time = time.time() if not ftocp.solve(x0): raise "FTOCP DID NOT SOLVE SUCCESSFULLY!" print("Replan Time: ", time.time() - s_time) return ###### SOLVE THE FTOCP PROBLEM ONCE FIRST replanMPC(robot, ftocp) # Init Variables for plotting Xref_uni = [] Yref_uni = [] t_MPC = [i*dt_mpc for i in range(N+1)] x_MPC = ftocp.xPred[0,:] y_MPC = ftocp.xPred[1,:] vx_MPC = ftocp.xPred[2,:] vy_MPC = ftocp.xPred[3,:] ax_MPC = ftocp.uPred[0,:] ay_MPC = ftocp.uPred[1,:] ###### Save initial solution plt.figure() mapEnv.plotMap() mapTight.plotMap(linestyle='dashed') plt.plot(x_MPC, y_MPC, '--rx', label='Double Integrator MPC trajectory') plt.scatter(x0[0], x0[1], marker='o') plt.scatter(goal[0], goal[1], marker='o') plt.savefig("figs/INITIAL_PATH_tracking.eps") plt.savefig("figs/INITIAL_PATH_tracking.png") plt.figure() plt.subplot(211) plt.plot(t_MPC, x_MPC) plt.ylabel('x') plt.subplot(212) plt.plot(t_MPC, y_MPC) plt.ylabel('y') plt.xlabel('time') plt.savefig("figs/Initial_MPC_xy.eps") plt.savefig("figs/Initial_MPC_xy.png") plt.figure() plt.subplot(211) plt.plot(t_MPC, vx_MPC) plt.ylabel('vx') plt.subplot(212) plt.plot(t_MPC, vy_MPC) plt.ylabel('vy') plt.xlabel('time') plt.savefig("figs/Initial_MPC_velocity.eps") plt.savefig("figs/Initial_MPC_velocity.png") plt.figure() plt.subplot(211) plt.plot(t_MPC[:-1], ax_MPC) plt.ylabel('ax') plt.subplot(212) plt.plot(t_MPC[:-1], ay_MPC) plt.ylabel('ay') plt.xlabel('time') plt.savefig("figs/Initial_MPC_accelerations.eps") plt.savefig("figs/Initial_MPC_accelerations.png") # ============================================================================================== # MAIN SIMULATION LOOP # ============================================================================================== reached = False MPC_x = [x0[0]] MPC_y = [x0[1]] MPC_vx = [x0[2]] MPC_vy = [x0[3]] MPC_ux = [ftocp.uPred[0,0]] MPC_uy = [ftocp.uPred[1,0]] MPC_x_current = [x0[0]] MPC_y_current = [x0[1]] MPC_t = [robot.time] ref_index = 0 MPC_index = 0 last_replan_time = robot.time X_ref = np.array([ftocp.xPred[:,0]]).T U_ref = np.array([ftocp.uPred[0,0], ftocp.uPred[1,0] ]).reshape(-1,1) MPC_x.append(X_ref[0,0]) MPC_y.append(X_ref[1,0]) MPC_t.append(robot.time) MPC_ux.append(U_ref[0,0]) MPC_uy.append(U_ref[1,0]) MPC_vx.append(X_ref[2,0]) MPC_vy.append(X_ref[3,0]) ref_index += 1 print('================== Starting time loop') try: # simulate forward in time while robot.time <= SIMULATE_T and np.linalg.norm(robot.X[0:2] - goal[0:2])>0.05: # check if need to replan if (robot.time >= last_replan_time + dt_mpc): replanMPC(robot, ftocp) last_replan_time = robot.time ref_time = robot.time X_ref = np.array([ftocp.xPred[:,0]]).T U_ref = np.array([ftocp.uPred[0,0], ftocp.uPred[1,0] ]).reshape(-1,1) MPC_t.append(robot.time) MPC_x.append(X_ref[0,0]) MPC_y.append(X_ref[1,0]) MPC_vx.append(X_ref[2,0]) MPC_vy.append(X_ref[3,0]) MPC_ux.append(U_ref[0,0]) MPC_uy.append(U_ref[1,0]) # regardless, compute low-level u, reached = robot.low_level(dt_mpc, dt_uni, X_ref, U_ref, robot_params) if reached: robot.step([0,0], dt_uni) print("EXITING HERE!") break robot.step(u, dt_uni, robot_params["w"], enable_perturbations=enable_perturbations) # propagate X_ref in time for tracking X_ref = A_di @ X_ref + B_di @ U_ref Xref_uni.append(X_ref[0,0]) Yref_uni.append(X_ref[1,0]) # exit() except Exception as e: traceback.print_exc() print(e) exit() print("Simulation Completed!") # ============================================================================================== # PLOTTING # ============================================================================================== plt.figure() mapEnv.plotMap() mapTight.plotMap(linestyle='dashed') plt.plot([x0[0]], [x0[1]], 'o') plt.plot([goal[0]], [goal[1]], 'x') plt.plot(Xref_uni,Yref_uni,'k.', label = "Reference") plt.plot(MPC_x, MPC_y, 'rx', label="Waypoints") plt.plot(robot.states[:,0], robot.states[:,1],'g', label="Path") plt.savefig("figs/map_tracking.eps") plt.savefig("figs/map_tracking.png") plt.figure() plt.subplot(311) plt.plot(MPC_t,MPC_x,'rx',label='MPC Waypoints') plt.plot(robot.times[:-1],Xref_uni, '.-', label='Tracking Waypoints') plt.axhline([goal[0]]) plt.ylabel('X') plt.legend() plt.subplot(312) plt.plot(MPC_t,MPC_y,'rx',label='MPC Waypoints') plt.plot(robot.times[:-1],Yref_uni, '.-', label='Tracking Waypoints') plt.ylabel('Y') plt.axhline([goal[1]]) plt.xlabel('time') plt.legend() plt.subplot(313) plt.plot(robot.times[1:], robot.lyapunov) plt.axhline(Vmax, linestyle='--', label = 'Max Lyapunov') plt.xlabel('time') plt.ylabel("Lyapunov Function") plt.savefig("figs/Tracking reference.eps") plt.savefig("figs/Tracking reference.png") plt.figure() plt.plot(robot.times[1:], robot.lyapunov) plt.axhline(Vmax, linestyle='--', label = 'Max Lyapunov') plt.xlabel('time') plt.ylabel("Lyapunov Function") plt.savefig("figs/lyapunov.eps") plt.savefig("figs/lyapunov.png") robot.times = list(robot.times) plt.figure() plt.subplot(211) plt.plot(robot.times, robot.controls_v_perturbed,'r') plt.plot(robot.times, robot.controls_v,'g') plt.ylabel("Linear Velocity") plt.subplot(212) plt.plot(robot.times[1:], robot.controls_w_perturbed[1:]) plt.plot(robot.times, robot.controls_w,'g') plt.ylabel("Angular velocity") plt.savefig("figs/controls_tracking.eps") plt.savefig("figs/controls_tracking.png") vx = [] vy = [] for index, value in enumerate(robot.controls_v): vx.append(robot.controls_v[index]*np.cos(robot.states[index][2]) ) # V*cos(theta) vy.append(robot.controls_v[index]*np.sin(robot.states[index][2]) ) plt.figure() plt.subplot(211) plt.plot(robot.times, vx,label='vx') plt.step(MPC_t,MPC_vx,label='vx_ref',where='post') plt.ylabel("X velocity") plt.legend() plt.subplot(212) plt.plot(robot.times, vy,label='vy') plt.step(MPC_t,MPC_vy,label='vy_ref',where='post') plt.ylabel("Y velocity") plt.xlabel('time') plt.legend() plt.savefig("figs/velocity_xy_tracking.eps") plt.savefig("figs/velocity_xy_tracking.png") plt.figure() plt.subplot(211) plt.plot(MPC_t,MPC_ux,label='ax') plt.ylabel("X acceleration") plt.subplot(212) plt.plot(MPC_t,MPC_uy,label='ay') plt.ylabel("Y acceleration") plt.savefig("figs/acceleration MPC.eps") plt.savefig("figs/acceleration MPC.png")
StarcoderdataPython
1711926
<gh_stars>1000+ # -*- coding: utf-8 -*- """ Created on Tue Aug 8 20:54:15 2017 @author: DIP @Copyright: <NAME> """ import numpy as np # prints components of all the topics # obtained from topic modeling def print_topics_udf(topics, total_topics=1, weight_threshold=0.0001, display_weights=False, num_terms=None): for index in range(total_topics): topic = topics[index] topic = [(term, float(wt)) for term, wt in topic] topic = [(word, round(wt,2)) for word, wt in topic if abs(wt) >= weight_threshold] if display_weights: print('Topic #'+str(index+1)+' with weights') print(topic[:num_terms]) if num_terms else topic else: print('Topic #'+str(index+1)+' without weights') tw = [term for term, wt in topic] print(tw[:num_terms]) if num_terms else tw print() # extracts topics with their terms and weights # format is Topic N: [(term1, weight1), ..., (termn, weightn)] def get_topics_terms_weights(weights, feature_names): feature_names = np.array(feature_names) sorted_indices = np.array([list(row[::-1]) for row in np.argsort(np.abs(weights))]) sorted_weights = np.array([list(wt[index]) for wt, index in zip(weights,sorted_indices)]) sorted_terms = np.array([list(feature_names[row]) for row in sorted_indices]) topics = [np.vstack((terms.T, term_weights.T)).T for terms, term_weights in zip(sorted_terms, sorted_weights)] return topics
StarcoderdataPython
165251
# <NAME> # Solution to https://www.urionlinejudge.com.br/judge/problems/view/1197 # -*- coding: utf-8 -*- while True: try: a,b = [int(i) for i in raw_input().split(" ")] print 2*a*b except EOFError: break
StarcoderdataPython
124755
""" Copyright thautwarm (c) 2019 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of thautwarm nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from typeschema import * from typing import Generic, TypeVar T = TypeVar('T') class Tokens(): __slots__ = ['array', 'offset'] def __init__(self, array): self.array = array self.offset = 0 class State(): def __init__(self): pass class AST(Generic[T]): __slots__ = ['tag', 'contents'] def __init__(self, tag: str, contents: T): self.tag = tag self.contents = contents class Nil(): nil = None __slots__ = [] def __init__(self): if (Nil.nil is None): Nil.nil = self return raise ValueError('Nil cannot get instantiated twice.') def __len__(self): return 0 def __getitem__(self, n): raise IndexError('Out of bounds') @property def head(self): raise IndexError('Out of bounds') @property def tail(self): raise IndexError('Out of bounds') def __repr__(self): return '[]' _nil = Nil() class Cons(): __slots__ = ['head', 'tail'] def __init__(self, _head, _tail): self.head = _head self.tail = _tail def __len__(self): nil = _nil l = 0 while (self is not nil): l += 1 self = self.tail return l def __iter__(self): nil = _nil while (self is not nil): (yield self.head) self = self.tail def __getitem__(self, n): while (n != 0): self = self.tail n -= 1 return self.head def __repr__(self): return repr(list(self)) try: def mk_pretty(): from prettyprinter import register_pretty, pretty_call, pprint @register_pretty(Tokens) def pretty_tokens(value, ctx): return pretty_call(ctx, Tokens, offset=value.offset, array=value.array) @register_pretty(AST) def pretty_ast(value, ctx): return pretty_call(ctx, AST, tag=value.tag, contents=value.contents) mk_pretty() del mk_pretty except ImportError: pass del T, Generic, TypeVar builtin_cons = Cons builtin_nil = _nil builtin_mk_ast = AST def mk_parser(): pass def rbnf_named_lr_step_rbnfmacro_0(rbnf_tmp_0, builtin_state, builtin_tokens): lcl_0 = rbnf_named_parse_classdef(builtin_state, builtin_tokens) rbnf_named__check_1 = lcl_0 lcl_0 = rbnf_named__check_1[0] lcl_0 = (lcl_0 == False) if lcl_0: lcl_0 = rbnf_named__check_1 else: lcl_1 = rbnf_named__check_1[1] rbnf_tmp_1 = lcl_1 lcl_1 = rbnf_tmp_0.append lcl_1 = lcl_1(rbnf_tmp_1) rbnf_tmp_1_ = rbnf_tmp_0 lcl_2 = (True, rbnf_tmp_1_) lcl_0 = lcl_2 return lcl_0 def rbnf_named_lr_loop_rbnfmacro_0(rbnf_tmp_0, builtin_state, builtin_tokens): rbnf_named_lr_rbnfmacro_0_reduce = rbnf_tmp_0 lcl_0 = builtin_tokens.offset rbnf_named__off_0 = lcl_0 lcl_0 = rbnf_named_lr_step_rbnfmacro_0(rbnf_named_lr_rbnfmacro_0_reduce, builtin_state, builtin_tokens) rbnf_named_lr_rbnfmacro_0_try = lcl_0 lcl_0 = rbnf_named_lr_rbnfmacro_0_try[0] lcl_0 = (lcl_0 is not False) while lcl_0: lcl_1 = builtin_tokens.offset rbnf_named__off_0 = lcl_1 lcl_1 = rbnf_named_lr_rbnfmacro_0_try[1] rbnf_named_lr_rbnfmacro_0_reduce = lcl_1 lcl_1 = rbnf_named_lr_step_rbnfmacro_0(rbnf_named_lr_rbnfmacro_0_reduce, builtin_state, builtin_tokens) rbnf_named_lr_rbnfmacro_0_try = lcl_1 lcl_1 = rbnf_named_lr_rbnfmacro_0_try[0] lcl_1 = (lcl_1 is not False) lcl_0 = lcl_1 lcl_0 = builtin_tokens.offset lcl_0 = (lcl_0 == rbnf_named__off_0) if lcl_0: lcl_1 = (True, rbnf_named_lr_rbnfmacro_0_reduce) lcl_0 = lcl_1 else: lcl_0 = rbnf_named_lr_rbnfmacro_0_try return lcl_0 def rbnf_named_lr_step_rbnfmacro_1(rbnf_tmp_0, builtin_state, builtin_tokens): try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 6): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_0 = _rbnf_cur_token rbnf_tmp_1 = lcl_0 lcl_0 = (rbnf_tmp_1 is None) if lcl_0: lcl_1 = builtin_tokens.offset lcl_1 = (lcl_1, 'quote , not match') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 else: lcl_1 = rbnf_named_parse_fieldef(builtin_state, builtin_tokens) rbnf_named__check_2 = lcl_1 lcl_1 = rbnf_named__check_2[0] lcl_1 = (lcl_1 == False) if lcl_1: lcl_1 = rbnf_named__check_2 else: lcl_2 = rbnf_named__check_2[1] rbnf_tmp_2 = lcl_2 lcl_2 = rbnf_tmp_0.append lcl_2 = lcl_2(rbnf_tmp_2) rbnf_tmp_1_ = rbnf_tmp_0 lcl_3 = (True, rbnf_tmp_1_) lcl_1 = lcl_3 lcl_0 = lcl_1 return lcl_0 def rbnf_named_lr_loop_rbnfmacro_1(rbnf_tmp_0, builtin_state, builtin_tokens): rbnf_named_lr_rbnfmacro_1_reduce = rbnf_tmp_0 lcl_0 = builtin_tokens.offset rbnf_named__off_0 = lcl_0 lcl_0 = rbnf_named_lr_step_rbnfmacro_1(rbnf_named_lr_rbnfmacro_1_reduce, builtin_state, builtin_tokens) rbnf_named_lr_rbnfmacro_1_try = lcl_0 lcl_0 = rbnf_named_lr_rbnfmacro_1_try[0] lcl_0 = (lcl_0 is not False) while lcl_0: lcl_1 = builtin_tokens.offset rbnf_named__off_0 = lcl_1 lcl_1 = rbnf_named_lr_rbnfmacro_1_try[1] rbnf_named_lr_rbnfmacro_1_reduce = lcl_1 lcl_1 = rbnf_named_lr_step_rbnfmacro_1(rbnf_named_lr_rbnfmacro_1_reduce, builtin_state, builtin_tokens) rbnf_named_lr_rbnfmacro_1_try = lcl_1 lcl_1 = rbnf_named_lr_rbnfmacro_1_try[0] lcl_1 = (lcl_1 is not False) lcl_0 = lcl_1 lcl_0 = builtin_tokens.offset lcl_0 = (lcl_0 == rbnf_named__off_0) if lcl_0: lcl_1 = (True, rbnf_named_lr_rbnfmacro_1_reduce) lcl_0 = lcl_1 else: lcl_0 = rbnf_named_lr_rbnfmacro_1_try return lcl_0 def rbnf_named_lr_step_rbnfmacro_2(rbnf_tmp_0, builtin_state, builtin_tokens): try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 6): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_0 = _rbnf_cur_token rbnf_tmp_1 = lcl_0 lcl_0 = (rbnf_tmp_1 is None) if lcl_0: lcl_1 = builtin_tokens.offset lcl_1 = (lcl_1, 'quote , not match') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 else: lcl_1 = rbnf_named_parse_type(builtin_state, builtin_tokens) rbnf_named__check_2 = lcl_1 lcl_1 = rbnf_named__check_2[0] lcl_1 = (lcl_1 == False) if lcl_1: lcl_1 = rbnf_named__check_2 else: lcl_2 = rbnf_named__check_2[1] rbnf_tmp_2 = lcl_2 lcl_2 = rbnf_tmp_0.append lcl_2 = lcl_2(rbnf_tmp_2) rbnf_tmp_1_ = rbnf_tmp_0 lcl_3 = (True, rbnf_tmp_1_) lcl_1 = lcl_3 lcl_0 = lcl_1 return lcl_0 def rbnf_named_lr_loop_rbnfmacro_2(rbnf_tmp_0, builtin_state, builtin_tokens): rbnf_named_lr_rbnfmacro_2_reduce = rbnf_tmp_0 lcl_0 = builtin_tokens.offset rbnf_named__off_0 = lcl_0 lcl_0 = rbnf_named_lr_step_rbnfmacro_2(rbnf_named_lr_rbnfmacro_2_reduce, builtin_state, builtin_tokens) rbnf_named_lr_rbnfmacro_2_try = lcl_0 lcl_0 = rbnf_named_lr_rbnfmacro_2_try[0] lcl_0 = (lcl_0 is not False) while lcl_0: lcl_1 = builtin_tokens.offset rbnf_named__off_0 = lcl_1 lcl_1 = rbnf_named_lr_rbnfmacro_2_try[1] rbnf_named_lr_rbnfmacro_2_reduce = lcl_1 lcl_1 = rbnf_named_lr_step_rbnfmacro_2(rbnf_named_lr_rbnfmacro_2_reduce, builtin_state, builtin_tokens) rbnf_named_lr_rbnfmacro_2_try = lcl_1 lcl_1 = rbnf_named_lr_rbnfmacro_2_try[0] lcl_1 = (lcl_1 is not False) lcl_0 = lcl_1 lcl_0 = builtin_tokens.offset lcl_0 = (lcl_0 == rbnf_named__off_0) if lcl_0: lcl_1 = (True, rbnf_named_lr_rbnfmacro_2_reduce) lcl_0 = lcl_1 else: lcl_0 = rbnf_named_lr_rbnfmacro_2_try return lcl_0 def rbnf_named_parse_START(builtin_state, builtin_tokens): try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 0): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_0 = _rbnf_cur_token rbnf_tmp_0 = lcl_0 lcl_0 = (rbnf_tmp_0 is None) if lcl_0: lcl_1 = builtin_tokens.offset lcl_1 = (lcl_1, 'BOF not match') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 else: try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 1): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_1 = _rbnf_cur_token rbnf_tmp_1 = lcl_1 lcl_1 = (rbnf_tmp_1 is None) if lcl_1: lcl_2 = builtin_tokens.offset lcl_2 = (lcl_2, 'quote backend not match') lcl_2 = builtin_cons(lcl_2, builtin_nil) lcl_2 = (False, lcl_2) lcl_1 = lcl_2 else: try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 2): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_2 = _rbnf_cur_token rbnf_tmp_2 = lcl_2 lcl_2 = (rbnf_tmp_2 is None) if lcl_2: lcl_3 = builtin_tokens.offset lcl_3 = (lcl_3, 'Ident not match') lcl_3 = builtin_cons(lcl_3, builtin_nil) lcl_3 = (False, lcl_3) lcl_2 = lcl_3 else: lcl_3 = rbnf_named_parse_typeschema(builtin_state, builtin_tokens) rbnf_named__check_3 = lcl_3 lcl_3 = rbnf_named__check_3[0] lcl_3 = (lcl_3 == False) if lcl_3: lcl_3 = rbnf_named__check_3 else: lcl_4 = rbnf_named__check_3[1] rbnf_tmp_3 = lcl_4 try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 3): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_4 = _rbnf_cur_token rbnf_tmp_4 = lcl_4 lcl_4 = (rbnf_tmp_4 is None) if lcl_4: lcl_5 = builtin_tokens.offset lcl_5 = (lcl_5, 'EOF not match') lcl_5 = builtin_cons(lcl_5, builtin_nil) lcl_5 = (False, lcl_5) lcl_4 = lcl_5 else: lcl_5 = rbnf_tmp_2.value lcl_5 = (lcl_5, rbnf_tmp_3) rbnf_tmp_1_ = lcl_5 lcl_5 = (True, rbnf_tmp_1_) lcl_4 = lcl_5 lcl_3 = lcl_4 lcl_2 = lcl_3 lcl_1 = lcl_2 lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_classdef(builtin_state, builtin_tokens): try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 7): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_0 = _rbnf_cur_token rbnf_tmp_0 = lcl_0 lcl_0 = (rbnf_tmp_0 is None) if lcl_0: lcl_1 = builtin_tokens.offset lcl_1 = (lcl_1, 'quote | not match') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 else: try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 2): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_1 = _rbnf_cur_token rbnf_tmp_1 = lcl_1 lcl_1 = (rbnf_tmp_1 is None) if lcl_1: lcl_2 = builtin_tokens.offset lcl_2 = (lcl_2, 'Ident not match') lcl_2 = builtin_cons(lcl_2, builtin_nil) lcl_2 = (False, lcl_2) lcl_1 = lcl_2 else: try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 8): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_2 = _rbnf_cur_token rbnf_tmp_2 = lcl_2 lcl_2 = (rbnf_tmp_2 is None) if lcl_2: lcl_3 = builtin_tokens.offset lcl_3 = (lcl_3, 'quote ( not match') lcl_3 = builtin_cons(lcl_3, builtin_nil) lcl_3 = (False, lcl_3) lcl_2 = lcl_3 else: lcl_3 = rbnf_named_parse_rbnfmacro_1(builtin_state, builtin_tokens) rbnf_named__check_3 = lcl_3 lcl_3 = rbnf_named__check_3[0] lcl_3 = (lcl_3 == False) if lcl_3: lcl_3 = rbnf_named__check_3 else: lcl_4 = rbnf_named__check_3[1] rbnf_tmp_3 = lcl_4 try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 9): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_4 = _rbnf_cur_token rbnf_tmp_4 = lcl_4 lcl_4 = (rbnf_tmp_4 is None) if lcl_4: lcl_5 = builtin_tokens.offset lcl_5 = (lcl_5, 'quote ) not match') lcl_5 = builtin_cons(lcl_5, builtin_nil) lcl_5 = (False, lcl_5) lcl_4 = lcl_5 else: lcl_5 = rbnf_tmp_1.value lcl_5 = CaseTypeDef(lcl_5, rbnf_tmp_3) rbnf_tmp_1_ = lcl_5 lcl_5 = (True, rbnf_tmp_1_) lcl_4 = lcl_5 lcl_3 = lcl_4 lcl_2 = lcl_3 lcl_1 = lcl_2 lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_fieldef(builtin_state, builtin_tokens): lcl_0 = builtin_tokens.offset rbnf_named__off_0 = lcl_0 try: builtin_tokens.array[(builtin_tokens.offset + 0)] _rbnf_peek_tmp = True except IndexError: _rbnf_peek_tmp = False lcl_0 = _rbnf_peek_tmp if lcl_0: lcl_2 = builtin_tokens.array[(builtin_tokens.offset + 0)] lcl_2 = lcl_2.idint if (lcl_2 == 2): lcl_3 = builtin_tokens.offset rbnf_named__off_1 = lcl_3 try: builtin_tokens.array[(builtin_tokens.offset + 1)] _rbnf_peek_tmp = True except IndexError: _rbnf_peek_tmp = False lcl_3 = _rbnf_peek_tmp if lcl_3: lcl_5 = builtin_tokens.array[(builtin_tokens.offset + 1)] lcl_5 = lcl_5.idint if (lcl_5 == 11): lcl_6 = rbnf_named_parse_type(builtin_state, builtin_tokens) rbnf_named__check_0 = lcl_6 lcl_6 = rbnf_named__check_0[0] lcl_6 = (lcl_6 == False) if lcl_6: lcl_6 = rbnf_named__check_0 else: lcl_7 = rbnf_named__check_0[1] rbnf_tmp_0 = lcl_7 lcl_7 = FieldDef(None, rbnf_tmp_0) rbnf_tmp_1_ = lcl_7 lcl_7 = (True, rbnf_tmp_1_) lcl_6 = lcl_7 lcl_4 = lcl_6 elif (lcl_5 == 10): _rbnf_old_offset = builtin_tokens.offset _rbnf_cur_token = builtin_tokens.array[_rbnf_old_offset] builtin_tokens.offset = (_rbnf_old_offset + 1) lcl_6 = _rbnf_cur_token rbnf_tmp_0 = lcl_6 _rbnf_old_offset = builtin_tokens.offset _rbnf_cur_token = builtin_tokens.array[_rbnf_old_offset] builtin_tokens.offset = (_rbnf_old_offset + 1) lcl_6 = _rbnf_cur_token rbnf_tmp_1 = lcl_6 lcl_6 = rbnf_named_parse_type(builtin_state, builtin_tokens) rbnf_named__check_2 = lcl_6 lcl_6 = rbnf_named__check_2[0] lcl_6 = (lcl_6 == False) if lcl_6: lcl_6 = rbnf_named__check_2 else: lcl_7 = rbnf_named__check_2[1] rbnf_tmp_2 = lcl_7 lcl_7 = rbnf_tmp_0.value lcl_7 = FieldDef(lcl_7, rbnf_tmp_2) rbnf_tmp_1_ = lcl_7 lcl_7 = (True, rbnf_tmp_1_) lcl_6 = lcl_7 lcl_4 = lcl_6 else: lcl_6 = rbnf_named_parse_type(builtin_state, builtin_tokens) rbnf_named__check_0 = lcl_6 lcl_6 = rbnf_named__check_0[0] lcl_6 = (lcl_6 == False) if lcl_6: lcl_6 = rbnf_named__check_0 else: lcl_7 = rbnf_named__check_0[1] rbnf_tmp_0 = lcl_7 lcl_7 = FieldDef(None, rbnf_tmp_0) rbnf_tmp_1_ = lcl_7 lcl_7 = (True, rbnf_tmp_1_) lcl_6 = lcl_7 lcl_4 = lcl_6 lcl_3 = lcl_4 else: lcl_4 = (rbnf_named__off_1, 'fieldef got EOF') lcl_4 = builtin_cons(lcl_4, builtin_nil) lcl_4 = (False, lcl_4) lcl_3 = lcl_4 lcl_1 = lcl_3 else: lcl_3 = (rbnf_named__off_0, 'fieldef lookahead failed') lcl_3 = builtin_cons(lcl_3, builtin_nil) lcl_3 = (False, lcl_3) lcl_1 = lcl_3 lcl_0 = lcl_1 else: lcl_1 = (rbnf_named__off_0, 'fieldef got EOF') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_rbnfmacro_0(builtin_state, builtin_tokens): lcl_0 = rbnf_named_parse_classdef(builtin_state, builtin_tokens) rbnf_named__check_0 = lcl_0 lcl_0 = rbnf_named__check_0[0] lcl_0 = (lcl_0 == False) if lcl_0: lcl_0 = rbnf_named__check_0 else: lcl_1 = rbnf_named__check_0[1] rbnf_tmp_0 = lcl_1 lcl_1 = [] _rbnf_immediate_lst = lcl_1 _rbnf_immediate_lst.append(rbnf_tmp_0) lcl_1 = _rbnf_immediate_lst rbnf_tmp_1_ = lcl_1 lcl_1 = rbnf_named_lr_loop_rbnfmacro_0(rbnf_tmp_1_, builtin_state, builtin_tokens) lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_rbnfmacro_1(builtin_state, builtin_tokens): lcl_0 = rbnf_named_parse_fieldef(builtin_state, builtin_tokens) rbnf_named__check_0 = lcl_0 lcl_0 = rbnf_named__check_0[0] lcl_0 = (lcl_0 == False) if lcl_0: lcl_0 = rbnf_named__check_0 else: lcl_1 = rbnf_named__check_0[1] rbnf_tmp_0 = lcl_1 lcl_1 = [] _rbnf_immediate_lst = lcl_1 _rbnf_immediate_lst.append(rbnf_tmp_0) lcl_1 = _rbnf_immediate_lst rbnf_tmp_1_ = lcl_1 lcl_1 = rbnf_named_lr_loop_rbnfmacro_1(rbnf_tmp_1_, builtin_state, builtin_tokens) lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_rbnfmacro_2(builtin_state, builtin_tokens): lcl_0 = rbnf_named_parse_type(builtin_state, builtin_tokens) rbnf_named__check_0 = lcl_0 lcl_0 = rbnf_named__check_0[0] lcl_0 = (lcl_0 == False) if lcl_0: lcl_0 = rbnf_named__check_0 else: lcl_1 = rbnf_named__check_0[1] rbnf_tmp_0 = lcl_1 lcl_1 = [] _rbnf_immediate_lst = lcl_1 _rbnf_immediate_lst.append(rbnf_tmp_0) lcl_1 = _rbnf_immediate_lst rbnf_tmp_1_ = lcl_1 lcl_1 = rbnf_named_lr_loop_rbnfmacro_2(rbnf_tmp_1_, builtin_state, builtin_tokens) lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_type(builtin_state, builtin_tokens): try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 2): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_0 = _rbnf_cur_token rbnf_tmp_0 = lcl_0 lcl_0 = (rbnf_tmp_0 is None) if lcl_0: lcl_1 = builtin_tokens.offset lcl_1 = (lcl_1, 'Ident not match') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 else: lcl_1 = builtin_tokens.offset rbnf_named__off_1 = lcl_1 try: builtin_tokens.array[(builtin_tokens.offset + 0)] _rbnf_peek_tmp = True except IndexError: _rbnf_peek_tmp = False lcl_1 = _rbnf_peek_tmp if lcl_1: lcl_3 = builtin_tokens.array[(builtin_tokens.offset + 0)] lcl_3 = lcl_3.idint if (lcl_3 == 11): _rbnf_old_offset = builtin_tokens.offset _rbnf_cur_token = builtin_tokens.array[_rbnf_old_offset] builtin_tokens.offset = (_rbnf_old_offset + 1) lcl_4 = _rbnf_cur_token rbnf_tmp_1 = lcl_4 lcl_4 = rbnf_named_parse_rbnfmacro_2(builtin_state, builtin_tokens) rbnf_named__check_2 = lcl_4 lcl_4 = rbnf_named__check_2[0] lcl_4 = (lcl_4 == False) if lcl_4: lcl_4 = rbnf_named__check_2 else: lcl_5 = rbnf_named__check_2[1] rbnf_tmp_2 = lcl_5 try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 12): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_5 = _rbnf_cur_token rbnf_tmp_3 = lcl_5 lcl_5 = (rbnf_tmp_3 is None) if lcl_5: lcl_6 = builtin_tokens.offset lcl_6 = (lcl_6, 'quote ] not match') lcl_6 = builtin_cons(lcl_6, builtin_nil) lcl_6 = (False, lcl_6) lcl_5 = lcl_6 else: lcl_6 = rbnf_tmp_0.value lcl_6 = Typ(lcl_6, rbnf_tmp_2) rbnf_tmp_1_ = lcl_6 lcl_6 = (True, rbnf_tmp_1_) lcl_5 = lcl_6 lcl_4 = lcl_5 lcl_2 = lcl_4 else: lcl_4 = rbnf_tmp_0.value lcl_5 = [] lcl_4 = Typ(lcl_4, lcl_5) rbnf_tmp_1_ = lcl_4 lcl_4 = (True, rbnf_tmp_1_) lcl_2 = lcl_4 lcl_1 = lcl_2 else: lcl_2 = (rbnf_named__off_1, 'type got EOF') lcl_2 = builtin_cons(lcl_2, builtin_nil) lcl_2 = (False, lcl_2) lcl_1 = lcl_2 lcl_0 = lcl_1 return lcl_0 def rbnf_named_parse_typeschema(builtin_state, builtin_tokens): try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 4): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_0 = _rbnf_cur_token rbnf_tmp_0 = lcl_0 lcl_0 = (rbnf_tmp_0 is None) if lcl_0: lcl_1 = builtin_tokens.offset lcl_1 = (lcl_1, 'quote type not match') lcl_1 = builtin_cons(lcl_1, builtin_nil) lcl_1 = (False, lcl_1) lcl_0 = lcl_1 else: try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 2): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_1 = _rbnf_cur_token rbnf_tmp_1 = lcl_1 lcl_1 = (rbnf_tmp_1 is None) if lcl_1: lcl_2 = builtin_tokens.offset lcl_2 = (lcl_2, 'Ident not match') lcl_2 = builtin_cons(lcl_2, builtin_nil) lcl_2 = (False, lcl_2) lcl_1 = lcl_2 else: try: _rbnf_cur_token = builtin_tokens.array[builtin_tokens.offset] if (_rbnf_cur_token.idint is 5): builtin_tokens.offset += 1 else: _rbnf_cur_token = None except IndexError: _rbnf_cur_token = None lcl_2 = _rbnf_cur_token rbnf_tmp_2 = lcl_2 lcl_2 = (rbnf_tmp_2 is None) if lcl_2: lcl_3 = builtin_tokens.offset lcl_3 = (lcl_3, 'quote = not match') lcl_3 = builtin_cons(lcl_3, builtin_nil) lcl_3 = (False, lcl_3) lcl_2 = lcl_3 else: lcl_3 = rbnf_named_parse_rbnfmacro_0(builtin_state, builtin_tokens) rbnf_named__check_3 = lcl_3 lcl_3 = rbnf_named__check_3[0] lcl_3 = (lcl_3 == False) if lcl_3: lcl_3 = rbnf_named__check_3 else: lcl_4 = rbnf_named__check_3[1] rbnf_tmp_3 = lcl_4 lcl_4 = rbnf_tmp_1.value lcl_4 = TypeSchema(lcl_4, rbnf_tmp_3) rbnf_tmp_1_ = lcl_4 lcl_4 = (True, rbnf_tmp_1_) lcl_3 = lcl_4 lcl_2 = lcl_3 lcl_1 = lcl_2 lcl_0 = lcl_1 return lcl_0 return rbnf_named_parse_START
StarcoderdataPython
3253180
import functools import contextlib def to_decorator(wrapped_func): """ Encapsulates the decorator logic for most common use cases. Expects a wrapped function with compatible type signature to: wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs) Example: @to_decorator def foo(func, args, kwargs): print(func) return func(*args, **kwargs) @foo() def bar(): print(42) """ @functools.wraps(wrapped_func) def arg_wrapper(*outer_args, **outer_kwargs): def decorator(func): @functools.wraps(func) def wrapped(*args, **kwargs): return wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs) return wrapped return decorator return arg_wrapper def g_decorator(generator_expr): """ Converts generator expression into a decorator Takes in a generator expression, such as one accepted by contextlib.contextmanager, converts it to a context manager, and returns a decorator equivalent to being within that context manager. TODO do something with yielded value Example: @g_decorator def foo(): print("Hello") yield print("World") @foo() def bar(): print("Something") """ cm = contextlib.contextmanager(generator_expr) @to_decorator def wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs): with cm(*outer_args, **outer_kwargs) as yielded: return func(*args, **kwargs) return wrapped_func
StarcoderdataPython
3326427
#Desafio 31 distancia = float(input('\033[0;35mqual é a distância da sua viagem? ')) print('\033[0;31mVocê está prestes a começar uma viagem de {:.0f}km'.format(distancia)) preco = (distancia * 0.50) preco2 = (distancia * 0.45) if distancia <= 200: print('\033[0;35msua passagem custará \033[0;33mR${:.2f}'.format(preco)) else: print('\033[0;35msua passagem custará \033[0;33mR${:.2f}'.format(preco2))
StarcoderdataPython
183534
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import Tools,config,sys, getopt if __name__ == "__main__": if len(sys.argv)<3: print("error") exit() op=sys.argv[1] task_name=sys.argv[2] if op=="-t": if task_name=="say_hello": Tools.send_to_admin("您好,这是一条测试信息") elif task_name=="status": Tools.send_to_admin("我状态很好") elif task_name=="check_conoha": Charge_C=Tools.GetConohaCharge() Status_C=Tools.GetConohaStatus() if(Charge_C<=config.Conoha_Warning_Charge): Tools.send_to_admin("你的Conoha账户余额已经小于70日元,请尽快续费!") elif Status_C!="Active" : Tools.send_to_admin("你的Conoha服务器已经停止运行,请尽快补清欠费!") elif task_name=="check_cloudcone": M=Tools.GetCloudConeInfo() if M["status"]!="online": Tools.send_to_admin("你的CloudCone账户已经停机,请尽快缴费!") elif task_name=="check_server": pass else: print("Error") exit() else: print("Error") exit()
StarcoderdataPython
4805217
<filename>101_people_counter/main_generate_training_data.py "main function, entry point for " import logging import argparse import video_source as vs import frame as f import contour as c import cv2 import time import pickle import pandas as pd import datetime import os if __name__ == "__main__": #--------------------------------------------------------------------------------------------------# # Logger & Parameter # Logger: create logger logger = logging.getLogger('training_logger') logger.setLevel(logging.DEBUG) # Logger: create file handler which logs even debug messages filehandler_debug = logging.FileHandler('../204_logs/training_debug.log') filehandler_debug.setLevel(logging.DEBUG) # Logger: create file handler which logs even debug messages filehandler_info = logging.FileHandler('../204_logs/training_info.log') filehandler_info.setLevel(logging.INFO) # Logger: create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.INFO) # Logger: create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s |') filehandler_debug.setFormatter(formatter) filehandler_info.setFormatter(formatter) ch.setFormatter(formatter) # Logger: add the handlers to the logger logger.addHandler(filehandler_debug) logger.addHandler(filehandler_info) logger.addHandler(ch) # END Logger & Parameter #--------------------------------------------------------------------------------------------------# #--------------------------------------------------------------------------------------------------# # Parse Args parser = argparse.ArgumentParser( description='Ampel2Go training module', epilog="") parser.add_argument( '-i', '--input', help="If input is given, the videofile will be used as input,"\ , default='thresh_frame_1.png') parser.add_argument( '-o', '--output', help="if this arg is given, the video is saved into output file = save file") parser.add_argument( '-c', '--customer', help="if this arg is given, the video is saved into output file = save file", required=True) parser.add_argument( '-s', '--playback_speed', help="amount of miliseconds waitingtime between each loop normal inserts waiting "\ "time between each loop", default=0) args = parser.parse_args() # END Parse Args # #--------------------------------------------------------------------------------------------------# # Only a check whether the outputfilename exists: print(args.customer) outputfilename_csv = '../109_training/observations_' + args.customer + '_csv/observations_' + os.path.basename(args.input) \ + '_' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.csv' outputfilename_pickle ='../109_training/observations_' + args.customer + '_pickle/observations_' + os.path.basename(args.input) \ + '_' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.pickle' df = pd.DataFrame() df.to_csv(outputfilename_csv, mode='a', index=False, sep=';', header=False) # start of routine video_source_instance = vs.VideoSource() video_source_instance.open_input(args.input) video_source_instance.parameter_space_instance.assign_parameter_space(args.customer, video_source_instance.frame_height) video_source_instance.create_backgroundsubstractor() FRAME_COUNT = 0 observations_by_input = [] for frame_instance in range(video_source_instance.total_frame_count): frame_instance = f.Frame() frame_instance.frame_id = args.input + '-' + str(FRAME_COUNT).rjust(6, '0') frame_instance.frame_color, last_frame = video_source_instance.get_next_frame() if last_frame: logger.info("last frame processed, over and out.") break logger.debug("Received new Frame and assigned frame_id %s", frame_instance.frame_id) frame_instance.enhance_contrast() frame_instance.subsctract_background(video_source_instance.backgroundsubstractor) frame_instance.find_contours() frame_instance.initiate_contour_instances() frame_instance.filter_contour_instances(video_source_instance.parameter_space_instance.crop_window_up\ , video_source_instance.parameter_space_instance.crop_window_down) frame_instance.calculate_contour_instances_properties() key_input = frame_instance.assign_contour_instances_labels() if key_input ==27: raise EOFError if key_input == 8: observations_by_input.pop() continue observations_by_frame = frame_instance.get_observations_by_frame() observations_by_input.extend(observations_by_frame) time.sleep(float(args.playback_speed)*0.1) FRAME_COUNT += 1 # write output into files: df = pd.DataFrame(observations_by_input) #output filename defined above, so that potential error happens befor generating the data df.to_csv(outputfilename_csv, mode='a', index=False, sep=';', header=False) with open(outputfilename_pickle,'wb') as file: pickle.dump(df, file) # with open('test.txt', 'w') as file : # file.write(str(observations_by_input)) else: raise ImportError("Run this file directly, don't import it!")
StarcoderdataPython
1635153
from pyPks.Utils.Config import getBoolOffYesNoTrueFalse as getBool from pyPks.Utils.DataBase import getTableDict def getMarketsDict( sMarketsTable ): # dConverts = dict( bHasCategories = getBool, iEbaySiteID = int, iCategoryVer = int, iUtcPlusOrMinus = int ) # setNone4Empty = ( 'cUseCategoryID', ) # dMarkets = getTableDict( sMarketsTable, 'iEbaySiteID', dConverts, setNone4Empty ) # return dMarkets
StarcoderdataPython
139071
<reponame>dlyongemallo/qflex # Lint as: python3 """ Provides utils for qFlex. """ import numpy as np import cirq import re def ComputeSchmidtRank(gate): if len(gate.qubits) == 1: return 1 if len(gate.qubits) > 2: raise AssertionError("Not yet implemented.") V, S, W = np.linalg.svd( np.reshape( np.einsum('abcd->acbd', np.reshape(cirq.unitary(gate), [2, 2, 2, 2])), [4, 4])) return sum(S != 0) def GetGridQubits(grid_stream): grid = [[y for y in x.strip() if y == '0' or y == '1'] for x in grid_stream.readlines() if len(x) and x[0] != '#'] # Get the number of rows grid_I = len(grid) # Check that the number of columns is consistent if len(set(len(x) for x in grid)) != 1: raise AssertionError("Number of columns in grid are not consistent.") # Get the number of columns grid_J = len(grid[0]) # Return cirq.GridQubit return { I * grid_J + J: cirq.GridQubit(I, J) for I in range(grid_I) for J in range(grid_J) if grid[I][J] == '1' } def GetGate(line, qubits): return GetMomentAndGate(line, qubits)[1] def GetMomentAndGate(line, qubits): # Get map from gate name to cirq gates_map = {} gates_map['h'] = cirq.H gates_map['x'] = cirq.X gates_map['z'] = cirq.Z gates_map['t'] = cirq.Z**(0.25) gates_map['x_1_2'] = cirq.X**(0.5) gates_map['y_1_2'] = cirq.Y**(0.5) gates_map['h_1_2'] = cirq.H**(0.5) gates_map['cz'] = cirq.CZ gates_map['cx'] = cirq.CNOT gates_map['rz'] = cirq.ZPowGate gates_map['hz_1_2'] = cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5) gates_map['fsim'] = cirq.FSimGate # Remove last cr line = line.strip() # Remove everything after '#' line = re.sub(r"#.*", r"", line) # Remove any special character line = re.sub(r"[^)(\s\ta-zA-Z0-9_.,-]", r"", line) # Convert tabs to spaces line = re.sub(r"[\t]", " ", line) # Remove multiple spaces line = re.sub(r"[\s]{2,}", r" ", line) # Remove last space line = re.sub(r"\s+$", r"", line) # Remove any space between a non-space char and '(' line = re.sub(r"[\s]+[(]", r"(", line) # Remove spaces between parentheses line = re.sub(r"\s+(?=[^()]*\))", r"", line) # After stripping, line should follow the format # 0 gate(p1,p2,...) q1 q2 ... # Only one open parenthesis is allowed, followed by one closed if line.count('(') == 1: if line.count(')') != 1: raise AssertionError('ERROR: Open parenthesis is not matched.') elif line.count('(') > 1: raise AssertionError('ERROR: Too many open parentheses.') elif line.count(')') != 0: raise AssertionError('ERROR: Too many close parentheses.') line = line.split() cycle = int(line[0]) gate_qubits = [int(x) for x in line[2:]] if line[1].count('('): gate_name, params = line[1].split('(') params = [float(x) for x in params.replace(')', '').split(',')] else: gate_name = line[1] params = None if not gate_name in gates_map: raise AssertionError( "ERROR: Gate {} not supported yet.".format(gate_name)) if params is None: return cycle, gates_map[gate_name](*[qubits[q] for q in gate_qubits]) else: if gate_name == "fsim": # the Cirq Fsim gate takes angles and not exponents # Transform the params params = [p * np.pi for p in params] return cycle, gates_map[gate_name]( theta=params[0], phi=params[1])(*[qubits[q] for q in gate_qubits]) if gate_name == "rz": # the Cirq Fsim gate takes angles and not exponents # Transform the params # params = [p * np.pi for p in params] return cycle, gates_map[gate_name](exponent=params[0])( qubits[gate_qubits[0]]) return cycle, gates_map[gate_name](*params)( *[qubits[q] for q in gate_qubits]) def GetCircuit(circuit_stream, qubits): circuit = cirq.Circuit() circuit.append( gate for gate in (GetGate(line, qubits) for line in circuit_stream if len(line) and len(line.strip().split()) > 1)) return circuit def GetCircuitOfMoments(file_name, qubits): with open(file_name, "r") as circuit_stream: moment_index = -1 current_moment = [] moments = [] for line in circuit_stream: if not (len(line) and len(line.strip().split()) > 1): continue parts = GetMomentAndGate(line, qubits) moment_idx_dif = int(parts[0]) - moment_index if moment_idx_dif != 0: moment_index = int(parts[0]) if len(current_moment) > 0: moments.append(cirq.Moment(current_moment)) for mi in range(moment_idx_dif - 1): # add empty moments moments.append(cirq.Moment([])) current_moment = [] current_moment.append(parts[1]) if len(current_moment) > 0: moments.append(cirq.Moment(current_moment)) return cirq.Circuit(moments=moments) def GetNumberOfQubits(cirq_circuit): """ Determine the number of qubits from an unknown Cirq circuit :param cirq_circuit: :return: """ known_qubits = {} size = 0 for operation in cirq_circuit: for qub in operation.qubits: if not qub in known_qubits: size += 1 known_qubits[qub] = size return size def GetGridQubitFromIndex(index, rows=11, cols=12): row = index // cols col = index % cols if row >= rows: raise ValueError("Wrong maximum of rows?") qub = cirq.GridQubit(row, col) return qub def GetIndexFromGridQubit(grid_qubit, rows=11, cols=12): if grid_qubit.row >= rows: raise ValueError("This GridQubit seems to have wrong row coordinate...") return grid_qubit.row * cols + grid_qubit.col
StarcoderdataPython
71539
<reponame>YasinBlackhat/read-file-csv--finde-password-0-10000<gh_stars>1-10 # my lib an valid and dict and list import csv lihash_filecsv = dict() li =[] lihash=[] countname = 0 count_csv_hash = 0 d = 1 # read file csv for crack <<<<<<< HEAD print('Example Type location : E:\\Land program\\new folder\\2.csv') locat = str(input('Enter your location file csv : ')) with open(locat) as f: ======= locate = str(input('Type or Paste location file csv : ')) with open(locate) as f: >>>>>>> 5d2287294494f8125584f9bcc7d1c77a22306ef4 reader = csv.reader(f) for row in reader: name = row[0] d += 1 for code in row[1:]: hashcode = code lihash_filecsv[name]=hashcode a = list(lihash_filecsv.keys()) b = list(lihash_filecsv.values()) #creat password list for pass_list in range(0,10000): count = pass_list hshing = str(pass_list).encode('utf-8') from hashlib import sha256 t = sha256(hshing).hexdigest() #if// for find password try : with open('E:\\Land program\\maktabkhooneh\\maktabkhooneh\\Begin\\Chapter6 (Project)\\2.csv') as s: reade_csv = csv.reader(s) for line_csv in reade_csv: if t == b[count_csv_hash]: lihash.append(t) lihash.append(count) print('Number =>=> %i' % (countname+1)) print('Name =>=> %s' % a[countname]) print('Password =>=> %i' % count) print('hash code =>=> %s' % t) print('********************') countname += 1 count_csv_hash += 1 except : print('""WooooW"" These passwords for you :) ') break <<<<<<< HEAD print('') print('My Working End**') ======= >>>>>>> 5d2287294494f8125584f9bcc7d1c77a22306ef4
StarcoderdataPython
3214824
import re import sys import logging import logging.handlers from pygments.lexer import RegexLexer, include from pygments.token import (Punctuation, Text, Comment, Keyword, Name, String, Generic, Operator, Number, Whitespace, Literal, Error, Token) from pygments import highlight from pygments.formatters import get_formatter_by_name from pygments.style import Style class LogStyle(Style): background_color = "#000000" highlight_color = "#222222" default_style = "#cccccc" styles = { Token: "#cccccc", Whitespace: "", Comment: "#000080", Comment.Preproc: "", Comment.Special: "bold #2BB537", Keyword: "#cdcd00", Keyword.Declaration: "#00cd00", Keyword.Namespace: "#cd00cd", Keyword.Pseudo: "bold #00cd00", Keyword.Type: "#00cd00", Operator: "#3399cc", Operator.Word: "#cdcd00", Name: "", Name.Class: "#00cdcd", Name.Builtin: "#cd00cd", Name.Exception: "bold #666699", Name.Variable: "#00cdcd", String: "#cd0000", Number: "#cd00cd", Punctuation: "nobold #FFF", Generic.Heading: "nobold #FFF", Generic.Subheading: "#800080", Generic.Deleted: "nobold #cd3", Generic.Inserted: "#00cd00", Generic.Error: "bold #FF0000", Generic.Emph: "bold #FFFFFF", Generic.Strong: "bold #FFFFFF", Generic.Prompt: "bold #3030F0", Generic.Output: "#888", Generic.Traceback: "bold #04D", Error: "bg:#FF0000 bold #FFF" } class LogLexer(RegexLexer): name = 'Logging.py Logs' aliases = ['log'] filenames = ['*.log'] mimetypes = ['text/x-log'] flags = re.VERBOSE _logger = r'-\s(peri)(\.([a-z._\-0-9]+))*\s-' _uuid = r"([A-Z]{2}_[0-9]{12}_[0-9]{3}-and-[A-Z]{2}_[0-9]{12}_[0-9]{3}-[0-9]{5,})" _kimid = r"((?:[_a-zA-Z][_a-zA-Z0-9]*?_?_)?[A-Z]{2}_[0-9]{12}(?:_[0-9]{3})?)" _path = r'(?:[a-zA-Z0-9_-]{0,}/{1,2}[a-zA-Z0-9_\.-]+)+' _debug = r'DEBUG' _info = r'INFO' _pass = r'PASS' _warn = r'WARNING' _error = r'ERROR' _crit = r'CRITICAL' _date = r'\d{4}-\d{2}-\d{2}' _time = r'\d{2}:\d{2}:\d{2},\d{3}' _ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+' _json = r'{.*}' tokens = { 'whitespace': [ (_ws, Text), (r'\n', Text), (r'\s+', Text), (r'\\\n', Text), (r'\s-\s', Text) ], 'root': [ include('whitespace'), (_uuid, Comment.Special), (_kimid, Generic.Prompt), (_logger, Generic.Emph), (_date, Generic.Output), (_time, Generic.Output), (_path, Generic.Subheading), (_json, Generic.Deleted), (_warn, Generic.Strong), (_info, Generic.Traceback), (_error, Generic.Error), (_pass, Keyword.Pseudo), (_crit, Error), (r'[0-9]+', Generic.Heading), ('[a-zA-Z_][a-zA-Z0-9_]*', Generic.Heading), (r'[{}`()\"\[\]@.,:-\\]', Punctuation), (r'[~!%^&*+=|?:<>/-]', Punctuation), (r"'", Punctuation) ] } lexer = LogLexer() def pygmentize(text, formatter='256', outfile=sys.stdout, style=LogStyle): fmtr = get_formatter_by_name(formatter, style=style) highlight(text, lexer, fmtr, outfile) class PygmentHandler(logging.StreamHandler): """ A beanstalk logging handler """ def __init__(self): super(PygmentHandler,self).__init__() def emit(self,record): """ Send the message """ err_message = self.format(record) pygmentize(err_message)
StarcoderdataPython
113289
<reponame>CuchulainX/dffml import asyncio from .asynchelper import concurrently async def run_command(cmd, logger=None, **kwargs): r""" Run a command using :py:func:`asyncio.create_subprocess_exec`. If ``logger`` is supplied, write stdout and stderr to logger debug. ``kwargs`` are passed to :py:func:`asyncio.create_subprocess_exec`, except for stdout and stderr which are pipes used for logging. Examples -------- >>> import sys >>> import asyncio >>> import logging >>> >>> import dffml >>> >>> logging.basicConfig(level=logging.DEBUG) >>> logger = logging.getLogger("mylogger") >>> >>> asyncio.run(dffml.run_command([ ... sys.executable, "-c", "print('Hello World')" ... ], logger=logger)) You should see "Hello World" in the logging output .. code-block:: DEBUG:asyncio:Using selector: EpollSelector DEBUG:mylogger:Running ['/usr/bin/python3.7', '-c', "print('Hello World')"], {'stdout': -1, 'stderr': -1} DEBUG:mylogger:['/usr/bin/python3.7', '-c', "print('Hello World')"]: stdout.readline: Hello World DEBUG:mylogger:['/usr/bin/python3.7', '-c', "print('Hello World')"]: stderr.readline: """ kwargs = { "stdout": asyncio.subprocess.PIPE, "stderr": asyncio.subprocess.PIPE, **kwargs, } if logger is not None: logger.debug(f"Running {cmd}, {kwargs}") proc = await asyncio.create_subprocess_exec(*cmd, **kwargs) work = { asyncio.create_task(proc.wait()): "wait", } for output in ["stdout", "stderr"]: if output in kwargs and kwargs[output] is asyncio.subprocess.PIPE: coro = getattr(proc, output).readline() task = asyncio.create_task(coro) work[task] = f"{output}.readline" output = [] async for event, result in concurrently(work): if event.endswith("readline"): # Log line read if logger is not None: logger.debug(f"{cmd}: {event}: {result.decode().rstrip()}") # Append to output in case of error output.append(result) # Read another line if that's the event coro = getattr(proc, event.split(".")[0]).readline() task = asyncio.create_task(coro) work[task] = event else: # When wait() returns process has exited break if proc.returncode != 0: raise RuntimeError(repr(cmd) + ": " + b"\n".join(output).decode())
StarcoderdataPython
1758810
<reponame>jumaamohammed/404 import urllib.request as foOfo import urllib.error as oohhh import base64, time, socket, os import subprocess from subprocess import (PIPE, Popen) check = '' ip = '172.16.176.156' class four0four: def __init__(self): self.url = 'http://172.16.176.156/pop.html' self.opsys = os.name def nt(self,y): cmd_result='' z=str(base64.b64decode(y))[2:-1] attack = "powershell -nop -win hidden -noni -enc " + base64.b64encode(z.encode('utf_16_le')).decode('utf-8') print(attack) result = (Popen(attack, stdout=PIPE, shell=True).stdout.read()) try: sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) sock.connect((ip, 31337)) print('Sending request') sock.send(result) except: pass result = str(result)[2:-1] cln = result.split('\\r\\n') for i in cln: cmd_result+=i+'\n' return cmd_result def posix(self,y): cmd_result='' z=str(base64.b64decode(y))[2:-1] print(z) x=z.split(' ') output = subprocess.check_output(x) try: sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) sock.connect((ip, 31337)) print('Sending request') sock.send(output) except: pass result = str(output)[2:-1] cln = result.split('\\n') for i in cln: cmd_result+=i+'\n' return cmd_result f0f = four0four() while True: x='' try: foOfo.urlopen(f0f.url) except oohhh.HTTPError as e: x=str(e.read()) if len(x)==0: exit() try: y=((x.split('HTMLDOC'))[1].split('HTMLDOC')[0]) if check == y: pass else: check = y if f0f.opsys == 'nt': f0f_result=f0f.nt(y) else: f0f_result=f0f.posix(y) except: pass time.sleep(5)
StarcoderdataPython
143768
<filename>tests/conftest.py # Copyright (c) 2021 Food-X Technologies # # This file is part of foodx_devops_tools. # # You should have received a copy of the MIT License along with # foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>. import copy import pathlib import typing import unittest.mock import pydantic import pytest from asynctest import CoroutineMock from foodx_devops_tools.pipeline_config import PipelineConfiguration from foodx_devops_tools.pipeline_config.views import ( DeploymentContext, ReleaseView, ) from tests.ci.support.pipeline_config import MOCK_RESULTS, MOCK_TO @pytest.fixture() def mock_verify_puff_target(mocker): mocker.patch("foodx_devops_tools.utilities.templates._verify_puff_target") @pytest.fixture() def mock_run_puff_check(mock_async_method): mock_async_method("foodx_devops_tools.utilities.templates.run_puff") @pytest.fixture() def mock_apply_template(mock_async_method): mock_async_method("foodx_devops_tools.utilities.templates._apply_template") @pytest.fixture def apply_pipeline_config_test(mocker): def _apply( mock_content: str, method_under_test: typing.Callable[[pathlib.Path], pydantic.BaseModel], ): mock_path = mocker.create_autospec(pathlib.Path)("some/path") mock_path.open = mocker.mock_open(read_data=mock_content) result = method_under_test(mock_path) return result return _apply @pytest.fixture def mock_pipeline_config(): def _apply(mock_data=copy.deepcopy(MOCK_RESULTS)) -> PipelineConfiguration: return PipelineConfiguration.parse_obj(mock_data) return _apply @pytest.fixture() def mock_flattened_deployment(mock_pipeline_config): base_context = DeploymentContext( commit_sha="abc123", git_ref="refs/heads/this/branch", pipeline_id="123456", release_id="3.1.4+local", release_state="r1", ) pipeline_state = ReleaseView(mock_pipeline_config(), base_context) mock_flattened = pipeline_state.flatten(MOCK_TO) return copy.deepcopy(mock_flattened) @pytest.fixture() def mock_async_method(mocker): def _apply( path_to_mock: str, return_value: typing.Optional[typing.Any] = None, side_effect: typing.Optional[typing.Any] = None, ): async_mock = unittest.mock.AsyncMock( return_value=return_value, side_effect=side_effect ) this_mock = mocker.patch(path_to_mock, side_effect=async_mock) return this_mock return _apply @pytest.fixture() def mock_context(mocker): def _apply(path_to_mock: str): this_mock = mocker.patch(path_to_mock) this_mock.return_value.__aenter__.return_value.write = CoroutineMock() return this_mock return _apply @pytest.fixture() def mock_puff_mkdirs(mocker): mocker.patch("foodx_devops_tools.puff.arm.os.makedirs")
StarcoderdataPython
1760052
<reponame>tbeckham/eutester<gh_stars>0 import unittest import inspect import time import gc import argparse import re import sys import os import types import traceback import random import string from eutester.eulogger import Eulogger from eutester.euconfig import EuConfig import StringIO import copy from eutester.timer import Timer import uuid ''' This is the base class for any test case to be included in the Eutester repo. It should include any functionality that we expected to be repeated in most of the test cases that will be written. Currently included: - Debug method - Allow parameterized test cases - Method to run test case - Run a list of test cases - Start, end and current status messages - Enum class for possible test results Necessary to work on: - Argument parsing - Metric tracking (need to define what metrics we want - Standardized result summary - Logging standardization - Use docstring as description for test case - Standardized setUp and tearDown that provides useful/necessary cloud resources (ie group, keypair, image) ''' class EutesterTestResult(): ''' standardized test results ''' not_run="not_run" passed="passed" failed="failed" class TestColor(): reset = '\033[0m' #formats formats={'reset':'0', 'bold':'1', 'dim':'2', 'uline':'4', 'blink':'5', 'reverse':'7', 'hidden':'8', } foregrounds = {'black':30, 'red':31, 'green':32, 'yellow':33, 'blue':34, 'magenta':35, 'cyan':36, 'white':37, 'setasdefault':39} backgrounds = {'black':40, 'red':41, 'green':42, 'yellow':43, 'blue':44, 'magenta':45, 'cyan':46, 'white':47, 'setasdefault':49} #list of canned color schemes, for now add em as you need 'em? canned_colors ={'reset' : '\033[0m', #self.TestColor.get_color(fg=0) 'whiteonblue' : '\33[1;37;44m', #get_color(fmt=bold, fg=37,bg=44) 'whiteongreen' : '\33[1;37;42m', 'red' : '\33[31m', #TestColor.get_color(fg=31) 'failred' : '\033[31m', #TestColor.get_color(fg=31) 'blueongrey' : '\33[1;34;47m', #TestColor.get_color(fmt=bold, fg=34, bg=47)#'\33[1;34;47m' 'redongrey' : '\33[1;31;47m', #TestColor.get_color(fmt=bold, fg=31, bg=47)#'\33[1;31;47m' 'blinkwhiteonred' : '\33[1;5;37;41m', #TestColor.get_color(fmt=[bold,blink],fg=37,bg=41)# } @classmethod def get_color(cls,fmt=0,fg='', bg=''): ''' Description: Method to return ascii color codes to format terminal output. Examples: blinking_red_on_black = get_color('blink', 'red', 'blue') bold_white_fg = get_color('bold', 'white, '') green_fg = get_color('','green','') print bold_white_fg+"This text is bold white"+TestColor.reset :type fmt: color attribute :param fmt: An integer or string that represents an ascii color attribute. see TestColor.formats :type fg: ascii foreground attribute :param fg: An integer or string that represents an ascii foreground color attribute. see TestColor.foregrounds :type bg: ascii background attribute :param bg: An integer or string that represents an ascii background color attribute. see TestColor.backgrounds ''' fmts='' if not isinstance(fmt, types.ListType): fmt = [fmt] for f in fmt: if isinstance(f,types.StringType): f = TestColor.get_format_from_string(f) if f: fmts += str(f)+';' if bg: if isinstance(bg,types.StringType): bg = TestColor.get_bg_from_string(bg) if bg: bg = str(bg) if fg: if isinstance(fg,types.StringType): fg = TestColor.get_fg_from_string(fg) if fg: fg = str(fg)+';' return '\033['+str(fmts)+str(fg)+str(bg)+'m' @classmethod def get_format_from_string(cls,format): if format in TestColor.formats: return TestColor.formats[format] else: return '' @classmethod def get_fg_from_string(cls,fg): if fg in TestColor.foregrounds: return TestColor.foregrounds[fg] else: return '' @classmethod def get_bg_from_string(cls,bg): if bg in TestColor.backgrounds: return TestColor.backgrounds[bg] else: return '' @classmethod def get_canned_color(cls,color): try: return TestColor.canned_colors[color] except: return "" class EutesterTestUnit(): ''' Description: Convenience class to run wrap individual methods, and run and store and access results. type method: method param method: The underlying method for this object to wrap, run and provide information on type args: list of arguments param args: the arguments to be fed to the given 'method' type eof: boolean param eof: boolean to indicate whether a failure while running the given 'method' should end the test case exectution. ''' def __init__(self,method, *args, **kwargs): self.method = method self.method_possible_args = EutesterTestCase.get_meth_arg_names(self.method) self.args = args self.kwargs = kwargs self.name = str(method.__name__) self.result=EutesterTestResult.not_run self.time_to_run=0 if self.kwargs.get('html_anchors', False): if not 'html_anchors' in self.method_possible_args: self.kwargs.pop('html_anchors') self.anchor_id = str(str(time.ctime()) + self.name + "_" + str( ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(3))) + "_" ).replace(" ","_") self.error_anchor_id = "ERROR_" + self.anchor_id self.description=self.get_test_method_description() self.eof=False self.error = "" print "Creating testunit:" + str(self.name)+", args:" for count, thing in enumerate(args): print '{0}. {1}'.format(count, thing) for name, value in kwargs.items(): print '{0} = {1}'.format(name, value) @classmethod def create_testcase_from_method(cls, method, eof=False, *args, **kwargs): ''' Description: Creates a EutesterTestUnit object from a method and set of arguments to be fed to that method type method: method param method: The underlying method for this object to wrap, run and provide information on type args: list of arguments param args: the arguments to be fed to the given 'method' ''' testunit = EutesterTestUnit(method, args, kwargs) testunit.eof = eof return testunit def set_kwarg(self,kwarg,val): self.kwargs[kwarg]=val def get_test_method_description(self): ''' Description: Attempts to derive test unit description for the registered test method. Keys off the string "Description:" preceded by any amount of white space and ending with either a blank line or the string "EndDescription". This is used in debug output when providing info to the user as to the method being run as a testunit's intention/description. ''' desc = "\nMETHOD:"+str(self.name) + ", TEST DESCRIPTION:\n" ret = [] add = False try: doc = str(self.method.__doc__) if not doc or not re.search('Description:',doc): try: desc = desc+"\n".join(self.method.im_func.func_doc.title().splitlines()) except:pass return desc has_end_marker = re.search('EndDescription', doc) for line in doc.splitlines(): line = line.lstrip().rstrip() if re.search('^Description:',line.lstrip()): add = True if not has_end_marker: if not re.search('\w',line): if add: break add = False else: if re.search('^EndDescription'): add = False break if add: ret.append(line) except Exception, e: print('get_test_method_description: error'+str(e)) if ret: desc = desc+"\n".join(ret) return desc def run(self, eof=None): ''' Description: Wrapper which attempts to run self.method and handle failures, record time. ''' if eof is None: eof = self.eof for count, thing in enumerate(self.args): print 'ARG:{0}. {1}'.format(count, thing) for name, value in self.kwargs.items(): print 'KWARG:{0} = {1}'.format(name, value) try: start = time.time() if not self.args and not self.kwargs: ret = self.method() else: ret = self.method(*self.args, **self.kwargs) self.result=EutesterTestResult.passed return ret except SkipTestException, se: print TestColor.get_canned_color('failred') + \ "TESTUNIT SKIPPED:" + str(self.name) + "\n" + str(se) + TestColor.reset self.error = str(se) self.result = EutesterTestResult.not_run except Exception, e: buf = '\nTESTUNIT FAILED: ' + self.name if self.kwargs.get('html_anchors',False): buf += "<font color=red> Error in test unit '" + self.name + "':\n" out = StringIO.StringIO() traceback.print_exception(*sys.exc_info(),file=out) out.seek(0) buf += out.read() if self.kwargs.get('html_anchors',False): buf += ' </font>' print '<a name="' + str(self.error_anchor_id) + '"></a>' print TestColor.get_canned_color('failred') + buf + TestColor.reset self.error = str(e) self.result = EutesterTestResult.failed if eof: raise e else: pass finally: self.time_to_run = int(time.time()-start) class EutesterTestCase(unittest.TestCase): color = TestColor() def __init__(self,name=None, debugmethod=None, log_level='debug', logfile=None, logfile_level='debug'): return self.setuptestcase(name=name, debugmethod=debugmethod, logfile=logfile, logfile_level=logfile_level) def setuptestcase(self, name=None, debugmethod=None, use_default_file=False, default_config='eutester.conf', log_level='debug', logfile=None, logfile_level='debug'): self.name = self._testMethodName = name self.log_level = log_level self.logfile = logfile self.logfile_level = logfile_level if not self.name: callerfilename=inspect.getouterframes(inspect.currentframe())[1][1] self.name = os.path.splitext(os.path.basename(callerfilename))[0] self._testMethodName = self.name print "setuptestname:"+str(name) if not hasattr(self,'args'): self.args=argparse.Namespace() self.debugmethod = debugmethod if not self.debugmethod: self.setup_debugmethod(logfile=self.logfile, logfile_level=self.logfile_level) #For QA output add preformat tag self.debug('<pre>') if not hasattr(self,'testlist'): self.testlist = [] self.list = None if not hasattr(self,'configfiles'): self.configfiles=[] self.default_config = default_config self.use_default_file = use_default_file if use_default_file: #first add $USERHOME/.eutester/eutester.conf if it exists self.default_config=self.get_default_userhome_config(fname=default_config) if self.default_config: self.configfiles.append(self.default_config) self.show_self() def compile_all_args(self): self.setup_parser() self.get_args() def setup_parser(self, testname=None, description=None, emi=True, zone=True, vmtype=True, keypair=True, credpath=True, password=<PASSWORD>, config=True, configblocks=True, ignoreblocks=True, color=True, testlist=True, userdata=True, instance_user=True, stdout_log_level=True, logfile_level=True, logfile=True, instance_password=True, region=True): ''' Description: Convenience method to setup argparse parser and some canned default arguments, based upon the boolean values provided. For each item marked as 'True' this method will add pre-defined command line arguments, help strings and default values. This will then be available by the end script as an alternative to recreating these items on a per script bassis. :type testname: string :param testname: Name used for argparse (help menu, etc.) :type description: string :param description: Description used for argparse (help menu, etc.) :type emi: boolean :param emi: Flag to present the emi command line argument/option for providing an image emi id via the cli :type zone: boolean :param zone: Flag to present the zone command line argument/option for providing a zone via the cli :type vmtype: boolean :param vmtype: Flag to present the vmtype command line argument/option for providing a vmtype via the cli :type keypair: boolean :param kepair: Flag to present the keypair command line argument/option for providing a keypair via the cli :type credpath: boolean :param credpath: Flag to present the credpath command line argument/option for providing a local path to creds via the cli :type password: boolean :param password: Flag to present the password command line argument/option for providing password used in establishing machine ssh sessions :type config: boolean :param config: Flag to present the config file command line argument/option for providing path to config file :type configblocks: string list :param configblocks: Flag to present the configblocks command line arg/option used to provide list of configuration blocks to read from Note: By default if a config file is provided the script will only look for blocks; 'globals', and the filename of the script being run. :type ignoreblocks: string list :param ignoreblocks: Flag to present the configblocks command line arg/option used to provide list of configuration blocks to ignore if present in configfile Note: By default if a config file is provided the script will look for blocks; 'globals', and the filename of the script being run :type testlist: string list :param testlist: Flag to present the testlist command line argument/option for providing a list of testnames to run :type userdata: boolean :param userdata: Flag to present the userdata command line argument/option for providing userdata to instance(s) within test :type instance_user: boolean :param instance_user: Flag to present the instance_user command line argument/option for providing an ssh username for instance login via the cli :type instance_password: boolean :param instance_password: Flag to present the instance_password command line argument/option for providing a ssh password for instance login via the cli :type use_color: flag :param use_color: Flag to enable/disable use of ascci color codes in debug output. :param stdout_log_level: boolean flag to present the --log_leveel command line option to set stdout log level :param logfile_level: boolean flag to present the --logfile_level command line option to set the log file log level :param logfile: boolean flag to present the --logfile command line option to set the log file path to log to :param region: boolean flag to present the --region command line option to set the region for the test to use ''' testname = testname or self.name description = description or "Test Case Default Option Parser Description" #create parser parser = argparse.ArgumentParser( prog=testname, description=description) #add some typical defaults: if emi: parser.add_argument('--emi', help="pre-installed emi id which to execute these tests against", default=None) if credpath: parser.add_argument('--credpath', help="path to credentials", default=None) if password: parser.add_argument('--password', help="password to use for machine root ssh access", default=None) if config: parser.add_argument('--config', help='path to config file', default=None) if configblocks: parser.add_argument('--configblocks', nargs='+', help="Config sections/blocks in config file to read in", default=[]) if ignoreblocks: parser.add_argument('--ignoreblocks', nargs='+', help="Config blocks to ignore, ie:'globals', 'my_scripts_name', etc..", default=[]) if testlist: parser.add_argument('--tests', nargs='+', help="test cases to be executed", default = []) if keypair: parser.add_argument('--keypair', help="Keypair to use in this test", default=None) if zone: parser.add_argument('--zone', help="Zone to use in this test", default=None) if vmtype: parser.add_argument('--vmtype', help="Virtual Machine Type to use in this test", default='c1.medium') if userdata: parser.add_argument('--user-data', help="User data string to provide instance run within this test", default=None) if instance_user: parser.add_argument('--instance-user', help="Username used for ssh login. Default:'root'", default='root') if instance_password: parser.add_argument('--instance-password', help="Password used for ssh login. When value is 'None' ssh keypair will be used and not username/password, default:'None'", default=None) if region: parser.add_argument('--region', help="Use AWS region instead of Eucalyptus", default=None) if color: parser.add_argument('--use_color', dest='use_color', action='store_true', default=False) if stdout_log_level: parser.add_argument('--log_level', help="log level for stdout logging", default='debug') if logfile: parser.add_argument('--logfile', help="file path to log to (in addtion to stdout", default=None) if logfile_level: parser.add_argument('--logfile_level', help="log level for log file logging", default='debug') parser.add_argument('--html-anchors', dest='html_anchors', action='store_true', help="Print HTML anchors for jumping through test results", default=False) self.parser = parser return parser def disable_color(self): self.set_arg('use_color', False) self.use_color = False os.environ['EUTESTER_FORCE_ANSI_ESCAPE'] = 'False' def enable_color(self): self.set_arg('use_color', True) self.use_color = True os.environ['EUTESTER_FORCE_ANSI_ESCAPE'] = 'True' def setup_debugmethod(self, testcasename=None, log_level=None, logfile=None, logfile_level=None): print "setup_debugmethod: \ntestcasename:"+ str(testcasename) \ + '\nlog_level:'+str(log_level) \ + '\nlogfile:' +str(logfile) \ + '\nlogfile_level:' +str(logfile_level) name = testcasename or self.name if not logfile and self.has_arg('logfile'): logfile = self.args.logfile logfile = logfile or self.logfile if self.has_arg('logfile_level'): logfile_level = self.args.logfile_level logfile_level = logfile_level or self.logfile_level or 'debug' if not log_level and self.has_arg('log_level'): log_level = self.args.log_level log_level = log_level or self.log_level or 'debug' print "Starting setup_debugmethod, name:"+str(name) print "After populating... setup_debugmethod: testcasename:"+ str(testcasename) \ + 'log_level:'+str(log_level) \ + 'logfile:' +str(logfile) \ + 'logfile_level:' +str(logfile_level) if not name: if hasattr(self,'name'): if isinstance(self.name, types.StringType): name = self.name else: name = 'EutesterTestCase' self.logger = Eulogger(identifier=str(name),stdout_level=log_level, logfile=logfile, logfile_level='debug') self.debugmethod = self.logger.log.debug if not self.has_arg('logger'): self.add_arg('logger',self.logger) if not self.has_arg('debug_method'): self.add_arg('debug_method', self.debug) def debug(self,msg,traceback=1,color=None, linebyline=True): ''' Description: Method for printing debug type msg: string param msg: Mandatory string buffer to be printed in debug message type traceback: integer param traceback: integer value for what frame to inspect to derive the originating method and method line number type color: TestColor color param color: Optional ascii text color scheme. See TestColor for more info. ''' try: if not self.debugmethod: self.setup_debugmethod() except: self.setup_debugmethod() if self.has_arg("use_color"): self.use_color = bool(self.args.use_color) else: self.use_color = False colorprefix="" colorreset="" #if a color was provide if color and self.use_color: colorprefix = TestColor.get_canned_color(color) or color colorreset = str(TestColor.get_canned_color('reset')) msg = str(msg) curframe = None curframe = inspect.currentframe(traceback) lineno = curframe.f_lineno self.curframe = curframe frame_code = curframe.f_code frame_globals = curframe.f_globals functype = type(lambda: 0) funcs = [] for func in gc.get_referrers(frame_code): if type(func) is functype: if getattr(func, "func_code", None) is frame_code: if getattr(func, "func_globals", None) is frame_globals: funcs.append(func) if len(funcs) > 1: return None cur_method= funcs[0].func_name if funcs else "" if linebyline: for line in msg.split("\n"): self.debugmethod("("+str(cur_method)+":"+str(lineno)+"): "+colorprefix+line.strip()+colorreset ) else: self.debugmethod("("+str(cur_method)+":"+str(lineno)+"): "+colorprefix+str(msg)+colorreset ) def run_test_list_by_name(self, list, eof=None): unit_list = [] for test in list: unit_list.append( self.create_testunit_by_name(test) ) ### Run the EutesterUnitTest objects return self.run_test_case_list(unit_list,eof=eof) def create_testunit_from_method(self,method, *args, **kwargs): ''' Description: Convenience method calling EutesterTestUnit. Creates a EutesterTestUnit object from a method and set of arguments to be fed to that method :type method: method :param method: The underlying method for this object to wrap, run and provide information on :type eof: boolean :param eof: Boolean to indicate whether this testunit should cause a test list to end of failure :type autoarg: boolean :param autoarg: Boolean to indicate whether to autopopulate this testunit with values from global testcase.args :type args: list of positional arguments :param args: the positional arguments to be fed to the given testunit 'method' :type kwargs: list of keyword arguements :param kwargs: list of keyword :rtype: EutesterTestUnit :returns: EutesterTestUnit object ''' eof=False autoarg=True methvars = self.get_meth_arg_names(method) #Pull out value relative to this method, leave in any that are intended to be passed through if 'autoarg' in kwargs: if 'autoarg' in methvars: autoarg = kwargs['autoarg'] else: autoarg = kwargs.pop('autoarg') if 'eof' in kwargs: if 'eof' in methvars: eof = kwargs['eof'] else: eof = kwargs.pop('eof') ## Only pass the arg if we need it otherwise it will print with all methods/testunits if self.args.html_anchors: testunit = EutesterTestUnit(method, *args, html_anchors=self.args.html_anchors ,**kwargs) else: testunit = EutesterTestUnit(method, *args, **kwargs) testunit.eof = eof #if autoarg, auto populate testunit arguements from local testcase.args namespace values if autoarg: self.populate_testunit_with_args(testunit) return testunit def status(self,msg,traceback=2, b=1,a=0 ,testcolor=None): ''' Description: Convenience method to format debug output :type msg: string :param msg: The string to be formated and printed via self.debug :type traceback: integer :param traceback: integer value for what frame to inspect to derive the originating method and method line number :type b: integer :param b:number of blank lines to print before msg :type a: integer :param a:number of blank lines to print after msg :type testcolor: TestColor color :param testcolor: Optional TestColor ascii color scheme ''' alines = "" blines = "" for x in xrange(0,b): blines=blines+"\n" for x in xrange(0,a): alines=alines+"\n" line = "-------------------------------------------------------------------------" out = blines+line+"\n"+msg+"\n"+line+alines self.debug(out, traceback=traceback, color=testcolor,linebyline=False) def startmsg(self,msg=""): self.status(msg, traceback=3,testcolor=TestColor.get_canned_color('whiteonblue')) def endtestunit(self,msg=""): msg = "- UNIT ENDED - " + msg self.status(msg, traceback=2,a=1, testcolor=TestColor.get_canned_color('whiteongreen')) def errormsg(self,msg=""): msg = "- ERROR - " + msg self.status(msg, traceback=2,a=1,testcolor=TestColor.get_canned_color('failred')) def endfailure(self,msg="" ): msg = "- FAILED - " + msg self.status(msg, traceback=2,a=1,testcolor=TestColor.get_canned_color('failred')) def resultdefault(self,msg,printout=True,color='blueongrey'): if printout: self.debug(msg,traceback=2,color=TestColor.get_canned_color('blueongrey'),linebyline=False) msg = self.format_line_for_color(msg, color) return msg def resultfail(self,msg,printout=True, color='redongrey'): if printout: self.debug(msg,traceback=2, color=TestColor.get_canned_color('redongrey'),linebyline=False) msg = self.format_line_for_color(msg, color) return msg def resulterr(self,msg,printout=True,color='failred'): if printout: self.debug(msg,traceback=2, color=TestColor.get_canned_color(color),linebyline=False) msg = self.format_line_for_color(msg, color) return msg def format_line_for_color(self,msg,color): if not self.use_color: return msg end="" if msg.endswith('\n'): msg = msg.rstrip() end="\n" msg = TestColor.get_canned_color(color)+str(msg)+TestColor.reset+end return msg def get_pretty_args(self,testunit): ''' Description: Returns a string buf containing formated arg:value for printing later :type: testunit: Eutestcase.eutestertestunit object :param: testunit: A testunit object for which the namespace args will be used :rtype: string :returns: formated string containing args and their values. ''' buf = "\nEnd on Failure:" +str(testunit.eof) buf += "\nPassing ARGS:" if not testunit.args and not testunit.kwargs: buf += '\"\"\n' else: buf += "\n---------------------\n" varnames = self.get_meth_arg_names(testunit.method) if testunit.args: for count,arg in enumerate(testunit.args): buf += str(varnames[count+1])+" : "+str(arg)+"\n" if testunit.kwargs: for key in testunit.kwargs: buf += str(key)+" : "+str(testunit.kwargs[key])+"\n" buf += "---------------------\n" return buf def run_test_case_list(self, list, eof=False, clean_on_exit=True, printresults=True): ''' Desscription: wrapper to execute a list of ebsTestCase objects :type list: list :param list: list of EutesterTestUnit objects to be run :type eof: boolean :param eof: Flag to indicate whether run_test_case_list should exit on any failures. If this is set to False it will exit only when a given EutesterTestUnit fails and has it's eof flag set to True. :type clean_on_exit: boolean :param clean_on_exit: Flag to indicate if clean_on_exit should be ran at end of test list execution. :type printresults: boolean :param printresults: Flag to indicate whether or not to print a summary of results upon run_test_case_list completion. :rtype: integer :returns: integer exit code to represent pass/fail of the list executed. ''' self.testlist = list start = time.time() tests_ran=0 test_count = len(list) t = Timer("/tmp/eutester_" + str(uuid.uuid4()).replace("-", "")) try: for test in list: tests_ran += 1 self.print_test_unit_startmsg(test) try: id = t.start() test.run(eof=eof or test.eof) t.end(id, str(test.name)) except Exception, e: self.debug('Testcase:'+ str(test.name)+' error:'+str(e)) if eof or (not eof and test.eof): self.endfailure(str(test.name)) raise e else: self.endfailure(str(test.name)) else: self.endtestunit(str(test.name)) self.debug(self.print_test_list_short_stats(list)) finally: elapsed = int(time.time()-start) msgout = "RUN TEST CASE LIST DONE:\n" msgout += "Ran "+str(tests_ran)+"/"+str(test_count)+" tests in "+str(elapsed)+" seconds\n" t.finish() if printresults: try: self.debug("Printing pre-cleanup results:") msgout += self.print_test_list_results(list=list,printout=False) self.status(msgout) except:pass try: if clean_on_exit: cleanunit = self.create_testunit_from_method(self.clean_method) list.append(cleanunit) try: self.print_test_unit_startmsg(cleanunit) cleanunit.run() except Exception, e: out = StringIO.StringIO() traceback.print_exception(*sys.exc_info(),file=out) out.seek(0) self.debug("Failure in cleanup: " + str(e) + "\n" + out.read()) if printresults: msgout = self.print_test_list_results(list=list,printout=False) self.status(msgout) except: pass self.testlist = copy.copy(list) passed = 0 failed = 0 not_run = 0 for test in list: if test.result == EutesterTestResult.passed: passed += 1 if test.result == EutesterTestResult.failed: failed += 1 if test.result == EutesterTestResult.not_run: not_run += 1 total = passed + failed + not_run print "passed:"+str(passed)+" failed:" + str(failed) + " not_run:" + str(not_run) + " total:"+str(total) if failed: return(1) else: return(0) def print_test_unit_startmsg(self,test): startbuf = '' if self.args.html_anchors: link = '<a name="' + str(test.anchor_id) + '"></a>\n' startbuf += '<div id="myDiv" name="myDiv" title="Example Div Element" style="color: #0900C4; font: Helvetica 12pt;border: 1px solid black;">' startbuf += str(link) startbuf += "STARTING TESTUNIT: " + test.name argbuf = self.get_pretty_args(test) startbuf += str(test.description)+str(argbuf) startbuf += 'Running list method: "'+str(self.print_testunit_method_arg_values(test))+'"' if self.args.html_anchors: startbuf += '\n </div>' self.startmsg(startbuf) def has_arg(self,arg): ''' Description: If arg is present in local testcase args namespace, will return True, else False :type arg: string :param arg: string name of arg to check for. :rtype: boolean :returns: True if arg is present, false if not ''' arg = str(arg) if hasattr(self,'args'): if self.args and (arg in self.args): return True return False def get_arg(self,arg): ''' Description: Fetchs the value of an arg within the local testcase args namespace. If the arg does not exist, None will be returned. :type arg: string :param arg: string name of arg to get. :rtype: value :returns: Value of arguement given, or None if not found ''' if self.has_arg(arg): return getattr(self.args,str(arg)) return None def add_arg(self,arg,value): ''' Description: Adds an arg 'arg' within the local testcase args namespace and assigns it 'value'. If arg exists already in testcase.args, then an exception will be raised. :type arg: string :param arg: string name of arg to set. :type value: value :param value: value to set arg to ''' if self.has_arg(arg): raise Exception("Arg"+str(arg)+'already exists in args') else: self.args.__setattr__(arg,value) def set_arg(self,arg, value): ''' Description: Sets an arg 'arg' within the local testcase args namespace to 'value'. If arg does not exist in testcase.args, then it will be created. :type arg: string :param arg: string name of arg to set. :type value: value :param value: value to set arg to ''' if self.has_arg(arg): new = argparse.Namespace() for val in self.args._get_kwargs(): if arg != val[0]: new.__setattr__(val[0],val[1]) new.__setattr__(arg,value) self.args = new else: self.args.__setattr__(arg,value) def clean_method(self): raise Exception("Clean_method was not implemented. Was run_list using clean_on_exit?") def print_test_list_results(self,list=None, printout=True, printmethod=None): ''' Description: Prints a formated list of results for a list of EutesterTestUnits :type list: list :param list: list of EutesterTestUnits :type printout: boolean :param printout: boolean to flag whether to print using printmethod or self.debug, or to return a string buffer representing the results output :type printmethod: method :param printmethod: method to use for printing test result output. Default is self.debug ''' buf = "\nTESTUNIT LIST SUMMARY FOR " + str(self.name) + "\n" if list is None: list=self.testlist if not list: raise Exception("print_test_list_results, error: No Test list provided") if printmethod is None: printmethod = lambda msg: self.debug(msg,linebyline=False) printmethod("Test list results for testcase:"+str(self.name)) for testunit in list: buf += self.resultdefault("\n"+ self.getline(80)+"\n", printout=False) #Ascii mark up errors using pmethod() so errors are in bold/red, etc... pmethod = self.resultfail if not testunit.result == EutesterTestResult.passed else self.resultdefault test_summary_line = str(" ").ljust(20) + str("| RESULT: " + str(testunit.result)).ljust(20) + "\n" +\ str(" ").ljust(20) + "| TEST NAME: " + str(testunit.name) + "\n" + \ str(" ").ljust(20) + str("| TIME : " + str(testunit.time_to_run)) buf += pmethod(str(test_summary_line),printout=False) buf += pmethod("\n" + str(" ").ljust(20) + "| ARGS: " + str(self.print_testunit_method_arg_values(testunit)), printout=False) #Print additional line showing error in the failed case... if testunit.result == EutesterTestResult.failed: err_sum = "\n".join(str(testunit.error).splitlines()[0:3]) test_error_line = 'ERROR:('+str(testunit.name)+'): '\ + str(err_sum) \ + '\n' buf += "\n"+str(self.resulterr(test_error_line, printout=False)) if testunit.result == EutesterTestResult.not_run: err_sum = "\n".join(str(testunit.error).splitlines()[0:3]) test_error_line = 'NOT_RUN:('+str(testunit.name)+'): ' \ + str(err_sum) \ + '\n' buf += "\n"+str(self.resulterr(test_error_line, printout=False)) buf += self.resultdefault("\n"+ self.getline(80)+"\n", printout=False) buf += str(self.print_test_list_short_stats(list)) buf += "\n" if printout: printmethod(buf) else: return buf def print_test_list_short_stats(self,list,printmethod=None): results={} mainbuf = "RESULTS SUMMARY FOR '"+str(self.name)+"':\n" fieldsbuf = "" resultsbuf= "" total = 0 elapsed = 0 #initialize a dict containing all the possible defined test results fields = dir(EutesterTestResult) for fieldname in fields[2:len(fields)]: results[fieldname]=0 #increment values in results dict based upon result of each testunit in list for testunit in list: total += 1 elapsed += testunit.time_to_run results[testunit.result] += 1 fieldsbuf += str('| TOTAL').ljust(10) resultsbuf += str('| ' + str(total)).ljust(10) for field in results: fieldsbuf += str('| ' + field.upper()).ljust(10) resultsbuf += str('| ' + str(results[field])).ljust(10) fieldsbuf += str('| TIME_ELAPSED').ljust(10) resultsbuf += str('| '+str(elapsed)).ljust(10) mainbuf += "\n"+self.getline(len(fieldsbuf))+"\n" mainbuf += fieldsbuf mainbuf += "\n"+self.getline(len(fieldsbuf))+"\n" mainbuf += resultsbuf mainbuf += "\n"+self.getline(len(fieldsbuf))+"\n" if printmethod: printmethod(mainbuf) return mainbuf @classmethod def get_testunit_method_arg_dict(cls,testunit): argdict={} spec = inspect.getargspec(testunit.method) if isinstance(testunit.method,types.FunctionType): argnames = spec.args else: argnames = spec.args[1:len(spec.args)] defaults = spec.defaults or [] #Initialize the return dict for argname in argnames: argdict[argname]='<!None!>' #Set the default values of the testunits method for x in xrange(0,len(defaults)): argdict[argnames.pop()]=defaults[len(defaults)-x-1] #Then overwrite those with the testunits kwargs values for kwarg in testunit.kwargs: argdict[kwarg]=testunit.kwargs[kwarg] #then add the positional args in if they apply... for count, value in enumerate(testunit.args): argdict[argnames[count]]=value return argdict @classmethod def print_testunit_method_arg_values(cls,testunit): buf = testunit.name+"(" argdict = EutesterTestCase.get_testunit_method_arg_dict(testunit) for arg in argdict: buf += str(arg)+":"+str(argdict[arg])+"," buf = buf.rstrip(',') buf += ")" return buf def getline(self,len): buf = '' for x in xrange(0,len): buf += '-' return buf def run_method_by_name(self,name, obj=None, *args, **kwargs): ''' Description: Find a method within an instance of obj and run that method with either args/kwargs provided or any self.args which match the methods varname. :type name: string :param name: Name of method to look for within instance of object 'obj' :type obj: class instance :param obj: Instance type, defaults to self testcase object :type args: positional arguements :param args: None or more positional arguments to be passed to method to be run :type kwargs: keyword arguments :param kwargs: None or more keyword arguements to be passed to method to be run ''' obj = obj or self meth = getattr(obj,name) return self.do_with_args(meth, *args, **kwargs) def create_testunit_by_name(self, name, obj=None, eof=False, autoarg=True, *args,**kwargs ): ''' Description: Attempts to match a method name contained with object 'obj', and create a EutesterTestUnit object from that method and the provided positional as well as keyword arguments provided. :type name: string :param name: Name of method to look for within instance of object 'obj' :type obj: class instance :param obj: Instance type, defaults to self testcase object :type args: positional arguements :param args: None or more positional arguments to be passed to method to be run :type kwargs: keyword arguments :param kwargs: None or more keyword arguements to be passed to method to be run ''' autoarg=autoarg obj = obj or self meth = getattr(obj,name) methvars = self.get_meth_arg_names(meth) #Pull out value relative to this method, leave in any that are intended to be passed through if 'autoarg' in kwargs: if 'autoarg' in methvars: autoarg = kwargs['autoarg'] else: autoarg = kwargs.pop('autoarg') if 'eof' in kwargs: if 'eof' in methvars: eof = kwargs['eof'] else: eof = kwargs.pop('eof') if 'obj' in kwargs: if 'obj' in methvars: obj = kwargs['obj'] else: obj = kwargs.pop('obj') testunit = EutesterTestUnit(meth, *args, **kwargs) testunit.eof = eof #if autoarg, auto populate testunit arguements from local testcase.args namespace values if autoarg: self.populate_testunit_with_args(testunit) return testunit def get_args(self,use_cli=True, file_sections=[]): ''' Description: Method will attempt to retrieve all command line arguments presented through local testcase's 'argparse' methods, as well as retrieve all EuConfig file arguments. All arguments will be combined into a single namespace object held locally at 'testcase.args'. Note: cli arg 'config' must be provided for config file valus to be store in self.args. :type use_cli: boolean :param use_cli: Boolean to indicate whether or not to create and read from a cli argparsing object :type use_default_file: boolean :param use_default_files: Boolean to indicate whether or not to read default config file at $HOME/.eutester/eutester.conf (not indicated by cli) :type sections: list :param sections: list of EuConfig sections to read configuration values from, and store in self.args. :rtype: arparse.namespace obj :returns: namespace object with values from cli and config file arguements ''' configfiles=[] args=None #build out a namespace object from the config file first cf = argparse.Namespace() if (hasattr(self, 'use_default_file') and self.use_default_file) and \ (hasattr(self, 'use_default_config') and self.default_config): try: configfiles.append(self.default_config) except Exception, e: self.debug("Unable to read config from file: " + str(e)) #Setup/define the config file block/sections we intend to read from confblocks = file_sections or ['MEMO','globals'] if self.name: confblocks.append(self.name) if use_cli: #See if we have CLI args to read if not hasattr(self,'parser') or not self.parser: self.setup_parser() #first get command line args to see if there's a config file cliargs = self.parser.parse_args() #if a config file was passed, combine the config file and command line args into a single namespace object if cliargs: #Check to see if there's explicit config sections to read if 'configblocks' in cliargs.__dict__: confblocks = confblocks +cliargs.configblocks #Check to see if there's explicit config sections to ignore if 'ignoreblocks' in cliargs.__dict__: for block in cliargs.ignoreblocks: if block in confblocks: confblocks.remove(block) #if a file or list of config files is specified add it to our list... if ('config' in cliargs.__dict__) and cliargs.config: for cfile in str(cliargs.config).split(','): if not cfile in configfiles: configfiles.append(cfile) #legacy support for config, configfile config_file arg names... if ('config_file' in cliargs.__dict__) and cliargs.config: for cfile in str(cliargs.config).split(','): if not cfile in configfiles: configfiles.append(cfile) #legacy support for config, configfile config_file arg names... if ('configfile' in cliargs.__dict__) and cliargs.config: for cfile in str(cliargs.config).split(','): if not cfile in configfiles: configfiles.append(cfile) #store config block list for debug purposes cf.__setattr__('configsections',copy.copy(confblocks)) #create euconfig configparser objects from each file. euconfigs = [] self.configfiles = configfiles try: for configfile in configfiles: euconfigs.append(EuConfig(filename=configfile)) except Exception, e: self.debug("Unable to read config from file: " + str(e)) for conf in euconfigs: cblocks = copy.copy(confblocks) #if MEMO field in our config block add it first if to set least precedence if 'MEMO' in cblocks: if conf.config.has_section('MEMO'): for item in conf.config.items('MEMO'): cf.__setattr__(str(item[0]), item[1]) cblocks.remove('MEMO') #If globals are still in our confblocks, add globals first if the section is present in config if 'globals' in cblocks: if conf.config.has_section('globals'): for item in conf.config.items('globals'): cf.__setattr__(str(item[0]), item[1]) cblocks.remove('globals') #Now iterate through remaining config block in file and add to args... for section in confblocks: if conf.config.has_section(section): for item in conf.config.items(section): cf.__setattr__(str(item[0]), item[1]) if cliargs: #Now make sure any conflicting args provided on the command line take precedence over config file args for val in cliargs._get_kwargs(): if (not val[0] in cf ) or (val[1] is not None): cf.__setattr__(str(val[0]), val[1]) args = cf #Legacy script support: level set var names for config_file vs configfile vs config and credpath vs cred_path try: if 'config' in args: args.config_file = args.config args.configfile = args.config except: pass try: args.cred_path = args.credpath except: pass self.args = args #finally add the namespace args to args for populating other testcase objs from this one if not self.has_arg('args'): args.__setattr__('args',copy.copy(args)) #Refresh our debug method(s) in the case the args provided give instruction on logging self.setup_debugmethod() self.show_self() return args def get_default_userhome_config(self,fname='eutester.conf'): ''' Description: Attempts to fetch the file 'fname' from the current user's home dir. Returns path to the user's home dir default eutester config file. :type fname: string :param fname: the eutester default config file name :rtype: string :returns: string representing the path to 'fname', the default eutester conf file. ''' try: def_path = os.getenv('HOME')+'/.eutester/'+str(fname) except: return None try: os.stat(def_path) return def_path except: self.debug("Default config not found:"+str(def_path)) return None def show_self(self): list=[] list.append(("NAME:", str(self.name))) list.append(('TEST LIST:', str(self.testlist))) list.append(('CONFIG FILES:', self.configfiles)) argbuf="" argbuf = str("TESTCASE INFO:").ljust(25) argbuf += str("\n----------").ljust(25) for val in list: argbuf += '\n'+str(val[0]).ljust(25)+" --->: "+str(val[1]) self.status(argbuf) self.show_args() def show_args(self,args=None): ''' Description: Prints args names and values for debug purposes. By default will use the local testcase.args, else args can be provided. :type args: namespace object :param args: namespace object to be printed,by default None will print local testcase's args. ''' args= args or self.args if hasattr(self,'args') else None argbuf = str("TEST ARGS:").ljust(25)+" "+str("VALUE:") argbuf += str("\n----------").ljust(25)+" "+str("------") if args: for val in args._get_kwargs(): argbuf += '\n'+str(val[0]).ljust(25)+" --->: "+str(val[1]) self.status(argbuf) def populate_testunit_with_args(self,testunit,namespace=None): ''' Description: Checks a given test unit's available positional and key word args lists for matching values contained with the given namespace, by default will use local testcase.args. If testunit's underlying method has arguments matching the namespace provided, then those args will be applied to the testunits args referenced when running the testunit. Namespace values will not be applied/overwrite testunits, if the testunit already has conflicting values in it's args(positional) list or kwargs(keyword args) dict. :type: testunit: Eutestcase.eutestertestunit object :param: testunit: A testunit object for which the namespace values will be applied :type: namespace: namespace obj :param: namespace: namespace obj containing args/values to be applied to testunit. None by default will use local testunit args. ''' self.debug("Attempting to populate testunit:"+str(testunit.name)+", with testcase.args...") args_to_apply = namespace or self.args if not args_to_apply: return testunit_obj_args = {} #copy the test units key word args testunit_obj_args.update(copy.copy(testunit.kwargs)) self.debug("Testunit keyword args:"+str(testunit_obj_args)) #Get all the var names of the underlying method the testunit is wrapping method_args = self.get_meth_arg_names(testunit.method) offset = 0 if isinstance(testunit.method,types.FunctionType) else 1 self.debug("Got method args:"+str(method_args)) #Add the var names of the positional args provided in testunit.args to check against later #Append to the known keyword arg list for x,arg in enumerate(testunit.args): testunit_obj_args[method_args[x+offset]] = arg self.debug("test unit total args:"+str(testunit_obj_args)) #populate any global args which do not conflict with args already contained within the test case #first populate matching method args with our global testcase args taking least precedence for apply_val in args_to_apply._get_kwargs(): for methvar in method_args: if methvar == apply_val[0]: self.debug("Found matching arg for:"+str(methvar)) #Don't overwrite existing testunit args/kwargs that have already been assigned if apply_val[0] in testunit_obj_args: self.debug("Skipping populate because testunit already has this arg:"+str(methvar)) continue #Append cmdargs list to testunits kwargs testunit.set_kwarg(methvar,apply_val[1]) #testunit.kwargs[methvar]=apply_val[1] def do_with_args(self, meth, *args, **kwargs): ''' Description: Convenience method used to wrap the provided instance_method, function, or object type 'meth' and populate meth's positional and keyword arguments with the local testcase.args created from the CLI and/or config file, as well as the *args and **kwargs variable length arguments passed into this method. :type meth: method :param meth: A method or class initiator to wrapped/populated with this testcase objects namespace args :type args: positional arguments :param args: None or more values representing positional arguments to be passed to 'meth' when executed. These will take precedence over local testcase obj namespace args :type kwargs: keyword arguments :param kwargs: None or more values reprsenting keyword arguments to be passed to 'meth' when executed. These will take precedence over local testcase obj namespace args and positional args ''' if not hasattr(self,'args'): raise Exception('TestCase object does not have args yet, see: get_args and setup_parser options') tc_args = self.args cmdargs={} f_code = self.get_method_fcode(meth) vars = self.get_meth_arg_names(meth) self.debug("do_with_args: Method:"+str(f_code.co_name)+", Vars:"+str(vars)) #first populate matching method args with our global testcase args... for val in tc_args._get_kwargs(): for var in vars: if var == val[0]: cmdargs[var]=val[1] #Then overwrite/populate with any given positional local args... for count,arg in enumerate(args): cmdargs[vars[count+1]]=arg #Finall overwrite/populate with any given key word local args... for name,value in kwargs.items(): for var in vars: if var == name: cmdargs[var]=value self.debug('create_with_args: running '+str(f_code.co_name)+"("+str(cmdargs).replace(':','=')+")") return meth(**cmdargs) @classmethod def get_method_fcode(cls, meth): f_code = None #Find the args for the method passed in... #Check for object/class init... if isinstance(meth,types.ObjectType): try: f_code = meth.__init__.__func__.func_code except:pass #Check for instance method... if isinstance(meth,types.MethodType): try: f_code = meth.im_func.func_code except:pass #Check for function... if isinstance(meth,types.FunctionType): try: f_code = meth.func_code except:pass if not f_code: raise Exception("get_method_fcode: Could not find function_code for passed method of type:"+str(type(meth))) return f_code @classmethod def get_meth_arg_names(cls,meth): ''' Description: Return varnames within argcount :type:meth: method :param: meth: method to fetch arg names for :rtype: list :returns: list of strings representing the varnames within argcount for this method ''' fcode = cls.get_method_fcode(meth) varnames = fcode.co_varnames[0:fcode.co_argcount] return varnames class SkipTestException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
StarcoderdataPython
3259802
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 @author: <NAME> """ import random import numpy as np import seaborn as sns import matplotlib.pyplot as plt class FrozenLake: """Environment of frozen lake. Attributes: map_idx: 0 for 4x4 map, 1 for 10x10 map. """ def __init__(self, map_idx): """Define and decode the map. Do not change the params here. Args: map_idx (int): map index """ self.ACTIONS = { # coord in the matrix 0: (-1, 0), # Up 1: ( 0, 1), # Right 2: ( 1, 0), # Down 3: ( 0, -1), # Left } self.CELL = { # interpret the map file 0: 'ice', 1: 'hole', 2: 'start', 3: 'frisbee', } self.filepath = ['./map_4x4.txt', './map_10x10.txt'] self.state = None self.map = np.loadtxt(self.filepath[map_idx], dtype=int) self.MAP_X, self.MAP_Y = self.map.shape self.init_states = [(x, y) for x in range(self.MAP_X) for y in range(self.MAP_Y) if self.CELL[self.map[x, y]] == 'start'] # find init state self.e_fail, self.e_success, self.e_opt_policy = {}, {}, [] def reset(self): """Reset the state to the start Returns: tuple: state coord """ self.state = random.choice(self.init_states) return self.state def step(self, action:int): """Take a step given state and action, and return the next step and reward. Args: action (int): input an action Raises: RuntimeWarning: If there is no corresponding cell, the map file might contain illegal characters. Returns: tuple: next valid state given action float: the reward of next state bool: if next state is terminal """ done = False reward = 0 dx, dy = self.ACTIONS[action] new_state = self.state[0] + dx, self.state[1] + dy reward -= 0 # penalty for moving each timestep, 0 by default if not (0 <= new_state[0] < self.MAP_X and 0 <= new_state[1] < self.MAP_Y): reward -= 0 # penalty for going out of bound, 0 by default. Keep where they are elif self.CELL[self.map[new_state]] in ['ice', 'start']: self.state = new_state reward -= 0 # penalty for moving, 0 by default elif self.CELL[self.map[new_state]] == 'hole': self.state = new_state reward -= 1 # penalty for fall into the hole, -1 by default. terminal state done = True elif self.CELL[self.map[new_state]] == 'frisbee': self.state = new_state reward += 1 # reward for get the frisbee, +1 by default. terminalstate done = True else: raise RuntimeWarning('No corresponding cell. Check your map file.') return self.state, reward, done def render(self, e_len, e, e_all, policy): """Store the info for each episode. Detect whether the episode ends with getting the frisbee, and store it in the attributes. Args: e_len (int): length of the episode e (int): current episode e_all (int): number of total episode policy (dict): the policy table """ self._show_progress(e) # show progress of training on the sreen if self.CELL[self.map[self.state]] == 'frisbee': # store if the episode ends with getting the frisbee or not self.e_success[e] = e_len else: self.e_fail[e] = e_len if self._is_success(policy): # judge if the policy is optimal or not, record if it is optimal self.e_opt_policy.append(e) if e == e_all - 1: # judge at the last episode, show if a successful policy has been reached during the training if self.e_success: print('Frisbee firstly reach at episode:', list(self.e_success.keys())[0]) else: print('More training is needed.') if e in self.e_success: self.render_policy(policy) # show the policy def render_all(self, e_all, name, policy_table, Qtable): """Render graphs when finished the training. Args: e_all (int): number of total episode name (string): name of the algorithm policy_table (dict): policy table Qtable (dict): Q table """ plt.figure() l1 = plt.scatter(self.e_fail.keys(), self.e_fail.values(), s=0.8, alpha=0.3, label='Fail') # plot failed points in blue l2 = plt.scatter(self.e_success.keys(), self.e_success.values(), s=0.8, c='red', alpha=1.0) # plot successful points in red l3 = plt.vlines(self.e_opt_policy, 0, max(self.e_fail.values()), colors='green', alpha=0.05) # plot optimal policy lines in green plt.legend(handles=[l1,l2,l3], labels=['Fail','Success','Optimal policy'], loc='upper right') plt.title('Training Process of '+ name) plt.xlabel('#Episode') plt.ylabel('Step length') # plt.savefig(r'xxx.png', dpi=300) # save figure for report self.render_heatmap(policy_table, Qtable, name) # render the heatmap def render_heatmap(self, policy_table, Qtable, name): """Render heatmap. Args: policy_table (dict): policy table Qtable (dict): Q table name (string): name of the algorithm """ num_cell = max(Qtable.keys())[0] + 1 # number of the states Q = np.full((num_cell, num_cell), 0, dtype=float) # create a square state matrix mask = np.full((num_cell, num_cell), False, dtype=bool) # for the use of mask of heatmap for x, y in Qtable.keys(): Q[x][y] = max(Qtable[(x, y)]) # put the values of Q table dict into the 2D array correspondingly for y in range(self.MAP_Y): for x in range(self.MAP_X): if self.CELL[self.map[(x, y)]] == 'hole': # create mask, to make the cells at holes and target blank mask[x][y] = True elif self.CELL[self.map[(x, y)]] == 'frisbee': mask[x][y] = True plt.figure() sns.heatmap(Q, annot=True, cmap='RdBu_r', square=True, mask=mask, linewidths=0.3, linecolor='black', annot_kws={'size': 5}) # plot the heatmap with mask # sns.heatmap(Q, cmap='RdBu_r', square=True, mask=mask, linewidths=0.3, linecolor='black') # heatmap without annotations plt.title('Max state-action value given state ({})'.format(name)) # plt.savefig(r'{}.png'.format(name), dpi=300) # save figure for report def render_policy(self, policy_table): """Show policy on the screen.""" done = False self.state = self.reset() state_list, action_list = [self.state], [] while not done: action = int(np.argmax(policy_table[self.state])) _, _, done = self.step(action) state_list.append(self.state) action_list.append(action) print('Policy (state): {}'.format(state_list)) print('Policy (action): {}'.format(action_list)) def _is_success(self, policy_table): """Judge whether the policy is optimal. Args: policy_table (dict) Returns: bool: True if optimal, false otherwise """ state = self.reset() done = False state_list = [] while not done: action = int(np.argmax(policy_table[state])) # use argmax to extract the policy dx, dy = self.ACTIONS[action] state_list.append(state) new_state = state[0] + dx, state[1] + dy if not (0 <= new_state[0] < self.MAP_X and 0 <= new_state[1] < self.MAP_Y): done = True # an optimal policy should not hit the wall elif new_state in state_list: done = True # an optimal policy should not be recurrent elif self.CELL[self.map[new_state]] == 'ice': state = new_state elif self.CELL[self.map[new_state]] in ['hole', 'start']: done = True # an optimal policy should not fall into the hole or back to the start elif self.CELL[self.map[new_state]] == 'frisbee': return True # an optimal policy should lead to the target successfully return False def _show_progress(self, e): """Show progress on the sreen.""" if e % 10 == 0: print('Episode: %d' % e, end='\r') def render_learn_curve(envS, envQ, envM): """Render the learning curve of three algorithms. Args: envS (class): SARSA env envQ (class): Q-learning env envM (class): Monte Carlo env """ l = [] num_e = len(envS.env.e_fail) + len(envS.env.e_success) E = list(range(num_e)) plt.figure() for env in [envS, envQ, envM]: # loop for all the envs s_all = 0 # accumulative step number s = [] # accumulative step number for each episode for e in range(num_e): if e in env.env.e_fail.keys(): s_all += env.env.e_fail[e] s.append(s_all) elif e in env.env.e_success.keys(): s_all += env.env.e_success[e] s.append(s_all) handle, = plt.plot(E, s) # comma after handle to unzip l.append(handle) plt.legend(handles=l, labels=[envS.name, envQ.name, envM.name]) plt.xlabel('#Episode') plt.ylabel('Accumulative steps') plt.title('Comparison of learning curve') def render_success_rate(envS, envQ, envM, smooth_size=20): """ Render success rate for each env. Args: envS (class): SARSA env envQ (class): Q-learning env envM (class): Monte Carlo env smooth_size (int, optional): take an average to a batch of episodes to smooth the curve. Defaults to 20. """ l = [] num_e = len(envS.env.e_fail) + len(envS.env.e_success) plt.figure() for env in [envS, envQ, envM]: e_smooth, s = [], [] for batch in range(num_e // smooth_size): e_smooth.append(batch * smooth_size + smooth_size // 2) # center loc of the batch cnt = 0 # counter for sccessful exploration for e in range(batch*smooth_size, (batch + 1)*smooth_size): if e in env.env.e_success.keys(): cnt += 1 s.append(100 * cnt / smooth_size) # percentage of average sccess rate in a batch handle, = plt.plot(e_smooth, s) l.append(handle) plt.legend(handles=l, labels=[envS.name, envQ.name, envM.name]) plt.title('Comparison of three method with a smoothness of {} episodes'.format(smooth_size))
StarcoderdataPython
18231
# Copyright (c) 2016-2018 <NAME>. All rights reserved. A # copyright license for redistribution and use in source and binary forms, # with or without modification, is hereby granted for non-commercial, # experimental and research purposes, provided that the following conditions # are met: # - Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimers. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimers in the # documentation and/or other materials provided with the distribution. If # you wish to use this software commercially, kindly contact # <EMAIL> to obtain a commercial license. # # This license extends only to copyright and does not include or grant any # patent license or other license whatsoever. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import subprocess import sys import pysnark.options def run(eksize, pksize, genmk=False): """ Run the qapgen tool :param eksize: Desired master evaluation key size :param pksize: Desired master public key size :param genmk: True if a new master secret key should be generated, False otherwise :return: None """ mskfile = pysnark.options.get_mskey_file() mkeyfile = pysnark.options.get_mkey_file() mpkeyfile = pysnark.options.get_mpkey_file() if not genmk and not os.path.isfile(mskfile): raise IOError("Could not enlarge master key materiak: master secret key missing") print >> sys.stderr, "*** " + ("Generating" if genmk else "Enlarging") + " master key material" if subprocess.call([pysnark.options.get_qaptool_exe("qapgen"), str(max(pksize,eksize,0)), str(max(pksize,0)), mskfile, mkeyfile, mpkeyfile]) != 0: sys.exit(2) def get_mekey_size(): """ Get the size (maximal exponent) of the current master evaluation key :return: Size, or -1 if key does not exist """ try: mekf = open(pysnark.options.get_mkey_file()) curmk = int(mekf.next().strip().split(" ")[2]) mekf.close() return curmk except IOError: return -1 def get_mpkey_size(): """ Get the size (maximal exponent) of the current master public key :return: Size, or -1 if key does not exist """ try: mpkf = open(pysnark.options.get_mpkey_file()) curmpk = int(mpkf.next().strip().split(" ")[2]) mpkf.close() return curmpk except IOError: return -1 def ensure_mkey(eksize, pksize): """ Ensures that there are master evaluation and public keys of the given sizes. If master evaluation/public keys exist but are to small, and there is no master secret key, this raises an error. If there is no key material at all, a fresh master secret key will be generated. :param eksize: Minimal evaluation key size (-1 if not needed) :param pksize: Minimal public key size (-1 if not needed) :return: Actual evaluation key, public key size after key generation """ curek = get_mekey_size() curpk = get_mpkey_size() havemsk = os.path.isfile(pysnark.options.get_mskey_file()) havekeys = os.path.isfile(pysnark.options.get_mpkey_file()) or os.path.isfile(pysnark.options.get_mkey_file()) if curek < eksize or curpk < pksize: if havemsk: run(max(curek, eksize), max(curpk, pksize), False) return (max(curek, eksize), max(curpk, pksize)) elif havekeys: raise IOError("Key material too small ("+str(curek)+","+str(curpk)+ ")<("+str(eksize)+","+str(pksize)+") and missing master secret key") else: run(eksize, pksize, True) return (eksize,pksize) else: return (curek,curpk) if __name__ == "__main__": if len(sys.argv)<3: print >>sys.stderr, "*** Usage:", sys.argv[0], "<eksize>", "<pksize>" sys.exit(2) argeksize = int(sys.argv[1]) argpksize = int(sys.argv[2]) run(argeksize, argpksize, not os.path.isfile(pysnark.options.get_mskey_file()))
StarcoderdataPython
3203724
<gh_stars>0 import pytest from sopel.tests import rawlist from sopel_help import providers TMP_CONFIG = """ [core] owner = testnick nick = TestBot enable = coretasks, help [help] output = local origin_base_url = https://example.com/sopel/ origin_output_name = help.html origin_output_dir = /tmp/ """ CHANNEL_LINE = ':Test!<EMAIL> PRIVMSG #channel :.help' QUERY_LINE = ':Test!<EMAIL> PRIVMSG TestBot :.help' @pytest.fixture def tmpconfig(configfactory): return configfactory('test.cfg', TMP_CONFIG) @pytest.fixture def mockbot(tmpconfig, botfactory): return botfactory.preloaded(tmpconfig, preloads=['help']) def test_send_help_commands(mockbot, triggerfactory, tmpdir): mockbot.settings.help.origin_output_dir = str(tmpdir.mkdir('docs')) print(mockbot.settings.help.origin_output_dir) provider = providers.LocalFile() provider.setup(mockbot) wrapper = triggerfactory.wrapper(mockbot, CHANNEL_LINE) provider.send_help_commands( wrapper, wrapper._trigger, ['line 1', 'line 2']) assert mockbot.backend.message_sent == rawlist( "PRIVMSG #channel :Test: I've published a list of my commands at: " "https://example.com/sopel/help.html", )
StarcoderdataPython
3244924
<reponame>uhh-lt/SCoT import csv FILE_NAMES = [ "gbooks_1520_1908.csv", "gbooks_1909_1953.csv", "gbooks_1954_1972.csv", "gbooks_1973_1986.csv", "gbooks_1987_1995.csv", "gbooks_1996_2001.csv", "gbooks_2002_2005.csv", "gbooks_2006_2008.csv" ] def main(): for file_name in FILE_NAMES: lines = [] with open(file_name, 'r') as file: for i, line in enumerate(file): if i == 0: lines.append(line) elif "word1" in line and "word2" in line: continue else: lines.append(line) with open(file_name, 'w') as file: for line in lines: #print(line) file.write(line) if __name__ == "__main__": main()
StarcoderdataPython
3270219
<gh_stars>10-100 """Sampler classes. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gin import tensorflow as tf from robovat.envs.push import heuristic_push_sampler from networks import samplers @gin.configurable class HeuristicPushSampler(samplers.Base): """Samples starting pose using heuristics.""" def __init__(self, input_tensor_spec, output_tensor_spec, num_steps=None, config=None): self._output_tensor_spec = output_tensor_spec flat_output_tensor_spec = tf.nest.flatten(output_tensor_spec) if len(flat_output_tensor_spec) > 1: raise ValueError( 'Only a single action is supported by this network.') self.num_steps = None self._sampler = heuristic_push_sampler.HeuristicPushSampler( cspace_low=config.ACTION.CSPACE.LOW, cspace_high=config.ACTION.CSPACE.HIGH, translation_x=config.ACTION.MOTION.TRANSLATION_X, translation_y=config.ACTION.MOTION.TRANSLATION_Y) def __call__(self, observation, num_samples, seed): position = tf.squeeze(observation['position'], 0) body_mask = tf.squeeze(observation['body_mask'], 0) num_episodes = tf.squeeze(observation['num_episodes'], 0) num_steps = tf.squeeze(observation['num_steps'], 0) action = tf.compat.v1.py_func( self._sampler.sample, [position, body_mask, num_episodes, num_steps, tf.convert_to_tensor(num_samples)], [tf.float32]) shape = list(self._output_tensor_spec.shape) action = tf.reshape(action, [num_samples] + shape) if self.num_steps is not None: action = tf.expand_dims(action, 0) return action
StarcoderdataPython
2802
<reponame>christiansencq/ibm_capstone import requests import json # import related models here from .models import CarDealer, DealerReview from requests.auth import HTTPBasicAuth import logging logger = logging.getLogger(__name__) # Create a `get_request` to make HTTP GET requests # e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'}, # auth=HTTPBasicAuth('apikey', api_key)) def get_request(url, api_key, **kwargs): print("GET from {}".format(url)) print(kwargs) try: if api_key is not None: response = requests.get(url, headers={'Content-Type': 'application/json'}, params=kwargs, auth=HTTPBasicAuth('apikey', api_key)) else: response = requests.get(url, headers={'Content-Type': 'application/json'}, params=kwargs) except: print("Network Error") status_code = response.status_code print("With status code {}".format(status_code)) json_data = json.loads(response.text) return json_data, status_code # Create a `post_request` to make HTTP POST requests # e.g., response = requests.post(url, params=kwargs, json=payload) def post_request(url, json_payload, **kwargs): print("Post to url: {} ".format(url)) print(kwargs) print(json_payload) response = requests.post(url, headers={'Content-Type': 'application/json'}, params=kwargs, json=json_payload) status_code = response.status_code print("With status code {}".format(status_code)) json_data = json.loads(response.text) return json_data, status_code # Create a get_dealers_from_cf method to get dealers from a cloud function def get_dealers_from_cf(url, **kwargs): info = [] result = "ok" # - Call get_request() with specified arguments logger.info("Get Dealers from CF Called!") json_result, status_code = get_request(url, None) if status_code == 200 and json_result: dealers = json_result['rows'] logger.info(len(dealers)) for dealer in dealers: dlr_data = dealer['doc'] #print('ADDRESS', dlr_data["address"]) if dlr_data.get('address'): # Create a CarDealer object with values in `doc` object dealer_obj = CarDealer(address=dlr_data.get("address"), city=dlr_data.get("city"), full_name=dlr_data.get("full_name"), id=dlr_data.get("id"), lat=dlr_data.get("lat"), long=dlr_data.get("long"), short_name=dlr_data.get("short_name"), state=dlr_data.get("state"), st=dlr_data.get("st"), zip=dlr_data.get("zip")) # dealer_obj = CarDealer(address=dealer["doc"]["address"], city=dealer["doc"]["city"], full_name=dealer["doc"]["full_name"], # id=dealer["doc"]["id"], lat=dealer["doc"]["lat"], long=dealer["doc"]["long"], # short_name=dealer["doc"]["short_name"], # st=dealer["doc"]["st"], state=dealer["doc"]["state"], zip=dealer["doc"]["zip"]) info.append(dealer_obj) elif json_result: result = json_result["message"] else: result = "Unknown error" return info, result def get_dealer_by_id(url, dealerId): # Call get_request with a URL parameter info = None result = "ok" json_result, status_code = get_request(url, None, dealerId=dealerId) # json_result, status_code = get_request(url, None, dealerId=dealerId) if status_code == 200 and json_result: # Get the row list in JSON as dealers dealers = json_result["rows"] for dealer in dealers: # Create a CarDealer object with values in `doc` object info = CarDealer(address=dealer.get("address"), city=dealer.get("city"), full_name=dealer.get("full_name"), id=dealer.get("id"), lat=dealer.get("lat"), long=dealer.get("long"), short_name=dealer.get("short_name"), st=dealer.get("st"), state=dealer.get("state"), zip=dealer.get("zip")) # info = CarDealer(address=dealer["address"], city=dealer["city"], full_name=dealer["full_name"], # id=dealer["id"], lat=dealer["lat"], long=dealer["long"], # short_name=dealer["short_name"], state=dealer["state"], # st=dealer["st"], zip=dealer["zip"]) elif json_result: result = json_result["message"] else: result = "Unknown error" return info, result def get_dealers_by_state (url, state): info = [] result = "ok" # Call get_request with a URL parameter json_result, status_code = get_request(url, None, state=state) if status_code == 200 and json_result: # Get the row list in JSON as dealers dealers = json_result["rows"] # For each dealer object for dealer in dealers: # dlr_data = dealer["doc"] # Create a CarDealer object with values in `doc` object dealer_obj = CarDealer(address=dealer.get("address"), city=dealer.get("city"), full_name=dealer.get("full_name"), id=dealer.get("id"), lat=dealer.get("lat"), long=dealer.get("long"), short_name=dealer.get("short_name"), state=dealer.get("state"), st=dealer.get("st"), zip=dealer.get("zip")) # dealer_obj = CarDealer(address=dlr_data.get("address"), city=dlr_data.get("city"), full_name=dlr_data.get("full_name"), # id=dlr_data.get("id"), lat=dlr_data.get("lat"), long=dlr_data.get("long"), # short_name=dlr_data.get("short_name"), state=dlr_data.get("state"), # st=dlr_data.get("st"), zip=dlr_data.get("zip")) info.append(dealer_obj) elif json_result: result = json_result["message"] else: result = "Unknown error" return info, result def get_dealer_reviews_from_cf (url, dealerId): info = [] result = "ok" # Call get_request with a URL parameter json_result, status_code = get_request(url, None, dealerId=dealerId) if status_code == 200 and json_result: # Get the row list in JSON as reviews reviews = json_result["body"]["data"] # For each review object for review in reviews: if (dealerId == review.get("dealership")): # Create a DealerReview object with values in object #sentiment = analyze_review_sentiments(review["review"]) review_obj = DealerReview( id=review.get("id"), name=review.get("name"), review=review.get("review"), purchase=review.get("purchase"), car_make=review.get("car_make", None), car_model=review.get("car_model", None), car_year=review.get("car_year", None), purchase_date=review.get("purchase_date", None)) info.append(review_obj) elif json_result: result = json_result["message"] else: result = "Unknown error" return info, result # Create an `analyze_review_sentiments` method to call Watson NLU and analyze text # def analyze_review_sentiments(text): # - Call get_request() with specified arguments # - Get the returned sentiment label such as Positive or Negative
StarcoderdataPython
23276
from functools import reduce from itertools import groupby from operator import add, itemgetter def merge_records_by(key, combine): return lambda first, second: { k: first[k] if k == key else combine(first[k], second[k]) for k in first } def merge_list_of_records_by(key, combine): keyprop = itemgetter(key) return lambda lst: [ reduce(merge_records_by(key, combine), records) for _, records in groupby(sorted(lst, key=keyprop), keyprop) ]
StarcoderdataPython
3375453
<gh_stars>1-10 #Ref: https://0x00sec.org/t/get-file-signature-with-python/931 #!/usr/bin/env python # check_sigs.py - EnergyWolf 2016 # Take a file path as argument, and check it for known file # signatures using www.filesignatures.net # pickling the signatures file makes subsequent look ups # significantly faster # https://0x00sec.org/t/get-file-signature-with-python/931 # python signature.py file_path import os from urllib.request import urlopen import pickle as Pickle from argparse import ArgumentParser import binascii from bs4 import BeautifulSoup # the {} will be used to dynamically enter different ints with .format() URL = "http://www.filesignatures.net/index.php?page=all&currentpage={}" PATH = os.path.expanduser('./file_sigs.pickle') signatures = [] # contains all (signatures, descriptions) def compile_sigs(): """ Compile the list of file signatures """ global signatures, PATH if not os.path.exists(PATH): for i in range(19): # 19 pages of signatures on the site response = urlopen(URL.format(i)) html = response.read() # get the html as a string soup = BeautifulSoup(html, "lxml") # parse the source t_cells = soup.find_all("td", {"width": 236}) # find td elements with width=236 for td in t_cells: # append (signature, description) to signatures sig = str(td.get_text()).replace(' ', '').lower() # strip spaces, lowercase desc = str(td.find_next_sibling("td").get_text()) signatures.append([sig, desc]) # pickle them sigs with open(PATH, 'wb') as f: Pickle.dump(signatures, f) else: with open(PATH, 'rb') as f: signatures = Pickle.load(f) def check_sig(fn): """ Hex dump the file and search for signatures """ with open(fn, 'rb') as fn: dump = str(binascii.hexlify(fn.read()))[2:-1] res = [] for sig, desc in signatures: if sig in dump: res.append([sig, desc, dump.find(sig)]) res.sort(key=lambda x: x[2]) # sort tmp by offset in file return res # [(sig, desc, offset), (sig, desc, offset), ... etc.] # script really starts here if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("file_path", help="Detect signatures in file at this path") args = parser.parse_args() print("[*] Checking File for Known Signatures") print("[*] This may take a moment...") compile_sigs() results = check_sig(args.file_path) if results: # find longest signature, and desc for output formatting purposes big_sig = len(max([i[0] for i in results], key=lambda x: len(x))) big_desc = len(max([i[1] for i in results], key=lambda x: len(x))) print("\n[*] File Signature(s) detected:\n") for sig, desc, offset in results: s = ("[+] {0:<%ds} : {1:<%d} {2:<20s}" % (big_sig, big_desc)).format(sig, desc, "<- Offset: "+str(offset)) print(s) print("\n[*] First candidate signature:\n") sig, desc, offset = results[0][0],results[0][1],results[0][2] s = ("[+] {0:<%ds} : {1:<%d} {2:<20s}" % (big_sig, big_desc)).format(sig, desc, "<- Offset: " + str(offset)) print(s) else: print("\n[!] No File Signature Detected.\n")
StarcoderdataPython
41993
<reponame>Redaloukil/PackageWay<gh_stars>0 from django.apps import AppConfig class HelpsAppConfig(AppConfig): name = "backend.helps" verbose_name = "Helps" def ready(self): try: import users.signals # noqa F401 except ImportError: pass
StarcoderdataPython
1641294
from __future__ import absolute_import from sentry.api import client from sentry.api.bases.group import GroupEndpoint class GroupEventsLatestEndpoint(GroupEndpoint): def get(self, request, group): event = group.get_latest_event() return client.get('/events/{}/'.format(event.id), request.user, request.auth)
StarcoderdataPython
155627
<reponame>ivanlyon/exercises<gh_stars>0 ''' Is there a way to create an sum of a few fixed numbers Status: Accepted ''' from collections import deque ############################################################################### def main(): """Read input and print output""" _ = input() # Read past unnecessary line angles = [int(i) for i in input().split()] for query in map(int, input().split()): the_q, located = deque([query]), set() while the_q: location = the_q.popleft() for angle in angles: guess = (location + angle) % 360 if guess not in located: located.add(guess) the_q.append(guess) guess2 = (location - angle + 360) % 360 if guess2 not in located: located.add(guess2) the_q.append(guess2) if 0 in located: print("YES") else: print("NO") ############################################################################### if __name__ == '__main__': main()
StarcoderdataPython
1666297
# # (C) Copyright IBM Corp. 2022 # # 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 os from lithops.constants import TEMP_DIR FH_ZIP_LOCATION = os.path.join(os.getcwd(), 'lithops_azure_ca.zip') CA_JSON_LOCATION = os.path.join(TEMP_DIR, 'lithops_containerapp.yaml') DEFAULT_CONFIG_KEYS = { 'runtime_timeout': 600, # Default: 600 seconds => 10 minutes 'runtime_memory': 512, # Default memory: 512 MB 'max_workers': 1000, 'worker_processes': 1, 'invoke_pool_threads': 32, 'invocation_type': 'event', 'environment': 'lithops', 'docker_server': 'docker.io' } ALLOWED_MEM = { 512: ('0.5Gi', 0.25), 1024: ('1Gi', 0.5), 1536: ('1.5Gi', 0.75), 2048: ('2Gi', 1), 2560: ('2.5Gi', 1.25), 3072: ('3Gi', 1.5), 3584: ('3.5Gi', 1.75), 4096: ('4Gi', 2), } REQUIRED_AZURE_STORAGE_PARAMS = ['storage_account_name', 'storage_account_key'] REQUIRED_AZURE_CONTAINERS_PARAMS = ['resource_group', 'location'] CONTAINERAPP_JSON = { "type": "Microsoft.App/containerApps", "name": "", "apiVersion": "2022-03-01", "kind": "containerapp", "location": "", "tags": { "type": "", "lithops_version": "", "runtime_name": "", "runtime_memory": "", }, "properties": { "managedEnvironmentId": "", "configuration": { "activeRevisionsMode": "single", "secrets": [{ "name": "queueconnection", "value": "" }, { "name": "dockerhubtoken", "value": "" }], "registries": [{ "server": "", "username": "", "passwordSecretRef": "dockerhub<PASSWORD>" }], }, "template": { "containers": [ { "image": "", "name": "lithops-runtime", "env": [ { "name": "QueueName", "value": "", }, { "name": "QueueConnectionString", "secretRef": "queueconnection" } ], "resources": { "cpu": 0.25, "memory": "0.5Gi" }, } ], "scale": { "minReplicas": 0, "maxReplicas": 30, "rules": [ { "name": "queue-based-autoscaling", "azureQueue": { "queueName": "", "queueLength": 1, "auth": [ { "secretRef": "queueconnection", "triggerParameter": "connection" } ] } } ] } } } } DEFAULT_DOCKERFILE = """ RUN apt-get update && apt-get install -y \ zip \ && rm -rf /var/lib/apt/lists/* RUN pip install --upgrade --ignore-installed setuptools six pip \ && pip install --upgrade --no-cache-dir --ignore-installed \ azure-storage-blob \ azure-storage-queue \ pika \ flask \ gevent \ redis \ requests \ PyYAML \ kubernetes \ numpy \ cloudpickle \ ps-mem \ tblib WORKDIR /app COPY lithops_azure_ca.zip . RUN unzip lithops_azure_ca.zip && rm lithops_azure_ca.zip CMD ["python", "lithopsentry.py"] """ def load_config(config_data): if 'azure_storage' not in config_data: raise Exception("azure_storage section is mandatory in the configuration") if 'azure_containers' not in config_data: raise Exception("azure_containers section is mandatory in the configuration") for key in DEFAULT_CONFIG_KEYS: if key not in config_data['azure_containers']: config_data['azure_containers'][key] = DEFAULT_CONFIG_KEYS[key] for key in REQUIRED_AZURE_STORAGE_PARAMS: if key not in config_data['azure_storage']: raise Exception(f'{key} key is mandatory in azure section of the configuration') for key in REQUIRED_AZURE_CONTAINERS_PARAMS: if key not in config_data['azure_containers']: raise Exception(f'{key} key is mandatory in azure section of the configuration') config_data['azure_containers'].update(config_data['azure_storage'])
StarcoderdataPython
1694227
<filename>pyleecan/Functions/MeshSolution/build_meshsolution.py from ...Classes.MeshSolution import MeshSolution def build_meshsolution(list_solution, list_mesh, label="", dimension=2, group=None): """Build the MeshSolution objets from FEMM outputs. Parameters ---------- field : ndarray a vec is_get_mesh : bool 1 to load the mesh and solution into the simulation is_save_FEA : bool 1 to save the mesh and solution into a .json file j_t0 : int Targeted time step Returns ------- meshsol: MeshSolution a MeshSolution object with FEMM outputs at every time step """ if len(list_mesh) == 1: is_same_mesh = True meshsol = MeshSolution( label=label, mesh=list_mesh, solution=list_solution, is_same_mesh=is_same_mesh, dimension=dimension, group=group, ) return meshsol
StarcoderdataPython
60161
""" Middleware for managing internal server errors, and response with a apt error message """ import falcon class InternalServerErrorManager(object): """Middleware for managing internal server errors""" def process_response(self, request, resp, resource, req_succeeded): """ Manages response if the server encounters any internal server errors. For 500 status Args: req (object): request object resp (object): response object resource (object): Target respource req_succeeded (bool): Does this response succedded Returns: None Raises: falcon.HTTPInternalServerError: Raises Falcon internal server error. """ if resp.status == falcon.HTTP_500: raise falcon.HTTPInternalServerError( title="Internal Server Error", description="Something went wrong on our side. Please try again later.", ) else: return
StarcoderdataPython
96177
<reponame>hqman/velruse """Bitbucket Authentication Views http://confluence.atlassian.com/display/BITBUCKET/OAuth+on+Bitbucket """ import json from urlparse import parse_qs import oauth2 as oauth import requests from pyramid.httpexceptions import HTTPFound from pyramid.security import NO_PERMISSION_REQUIRED from velruse.api import ( AuthenticationComplete, AuthenticationDenied, register_provider, ) from velruse.exceptions import ThirdPartyFailure from velruse.settings import ProviderSettings REQUEST_URL = 'https://bitbucket.org/api/1.0/oauth/request_token/' ACCESS_URL = 'https://bitbucket.org/api/1.0/oauth/access_token/' USER_URL = 'https://bitbucket.org/api/1.0/user' SIGMETHOD = oauth.SignatureMethod_HMAC_SHA1() class BitbucketAuthenticationComplete(AuthenticationComplete): """Bitbucket auth complete""" def includeme(config): config.add_directive('add_bitbucket_login', add_bitbucket_login) config.add_directive('add_bitbucket_login_from_settings', add_bitbucket_login_from_settings) def add_bitbucket_login_from_settings(config, prefix='velruse.bitbucket.'): settings = config.registry.settings p = ProviderSettings(settings, prefix) p.update('consumer_key', required=True) p.update('consumer_secret', required=True) p.update('login_path') p.update('callback_path') config.add_bitbucket_login(**p.kwargs) def add_bitbucket_login(config, consumer_key, consumer_secret, login_path='/bitbucket/login', callback_path='/bitbucket/login/callback', name='bitbucket'): """ Add a Bitbucket login provider to the application. """ provider = BitbucketProvider(name, consumer_key, consumer_secret) config.add_route(provider.login_route, login_path) config.add_view(provider.login, route_name=provider.login_route, permission=NO_PERMISSION_REQUIRED) config.add_route(provider.callback_route, callback_path, use_global_views=True, factory=provider.callback) register_provider(config, name, provider) class BitbucketProvider(object): def __init__(self, name, consumer_key, consumer_secret): self.name = name self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.login_route = 'velruse.%s-login' % name self.callback_route = 'velruse.%s-callback' % name def login(self, request): """Initiate a bitbucket login""" # Create the consumer and client, make the request consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) params = {'oauth_callback': request.route_url(self.callback_route)} # We go through some shennanigans here to specify a callback url oauth_request = oauth.Request.from_consumer_and_token(consumer, http_url=REQUEST_URL, parameters=params) oauth_request.sign_request(SIGMETHOD, consumer, None) r = requests.get(REQUEST_URL, headers=oauth_request.to_header()) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % ( r.status_code, r.content)) request_token = oauth.Token.from_string(r.content) request.session['token'] = r.content req_url = 'https://bitbucket.org/api/1.0/oauth/authenticate/' oauth_request = oauth.Request.from_token_and_callback( token=request_token, http_url=req_url) return HTTPFound(location=oauth_request.to_url()) def callback(self, request): """Process the bitbucket redirect""" if 'denied' in request.GET: return AuthenticationDenied("User denied authentication") request_token = oauth.Token.from_string(request.session['token']) verifier = request.GET.get('oauth_verifier') if not verifier: raise ThirdPartyFailure("No oauth_verifier returned") request_token.set_verifier(verifier) # Create the consumer and client, make the request consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer, request_token) resp, content = client.request(ACCESS_URL, "POST") if resp['status'] != '200': raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content)) access_token = dict(parse_qs(content)) cred = {'oauthAccessToken': access_token['oauth_token'][0], 'oauthAccessTokenSecret': access_token['oauth_token_secret'][0]} # Make a request with the data for more user info token = oauth.Token(key=cred['oauthAccessToken'], secret=cred['oauthAccessTokenSecret']) client = oauth.Client(consumer, token) resp, content = client.request(USER_URL) user_data = json.loads(content) data = user_data['user'] # Setup the normalized contact info profile = {} profile['accounts'] = [{ 'domain':'bitbucket.com', 'username':data['username'] }] profile['preferredUsername'] = data['username'] profile['name'] = { 'formatted': '%s %s' % (data['first_name'], data['last_name']), 'givenName': data['first_name'], 'familyName': data['last_name'], } profile['displayName'] = profile['name']['formatted'] return BitbucketAuthenticationComplete(profile=profile, credentials=cred)
StarcoderdataPython
1767685
# -*- coding: utf-8 -*- from django import template from django.http import QueryDict register = template.Library() @register.filter def number_format(number, args=''): qd = QueryDict(args) decimals = int(qd['decimals']) if 'decimals' in qd else 0 dec_point = str(qd['dec_point']) if 'dec_point' in qd else '.' thousands_sep = str(['thousands_sep']) if 'thousands_sep' in qd else ' ' try: number = round(float(number), decimals) except ValueError: return number neg = number < 0 integer, fractional = str(abs(number)).split('.') m = len(integer) % 3 if m: parts = [integer[:m]] else: parts = [] parts.extend([integer[m+t:m+t+3] for t in xrange(0, len(integer[m:]), 3)]) if decimals: return '%s%s%s%s' % ( neg and '-' or '', thousands_sep.join(parts), dec_point, fractional.ljust(decimals, '0')[:decimals] ) else: return '%s%s' % (neg and '-' or '', thousands_sep.join(parts)) @register.filter def replace(value, args): qd = QueryDict(args) value = unicode(value) if 'from' in qd and 'to' in qd: return value.replace(qd['from'], qd['to']) else: return value
StarcoderdataPython
57975
import re from collections import namedtuple from hon.utils.numberutils import to_int_ns from .preprocessor import Preprocessor class VariablesPreprocessor(Preprocessor): """The variable preprocessor. The variable preprocessor takes the variables defined in the book's configuration file, i.e. ``book.yaml``, and adds them to the context. """ _name = 'variables' def on_run(self, book, renderer, context): """ """ variables = book.config.get('variables', {}) context.data['book'].update(variables)
StarcoderdataPython
3242346
# We need the fsac server, which is provided separately. The build process should place the # required files here. from FSharp.lib import const from FSharp.lib.fsac.server import Server import sublime _server = None def get_server(): global _server if _server is None or not _server.proc.stdin: if sublime.platform() in ('osx', 'linux'): _server = Server('mono', const.path_to_fs_ac_binary()) else: assert sublime.platform() == 'windows' _server = Server(const.path_to_fs_ac_binary()) _server.start() pass return _server
StarcoderdataPython
1738181
# encoding: utf-8 from datetime import datetime import re from django.core.urlresolvers import reverse from django.utils.http import urlencode from django.utils.translation import ugettext as _ from django.db import models from django.contrib.comments.views.comments import post_comment from django.http import HttpResponse from django.test import Client from django.core.handlers.wsgi import WSGIRequest from django.contrib.auth.decorators import login_required from django.contrib.comments.models import Comment from django.http import Http404 from django.shortcuts import get_object_or_404 import django.contrib.comments.views.moderation as moderation from django.utils.encoding import smart_str, smart_unicode from django.conf import settings from mailer import send_html_mail from actstream.models import Action import traceback import hashlib def limit_by_request(qs, request): if 'num' in request.GET: num = int(request.GET['num']) page = 'page' in request.GET and int(request.GET['page']) or 0 return qs[page * num:(page + 1) * num] return qs def yearstart(year): return datetime(year, 1, 1) def yearend(year): return datetime(year, 12, 31) def slugify_name(name): s = smart_str(name).replace("'", '"').replace(' ', '-') if isinstance(name, unicode): return s.decode('utf8') return s def comment_post_wrapper(request): # Clean the request to prevent form spoofing if request.user.is_authenticated(): if (('name' in request.POST and (request.user.get_full_name() != request.POST['name'])) or \ ('email' in request.POST and (request.user.email == request.POST['email']))): return HttpResponse("Access denied") return post_comment(request) return HttpResponse("Access denied") @login_required def delete(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) if request.user == comment.user or request.user.is_staff: return moderation.delete(request, comment_id) else: raise Http404 shitty_chars = [u'\u200e', u'\u200f', u'\u202a', u'\u202b', u'\u202c', u'\u202d', u'\u202e', u'\u201d', u'\u2013'] trans = dict([(ord(chr), None) for chr in shitty_chars]) trans_clean = trans.copy() trans_clean[96] = None for c in ':0123456789(),-"\'': trans_clean[ord(c)] = None def clean_string(s): if isinstance(s, unicode): s = s.translate(trans) else: s = s.replace('\xe2\x80\x9d', '').replace('\xe2\x80\x93', '') return s def clean_string_no_quotes(a_str): return clean_string(a_str).replace('"', '') def cannonize(s): s = clean_string(s) s = s.replace('&nbsp', ' ').replace('gt;', '').replace('\n', '').replace('->', '') s = re.sub("""\d{4,4}""", '', s) return re.sub("""["'`\(\) /.,\-\xa0]""", '', s) # @IndentOk try: from functools import wraps except ImportError: from django.utils.functional import wraps import inspect def disable_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): for fr in inspect.stack(): if inspect.getmodulename(fr[1]) in ('loaddata', 'sync_dev'): return signal_handler(*args, **kwargs) return wrapper class RequestFactory(Client): """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) This class re-uses the django.test.client.Client interface, docs here: http://www.djangoproject.com/documentation/testing/#the-test-client Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def request(self, **request): """ Similar to parent class, but returns the request object as soon as it has created it. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1', } environ.update(self.defaults) environ.update(request) return WSGIRequest(environ) def notify_responsible_adult(msg): """Send an email to some responsible adult(s)""" adults = getattr(settings, 'RESPONSIBLE_ADULTS', None) if adults: from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', '<EMAIL>') send_html_mail(_('Open Knesset requires attention'), msg, msg, from_email, adults) def main_actions(): """ Actions used for main view latests actions and for /feeds/main """ return Action.objects.filter(verb__in=['comment-added', 'annotated']) \ .order_by('-timestamp') \ .prefetch_related('target') def reverse_with_query(viewname, args=None, kwargs=None, query_kwargs=None): """ Custom reverse to add a query string after the url Example usage: url = my_reverse('my_test_url', kwargs={'pk': object.id}, query_kwargs={'next': reverse('home')}) """ requested_url = reverse(viewname, args=None, kwargs=kwargs) if query_kwargs: return u'{0}?{1}'.format(requested_url, urlencode(query_kwargs)) return requested_url def send_chat_notification(file, text, data): from django_slack import slack_message text = ("{text}\n{data}\n-- {file}").format(file=file, text=text, data=data) if getattr(settings, 'SLACK_BACKEND', None) in (None, 'django_slack.backends.DisabledBackend'): print "-- SLACK MESSAGE" print text print "----" else: slack_message('django-slack/text.slack', {"text": text}) def send_chat_exception_notification(file, text_prefix, data, exception): data.update({'traceback': traceback.format_exc()}) send_chat_notification(file, text_prefix + " " + str(exception.message), data) def get_thousands_string(f): """ Get a nice string representation of a field of 1000's of NIS, which is int or None. """ if f is None: return "N/A" elif f == 0: return "0 NIS" else: return "%d000 NIS" % f def get_cache_key(str): str = str.encode('utf-8') return hashlib.sha1(str).hexdigest()
StarcoderdataPython
1674501
<gh_stars>10-100 from buffalo import utils utils.init() from chunk import Chunk from pluginManager import PluginManager PluginManager.loadPlugins() class TestChunk: def test_init(self): assert Chunk(0,0) is not None def test_data(self): chunk = Chunk(100,100) assert chunk.data is not None assert len(chunk.data) is 32 and len(chunk.data[0]) is 32 def test_pos(self): chunk = Chunk(100,100) assert chunk.pos == (100, 100) def test_surface(self): assert Chunk(0,0).surface is not None
StarcoderdataPython
1646758
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ok.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(645, 568) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("images.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setStyleSheet("background-color: rgb(252, 252, 252);\n" "border-top-color: rgb(166, 166, 166);\n" "border-top-color: rgb(172, 172, 172);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout_3.setObjectName("gridLayout_3") self.radioButton_4 = QtWidgets.QRadioButton(self.centralwidget) self.radioButton_4.setObjectName("radioButton_4") self.gridLayout_3.addWidget(self.radioButton_4, 5, 4, 1, 1) self.radioButton_3 = QtWidgets.QRadioButton(self.centralwidget) self.radioButton_3.setObjectName("radioButton_3") self.gridLayout_3.addWidget(self.radioButton_3, 5, 3, 1, 1) self.radioButton_2 = QtWidgets.QRadioButton(self.centralwidget) self.radioButton_2.setObjectName("radioButton_2") self.gridLayout_3.addWidget(self.radioButton_2, 5, 2, 1, 1) spacerItem = QtWidgets.QSpacerItem(50, 17, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem, 6, 6, 1, 1) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem1, 6, 0, 1, 1) spacerItem2 = QtWidgets.QSpacerItem(50, 17, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem2, 6, 8, 1, 1) self.label_8 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_8.setFont(font) self.label_8.setStyleSheet("color: rgb(85, 170, 255);") self.label_8.setObjectName("label_8") self.gridLayout_3.addWidget(self.label_8, 4, 10, 1, 1) self.label_17 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_17.setFont(font) self.label_17.setObjectName("label_17") self.gridLayout_3.addWidget(self.label_17, 6, 7, 1, 1) self.radioButton_1 = QtWidgets.QRadioButton(self.centralwidget) self.radioButton_1.setObjectName("radioButton_1") self.gridLayout_3.addWidget(self.radioButton_1, 5, 1, 1, 1) self.label_9 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_9.setFont(font) self.label_9.setAutoFillBackground(False) self.label_9.setStyleSheet("color: rgb(85, 170, 255);") self.label_9.setObjectName("label_9") self.gridLayout_3.addWidget(self.label_9, 4, 3, 1, 1) self.label_15 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_15.setFont(font) self.label_15.setObjectName("label_15") self.gridLayout_3.addWidget(self.label_15, 5, 9, 1, 1) self.label_16 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_16.setFont(font) self.label_16.setStyleSheet("color: rgb(85, 170, 255);") self.label_16.setObjectName("label_16") self.gridLayout_3.addWidget(self.label_16, 5, 10, 1, 1) self.label_25 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_25.setFont(font) self.label_25.setObjectName("label_25") self.gridLayout_3.addWidget(self.label_25, 4, 9, 1, 1) self.label_24 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_24.setFont(font) self.label_24.setObjectName("label_24") self.gridLayout_3.addWidget(self.label_24, 4, 1, 1, 2) self.label = QtWidgets.QLabel(self.centralwidget) self.label.setText("") self.label.setObjectName("label") self.gridLayout_3.addWidget(self.label, 3, 1, 1, 1) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setText("") self.label_2.setObjectName("label_2") self.gridLayout_3.addWidget(self.label_2, 0, 1, 1, 1) spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem3, 6, 11, 1, 1) self.groupBox = QtWidgets.QGroupBox(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.groupBox.setFont(font) self.groupBox.setStyleSheet("background-color: rgb(213, 213, 213);") self.groupBox.setTitle("") self.groupBox.setObjectName("groupBox") self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox) self.gridLayout_2.setObjectName("gridLayout_2") self.label_4 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_4.setFont(font) self.label_4.setStyleSheet("color: rgb(85, 170, 255);") self.label_4.setObjectName("label_4") self.gridLayout_2.addWidget(self.label_4, 1, 1, 1, 1) self.label_1 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_1.setFont(font) self.label_1.setObjectName("label_1") self.gridLayout_2.addWidget(self.label_1, 1, 0, 1, 1) self.label_11 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_11.setFont(font) self.label_11.setObjectName("label_11") self.gridLayout_2.addWidget(self.label_11, 1, 4, 1, 1) self.label_6 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_6.setFont(font) self.label_6.setStyleSheet("color: rgb(85, 170, 255);") self.label_6.setObjectName("label_6") self.gridLayout_2.addWidget(self.label_6, 1, 5, 1, 1) self.label_19 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_19.setFont(font) self.label_19.setObjectName("label_19") self.gridLayout_2.addWidget(self.label_19, 1, 6, 1, 1) self.label_7 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_7.setFont(font) self.label_7.setStyleSheet("color: rgb(85, 170, 255);") self.label_7.setObjectName("label_7") self.gridLayout_2.addWidget(self.label_7, 1, 7, 1, 1) self.label_21 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(11) self.label_21.setFont(font) self.label_21.setObjectName("label_21") self.gridLayout_2.addWidget(self.label_21, 0, 0, 1, 1) self.label_22 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_22.setFont(font) self.label_22.setObjectName("label_22") self.gridLayout_2.addWidget(self.label_22, 1, 2, 1, 1) self.label_5 = QtWidgets.QLabel(self.groupBox) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_5.setFont(font) self.label_5.setStyleSheet("color: rgb(85, 170, 255);") self.label_5.setObjectName("label_5") self.gridLayout_2.addWidget(self.label_5, 1, 3, 1, 1) self.gridLayout_3.addWidget(self.groupBox, 1, 1, 2, 10) self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setText("") self.label_3.setObjectName("label_3") self.gridLayout_3.addWidget(self.label_3, 7, 1, 1, 1) self.listWidget = QtWidgets.QListWidget(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.listWidget.setFont(font) self.listWidget.setObjectName("listWidget") self.gridLayout_3.addWidget(self.listWidget, 6, 1, 1, 5) self.listWidget_2 = QtWidgets.QListWidget(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.listWidget_2.setFont(font) self.listWidget_2.setObjectName("listWidget_2") self.gridLayout_3.addWidget(self.listWidget_2, 6, 9, 1, 2) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 645, 22)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.menubar.setFont(font) self.menubar.setStyleSheet("alternate-background-color: rgb(204, 204, 204);\n" "selection-background-color: rgb(202, 202, 202);") self.menubar.setObjectName("menubar") self.menuManage_Teams = QtWidgets.QMenu(self.menubar) self.menuManage_Teams.setObjectName("menuManage_Teams") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionNEW_Team = QtWidgets.QAction(MainWindow) self.actionNEW_Team.setObjectName("actionNEW_Team") self.actionOPEN_Team = QtWidgets.QAction(MainWindow) self.actionOPEN_Team.setObjectName("actionOPEN_Team") self.actionSAVE_Team = QtWidgets.QAction(MainWindow) self.actionSAVE_Team.setObjectName("actionSAVE_Team") self.actionEVALUATE_Team = QtWidgets.QAction(MainWindow) self.actionEVALUATE_Team.setObjectName("actionEVALUATE_Team") self.menuManage_Teams.addSeparator() self.menuManage_Teams.addAction(self.actionNEW_Team) self.menuManage_Teams.addSeparator() self.menuManage_Teams.addAction(self.actionOPEN_Team) self.menuManage_Teams.addSeparator() self.menuManage_Teams.addAction(self.actionSAVE_Team) self.menuManage_Teams.addSeparator() self.menuManage_Teams.addAction(self.actionEVALUATE_Team) self.menuManage_Teams.addSeparator() self.menuManage_Teams.addSeparator() self.menubar.addAction(self.menuManage_Teams.menuAction()) self.menuManage_Teams.triggered[QtWidgets.QAction].connect(self.menu) self.retranslateUi(MainWindow) self.radioButton_1.toggled.connect(self.ctg) self.radioButton_2.toggled.connect(self.ctg) self.radioButton_3.toggled.connect(self.ctg) self.radioButton_4.toggled.connect(self.ctg) self.listWidget.itemDoubleClicked.connect(self.removelist1) self.listWidget_2.itemDoubleClicked.connect(self.removelist2) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "fantasy Cricket")) self.radioButton_4.setText(_translate("MainWindow", "WK")) self.radioButton_3.setText(_translate("MainWindow", "AR")) self.radioButton_2.setText(_translate("MainWindow", "BOW")) self.label_8.setText(_translate("MainWindow", "###")) self.label_17.setText(_translate("MainWindow", ">")) self.radioButton_1.setText(_translate("MainWindow", "BAT")) self.label_9.setText(_translate("MainWindow", "###")) self.label_15.setText(_translate("MainWindow", "Team Name")) self.label_16.setText(_translate("MainWindow", "Display Here")) self.label_25.setText(_translate("MainWindow", "Points Used")) self.label_24.setText(_translate("MainWindow", "Points Available")) self.label_4.setText(_translate("MainWindow", "##")) self.label_1.setText(_translate("MainWindow", "Batsman (BAT)")) self.label_11.setText(_translate("MainWindow", "Allrounders (AR)")) self.label_6.setText(_translate("MainWindow", "##")) self.label_19.setText(_translate("MainWindow", "Wicket-keeper (WK)")) self.label_7.setText(_translate("MainWindow", "##")) self.label_21.setText(_translate("MainWindow", "Your Selection")) self.label_22.setText(_translate("MainWindow", "Bowler (BOW)")) self.label_5.setText(_translate("MainWindow", "##")) self.menuManage_Teams.setTitle(_translate("MainWindow", "Manage Teams")) self.actionNEW_Team.setText(_translate("MainWindow", "NEW Team")) self.actionOPEN_Team.setText(_translate("MainWindow", "OPEN Team")) self.actionSAVE_Team.setText(_translate("MainWindow", "SAVE Team")) self.actionEVALUATE_Team.setText(_translate("MainWindow", "EVALUATE Team")) def reset1 (self): self.label_4.setText("##") self.label_5.setText("##") self.label_6.setText("##") self.label_7.setText("##") self.label_8.setText("###") self.label_9.setText("###") self.label_16.setText("Display Here") self.listWidget.clear() self.listWidget_2.clear() def menu(self,action): txt=(action.text()) if txt=='NEW Team': self.bat=0 self.bow=0 self.ar=0 self.wk=0 self.point_used=0 self.point_ava=1000 self.listWidget.clear() self.listWidget_2.clear() sql="select name from teams" cur=conn.execute(sql) row=cur.fetchone() text, ok=QtWidgets.QInputDialog.getText(MainWindow, "Team", "Enter name of team:") for row in cur: if text == row[0]: self.showdlg("match found!!\ntry with another name") return self.label_16.setText(text) if self.label_16.text()=="": self.reset1() return self.show() if txt=='SAVE Team': if self.label_16.text()=='Display Here': self.showdlg("Create a team first\nManage Teams -> NEW Team") self.reset1() return count=self.listWidget_2.count() selected="" for i in range(count): selected+=self.listWidget_2.item(i).text() if i<count-1: selected+="," self.saveteam(self.label_16.text(),selected,self.point_used) if txt=='OPEN Team': self.bat=0 self.bow=0 self.ar=0 self.wk=0 self.point_used=0 self.point_ava=1000 self.listWidget.clear() self.listWidget_2.clear() self.show() #print("rgr") self.openteam() if txt=='EVALUATE Team': Dialog = QtWidgets.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) #print("effieh") ret=Dialog.exec() def show(self): self.label_4.setText(str(self.bat)) self.label_5.setText(str(self.bow)) self.label_6.setText(str(self.ar)) self.label_7.setText(str(self.wk)) self.label_8.setText(str(self.point_used)) self.label_9.setText(str(self.point_ava)) def saveteam(self,nm,ply,val): #print("rvrv") if self.bat+self.bow+self.ar+self.wk!=11: self.showdlg("Insufficient players") return if self.ar ==0: self.showdlg("Insufficient Allrounders") return if self.wk ==0: self.showdlg("Insufficient Wicketkeepers") return sql="select name from teams" cur=conn.execute(sql) row=cur.fetchone() #print(row) text=self.label_16.text() count=self.listWidget_2.count() for row in cur: if text == row[0]: self.showdlg("match found!\nteam is already Saved") self.reset1() return False sql1="INSERT INTO teams (name,players,value) VALUES ('"+nm+"','"+ply+"','"+str(val)+"');" #print("f3f4") try: #print("bjr") cur=conn.execute(sql1) #print("dehe") self.showdlg("Team Saved Succesfully") self.reset1() conn.commit() except: self.showdlg("Error in Operation") conn.rollback() def openteam(self): #print("rvrjbv") sql="select name from teams;" #print("efef") cur=conn.execute(sql) #print("vebjb") teams=["Select Team"] for row in cur: teams.append(row[0]) team, ok=QtWidgets.QInputDialog.getItem(MainWindow,"Fantasy Cricket","Choose A Team",teams,0,False) if ok and team: if team =="Select Team": self.showdlg("select a Team first") self.reset1() return self.label_16.setText(team) else: self.reset1() return sql1="SELECT players,value from teams where name='"+team+"';" cur=conn.execute(sql1) row=cur.fetchone() selected=row[0].split(',') self.listWidget_2.addItems(selected) self.point_used=row[1] self.point_ava=1000-row[1] count=self.listWidget_2.count() ##iterate to count no. of specific players for i in range(count): ply=self.listWidget_2.item(i).text() sql="select category from stats where player='"+ply+"';" cur=conn.execute(sql) row=cur.fetchone() ctgr=row[0] #print("ej") if ctgr=="BAT":self.bat+=1 if ctgr=="BWL":self.bow+=1 if ctgr=="AR":self.ar+=1 if ctgr=="WK":self.wk+=1 self.show() def criteria(self,ctgr,item): msg='' if ctgr=="BAT" and self.bat>=5:msg="Batsmen not more than 5" if ctgr=="BWL" and self.bow>=5:msg="bowlers not more than 5" if ctgr=="AR" and self.ar>=3:msg="Allrounders not more than 3" if ctgr=="WK" and self.wk>=1:msg="Wicketkeepers not more than 1" if msg!='': self.showdlg(msg) return False sql="SELECT value from stats where player='"+item.text()+"'" cur=conn.execute(sql) row=cur.fetchone() self.point_ava-=int(row[0]) self.point_used+=int(row[0]) #msg="You Have Exhausted your Points" if self.point_ava<0: self.showdlg("You Have Exhausted your Points\n Choose some diffrent players") self.point_ava+=int(row[0]) self.point_used-=int(row[0]) return False if ctgr=="BAT":self.bat+=1 if ctgr=="BWL":self.bow+=1 if ctgr=="AR":self.ar+=1 if ctgr=="WK":self.wk+=1 return True def ctg(self): ctgr='' if self.radioButton_1.isChecked()==True:ctgr='BAT' if self.radioButton_2.isChecked()==True:ctgr='BWL' if self.radioButton_3.isChecked()==True:ctgr='AR' if self.radioButton_4.isChecked()==True:ctgr='WK' self.fillList(ctgr) # to show message def showdlg(self,msg): Dialog=QtWidgets.QMessageBox() Dialog.setText(msg) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("images.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Dialog.setWindowIcon(icon) Dialog.setWindowTitle("Fantasy Cricket") font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) Dialog.setFont(font) ret=Dialog.exec() #to fill the left list def fillList(self,ctgr): if self.label_16.text()=='Display Here': self.showdlg("Enter name of team") return self.listWidget.clear() sql="SELECT player from stats where category='"+ctgr+"';" cur=conn.execute(sql) for row in cur: selected=[] for i in range(self.listWidget_2.count()): selected.append(self.listWidget_2.item(i).text()) if row[0] not in selected:self.listWidget.addItem(row[0]) #remove item from list 1 and add it to list 2 def removelist1(self,item): if self.bat+self.bow+self.ar+self.wk>=11: self.showdlg("players not more than 11") return ctgr='' if self.radioButton_1.isChecked()==True:ctgr='BAT' if self.radioButton_2.isChecked()==True:ctgr='BWL' if self.radioButton_3.isChecked()==True:ctgr='AR' if self.radioButton_4.isChecked()==True:ctgr='WK' ret=self.criteria(ctgr,item) if ret==True: self.listWidget.takeItem(self.listWidget.row(item)) self.listWidget_2.addItem(item.text()) self.show() #remove item from list 2 and add it to list 1 def removelist2(self,item): self.listWidget_2.takeItem(self.listWidget_2.row(item)) cursor = conn.execute("SELECT player,value,category from stats where player='"+item.text()+"'") row=cursor.fetchone() self.point_ava=self.point_ava+int(row[1]) self.point_used=self.point_used-int(row[1]) ctgr=row[2] if ctgr=="BAT": self.bat-=1 if self.radioButton_1.isChecked()==True:self.listWidget.addItem(item.text()) if ctgr=="BWL": self.bow-=1 if self.radioButton_2.isChecked()==True:self.listWidget.addItem(item.text()) if ctgr=="AR": self.ar-=1 if self.radioButton_3.isChecked()==True:self.listWidget.addItem(item.text()) if ctgr=="WK": self.wk-=1 if self.radioButton_4.isChecked()==True:self.listWidget.addItem(item.text()) self.show() #class containing Evaluate Team dailog box class Ui_Dialog(Ui_MainWindow): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 480) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("images.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Dialog.setWindowIcon(icon) self.gridLayout = QtWidgets.QGridLayout(Dialog) self.gridLayout.setObjectName("gridLayout") self.label_6 = QtWidgets.QLabel(Dialog) self.label_6.setText("") self.label_6.setObjectName("label_6") self.gridLayout.addWidget(self.label_6, 0, 2, 1, 1) self.label = QtWidgets.QLabel(Dialog) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 1, 2, 1, 3) self.label_7 = QtWidgets.QLabel(Dialog) self.label_7.setText("") self.label_7.setObjectName("label_7") self.gridLayout.addWidget(self.label_7, 2, 2, 1, 1) self.line = QtWidgets.QFrame(Dialog) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.gridLayout.addWidget(self.line, 4, 1, 1, 6) self.label_3 = QtWidgets.QLabel(Dialog) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.gridLayout.addWidget(self.label_3, 6, 1, 1, 1) self.comboBox = QtWidgets.QComboBox(Dialog) font = QtGui.QFont() font.setPointSize(9) self.comboBox.setFont(font) self.comboBox.setEditable(False) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("") self.gridLayout.addWidget(self.comboBox) sql="select name from teams" cur=conn.execute(sql) teams=[] for row in cur: self.comboBox.addItem(row[0]) self.gridLayout.addWidget(self.comboBox, 3, 1, 1, 2) self.label_4 = QtWidgets.QLabel(Dialog) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.gridLayout.addWidget(self.label_4, 6, 4, 1, 1) self.pushButton = QtWidgets.QPushButton(Dialog) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(10) font.setBold(True) font.setItalic(True) font.setWeight(75) self.pushButton.setFont(font) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.calculate) self.gridLayout.addWidget(self.pushButton, 8, 3, 1, 1) self.label_2 = QtWidgets.QLabel(Dialog) self.label_2.setText("") self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 9, 3, 1, 1) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 7, 7, 1, 1) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem1, 7, 0, 1, 1) self.comboBox_2 = QtWidgets.QComboBox(Dialog) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) self.comboBox_2.setFont(font) self.comboBox_2.setEditable(False) self.comboBox_2.setMaxVisibleItems(20) self.comboBox_2.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.comboBox_2.setObjectName("comboBox_2") self.comboBox_2.addItem("") self.comboBox_2.addItem("") self.comboBox_2.addItem("") self.comboBox_2.addItem("") self.comboBox_2.addItem("") self.comboBox_2.addItem("") self.gridLayout.addWidget(self.comboBox_2, 3, 4, 1, 2) self.label_8 = QtWidgets.QLabel(Dialog) self.label_8.setText("") self.label_8.setObjectName("label_8") self.gridLayout.addWidget(self.label_8, 5, 1, 1, 1) self.label_5 = QtWidgets.QLabel(Dialog) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(9) font.setBold(True) font.setWeight(75) self.label_5.setFont(font) self.label_5.setStyleSheet("selection-color: rgb(85, 170, 255);\n" "color: rgb(85, 170, 255);") self.label_5.setObjectName("label_5") self.gridLayout.addWidget(self.label_5, 6, 5, 1, 1) self.listWidget = QtWidgets.QListWidget(Dialog) font = QtGui.QFont() font.setFamily("Arial") self.listWidget.setFont(font) self.listWidget.setObjectName("listWidget") self.gridLayout.addWidget(self.listWidget, 7, 1, 1, 2) self.listWidget_2 = QtWidgets.QListWidget(Dialog) font = QtGui.QFont() font.setFamily("Arial") self.listWidget_2.setFont(font) self.listWidget_2.setObjectName("listWidget_2") self.gridLayout.addWidget(self.listWidget_2, 7, 4, 1, 2) self.retranslateUi(Dialog) self.comboBox_2.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(Dialog) #function used to calculate points scored by the team def calculate(self): if self.comboBox.currentText() =='Select Team': self.listWidget.clear() self.listWidget_2.clear() self.label_5.setText("###") t = Ui_MainWindow() t.showdlg('Select Team') return if self.comboBox_2.currentText() =="Select Match": self.listWidget.clear() self.listWidget_2.clear() self.label_5.setText("###") t = Ui_MainWindow() t.showdlg('Select Match') return team=self.comboBox.currentText() self.listWidget.clear() sql1="select players, value from teams where name='"+team+"'" cur=conn.execute(sql1) row=cur.fetchone() selected=row[0].split(',') self.listWidget.addItems(selected) teamttl=0 self.listWidget_2.clear() match=self.comboBox_2.currentText() for i in range(self.listWidget.count()): ttl, batscore, bowlscore, fieldscore=0,0,0,0 nm=self.listWidget.item(i).text() cursor=conn.execute("select * from "+match+" where player='"+nm+"'") row=cursor.fetchone() batscore=int(row[1]//2) if batscore>=50: batscore+=5 if batscore>=100: batscore+=10 if row[2]>0: sr=(row[1]/row[2])*100 if sr>=80: batscore+=2 if sr>=100:batscore+=4 batscore+=row[3] batscore+=2*row[4] bowlscore=row[8]*10 if row[8]>=3: bowlscore=bowlscore+5 if row[8]>=5: bowlscore=bowlscore+10 if row[5]>0: er=row[7]/row[5] if er<=2: bowlscore=bowlscore+10 elif er>2 and er<=3.5: bowlscore=bowlscore+7 elif er>3.5 and er<=4.5: bowlscore=bowlscore+4 fieldscore=(row[9]+row[10]+row[11])*10 ttl=batscore+bowlscore+fieldscore self.listWidget_2.addItem(str(ttl)) teamttl=teamttl+ttl self.label_5.setText(str(teamttl)) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Fantasy Cricket")) self.label.setText(_translate("Dialog", "Evaluate the Performance of your Fantasy Team")) self.label_3.setText(_translate("Dialog", "Players")) self.comboBox.setItemText(0, _translate("Dialog", "Select Team")) self.label_4.setText(_translate("Dialog", "Points")) self.pushButton.setText(_translate("Dialog", "Calculate Score")) self.comboBox_2.setCurrentText(_translate("Dialog", "Select Match")) self.comboBox_2.setItemText(0, _translate("Dialog", "Select Match")) self.comboBox_2.setItemText(1, _translate("Dialog", "match1")) self.comboBox_2.setItemText(2, _translate("Dialog", "match2")) self.comboBox_2.setItemText(3, _translate("Dialog", "match3")) self.comboBox_2.setItemText(4, _translate("Dialog", "match4")) self.comboBox_2.setItemText(5, _translate("Dialog", "match5")) self.label_5.setText(_translate("Dialog", "###")) self.listWidget_2.setWhatsThis(_translate("Dialog", "<html><head/><body><p>help</p></body></html>")) if __name__ == "__main__": import sys import sqlite3 conn = sqlite3.connect('FantasyCricket.db') app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
StarcoderdataPython
1685123
<gh_stars>0 import csv import cv2 import sys import numpy as np from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout from keras.layers.convolutional import Convolution2D from keras.models import Model import matplotlib.pyplot as plt from sklearn.utils import shuffle from sklearn.model_selection import train_test_split # Generator function to increase the efficiency of the training process def generator(samples, batch_size = 32): num_samples = len(samples) while 1: for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset + batch_size] images = [] steering_angles = [] # Extracting images for sample in batch_samples: if line[0].startswith("IMG"): img_center_path = "/Users/adityaborde/Self-Driving-Car-ND/CarND-Behavioral-Cloning-P3/CarND-Behavioral-Cloning-P3/data/" + str(sample[0]) else: img_center_path = line[0] if line[1].startswith(" IMG"): img_left_path = "/Users/adityaborde/Self-Driving-Car-ND/CarND-Behavioral-Cloning-P3/CarND-Behavioral-Cloning-P3/data/" + str(sample[1]) else: img_left_path = line[1] if line[2].startswith(" IMG"): img_right_path = "/Users/adityaborde/Self-Driving-Car-ND/CarND-Behavioral-Cloning-P3/CarND-Behavioral-Cloning-P3/data/" + str(sample[2]) else: img_right_path = line[2] # Extracting images from all the angles i.e. center, left, right img_center = cv2.imread(img_center_path.replace(" ", "")) img_left = cv2.imread(img_left_path.replace(" ", "")) img_right = cv2.imread(img_right_path.replace(" ", "")) img_center = cv2.cvtColor(img_center, cv2.COLOR_BGR2YUV) img_left = cv2.cvtColor(img_left, cv2.COLOR_BGR2YUV) img_right = cv2.cvtColor(img_right, cv2.COLOR_BGR2YUV) # Adding image to the list of images images.append(img_center) images.append(img_left) images.append(img_right) steering_angles.append((float)(sample[3])) # Adjusting steering angle for left and right images steering_angles.append((float)(sample[3]) + 0.2) steering_angles.append((float)(sample[3]) - 0.2) x_train = np.array(images) y_train = np.array(steering_angles) # Shuffling the data yield shuffle(x_train, y_train) lines = [] # Reading the csv file containing the image location and steering angles with open('data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: lines.append(line) lines = lines[1:] # Spliting the data into training and validation data train_samples, validation_samples = train_test_split(lines, test_size=0.2) train_generator = generator(train_samples, batch_size=32) validation_generator = generator(validation_samples, batch_size=32) print('Training Begins...') # Defining the model for training model = Sequential() # Building Network # Layer 1: Normalization of Image model.add(Lambda(lambda x: (x / 127.5) - 1, input_shape=(160, 320, 3))) # Layer 2: Cropping the image so that the relevant portion is highlighted model.add(Cropping2D(cropping=((50,20), (0,0)), input_shape=(160,320,3))) # Layer 3: Convolutional Layer 5x5 kernel model.add(Convolution2D(24, 5, 5, subsample=(2,2), activation='relu')) # Layer 4: Convolutional Layer 5x5 kernel model.add(Convolution2D(36, 5, 5, subsample=(2,2), activation='relu')) # Layer 5: Convolutional Layer 5x5 kernel model.add(Convolution2D(48, 5, 5, subsample=(2,2), activation='relu')) # Layer 6: Convolutional Layer 3x3 kernel model.add(Convolution2D(64, 3, 3, activation='relu')) # Layer 7: Convolutional Layer 3x3 kernel model.add(Convolution2D(64, 3, 3, activation='relu')) # Flattening image model.add(Flatten()) # Layer 8: Fully Connected Layer, Output: 100 model.add(Dense(100)) # Layer 9: Fully Connected Layer, Output: 50 model.add(Dense(50)) # Layer 10: Fully Connected Layer, Output: 10 model.add(Dense(10)) # Layer 11: Fully Connected Layer, Output: 1 model.add(Dense(1)) # Compiling model using MSE as loss function and Adam Optimizer model.compile(loss='mse', optimizer='adam') # Providing data to fit for the model model.fit_generator(train_generator, samples_per_epoch = len(train_samples), validation_data = validation_generator, nb_val_samples=len(validation_samples), nb_epoch=5) # Saving model model.save('model.h5')
StarcoderdataPython
31704
""" Discussion: Because we have a facilitatory synapses, as the input rate increases synaptic resources released per spike also increase. Therefore, we expect that the synaptic conductance will increase with input rate. However, total synaptic resources are finite. And they recover in a finite time. Therefore, at high frequency inputs synaptic resources are rapidly deleted at a higher rate than their recovery, so after first few spikes, only a small number of synaptic resources are left. This results in decrease in the steady-state synaptic conductance at high frequency inputs. """;
StarcoderdataPython
109908
#!/usr/bin/python3 # # Copyright 2017 <NAME>, Inc. # All rights reserved # # Redistribution and use in source and binary forms, with or without # modification, are permitted providing that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING # IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import argparse import traceback import librpc import os import readline class CommandDispatcher(object): def __init__(self, client): self.client = client self.current = client.instances['/'] def cmd_show(self, *args): print('Interfaces:') for i in self.current.interfaces: print(' {0}'.format(i)) print('Methods:') for ifname, iface in self.current.interfaces.items(): for mname in iface.methods: print(' {0}.{1}'.format(ifname, mname)) print('Properties:') for ifname, iface in self.current.interfaces.items(): for pname, fns in iface.properties.items(): getter, _ = fns try: value = repr(getter()) if getter else '<no getter>' except librpc.RpcException as err: value = '<error: {0}>'.format(str(err)) print(' {0}.{1} ({2})'.format(ifname, pname, value)) def cmd_cd(self, *args): self.current = self.client.instances[args[0]] def cmd_pwd(self, *args): print(self.current.path) def cmd_objects(self, *args): for i in sorted(self.client.instances): print(i) def cmd_call(self, *args): iface = self.current.interfaces[args[0]] try: fn = getattr(iface, args[1]) params = [eval(s) for s in args[2:]] result = fn(*params) if hasattr(result, '__next__'): for r in result: print(r) else: print(result) except Exception: traceback.print_exc() def cmd_get(self, *args): iface = self.current.interfaces[args[0]] try: prop = getattr(iface, args[1]) print(prop) except Exception: traceback.print_exc() def cmd_set(self, *args): iface = self.current.interfaces[args[0]] try: setattr(iface, args[1], eval(args[2])) except Exception: traceback.print_exc() def cmd_watch(self, *args): pass def repl(self): while True: line = input('{0}> '.format(self.current.path)) tokens = line.split() if not tokens: continue try: fn = getattr(self, 'cmd_{0}'.format(tokens[0])) fn(*tokens[1:]) except AttributeError: print('Command not found') continue def on_error(code, args): print('Connection closed: {0}'.format(str(code))) os._exit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument('--uri', help='Server URI', required=True) args = parser.parse_args() client = librpc.Client() client.connect(args.uri) client.error_handler = on_error client.unpack = True try: cmd = CommandDispatcher(client) cmd.repl() except KeyboardInterrupt: pass if __name__ == '__main__': main()
StarcoderdataPython
4812004
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "0.1.0", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = r""" --- module: launchdarkly_user_segment_sync short_description: Sync LaunchDarkly User Segments across Environments description: - Sync LaunchDarkly User Segments across Environments version_added: "0.1.0" options: project_key: description: - Project key to look for flag default: 'default' type: str user_segment_key: description: - A unique key that will be used to reference the user segment in this environment. type: str required: yes environment_key: description: - A unique key that will be used to determine source environment. required: yes type: str environment_targets: description: - A list of environments that flag settings will be copied to. required: yes type: list includedActions: description: - Manage a list of included actions for copying. required: no type: list choices: ['updateTargets', 'updateRules'] excludedActions: description: - Manage a list of excluded actions for copying. required: no type: list choices: [updateTargets', 'updateRules'] extends_documentation_fragment: launchdarkly_labs.collection.launchdarkly """ EXAMPLES = r""" # Sync a LaunchDarkly User Segment to multiple environments - launchdarkly_user_segment_sync: environment_key: test-environment-1 environment_targets: - dev - staging - production name: "Test Segment" includedActions: - updateOn - updateRules """ RETURN = r""" """ import inspect import traceback LD_IMP_ERR = None try: import launchdarkly_api from launchdarkly_api.rest import ApiException from dictdiffer import diff HAS_LD = True except ImportError: LD_IMP_ERR = traceback.format_exc() HAS_LD = False from ansible.module_utils.basic import AnsibleModule, missing_required_lib, env_fallback from ansible.module_utils._text import to_native from ansible.module_utils.common._json_compat import json from ansible_collections.launchdarkly_labs.collection.plugins.module_utils.base import ( configure_instance, fail_exit, ld_common_argument_spec, ) def main(): module = AnsibleModule( argument_spec=dict( state=dict(type="str", default="present", choices=["absent", "present"]), api_key=dict( required=True, type="str", no_log=True, fallback=(env_fallback, ["LAUNCHDARKLY_ACCESS_TOKEN"]), ), environment_key=dict(type="str", required=True), project_key=dict(type="str", required=True), user_segment_key=dict(type="str", required=True), environment_targets=dict(type="list", required=True), included_actions=dict( type="list", choices=["updateTargets", "updateRules"] ), excluded_actions=dict( type="list", choices=["updateTargets", "updateRules"] ), ) ) if not HAS_LD: module.fail_json( msg=missing_required_lib("launchdarkly_api"), exception=LD_IMP_ERR ) configuration = configure_instance(module.params["api_key"]) api_instance = launchdarkly_api.UserSegmentsApi( launchdarkly_api.ApiClient(configuration) ) _configure_user_sync(module, api_instance) def _configure_user_sync(module, api_instance): user_segment = api_instance.get_user_segment( module.params["project_key"], module.params["environment_key"], module.params["user_segment_key"], ) new_segment = launchdarkly_api.UserSegmentBody( name=user_segment.name, key=user_segment.key, description=user_segment.description, tags=user_segment.tags, ) for idx, env in enumerate(module.params["environment_targets"]): patches = [] try: response, status, headers = api_instance.post_user_segment_with_http_info( module.params["project_key"], env, new_segment ) except ApiException as e: if e.status == 409: ( response, status, headers, ) = api_instance.get_user_segment_with_http_info( module.params["project_key"], env, module.params["user_segment_key"] ) if user_segment.name is not None and user_segment.name != response.name: patches.append(_patch_op("replace", "/name", user_segment.name)) if ( user_segment.description is not None and user_segment.description != response.description ): patches.append( _patch_op("replace", "/description", user_segment.description) ) if user_segment.tags is not None and set(user_segment.tags) != set( response.tags ): patches.append(_patch_op("replace", "/tags", user_segment.tags)) else: fail_exit(module, e) if ( module.params["included_actions"] is None or ( "updateTargets" in module.params["included_actions"] or "updateTargets" not in module.params["excluded_actions"] ) and ( set(response.included) != set(user_segment.included) or set(response.excluded) != set(user_segment.excluded) ) ): patches.append(_patch_op("replace", "/included", user_segment.included)) patches.append(_patch_op("replace", "/excluded", user_segment.excluded)) if module.params["included_actions"] is None or ( "updateRules" in module.params["included_actions"] or "updateRules" not in module.params["excluded_actions"] ): for rule in user_segment.rules: patches.append( launchdarkly_api.PatchOperation( op="add", path="/rules", value=user_segment.rules ) ) try: response, status, headers = api_instance.patch_user_segment_with_http_info( module.params["project_key"], env, user_segment.key, patches ) except ApiException as e: if e.status == 404: module.exit_json( failed=True, msg="user segment key: %s not found" % module.params["user_segment_key"], ) else: fail_exit(module, e) module.exit_json( changed=True, msg="feature flags synced", user_segment=response.to_dict() ) if __name__ == "__main__": main()
StarcoderdataPython
100380
import gc import ctypes from . import list_methods from inspect import getmembers, isfunction def add_method(builtin_class, method_name, method_function): patchable_builtin_class = gc.get_referents(builtin_class.__dict__)[0] patchable_builtin_class[method_name] = method_function ctypes.pythonapi.PyType_Modified(ctypes.py_object(builtin_class)) all_list_methods = getmembers(list_methods, isfunction) for method_name, method_function in all_list_methods: add_method(list, method_name[:-7], method_function)
StarcoderdataPython
4808434
from django.contrib import admin from .models import Team, Player, Role admin.site.register(Team) admin.site.register(Player) admin.site.register(Role)
StarcoderdataPython
4801433
<gh_stars>0 import json from re import L from requests.api import get import logging from retrieve_config_data import news_apikey from retrieve_config_data import covid_terms def news_API_request(covid_terms = covid_terms): """argument string the phrases which to retreive articles with from the api gets news articles from the api which contain the correct terms return list(dictionary) the correct news articles from api """ key = news_apikey ##change this through config url = 'https://newsapi.org/v2/everything?q=' + covid_terms + "&apiKey=" + key logging.info("getting data from api") data = get(url).json()['articles'] logging.info("got data from api") return data ##key : 447b46b598644e9c83d9f2ae23b1ba20 ##note when submitting put insert api key here in the config file def update_news(covid_terms = covid_terms, articles = []): """argument list(dictionary) recalls the api and updates the news articles return list(dictionary) updated list of news articles """ for art in news_API_request(covid_terms): try: articles.append(art) except: logging.error("articles is not callable") logging.debug("type of articles is" + str(type(articles))) return articles
StarcoderdataPython
3362202
""" A DXT->PNG converter for the DXT1 Python Codeclub exercise. @author Romet """ from struct import unpack from PIL import Image def decode_rgb565(val): """Decode a RGB565 uint16 into a RGB888 tuple.""" r5 = (val & 0xf800) >> 11 g6 = (val & 0x7e0) >> 5 b5 = val & 0x1f return ( int((r5 * 255 + 15) / 31), int((g6 * 255 + 31) / 63), int((b5 * 255 + 15) / 31) ) def expand_palette(palette): """Generate 2 additional colours from an existing palette.""" col1 = palette[0] col2 = palette[1] col3 = tuple(int(2/3 * col1[x] + 1/3 * col2[x]) for x in range(3)) if sum(col2) < sum(col1): col4 = tuple(int(1/3 * col1[x] + 2/3 * col2[x]) for x in range(3)) else: col4 = (0, 0, 0, 0) return [col1, col2, col3, col4] class DXT(object): """A base class to contain and decode DXT-encoded image buffers.""" def __init__(self, image_data, size_tuple): """Initialize and decode a DXT object.""" (self.img_width, self.img_height) = size_tuple self.pixels = [] for i in range(0, len(image_data), 8): palette_buf = image_data[i:i+4] indices_buf = image_data[i+4:i+8] palette = [decode_rgb565(col) for col in unpack("HH", palette_buf)] palette = expand_palette(palette) for row_int in indices_buf: for bit_idx in range(0, 8, 2): palette_idx = (row_int >> bit_idx) & 3 self.pixels.append(palette[palette_idx]) def get_pil_image(self): """An abstract method placeholder for get_pil_image.""" raise NotImplementedError def export_png(self, filename, scale=1): """Export the DXT buffer as a PNG image using PIL.""" img = self.get_pil_image() if scale > 1: orig_size = img.size new_size = (orig_size[0] * scale, orig_size[1] * scale) img = img.resize(new_size, Image.NEAREST) img.save(filename, "PNG") class DXT1(DXT): """A class to contain, decode and export DXT1-encoded image buffers.""" def get_pil_image(self): """Create a PIL Image from DXT1 chunks.""" img = Image.new("RGBA", (self.img_width, self.img_height), "black") img_pixels = img.load() pixel_count = len(self.pixels) chunk_count = pixel_count // 16 chunks_wide = chunk_count // (self.img_height // 4) print("chunks_wide", chunks_wide) print("chunk_count", chunk_count) for chunk_idx in range(chunk_count): chunk_x = chunk_idx % chunks_wide chunk_y = chunk_idx // chunks_wide print("chunk:", chunk_x, chunk_y) for col_idx in range(16): x = col_idx % 4 + chunk_x * 4 y = col_idx // 4 + chunk_y * 4 print(x, y) try: img_pixels[x, y] = self.pixels[chunk_idx * 16 + col_idx] except: print("out of range") return img
StarcoderdataPython
74391
<gh_stars>1-10 from cursor import data from cursor import renderer from enum import Enum import wasabi import inspect import hashlib log = wasabi.Printer() class MinMax: def __init__(self, minx: int, maxx: int, miny: int, maxy: int): self.minx = minx self.maxx = maxx self.miny = miny self.maxy = maxy def center(self): return (self.minx + self.maxx) / 2, (self.miny + self.maxy) / 2 def tuple(self): return self.minx, self.maxx, self.miny, self.maxy class PlotterType(Enum): ROLAND_DPX3300 = 0 DIY_PLOTTER = 1 AXIDRAW = 2 HP_7475A_A4 = 3 HP_7475A_A3 = 4 ROLAND_DXY1200 = 5 ROLAND_DXY980 = 6 HP_7595A = 7 ROLAND_PNC1000 = 8 ROLAND_DPX3300_A2 = 9 ROLAND_DPX3300_A3 = 10 HP_7595A_A3 = 11 class ExportFormat(Enum): JPG = 0 SVG = 1 GCODE = 2 HPGL = 3 class ExportFormatMappings: maps = { PlotterType.ROLAND_DPX3300: ExportFormat.HPGL, PlotterType.ROLAND_DPX3300_A2: ExportFormat.HPGL, PlotterType.ROLAND_DPX3300_A3: ExportFormat.HPGL, PlotterType.DIY_PLOTTER: ExportFormat.GCODE, PlotterType.AXIDRAW: ExportFormat.SVG, PlotterType.HP_7475A_A3: ExportFormat.HPGL, PlotterType.HP_7475A_A4: ExportFormat.HPGL, PlotterType.ROLAND_DXY1200: ExportFormat.HPGL, PlotterType.ROLAND_DXY980: ExportFormat.HPGL, PlotterType.HP_7595A: ExportFormat.HPGL, PlotterType.ROLAND_PNC1000: ExportFormat.HPGL, PlotterType.HP_7595A_A3: ExportFormat.HPGL, } class MinmaxMapping: maps = { PlotterType.ROLAND_DPX3300: MinMax(-16920, 16340, -11180, 11180), PlotterType.ROLAND_DPX3300_A2: MinMax(-16920, 5440, -11180, 4629), PlotterType.ROLAND_DPX3300_A3: MinMax(-16920, -1112, -11180, -3276), PlotterType.DIY_PLOTTER: MinMax(0, 3350, 0, -1715), PlotterType.AXIDRAW: MinMax(0, 0, 0, -0), # todo: missing real bounds PlotterType.HP_7475A_A4: MinMax(0, 11040, 0, 7721), PlotterType.HP_7475A_A3: MinMax(0, 16158, 0, 11040), PlotterType.ROLAND_DXY1200: MinMax(0, 0, 0, 0), # todo: missing real bounds PlotterType.ROLAND_DXY980: MinMax(0, 16158, 0, 11040), PlotterType.HP_7595A: MinMax(-23160, 23160, -17602, 17602), PlotterType.ROLAND_PNC1000: MinMax(0, 0, 17200, 40000), # actually unlimited y PlotterType.HP_7595A_A3: MinMax(-7728, 7728 + 960, -5752, 5752), } class PaperSize(Enum): PORTRAIT_36_48 = 0 LANDSCAPE_48_36 = 1 PORTRAIT_42_56 = 2 LANDSCAPE_56_42 = 3 PORTRAIT_50_70 = 4 LANDSCAPE_70_50 = 5 SQUARE_70_70 = 6 PORTRAIT_70_100 = 7 LANDSCAPE_100_70 = 8 LANDSCAPE_A4 = 9 PORTRAIT_A4 = 10 LANDSCAPE_A1 = 11 LANDSCAPE_A0 = 12 PORTRAIT_A3 = 13 LANDSCAPE_A3 = 14 LANDSCAPE_80_50 = 15 PORTRAIT_50_80 = 16 LANDSCAPE_A2 = 17 SQUARE_59_59 = 18 class PlotterName: names = { PlotterType.ROLAND_DPX3300: "dpx3300", PlotterType.ROLAND_DPX3300_A2: "dpx3300_a2", PlotterType.ROLAND_DPX3300_A3: "dpx3300_a3", PlotterType.AXIDRAW: "axidraw", PlotterType.DIY_PLOTTER: "custom", PlotterType.HP_7475A_A3: "hp7475a_a3", PlotterType.HP_7475A_A4: "hp7475a_a4", PlotterType.ROLAND_DXY1200: "dxy1200", PlotterType.ROLAND_DXY980: "dxy980", PlotterType.HP_7595A: "hp7595a_draftmaster_sx", PlotterType.ROLAND_PNC1000: "roland_camm1", PlotterType.HP_7595A_A3: "hp7595a_draftmaster_sx_a3", } class PaperSizeName: names = { PaperSize.PORTRAIT_36_48: "portrait_36_48", PaperSize.LANDSCAPE_48_36: "landscape_48_36", PaperSize.PORTRAIT_42_56: "portrait_42_56", PaperSize.LANDSCAPE_56_42: "landscape_56_42", PaperSize.PORTRAIT_50_70: "portrait_50_70", PaperSize.LANDSCAPE_70_50: "landscape_70_50", PaperSize.SQUARE_70_70: "square_70_70", PaperSize.PORTRAIT_70_100: "portrait_70_100", PaperSize.LANDSCAPE_100_70: "landscape_100_70", PaperSize.LANDSCAPE_A4: "landscape_a4", PaperSize.PORTRAIT_A4: "portrait_a4", PaperSize.LANDSCAPE_A1: "landscape_a1", PaperSize.LANDSCAPE_A0: "landscape_a0", PaperSize.PORTRAIT_A3: "portrait_a3", PaperSize.LANDSCAPE_A3: "landscape_a3", PaperSize.LANDSCAPE_80_50: "landscape_80x50", PaperSize.PORTRAIT_50_80: "portrait_50_80", PaperSize.LANDSCAPE_A2: "landscape_a2", PaperSize.SQUARE_59_59: "square_59_59", } class Paper: sizes = { PaperSize.PORTRAIT_36_48: (360, 480), PaperSize.LANDSCAPE_48_36: (480, 360), PaperSize.PORTRAIT_42_56: (420, 560), PaperSize.LANDSCAPE_56_42: (560, 420), PaperSize.PORTRAIT_50_70: (500, 700), PaperSize.LANDSCAPE_70_50: (700, 500), PaperSize.SQUARE_70_70: (700, 700), PaperSize.PORTRAIT_70_100: (700, 1000), PaperSize.LANDSCAPE_100_70: (1000, 700), PaperSize.LANDSCAPE_A4: (297, 210), PaperSize.PORTRAIT_A4: (210, 297), PaperSize.LANDSCAPE_A1: (841, 594), PaperSize.LANDSCAPE_A0: (1189, 841), PaperSize.PORTRAIT_A3: (297, 420), PaperSize.LANDSCAPE_A3: (420, 297), PaperSize.LANDSCAPE_80_50: (800, 500), PaperSize.PORTRAIT_50_80: (500, 800), PaperSize.LANDSCAPE_A2: (594, 420), PaperSize.SQUARE_59_59: (590, 590), } class XYFactors: fac = { PlotterType.ROLAND_DPX3300: (40, 40), PlotterType.ROLAND_DPX3300_A2: (40, 40), PlotterType.ROLAND_DPX3300_A3: (40, 40), PlotterType.DIY_PLOTTER: (2.85714, 2.90572), PlotterType.AXIDRAW: (3.704, 3.704), PlotterType.HP_7475A_A3: (40, 40), PlotterType.HP_7475A_A4: (40, 40), PlotterType.ROLAND_DXY1200: (40, 40), PlotterType.ROLAND_DXY980: (40, 40), PlotterType.HP_7595A: (40, 40), PlotterType.ROLAND_PNC1000: (40, 40), PlotterType.HP_7595A_A3: (37, 37), } class Cfg: def __init__(self): self.__type = None self.__dimensions = None self.__margin = None self.__cutoff = None @property def type(self) -> PlotterType: return self.__type @type.setter def type(self, t: PlotterType) -> None: self.__type = t @property def dimension(self) -> PaperSize: return self.__dimensions @dimension.setter def dimension(self, t: PaperSize): self.__dimensions = t @property def margin(self) -> int: return self.__margin @margin.setter def margin(self, t: int): self.__margin = t @property def cutoff(self) -> int: return self.__cutoff @cutoff.setter def cutoff(self, t: int): self.__cutoff = t class Exporter: from cursor import path def __init__(self): self.__paths = None self.__cfg = None self.__name = None self.__suffix = None self.__gcode_speed = None self.__layer_pen_mapping = None self.__linetype_mapping = None @property def paths(self) -> path.PathCollection: return self.__paths @paths.setter def paths(self, t: path.PathCollection) -> None: self.__paths = t @property def cfg(self) -> Cfg: return self.__cfg @cfg.setter def cfg(self, t: Cfg) -> None: self.__cfg = t @property def name(self) -> str: return self.__name @name.setter def name(self, t: str) -> None: self.__name = t @property def suffix(self) -> str: return self.__suffix @suffix.setter def suffix(self, t: str) -> None: self.__suffix = t @property def gcode_speed(self) -> int: return self.__gcode_speed @gcode_speed.setter def gcode_speed(self, t: int) -> None: self.__gcode_speed = t @property def layer_pen_mapping(self) -> dict: return self.__layer_pen_mapping @layer_pen_mapping.setter def layer_pen_mapping(self, m: dict) -> None: self.__layer_pen_mapping = m @property def linetype_mapping(self) -> dict: return self.__linetype_mapping @linetype_mapping.setter def linetype_mapping(self, m: dict) -> None: self.__linetype_mapping = m def run(self, jpg: bool = False, source: bool = False) -> None: if self.cfg is None or self.paths is None or self.name is None: log.fail("Config, Name or Paths is None. Not exporting anything") return # jpeg fitting roughly self.paths.fit( Paper.sizes[self.cfg.dimension], padding_mm=self.cfg.margin, cutoff_mm=self.cfg.cutoff, ) stack = inspect.stack() frame = stack[2] module = inspect.getmodule(frame[0]) ms = inspect.getsource(module) if jpg: separate_layers = self.paths.get_layers() for layer, pc in separate_layers.items(): sizename = PaperSizeName.names[self.cfg.dimension] machinename = PlotterName.names[self.cfg.type] fname = ( f"{self.name}_{self.suffix}_{sizename}_{machinename}_{layer}_" f"{hashlib.sha256(ms.encode('utf-8')).hexdigest()}" ) jpeg_folder = data.DataDirHandler().jpg(self.name) jpeg_renderer = renderer.JpegRenderer(jpeg_folder) jpeg_renderer.render(pc, scale=4.0) jpeg_renderer.save(f"{fname}") if source: source_folder = data.DataDirHandler().source(self.name) sizename = PaperSizeName.names[self.cfg.dimension] machinename = PlotterName.names[self.cfg.type] fname = ( f"{self.name}_{self.suffix}_{sizename}_{machinename}_" f"{hashlib.sha256(ms.encode('utf-8')).hexdigest()}.py" ) import pathlib pathlib.Path(source_folder).mkdir(parents=True, exist_ok=True) log.good(f"Saved source to {source_folder / fname}") with open(source_folder / fname, "w") as file: file.write(ms) self.paths.fit( Paper.sizes[self.cfg.dimension], xy_factor=XYFactors.fac[self.cfg.type], padding_mm=self.cfg.margin, output_bounds=MinmaxMapping.maps[self.cfg.type].tuple(), cutoff_mm=self.cfg.cutoff, ) sizename = PaperSizeName.names[self.cfg.dimension] machinename = PlotterName.names[self.cfg.type] fname = f"{self.name}_{self.suffix}_{sizename}_{machinename}_{hashlib.sha256(ms.encode('utf-8')).hexdigest()}" format = ExportFormatMappings.maps[self.cfg.type] if self.linetype_mapping and format is ExportFormat.HPGL: hpgl_folder = data.DataDirHandler().hpgl(self.name) hpgl_renderer = renderer.HPGLRenderer( hpgl_folder, line_type_mapping=self.linetype_mapping ) hpgl_renderer.render(self.paths) hpgl_renderer.save(f"{fname}") if self.layer_pen_mapping is not None: if format is ExportFormat.HPGL: hpgl_folder = data.DataDirHandler().hpgl(self.name) hpgl_renderer = renderer.HPGLRenderer( hpgl_folder, layer_pen_mapping=self.layer_pen_mapping ) hpgl_renderer.render(self.paths) hpgl_renderer.save(f"{fname}") else: separate_layers = self.paths.get_layers() for layer, pc in separate_layers.items(): if format is ExportFormat.HPGL: hpgl_folder = data.DataDirHandler().hpgl(self.name) hpgl_renderer = renderer.HPGLRenderer(hpgl_folder) hpgl_renderer.render(pc) hpgl_renderer.save(f"{fname}_{layer}") if format is ExportFormat.SVG: svg_dir = data.DataDirHandler().svg(self.name) svg_renderer = renderer.SvgRenderer(svg_dir) svg_renderer.render(pc) svg_renderer.save(f"{fname}_{layer}") if format is ExportFormat.GCODE: gcode_folder = data.DataDirHandler().gcode(self.name) if self.gcode_speed: gcode_renderer = renderer.GCodeRenderer( gcode_folder, z_down=4.5 ) else: gcode_renderer = renderer.GCodeRenderer( gcode_folder, feedrate_xy=self.gcode_speed, z_down=4.5 ) gcode_renderer.render(pc) gcode_renderer.save(f"{layer}_{fname}") class SimpleExportWrapper: from cursor import path def ex( self, paths: path.PathCollection, ptype: PlotterType, psize: PaperSize, margin: int, name: str = "output_name", suffix: str = "", cutoff: int = None, gcode_speed: int = None, hpgl_pen_layer_mapping=None, hpgl_linetype_mapping=None, ): cfg = Cfg() cfg.type = ptype cfg.dimension = psize cfg.margin = margin cfg.cutoff = cutoff # paths.clean() exp = Exporter() exp.cfg = cfg exp.paths = paths exp.name = name exp.suffix = str(suffix) exp.gcode_speed = gcode_speed exp.layer_pen_mapping = hpgl_pen_layer_mapping exp.linetype_mapping = hpgl_linetype_mapping exp.run(True, True)
StarcoderdataPython
127810
import sys import unittest import pendulum from src import ( Crypto, CryptoCommandService, ) from minos.networks import ( InMemoryRequest, Response, ) from tests.utils import ( build_dependency_injector, ) class TestCryptoCommandService(unittest.IsolatedAsyncioTestCase): def setUp(self) -> None: self.injector = build_dependency_injector() async def asyncSetUp(self) -> None: await self.injector.wire(modules=[sys.modules[__name__]]) async def asyncTearDown(self) -> None: await self.injector.unwire() def test_constructor(self): service = CryptoCommandService() self.assertIsInstance(service, CryptoCommandService) async def test_remote_crypto(self): now = pendulum.now() now_minus_one_month = now.subtract(months=1) service = CryptoCommandService() response = service.call_remote("BTC/USD", now_minus_one_month.to_datetime_string()) self.assertIsInstance(service, CryptoCommandService) if __name__ == "__main__": unittest.main()
StarcoderdataPython
1777596
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # classify_images_into_subfolder.py # @Date : 02/08/2021 # @Author : garywei944 (<EMAIL>) # @Link : https://github.com/garywei944 # This script is modified from https://blog.csdn.net/y459541195/article/details/100687966 import numpy as np import pandas as pd import cv2 from preprocess import load_and_process import sys import os import argparse import logging from pathlib import Path import shutil parser = argparse.ArgumentParser(description='Move images into sub-folders according to their Lab Status') parser.add_argument('-i', '--input', type=str, required=True) logging.basicConfig(level=logging.WARNING, stream=sys.stderr) if __name__ == "__main__": args = parser.parse_args() input_path = Path(args.input) data, image_id = load_and_process() # Make directories for dirs in data['Lab Status'].unique(): dirs = str(dirs) (input_path / dirs).mkdir(parents=True, exist_ok=True) for files in os.listdir(input_path): if (input_path/files).is_dir(): continue file_name = os.path.splitext(files)[0] # logging.info("Processing {}".format(input_path / files)) # If the image is clipped from a video, the file_name does not match what records in image_id if file_name not in image_id['FileName'].values: file_name = file_name.split('_clip_')[0] file_name = file_name.split('_copy_')[0] global_id_list = image_id[image_id['FileName'] == file_name].index # logging the file_name if we cannot find the global id if global_id_list is None or len(global_id_list) == 0: logging.warning(file_name) continue global_id = global_id_list[0] label = str(data.loc[global_id, 'Lab Status']) # Move the file into according sub-folder shutil.move(str(input_path / files), str(input_path / label))
StarcoderdataPython
3350947
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuid import django.utils.timezone import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('backend', '0001_initial'), ] operations = [ migrations.CreateModel( name='Score', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)), ('score_id', models.UUIDField(unique=True, default=uuid.uuid4, editable=False)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, editable=False)), ('is_valid', models.BooleanField(default=True)), ('score', models.DecimalField(default=0.0, decimal_places=12, max_digits=20)), ('duration', models.DecimalField(default=0.0, max_digits=14, decimal_places=6, blank=True)), ('params', jsonfield.fields.JSONField(default={}, blank=True)), ('run', models.ForeignKey(to='backend.Run')), ], ), migrations.RemoveField( model_name='result', name='run', ), migrations.DeleteModel( name='Result', ), ]
StarcoderdataPython
3324529
#!/usr/bin/env python ###################################################### # -*- coding: utf-8 -*- # File Name: s3_log_parser.py # Author: <NAME> & <NAME> # Created Date: 2017-10-28 # Description: Parse CloudWatch logs ###################################################### import argparse import json import os import re import sys import boto3 import gzip import numpy as np import shutil import time # need to install python-dateutil import dateutil.parser from collections import OrderedDict TEMP_INPUT = 'download_log.gz' OUTPUT_DIR = './' def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--bucket', '-b', type=str, required=True, help='S3 bucket where logs files are stored') parser.add_argument('--prefix', '-p', type=str, required=True, help='S3 log files prefix') parser.add_argument('--expname', '-e', type=str, required=False, help='Experiment name, eg. example3_138_50_50') parser.add_argument('--outfile', '-o', type=str, required=True, help='File to save parsed output') return parser.parse_args() class StatsObject(object): def __init__(self, expname=None): self.numLambdas = 0 self.totalLogs = 0 if expname is not None: self.validLambda = False else: self.validLambda = True self.expName = expname self.data = OrderedDict() def incrementNumLambdas(self): self.totalLogs += 1 if self.validLambda: self.numLambdas += 1 if self.expName is not None: self.validLambda = False else: pass def record_key_value(self, k, v): if k not in self.data: self.data[k] = [] self.data[k].append(v) def print_stats(self): print 'Parsed %d lambda logs out of %d logs' % (self.numLambdas, self.totalLogs) for k, v in self.data.iteritems(): print k print ' mean:', np.mean(v) print ' stdev:', np.std(v) print ' median:', np.median(v) print ' min:', min(v) print ' max:', max(v) print ' 10th:', np.percentile(v, 10) print ' 25th:', np.percentile(v, 25) print ' 75th:', np.percentile(v, 75) print ' 90th:', np.percentile(v, 90) print ' 95th:', np.percentile(v, 95) print ' 99th:', np.percentile(v, 99) def dump_parsed_values(self, outfile): print >> sys.stderr, 'Writing parsed results to', outfile with open(outfile, 'w') as ofs: json.dump(self.data, ofs) REPORT_RE = re.compile(r'Duration: ([\d.]+) ms[\s]+Billed Duration: (\d+) ms[\s]+Memory Size: (\d+) MB[\s]+Max Memory Used: (\d+) MB') def parse_line(line, stats): if stats.expName and stats.expName in line: stats.validLambda = True if 'START' in line: timeStr, _ = line.split(' ', 1) parsedDate = dateutil.parser.parse(timeStr) stats.record_key_value('start-time', time.mktime(parsedDate.timetuple())) if 'END' in line: timeStr, _ = line.split(' ', 1) parsedDate = dateutil.parser.parse(timeStr) stats.record_key_value('end-time', time.mktime(parsedDate.timetuple())) if stats.validLambda: if 'Timelist:' in line: timelistObj = None try: _, timelist = line.split('Timelist:', 1) timelistObj = json.loads(json.loads(timelist.strip())) except Exception as e: try: timelistObj = json.loads(timelist) except Exception as e: print >> sys.stderr, e, line for k, v in timelistObj.iteritems(): stats.record_key_value(k, v) matchObj = REPORT_RE.search(line) if matchObj is not None: duration = float(matchObj.group(1)) billedDuration = int(matchObj.group(2)) memorySize = int(matchObj.group(3)) maxMemoryUsed = int(matchObj.group(4)) stats.record_key_value('duration', duration) stats.record_key_value('billed-duration', billedDuration) stats.record_key_value('memory-size', memorySize) stats.record_key_value('max-memory-used', maxMemoryUsed) stats.incrementNumLambdas() def ensure_clean_state(downloadDir=None): if downloadDir is not None: if os.path.exists(downloadDir): shutil.rmtree(downloadDir) os.mkdir(downloadDir) else: downloadDir = './' return downloadDir def main(args): downloadDir = args.prefix.split('/')[0] downloadFile = os.path.join(downloadDir, TEMP_INPUT) downloadDir = ensure_clean_state(downloadDir) print >> sys.stderr, 'Local file: ', downloadFile print >> sys.stderr, 'Bucket: ', args.bucket print >> sys.stderr, 'Prefix: ', args.prefix print >> sys.stderr, 'Experiment: ', args.expname stats = StatsObject(args.expname) s3 = boto3.resource('s3') inputBucket = args.bucket inputPrefix = args.prefix # We need to fetch file from S3 logsBucket = s3.Bucket(inputBucket) for obj in logsBucket.objects.filter(Prefix=inputPrefix): objKey = obj.key if objKey.endswith('.gz'): print >> sys.stderr, 'Parsing', objKey s3.Object(logsBucket.name, objKey).download_file(downloadFile) try: with gzip.open(downloadFile, 'rb') as logFile: for line in logFile: parse_line(line, stats) except Exception as e: print >> sys.stderr, e print('S3 Bucket: {}'.format(args.bucket)) print('File Prefix: {}'.format(args.prefix)) print('Experiment: {}'.format(args.expname)) stats.print_stats() if args.outfile is not None: stats.dump_parsed_values(args.outfile) if __name__ == '__main__': main(get_args())
StarcoderdataPython
1613470
<gh_stars>0 """ OpenstackDriver for Compute based on BaseDriver for Compute Resource """ import mock from keystoneauth1.exceptions.base import ClientException from calplus.tests import base from calplus.v1.compute.drivers.openstack import OpenstackDriver fake_config_driver = { 'os_auth_url': 'http://controller:5000/v2_0', 'os_username': 'test', 'os_password': '<PASSWORD>', 'os_project_name': 'demo', 'os_endpoint_url': 'http://controller:9696', 'os_driver_name': 'default', 'os_project_domain_name': 'default', 'os_user_domain_name': 'default', 'tenant_id': 'fake_tenant_id', 'limit': { "subnet": 10, "network": 10, "floatingip": 50, "subnetpool": -1, "security_group_rule": 100, "security_group": 10, "router": 10, "rbac_policy": -1, "port": 50 } } class FakeFloatingIPNotAssociate(object): def to_dict(self): dict = { 'instance_id': None, 'ip': 'fake_public_ip', 'fixed_ip': None, 'id': 'fake_public_ip_id', 'pool': 'provider-net' } return dict class FakeFloatingIP(object): def to_dict(self): dict = { 'instance_id': 'fake_instance_id', 'ip': 'fake_public_ip', 'fixed_ip': 'fake_privte_ip', 'id': 'fake_public_ip_id', 'pool': 'provider-net' } return dict class OpenstackDriverTest(base.TestCase): """docstring for OpenstackDriverTest""" def setUp(self): super(OpenstackDriverTest, self).setUp() self.fake_driver = OpenstackDriver(fake_config_driver) def test_create_successfully(self): self.mock_object( self.fake_driver.client.servers, 'create', mock.Mock(return_value=mock.Mock)) #NOTE: in fact: mock.Mock is novaclient.v2.servers.Server self.fake_driver.create( 'fake_image_id', 'fake_flavor_id', 'fake_net_id', 'fake_name' ) self.fake_driver.client.servers.create.\ assert_called_once_with( name='fake_name', image='fake_image_id', flavor='fake_flavor_id', nics=[{'net-id': 'fake_net_id'}] ) def test_create_without_instance_name(self): self.mock_object( self.fake_driver.client.servers, 'create', mock.Mock(return_value=mock.Mock)) # NOTE: in fact: mock.Mock is novaclient.v2.servers.Server self.fake_driver.create( 'fake_image_id', 'fake_flavor_id', 'fake_net_id' ) self.fake_driver.client.servers.create. \ assert_called_once_with( name=mock.ANY, image='fake_image_id', flavor='fake_flavor_id', nics=[{'net-id': 'fake_net_id'}] ) def test_create_unable_to_create_instance(self): self.mock_object( self.fake_driver.client.servers, 'create', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.create, 'fake_image_id', 'fake_flavor_id', 'fake_net_id', 'fake_name') self.fake_driver.client.servers.create. \ assert_called_once_with( name='fake_name', image='fake_image_id', flavor='fake_flavor_id', nics=[{'net-id': 'fake_net_id'}] ) def test_show_successfully(self): self.mock_object( self.fake_driver.client.servers, 'get', mock.Mock(return_value=mock.Mock)) # NOTE: in fact: mock.Mock is novaclient.v2.servers.Server self.fake_driver.show('fake_id') self.fake_driver.client.servers.get. \ assert_called_once_with('fake_id') def test_show_unable_to_show(self): self.mock_object( self.fake_driver.client.servers, 'get', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.show, 'fake_id') self.fake_driver.client.servers.get. \ assert_called_once_with('fake_id') def test_list_successfully(self): self.mock_object( self.fake_driver.client.servers, 'list', mock.Mock(return_value=[mock.Mock, mock.Mock])) # NOTE: in fact: return_value is novaclient.base.ListWithMeta # And return_value[0] is novaclient.v2.servers.Server self.fake_driver.list() self.fake_driver.client.servers.list. \ assert_called_once_with() def test_list_unable_to_list(self): self.mock_object( self.fake_driver.client.servers, 'list', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.list) self.fake_driver.client.servers.list. \ assert_called_once_with() def test_delete_successfully(self): self.mock_object( self.fake_driver.client.servers, 'delete', mock.Mock(return_value=True)) self.fake_driver.delete('fake_id') self.fake_driver.client.servers.delete. \ assert_called_once_with('fake_id') def test_delete_unable_to_delete(self): self.mock_object( self.fake_driver.client.servers, 'delete', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.delete, 'fake_id') self.fake_driver.client.servers.delete. \ assert_called_once_with('fake_id') def test_shutdown_successfully(self): self.mock_object( self.fake_driver.client.servers, 'stop', mock.Mock(return_value=True)) self.fake_driver.shutdown('fake_id') self.fake_driver.client.servers.stop. \ assert_called_once_with('fake_id') def test_shutdown_unable_to_shutdown(self): self.mock_object( self.fake_driver.client.servers, 'stop', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.shutdown, 'fake_id') self.fake_driver.client.servers.stop. \ assert_called_once_with('fake_id') def test_start_successfully(self): self.mock_object( self.fake_driver.client.servers, 'start', mock.Mock(return_value=True)) self.fake_driver.start('fake_id') self.fake_driver.client.servers.start. \ assert_called_once_with('fake_id') def test_start_unable_to_start(self): self.mock_object( self.fake_driver.client.servers, 'start', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.start, 'fake_id') self.fake_driver.client.servers.start. \ assert_called_once_with('fake_id') def test_reboot_successfully(self): self.mock_object( self.fake_driver.client.servers, 'reboot', mock.Mock(return_value=True)) self.fake_driver.reboot('fake_id') self.fake_driver.client.servers.reboot. \ assert_called_once_with('fake_id') def test_reboot_unable_to_reboot(self): self.mock_object( self.fake_driver.client.servers, 'reboot', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.reboot, 'fake_id') self.fake_driver.client.servers.reboot. \ assert_called_once_with('fake_id') def test_resize_successfully(self): self.mock_object( self.fake_driver.client.servers, 'resize', mock.Mock(return_value=())) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'confirm_resize', mock.Mock(return_value=())) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'revert_resize', mock.Mock()) self.assertEqual(True, self.fake_driver.resize('fake_id', 'fake_flavor_id')) self.fake_driver.client.servers.resize. \ assert_called_once_with('fake_id', 'fake_flavor_id') self.fake_driver.client.servers.confirm_resize. \ assert_called_once_with('fake_id') self.assertFalse( self.fake_driver.client.servers.revert_resize.called) def test_resize_can_not_confirm_resize(self): self.mock_object( self.fake_driver.client.servers, 'resize', mock.Mock(return_value=())) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'confirm_resize', mock.Mock(side_effect=ClientException)) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'revert_resize', mock.Mock(return_value=())) self.assertEqual(False, self.fake_driver.resize('fake_id', 'fake_flavor_id')) self.fake_driver.client.servers.resize. \ assert_called_once_with('fake_id', 'fake_flavor_id') self.fake_driver.client.servers.confirm_resize. \ assert_called_once_with('fake_id') self.fake_driver.client.servers.revert_resize. \ assert_called_once_with('fake_id') def test_resize_can_not_resize(self): self.mock_object( self.fake_driver.client.servers, 'resize', mock.Mock(side_effect=ClientException)) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'confirm_resize', mock.Mock()) self.mock_object( self.fake_driver.client.servers, 'revert_resize', mock.Mock()) self.assertRaises(ClientException, self.fake_driver.resize, 'fake_id', 'fake_flavor_id') self.fake_driver.client.servers.resize. \ assert_called_once_with('fake_id', 'fake_flavor_id') self.assertFalse( self.fake_driver.client.servers.confirm_resize.called) self.assertFalse( self.fake_driver.client.servers.revert_resize.called) def test_resize_can_not_revert(self): self.mock_object( self.fake_driver.client.servers, 'resize', mock.Mock(return_value=())) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'confirm_resize', mock.Mock(side_effect=ClientException)) # in fact: return_value is novaclient.base.TupleWithMeta # printable : () self.mock_object( self.fake_driver.client.servers, 'revert_resize', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.resize, 'fake_id', 'fake_flavor_id') self.fake_driver.client.servers.resize. \ assert_called_once_with('fake_id', 'fake_flavor_id') self.fake_driver.client.servers.confirm_resize. \ assert_called_once_with('fake_id') self.fake_driver.client.servers.revert_resize. \ assert_called_once_with('fake_id') def test_add_nic_successfully(self): self.mock_object( self.fake_driver.client.servers, 'interface_attach', mock.Mock(return_value=mock.Mock)) # NOTE: in fact: mock.Mock is novaclient.v2.servers.Server # but It have port_id and net_id attribute, != nornal Server object self.fake_driver.add_nic('fake_id', 'fake_net_id') self.fake_driver.client.servers.interface_attach. \ assert_called_once_with('fake_id', None, 'fake_net_id', None) def test_add_nic_unable_to_add(self): self.mock_object( self.fake_driver.client.servers, 'interface_attach', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.add_nic, 'fake_id', 'fake_net_id') self.fake_driver.client.servers.interface_attach. \ assert_called_once_with('fake_id', None, 'fake_net_id', None) def test_delete_nic_successfully(self): self.mock_object( self.fake_driver.client.servers, 'interface_detach', mock.Mock(return_value=mock.Mock)) # NOTE: in fact: mock.Mock is novaclient.base.TupleWithMeta # printable: () self.fake_driver.delete_nic('fake_id', 'fake_port_id') self.fake_driver.client.servers.interface_detach. \ assert_called_once_with('fake_id', 'fake_port_id') def test_delete_nic_unable_to_delete(self): self.mock_object( self.fake_driver.client.servers, 'interface_detach', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.delete_nic, 'fake_id', 'fake_port_id') self.fake_driver.client.servers.interface_detach. \ assert_called_once_with('fake_id', 'fake_port_id') def test_list_nic_successfully(self): self.mock_object( self.fake_driver.client.servers, 'interface_list', mock.Mock(return_value=[mock.Mock, mock.Mock])) # NOTE: in fact: return_value is novaclient.base.ListWithMeta # And return_value[0] is novaclient.v2.servers.Server # just call to_dict() for each item to use them easier self.fake_driver.list_nic('fake_id') self.fake_driver.client.servers.interface_list. \ assert_called_once_with('fake_id') def test_list_nic_unable_to_list(self): self.mock_object( self.fake_driver.client.servers, 'interface_list', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.list_nic, 'fake_id') self.fake_driver.client.servers.interface_list. \ assert_called_once_with('fake_id') def test_associate_public_ip_successfully(self): self.mock_object( self.fake_driver.client.floating_ips, 'get', mock.Mock(return_value=FakeFloatingIPNotAssociate())) # NOTE: return_value is novaclient.v2.floating_ips.FloatingIP self.mock_object( self.fake_driver.client.servers, 'add_floating_ip', mock.Mock(return_value=())) self.fake_driver.associate_public_ip( 'fake_id', 'fake_public_ip_id') self.fake_driver.client.floating_ips.get. \ assert_called_once_with('fake_public_ip_id') self.fake_driver.client.servers.add_floating_ip. \ assert_called_once_with( 'fake_id', 'fake_public_ip', None ) def test_associate_public_ip_unable_to_get_floating_ip(self): self.mock_object( self.fake_driver.client.floating_ips, 'get', mock.Mock(side_effect=ClientException)) self.mock_object( self.fake_driver.client.servers, 'add_floating_ip', mock.Mock()) self.assertRaises(ClientException, self.fake_driver.associate_public_ip, 'fake_id', 'fake_public_ip_id') self.fake_driver.client.floating_ips.get. \ assert_called_once_with('fake_public_ip_id') self.assertFalse( self.fake_driver.client.servers.add_floating_ip.called) def test_associate_public_ip_unable_to_add_floating_ip(self): self.mock_object( self.fake_driver.client.floating_ips, 'get', mock.Mock(return_value=FakeFloatingIPNotAssociate())) # NOTE: return_value is novaclient.v2.floating_ips.FloatingIP self.mock_object( self.fake_driver.client.servers, 'add_floating_ip', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.associate_public_ip, 'fake_id', 'fake_public_ip_id') self.fake_driver.client.floating_ips.get. \ assert_called_once_with('fake_public_ip_id') self.fake_driver.client.servers.add_floating_ip. \ assert_called_once_with( 'fake_id', 'fake_public_ip', None ) def test_disassociate_public_ip_successfully(self): self.mock_object( self.fake_driver.client.floating_ips, 'get', mock.Mock(return_value=FakeFloatingIP())) # NOTE: return_value is novaclient.v2.floating_ips.FloatingIP self.mock_object( self.fake_driver.client.servers, 'remove_floating_ip', mock.Mock(return_value=())) self.fake_driver.disassociate_public_ip('fake_public_ip_id') self.fake_driver.client.floating_ips.get. \ assert_called_once_with('fake_public_ip_id') self.fake_driver.client.servers.remove_floating_ip. \ assert_called_once_with( 'fake_instance_id', 'fake_public_ip' ) def test_disassociate_public_ip_unable_to_get_floating_ip(self): self.mock_object( self.fake_driver.client.floating_ips, 'get', mock.Mock(side_effect=ClientException)) self.mock_object( self.fake_driver.client.servers, 'remove_floating_ip', mock.Mock()) self.assertRaises(ClientException, self.fake_driver.disassociate_public_ip, 'fake_public_ip_id') self.fake_driver.client.floating_ips.get. \ assert_called_once_with('fake_public_ip_id') self.assertFalse( self.fake_driver.client.servers.remove_floating_ip.called) def test_disassociate_public_ip_unable_to_remove_floating_ip(self): self.mock_object( self.fake_driver.client.floating_ips, 'get', mock.Mock(return_value=FakeFloatingIP())) # NOTE: return_value is novaclient.v2.floating_ips.FloatingIP self.mock_object( self.fake_driver.client.servers, 'remove_floating_ip', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.disassociate_public_ip, 'fake_public_ip_id') self.fake_driver.client.floating_ips.get. \ assert_called_once_with('fake_public_ip_id') self.fake_driver.client.servers.remove_floating_ip. \ assert_called_once_with( 'fake_instance_id', 'fake_public_ip' ) def test_list_ip_successfully(self): self.mock_object( self.fake_driver.client.servers, 'ips', mock.Mock(return_value={'Int-net': 'fake_list'})) # NOTE: in fact: mock.Mock is novaclient.base.DictWithMeta # printable: show a dict self.fake_driver.list_ip('fake_id') self.fake_driver.client.servers.ips. \ assert_called_once_with('fake_id') def test_list_ip_unable_to_delete(self): self.mock_object( self.fake_driver.client.servers, 'ips', mock.Mock(side_effect=ClientException)) self.assertRaises(ClientException, self.fake_driver.list_ip, 'fake_id') self.fake_driver.client.servers.ips. \ assert_called_once_with('fake_id')
StarcoderdataPython
1776788
<reponame>DPsalmist/bincom # Generated by Django 3.1.4 on 2021-01-08 22:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('polls', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='states', name='state_id', ), ]
StarcoderdataPython
148976
<filename>src/cobra/apps/dashboard/autocheck/app.py from django.conf.urls import url from cobra.core.application import Application from cobra.core.loading import get_class class AutoCheckDashboardApplication(Application): name = None index_view = get_class('dashboard.autocheck.views', 'IndexView') def get_urls(self): urls = [ url(r'^$', self.index_view.as_view(), name='autocheck-index'), ] return self.post_process_urls(urls) application = AutoCheckDashboardApplication()
StarcoderdataPython
1767940
from .service import ContractService __all__ = ( 'ContractService', )
StarcoderdataPython
41221
<reponame>Sulles/YOLOL_Simulator """ Created: October 12, 2019 Author: Sulles === DESCRIPTION === This class houses the revamped GUI object and all associated objects """ # noinspection PyUnresolvedReferences from Classes.map import obj_map # noinspection PyUnresolvedReferences from gui_lib import ListObj, TabList, DisplayBox, InputExtendedListObj, CheckBox, ModifyTextBox from pygame import font as pygame_font, draw as pygame_draw # noinspection PyUnresolvedReferences from src.constants import colors class Menu: def __init__(self, name, options, screen_size): """ Constructor for the Menu object, will handle basic comparison, string, and drawing functionality of all menus :param name: String name of the Menu object :param options: List of strings of all menu options :param screen_size: dictionary with key, value pairs: - 'width': int (pixel width of screen) - 'height': int (pixel height of screen) """ self.name = name self.options = options self.menu = ListObj(self.options, screen_size) def __cmp__(self, other): """ Only use name for comparison """ return self.name == other def __str__(self): """ Only use name for string """ return self.name def draw(self, surface): """ Pass drawing to the list object """ return self.menu.draw(surface) class MainMenu(Menu): def __init__(self, screen_size): """ Constructor for the Main Menu object """ Menu.__init__(self, 'MainMenu', ['Edit Networks', 'Edit Settings', 'Exit'], screen_size) self.menu_to_state_map = {'Edit Networks': 'edit_network', 'Edit Settings': 'edit_settings'} def handle_action(self, action_type, mouse_pos=None, key=None): """ This method will handle all user actions for the Main Menu """ if action_type == 'LEFT_MOUSE_DOWN': response = self.menu.handle_left_mouse_down(mouse_pos) if response == 'Exit': return dict(type='terminate') elif response in self.menu_to_state_map.keys(): return dict(type='transition_state', new_state=self.menu_to_state_map[response]) elif action_type == 'MOUSE_HOVER': self.menu.handle_hover(mouse_pos) else: print('{} does not support: {}'.format(self.name, action_type)) def handle_escape(self): """ transition to normal state when escape is pressed """ self.clean_up() return 'normal' def clean_up(self): pass class EditNetwork(Menu): def __init__(self, screen_size): """ Constructor for the Edit Network object """ Menu.__init__(self, 'EditNetwork', ['Create a New Network', 'Edit Objects in a Network', 'Delete a Network'], screen_size) self.menu_to_state_map = {'Create a New Network': 'create_network', 'Edit Objects in a Network': 'edit_objects', 'Delete a Network': 'delete_network'} def handle_action(self, action_type, mouse_pos=None, key=None): """ This method will handle all user actions for the Main Menu """ if action_type == 'MOUSE_HOVER': self.menu.handle_hover(mouse_pos) elif action_type == 'LEFT_MOUSE_DOWN': response = self.menu.handle_left_mouse_down(mouse_pos) if response in self.menu_to_state_map.keys(): return dict(type='transition_state', new_state=self.menu_to_state_map[response]) else: print('{} does not support: {}'.format(self.name, action_type)) def handle_escape(self): """ transition to main_menu state when escape is pressed """ self.clean_up() return 'main_menu' def clean_up(self): pass class CreateNetwork: def __init__(self, screen_size): """ Constructor for creating a new network """ self.name = 'CreateNetwork' self.screen_size = screen_size self.all_states = dict(select_objects=CreateNetworkSelectObjects(screen_size), edit_objects=CreateNetworkEditObjects(screen_size)) self.state = self.all_states['select_objects'] def draw(self, surface): """ This method passes the drawing responsibility to the states """ self.state.draw(surface) def transition_state(self, new_state): if new_state not in self.all_states.keys(): print('{} IS AN INVALID {} STATE, only states available are: {}'.format( new_state, self.name, self.all_states.keys())) return print('{} Transitioning to state: {}'.format(self.name, new_state)) self.state = self.all_states[new_state] def handle_action(self, action_type, mouse_pos=None, key=None): """ This method will handle all user actions for creating a new network """ response = self.state.handle_action(action_type, mouse_pos, key) if type(response) is dict: if 'type' in response.keys() and response['type'] == 'transition_state': if response['new_state'] in self.all_states.keys(): self.transition_state(response['new_state']) self.state.add_objects(response['data']) def handle_escape(self): """ transition to edit_network state when escape is pressed """ self.clean_up() return 'edit_network' def clean_up(self): self.state = self.all_states['select_objects'] class CreateNetworkSelectObjects: def __init__(self, screen_size): """ Constructor for selecting objects to add to a new network """ self.screen_size = screen_size self.all_objects = InputExtendedListObj(list(obj_map.keys()), screen_size, x_offset=-int(screen_size['width'] / 2) + 80, y_offset=-int(screen_size['height'] / 4) + 60) # def __init__(self, center, text=None, color_map=None, width=50, height=50): self.submit = CheckBox([int(screen_size['width'] / 2), int(3 * screen_size['height'] / 4 + 50)], text='Continue?') def draw(self, surface): """ This method handles drawing all possible objects to be added to a new network """ self.all_objects.draw(surface) self.submit.draw(surface) def handle_action(self, action_type, mouse_pos, key): """ This method handles all actions while selecting objects to add to a new network """ response = self.all_objects.handle_action(action_type, mouse_pos) if response is None: if self.submit.handle_action(action_type, mouse_pos) == 'selected': return dict(type='transition_state', new_state='edit_objects', data=self.all_objects.get_network()) return response class CreateNetworkEditObjects: def __init__(self, screen_size): """ Constructor for editing objects in a new network """ self.screen_size = screen_size self.network_settings = list() self.object_options = list() self.selected_object = None def add_objects(self, add_obj_dict): print('Adding: {} to {}'.format(add_obj_dict, 'CreateNetworkEditObjects')) assert len(add_obj_dict) is not None, 'No objects selected for a new network...' for object_type, num in add_obj_dict.items(): if num != 0: for x in range(num): # Build default settings for each object self.network_settings.append({object_type: dict(name='default', center=[int(self.screen_size['width'] / 2), int(self.screen_size['height'] / 2)])}) print('Updated objects: {}'.format(self.network_settings)) self.create_all_objects() def create_all_objects(self): center = [150, 20] self.object_options = list() count = 0 for obj in self.network_settings: for object_type, settings in obj.items(): count += 1 center[1] += 30 # def __init__(self, prompt, center, width=None, height=50): self.object_options.append(ModifyTextBox(object_type, center, height=30)) # If filled up all left column, start next one if count >= 15: count = 0 center = [300, 20] else: center[0] = 150 def draw(self, surface): """ This method handles drawing all editing options for all objects in a new network """ for obj in self.object_options: obj.draw(surface) def handle_action(self, action_type, mouse_pos, key=None): """ This method handles all actions while editing object properties for a new network """ for obj in self.object_options: obj.handle_action(action_type, mouse_pos, key) class EditObjects: def __init__(self, screen_size): """ Constructor for editing objects in a network """ self.name = 'EditObjects' self.screen_size = screen_size def draw(self, surface): pass def handle_action(self, action_type, mouse_pos=None, key=None): """ This method will handle all user actions for editing objects in a network """ pass def handle_escape(self): """ transition to edit_network state when escape is pressed """ self.clean_up() return 'edit_network' def clean_up(self): pass class DeleteNetwork: def __init__(self, screen_size): """ Constructor for deleting a network """ self.name = 'DeleteNetwork' self.screen_size = screen_size def draw(self, surface): pass def handle_action(self, action_type, mouse_pos=None, key=None): """ This method will handle all user actions for deleting a network """ pass def handle_escape(self): """ transition to edit_network state when escape is pressed """ self.clean_up() return 'edit_network' def clean_up(self): pass class EditSettings(Menu): def __init__(self, screen_size): """ Constructor for the Edit Network object """ Menu.__init__(self, 'EditSettings', ['Change screen size', 'Change FPS'], screen_size) self.menu_to_state_map = {'Change screen size': 'change_screen_size', 'Change FPS': 'change_fps'} def draw(self, surface): pass def handle_escape(self): """ transition to main_menu state when escape is pressed """ self.clean_up() return 'main_menu' def handle_action(self, action_type, mouse_pos=None, key=None): """ This method will handle all user actions for the Edit Settings option """ if action_type == 'MOUSE_HOVER': self.menu.handle_hover(mouse_pos) elif action_type == 'LEFT_MOUSE_DOWN': response = self.menu.handle_left_mouse_down(mouse_pos) if response in self.menu_to_state_map.keys(): print('So you want to {}?'.format(response)) else: print('{} does not support: {}'.format(self.name, action_type)) def clean_up(self): pass class Normal: def __init__(self): """ Constructor for all normal operation for the GUI. This handles: - Network info - Network tabs - Network links - All objects in all networks """ self.name = 'Normal' self.all_networks = list() # self.small_font = pygame_font.Font('src/Cubellan.ttf', 8) self.basic_font = pygame_font.Font('src/Cubellan.ttf', 12) # self.large_font = pygame_font.Font('src/Cubellan.ttf', 18) self.network_tabs = TabList(self.basic_font, list()) self.active_tab = self.network_tabs.get_active_tab() self.all_network_tree_objects = dict() def add_network(self, network): """ This method adds a network to the Normal GUI state :param network: Network object with all objects associated with it """ self.all_networks.append(network) self.network_tabs.add_tab(network.name) self.build_network_tree_objects(network) def build_network_tree_objects(self, network): """ This method builds all the info tree objects for a Network object """ point = [10, 50] info_tree = network.get_info_tree() self.all_network_tree_objects[network.name] = list() self.all_network_tree_objects[network.name].append(DisplayBox(text=network.name, middle_left=point)) point[0] += 15 for obj_name, obj_stats in info_tree.items(): # print('object name? {}'.format(obj_name)) point[1] += 22 self.all_network_tree_objects[network.name].append(DisplayBox(text=obj_name, middle_left=point)) point[0] += 15 for stats in obj_stats: # print('stats? {}'.format(stats)) point[1] += 22 self.all_network_tree_objects[network.name].append(DisplayBox(text=stats, middle_left=point)) point[0] -= 15 self.all_network_tree_objects[network.name].append(info_tree) def step(self): """ Step all networks by one tick """ for network in self.all_networks: network.step() def draw(self, surface): """ This method handles drawing everything under normal circumstances :param surface: PyGame surface object :return: None, will raise error if fails """ self.active_tab = self.network_tabs.get_active_tab() self.network_tabs.draw(surface) self.draw_network_link(surface) for network in self.all_networks: network.draw(surface) self.draw_network_info_tree(surface) def draw_network_info_tree(self, surface): """ This method draws the active network's info tree :param surface: PyGame surface object """ # first check for info tree changes current_network_info_tree = self.all_networks[self.active_tab['index']].get_info_tree() if current_network_info_tree != self.all_network_tree_objects[self.active_tab['name']][-1]: # print('info trees do not match!') self.resolve_info_tree_mismatch() for x in range(len(self.all_network_tree_objects[self.active_tab['name']]) - 1): self.all_network_tree_objects[self.active_tab['name']][x].draw(surface) def draw_network_link(self, surface): """ This method will draw a link between all objects in a network and the corresponding network tab """ first_point = list(self.network_tabs.get_tab_center(self.active_tab)) first_point[1] += 20 second_point = [first_point[0], first_point[1] + 20] for obj in self.all_networks[self.active_tab['index']].objects: third_point = [obj.center[0], second_point[1]] fourth_point = [obj.center[0], int(obj.center[1] - obj.height / 2)] pygame_draw.lines(surface, colors['LIGHTGRAY'], False, [first_point, second_point, third_point, fourth_point]) def resolve_info_tree_mismatch(self): """ This method resolves any info tree data mismatch """ # TODO: This can be optimized to use update_text() instead of deleting and recreating the objects del self.all_network_tree_objects[self.active_tab['name']] self.build_network_tree_objects(self.all_networks[self.active_tab['index']]) def handle_action(self, action_type, mouse_pos=None, key=None): """ This method passes action handling to everything that is necessary. This method is responsible for: - Network tab action handling - All object action handling for all networks - **TBD** Network info tab action handling? """ # handle select nearest object first if action_type == 'RIGHT_MOUSE_DOWN': return dict(type='new_selection', object=self.all_networks[self.active_tab['index']].get_closest_obj(mouse_pos)) response = None for network in self.all_networks: response = network.handle_action(action_type, mouse_pos) if response is None: response = self.network_tabs.handle_action(action_type, mouse_pos) return response @staticmethod def handle_escape(): """ transition to main_menu state on when escape is pressed """ return 'main_menu' class GUI2: def __init__(self, screen_size): """ Constructor for the entire GUI """ self.name = 'GUI2' # Misc self.screen_size = screen_size # Creating all Menus/States self.all_states = dict(normal=Normal(), main_menu=MainMenu(screen_size), edit_network=EditNetwork(screen_size), edit_settings=EditSettings(screen_size), create_network=CreateNetwork(screen_size), edit_objects=EditObjects(screen_size), delete_network=DeleteNetwork(screen_size)) self.name_to_state_map = dict(Normal='normal', MainMenu='main_menu', EditNetwork='edit_network', EditSettings='edit_settings') self.state = self.all_states['normal'] def __cmp__(self, other): """ Only use name for comparison """ return self.name == other def __str__(self): """ Only use name for string """ return self.name def transition_state(self, new_state_name): if new_state_name not in self.all_states.keys(): print('INVALID GUI2 STATE: {}'.format(new_state_name)) print('GUI2 transitioning state to: {}'.format(new_state_name)) self.state = self.all_states[new_state_name] def add_network(self, network): """ This method properly handles the GUI adding a new network :param network: Network object to be added to GUI handling :return: None, will raise error if fails """ start_state = self.state.name # Get to Normal state if not in it if start_state != 'Normal': self.transition_state('normal') # Handle adding a network self.state.add_network(network) # Return to previous state if not already in Normal state if start_state != 'Normal': self.transition_state(self.name_to_state_map[start_state]) def draw(self, surface): """ Main draw handler :param surface: PyGame surface object :return: None, will raise error if fails """ try: self.state.draw(surface) except Exception as e: print('GUI2 is in state: "{}" when the following error was created: {}'.format(self.state.name, e)) raise def step(self): """ The main stepper for all networks :return: None, will raise error if fails """ # We only care about stepping for the Normal use case if self.state.name == 'Normal': self.state.step() def handle_action(self, action_type, mouse_pos=None, key=None): """ Main action handler :param action_type: String which describes the type of action that needs to be handled :param mouse_pos: [x, y] pixel position of the mouse :param key: PyGame event.key object for user input :return: None, will raise error if fails """ response = None if action_type == 'ESCAPE': self.handle_escape() elif self.state is not None: response = self.state.handle_action(action_type, mouse_pos, key) else: raise (AttributeError, 'GUI2 state is None, how???') # Handle responses if type(response) is dict: if 'type' in response.keys() and response['type'] == 'transition_state': print('Got GUI2 transition state request from: {}'.format(self.state.name)) self.transition_state(response['new_state']) return None # print('GUI got action response: {}'.format(response)) return response def handle_escape(self): """ This method is responsible for handling the transition between states for the GUI2 object """ self.transition_state(self.state.handle_escape())
StarcoderdataPython
3209810
""" Training config COLORMODE = Enum(['L', 'RGB']) """ MODEL = 'unet' IMAGE_COLORMODE = 'L' MASK_COLORMODE = 'RGB' """RGB setting """ MASK_USECOLORS = 'RB' BG_COLOR = False BACKGROUND_COLOR = [0, 1, 0] """ 'tversky' or 'categorical cross entropy' 'binary_crossentropy', 'weighted_binary_crossentropy' """ LOSS = 'binary_crossentropy' CLASS_WEIGHTS = [1.0, 0., 0.] TARGET_SIZE = (256, 256) SAMPLE_SIZE = (256, 256) FRAME_SIZE = 32 PCA_COLOR = True BATCH_SIZE = 4 TRAIN_STEPS = 100 VALID_STEPS = 50 EPOCHS = 30 EA_EPOCHS = 6 #: 基本的にはこの設定値なら影響がない PCA_COLOR_RANGE = (-0.2, 0.2) DATA_GEN_ARGS = dict( rescale=1./255, rotation_range=40, width_shift_range=0.05, height_shift_range=0.05, shear_range=0.05, zoom_range=0.05, vertical_flip=True, horizontal_flip=True, fill_mode='nearest') """ 基本はグレスケ入力-L/RGB出力を想定 未検証:RGB入力 UpSampling2D使用は出力の格子模様を防ぐ 領域塗分けは他ラベル問題ととらえbinary_crossentorpyを使う """
StarcoderdataPython
1786341
<filename>Chapter 9 - File IO/07_pr_03.py<gh_stars>0 #Write a program to generate multiplication tables from 2 to 20 and write it to the different files. # Place these files in a folder for a 13- year old boy. for i in range(2, 21): with open(f"tables/Multiplication_table_of_{i}.txt", 'w') as f: for j in range(1, 11): f.write(f"{i}X{j}={i*j}") if j!=10: f.write('\n')
StarcoderdataPython
3356920
import re import os from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.url import urljoin_rfc from scrapy.utils.response import get_base_url import csv, codecs, cStringIO from product_spiders.items import Product, ProductLoader HERE = os.path.abspath(os.path.dirname(__file__)) class futurebazaarSpider(BaseSpider): USER_AGENT = "Googlebot/2.1 ( http://www.google.com/bot.html)" name = 'futurebazaar.com' allowed_domains = ['www.futurebazaar.com'] start_urls = ('http://www.futurebazaar.com/home-living/ch/2226/', 'http://www.futurebazaar.com/kids-baby/ch/2707/', 'http://www.futurebazaar.com/electronics/ch/2458/', 'http://www.futurebazaar.com/supermarket/ch/2515/', ) def parse_product(self, response): hxs = HtmlXPathSelector(response) name = "".join(hxs.select('//div[@id="product_desc"]/h1/text()').extract()).strip() if not name: name = "".join(hxs.select('//div[@class="prod_details"]/h3/a/text()').extract()).strip() price = "".join(hxs.select('//td[@class="price_value forange fb f16"]/text()').re(r'([0-9\, ]+)')).strip() if not price: price = "".join(hxs.select('//td[@class="price_value fcop fb f17"]/text()').re(r'([0-9\, ]+)')).strip() if price: product_loader = ProductLoader(item=Product(), response=response) product_loader.add_value('price', price) product_loader.add_value('url', response.url) product_loader.add_value('name', name) yield product_loader.load_item() def parse(self,response): if not isinstance(response, HtmlResponse): return hxs = HtmlXPathSelector(response) base_url = get_base_url(response) #get cats cats = hxs.select('//div[@id="cat_filter"]/div/ul/li/a/@href').extract() for cat in cats: yield Request(urljoin_rfc(base_url,cat)) #pages pages = hxs.select('//div[@class="sort_bar"]/div[@class="right"]/span/a/@href').extract() for page in pages: yield Request(urljoin_rfc(base_url,page)) products = hxs.select('//div[@class="srp_greed_view"]/ul/li/div/div/a/@href').extract() for p in products: yield Request(urljoin_rfc(base_url,p), callback=self.parse_product)
StarcoderdataPython
3319300
import datetime import logging import os import boto3 CW = boto3.client("cloudwatch") logging.getLogger().setLevel(os.environ.get("LOGLEVEL", logging.INFO)) def handler(_event, _context): logging.debug("environment variables:\n %s", os.environ) timestamp = datetime.datetime.now(datetime.timezone.utc) timestamp = timestamp - datetime.timedelta( minutes=timestamp.minute % 5 + 10, seconds=timestamp.second, microseconds=timestamp.microsecond, ) logging.info("evaluating at [%s]", timestamp) metrics = get_metrics(timestamp) logging.debug("available metrics: %s", metrics) messages = metrics["maxANOMV"] requests = metrics["sumNOER"] machines = metrics["avgGISI"] logging.info("ANOMV=%s NOER=%s GISI=%s", messages, requests, machines) if machines > 0: load = 1.0 - requests / (machines * 0.098444 * 300) elif messages > 0: load = 1.0 else: return logging.info("L=%s", load) put_metric(timestamp, load) def get_metrics(timestamp): queue = os.environ["QueueName"] group = os.environ["GroupName"] response = CW.get_metric_data( StartTime=timestamp, EndTime=timestamp + datetime.timedelta(minutes=5), ScanBy="TimestampAscending", MetricDataQueries=[ { "Id": "maxANOMV", "MetricStat": { "Metric": { "Namespace": "AWS/SQS", "MetricName": "ApproximateNumberOfMessagesVisible", "Dimensions": [{"Name": "QueueName", "Value": f"{queue}"}], }, "Period": 300, "Stat": "Maximum", "Unit": "Count", }, }, { "Id": "sumNOER", "MetricStat": { "Metric": { "Namespace": "AWS/SQS", "MetricName": "NumberOfEmptyReceives", "Dimensions": [{"Name": "QueueName", "Value": f"{queue}"}], }, "Period": 300, "Stat": "Sum", "Unit": "Count", }, }, { "Id": "avgGISI", "MetricStat": { "Metric": { "Namespace": "AWS/AutoScaling", "MetricName": "GroupInServiceInstances", "Dimensions": [ {"Name": "AutoScalingGroupName", "Value": f"{group}"} ], }, "Period": 300, "Stat": "Average", "Unit": "None", }, }, ], ) return { m["Id"]: dict(zip(m["Timestamps"], m["Values"]))[timestamp] for m in response["MetricDataResults"] } def put_metric(time, value): CW.put_metric_data( Namespace="Turbine", MetricData=[ { "MetricName": "ClusterLoad", "Dimensions": [{"Name": "StackName", "Value": os.environ["StackName"]}], "Timestamp": time, "Value": value, "Unit": "None", } ], )
StarcoderdataPython
4842282
RED = "\033[93m{" GREEN = "\033[92m" BOLD = "\033[1m" END = "\033[0m" def bold_red(text: str) -> str: return BOLD + RED + text + END + END def bold_green(text: str) -> str: return BOLD + GREEN + text + END + END def bold(text: str) -> str: return BOLD + text + END
StarcoderdataPython
49307
""" .. module:: Augmentation :platform: Unix, Windows :synopsis: A useful module indeed. .. moduleauthor:: <NAME> <<EMAIL>> """ import numpy as np import random from nltk.corpus import wordnet import collections import math #import nltk #nltk.download('wordnet') class Augmentation: r""" This is the class to do data augmentation. Args: documents (:obj:`list`, optional, defaults to None): A list of documents. labels (:obj:`float`, optional, defaults to None): A list of labels. dataset_name (:obj:`string`, optional, defaults to ''): Name of the dataset. path (:obj:`string`, optional, defaults to ''): Path to save the report. Example:: from Manteia.Statistic import Statistic documents=['a text','text b'] labels=['a','b'] Statistic(documents,labels) Attributes: """ def __init__(self,documents=[],labels=[],strategy='daia',verbose=True): self.documents = documents self.labels = labels self.verbose = verbose if verbose: print('Augmentation %s.' % strategy) if strategy=='eda': self.documents_augmented,self.labels_augmented = eda(self.documents,self.labels) if strategy=='uda': self.documents_augmented,self.labels_augmented = eda(self.documents,self.labels) if strategy=='pyramid': self.documents_augmented,self.labels_augmented = pyramid(self.documents,self.labels) def test(self): return "Mantéïa Augmentation." def uda(documents,labels): documents_augmented=[] labels_augmented=[] data_stats=get_data_stats(documents) token_prob=0.9 op = TfIdfWordRep(token_prob, data_stats) for text,label in zip(documents,labels): text_aug=op(text) documents_augmented.append(text_aug) labels_augmented.append(label) return documents_augmented,labels_augmented #https://github.com/google-research/uda/blob/master/text/augmentation/word_level_augment.py def pyramid(documents,labels,level): r""" This function compute DAIA. Args: documents labels level return documents_augmented labels_augmented Example:: """ documents_augmented=[] labels_augmented=[] if level < 2:level=2 if level > 5:level=5 for text,label in zip(documents,labels): text_list,label_list=split_text(text,label,level) documents_augmented = documents_augmented+text_list labels_augmented = labels_augmented+label_list return documents_augmented,labels_augmented def get_data_stats(texts): """Compute the IDF score for each word. Then compute the TF-IDF score.""" word_doc_freq = collections.defaultdict(int) # Compute IDF for text in texts: cur_word_dict = {} cur_sent = text.split(' ') for word in cur_sent: cur_word_dict[word] = 1 for word in cur_word_dict: word_doc_freq[word] += 1 idf = {} for word in word_doc_freq: idf[word] = math.log(len(texts) * 1. / word_doc_freq[word]) # Compute TF-IDF tf_idf = {} for text in texts: cur_word_dict = {} cur_sent = text.split(' ') for word in cur_sent: if word not in tf_idf: tf_idf[word] = 0 tf_idf[word] += 1. / len(cur_sent) * idf[word] return { "idf": idf, "tf_idf": tf_idf, } class EfficientRandomGen(object): """A base class that generate multiple random numbers at the same time.""" def reset_random_prob(self): """Generate many random numbers at the same time and cache them.""" cache_len = 100000 self.random_prob_cache = np.random.random(size=(cache_len,)) self.random_prob_ptr = cache_len - 1 def get_random_prob(self): """Get a random number.""" value = self.random_prob_cache[self.random_prob_ptr] self.random_prob_ptr -= 1 if self.random_prob_ptr == -1: self.reset_random_prob() return value def get_random_token(self): """Get a random token.""" token = self.token_list[self.token_ptr] self.token_ptr -= 1 if self.token_ptr == -1: self.reset_token_list() return token class TfIdfWordRep(EfficientRandomGen): """TF-IDF Based Word Replacement.""" def __init__(self, token_prob, data_stats): super(TfIdfWordRep, self).__init__() self.token_prob = token_prob self.data_stats = data_stats self.idf = data_stats["idf"] self.tf_idf = data_stats["tf_idf"] tf_idf_items = data_stats["tf_idf"].items() tf_idf_items = sorted(tf_idf_items, key=lambda item: -item[1]) self.tf_idf_keys = [] self.tf_idf_values = [] for key, value in tf_idf_items: self.tf_idf_keys += [key] self.tf_idf_values += [value] self.normalized_tf_idf = np.array(self.tf_idf_values) self.normalized_tf_idf = (self.normalized_tf_idf.max() - self.normalized_tf_idf) self.normalized_tf_idf = (self.normalized_tf_idf / self.normalized_tf_idf.sum()) self.reset_token_list() self.reset_random_prob() def get_replace_prob(self, all_words): """Compute the probability of replacing tokens in a sentence.""" cur_tf_idf = collections.defaultdict(int) for word in all_words: cur_tf_idf[word] += 1. / len(all_words) * self.idf[word] replace_prob = [] for word in all_words: replace_prob += [cur_tf_idf[word]] replace_prob = np.array(replace_prob) replace_prob = np.max(replace_prob) - replace_prob replace_prob = (replace_prob / replace_prob.sum() * self.token_prob * len(all_words)) return replace_prob def __call__(self, example): all_words = example.split(' ') replace_prob = self.get_replace_prob(all_words) all_words = self.replace_tokens( all_words, replace_prob[:len(all_words)] ) return " ".join(all_words) def replace_tokens(self, word_list, replace_prob): """Replace tokens in a sentence.""" for i in range(len(word_list)): if self.get_random_prob() < replace_prob[i]: word_list[i] = self.get_random_token() return word_list def reset_token_list(self): cache_len = len(self.tf_idf_keys) token_list_idx = np.random.choice( cache_len, (cache_len,), p=self.normalized_tf_idf) self.token_list = [] for idx in token_list_idx: self.token_list += [self.tf_idf_keys[idx]] self.token_ptr = len(self.token_list) - 1 #print("sampled token list: {:s}".format(" ".join(self.token_list))) def eda(documents,labels): documents_augmented=[] labels_augmented=[] for document,label in zip(documents,labels): text_list,label_list = eda_text(document,label) documents_augmented = documents_augmented+text_list labels_augmented = labels_augmented+label_list return documents_augmented,labels_augmented def eda_text(text,label): text_list,label_list=[],[] #pour decoupage en word word_list_1=text.split(' ') #inversion de deux mot idx_1 = random.randint(0,len(word_list_1)-1) idx_2 = random.randint(0,len(word_list_1)-1) word_list_1[idx_1],word_list_1[idx_2] = word_list_1[idx_2],word_list_1[idx_1] text_list = [' '.join(word_list_1)] label_list= [label] #suppression d'un mot mot word_list_2=text.split(' ') idx_3 = random.randint(0,len(word_list_2)-1) del word_list_2[idx_1] text_list.append(' '.join(word_list_2)) label_list.append(label) #Synonym Replacement word_list_3=text.split(' ') idx_4 = random.randint(0,len(word_list_3)-1) if len(wordnet.synsets(word_list_3[idx_4]))>0: idx_synonym=random.randint(0,len(wordnet.synsets(word_list_3[idx_4]))-1) synonym = wordnet.synsets(word_list_3[idx_4])[idx_synonym].lemma_names()[0] if synonym!=word_list_3[idx_4]: word_list_3[idx_4]=synonym text_list.append(' '.join(word_list_2)) label_list.append(label) #Random Insertion (RI) word_list_4=text.split(' ') idx_5 = random.randint(0,len(word_list_4)-1) idx_6 = random.randint(0,len(word_list_4)-1) if len(wordnet.synsets(word_list_4[idx_5]))>0: idx_synonym=random.randint(0,len(wordnet.synsets(word_list_4[idx_5]))-1) synonym = wordnet.synsets(word_list_4[idx_5])[idx_synonym].lemma_names()[0] if synonym!=word_list_4[idx_5]: word_list_4.insert(idx_6, synonym) text_list.append(' '.join(word_list_2)) label_list.append(label) return text_list,label_list def split_text(text,label,level=3): text_list,label_list=[],[] decoup_1a = int(0.05*len(text)) decoup_1b = int(0.95*len(text)) decoup_2 = int(len(text)/2) decoup_3 = int(len(text)/3) decoup_4 = int(len(text)/4) decoup_5 = int(len(text)/5) if level >=1 : text_list = text_list+[text[decoup_1a:decoup_1b]] label_list = label_list+[label] if level >=2 : text_list = text_list+[text[:decoup_2],text[decoup_2:]] label_list = label_list+[label,label] if level >=3 : text_list = text_list+[text[:decoup_3],text[decoup_3:2*decoup_3],text[2*decoup_3:]] label_list = label_list+[label,label,label] if level >=4 : text_list = text_list+[text[:decoup_4],text[decoup_4:2*decoup_4],text[2*decoup_4:3*decoup_4],text[3*decoup_4:]] label_list = label_list+[label,label,label,label] if level >=5 : text_list = text_list+[text[:decoup_5],text[decoup_5:2*decoup_5],text[2*decoup_5:3*decoup_5],text[3*decoup_5:4*decoup_5],text[4*decoup_5:]] label_list = label_list+[label,label,label,label,label] return text_list,label_list
StarcoderdataPython
1601356
from .uuids import get_uuid, set_uuid import logging logger = logging.getLogger(__name__) def unproxy(uuid_mapping): """This is a convenience for unproxying a lot of objects at once. """ for uuid, obj in uuid_mapping.items(): if isinstance(obj, GenericLazyLoader): uuid_mapping[uuid] = obj.load() def make_lazy_class(cls_): # this is to mix-in inheritence class LazyLoader(GenericLazyLoader, cls_): pass return LazyLoader class GenericLazyLoader(object): def __init__(self, uuid, class_, storage): set_uuid(self, uuid) self.storage = storage self.class_ = class_ self._loaded_object = None def load(self): if self._loaded_object is None: self._loaded_object = \ self.storage.load([get_uuid(self)], force=True)[0] if self._loaded_object is None: raise RuntimeError("UUID not found in storage: " + get_uuid(self)) return self._loaded_object def __getattr__(self, attr): # apparently IPython pretty-printing looks for a bunch of # attributes; this means we auto-load if we try to autoprint the # repr in IPython (TODO) return getattr(self.load(), attr) def __getitem__(self, item): return self.load()[item] def __iter__(self): return self.load().__iter__() def __len__(self): return len(self.load()) def __str__(self): if self._loaded_object: return str(self._loaded_object) else: return repr(self) def __repr__(self): if self._loaded_object: return repr(self._loaded_object) else: return ("<LazyLoader for " + str(self.class_.__name__) + " UUID " + str(self.__uuid__) + ">") class ProxyObjectFactory(object): def __init__(self, storage, serialization_schema): self.storage = storage self.serialization_schema = serialization_schema self.lazy_classes = {} def make_lazy(self, cls, uuid): if cls not in self.lazy_classes: self.lazy_classes[cls] = make_lazy_class(cls) return self.lazy_classes[cls](uuid=uuid, class_=cls, storage=self.storage) def make_all_lazies(self, lazies): # lazies is dict of {table_name: list_of_lazy_uuid_rows} all_lazies = {} for (table, lazy_uuid_rows) in lazies.items(): logger.debug("Making {} lazy proxies for objects in table '{}'"\ .format(len(lazy_uuid_rows), table)) cls = self.serialization_schema.table_to_info[table].cls for row in lazy_uuid_rows: all_lazies[row.uuid] = self.make_lazy(cls, row.uuid) return all_lazies
StarcoderdataPython
3314470
import logging log = logging.getLogger(__name__) _type_map = {} class TypeMeta(type): def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) if '__metaclass__' not in attrs: _type_map[name.lower()] = cls from TelegramBotAPI.types.field import Field cls._valid_fields = {} for n in dir(cls): a = getattr(cls, n) if isinstance(a, Field): cls._valid_fields[n.lower()] = a delattr(cls, n) return cls class Type(object, metaclass=TypeMeta): __type_map = _type_map __from_raw_dropped = None __from_raw_found = None _fields = None _d = None def __init__(self, *args): for field in self._valid_fields.values(): field.setup_types() if len(args) > 1: raise TypeError('%s can take up to 1 argument (%d given)' % (self.__class__.__name__, len(args))) if args: self._from_raw(args[0]) def _from_raw(self, raw): self._d = {} self.__from_raw_dropped = {} self.__from_raw_found = 0 for key in raw: if key not in self._valid_fields: self.__from_raw_dropped[key] = raw[key] continue if self._valid_fields[key].ignore: self.__from_raw_found += 1 continue if self._valid_fields[key].list: ld = ListDelegate(self._d, key, self._valid_fields[key]) ld.extend(raw[key]) else: ad = AssignDelegate(self._d, key, self._valid_fields[key]) ad._from_raw(raw[key]) self.__from_raw_found += 1 for key, field in self._valid_fields.items(): if field.optional is False and key not in self._d: raise TypeError('"%s" is an expected field in %s' % (key, self.__class__.__name__)) if self.__from_raw_found == 0: raise TypeError('No fields were found for % in %s' % (self.__class__.__name__, raw)) def _to_raw(self, strict=True): if self._leaf: return self._d raw = {} for key in self._valid_fields: if self._d is not None and key in self._d: raw[key] = self._d[key]._to_raw(strict) elif strict and self._valid_fields[key].optional is False: raise KeyError('"%s" is an expected field in %s' % (key, self.__class__.__name__)) return raw def _from_raw_dropped(self): if self._leaf: return None dropped = self.__from_raw_dropped for key in self._valid_fields: if self._d is not None and key in self._d: d = self._d[key]._from_raw_dropped() if d: dropped[key] = d return dropped def _from_raw_found(self): if self._leaf: return 1 return self.__from_raw_found @classmethod def _new(cls, value, type_name=None): if type_name is None: type_name = set(value.keys()).intersection(list(cls.__type_map.keys())) assert len(type_name) == 1 type_name = type_name.pop() value = value[type_name] instance = cls.__type_map[type_name.lower()]() instance._from_raw(value) return instance @classmethod def _type(cls, name): return cls.__type_map[name.lower()] @property def _name(self): return self.__class__.__name__ @property def _leaf(self): return len(self._valid_fields) == 0 def __setattr__(self, key, value): self.__set(key, value) def __setitem__(self, key, value): self.__set(key, value) def __set(self, key, value): if key.startswith('_'): super(Type, self).__setattr__(key, value) return name = key.lower() if name in self._valid_fields: if self._d is None: self._d = {} ad = AssignDelegate(self._d, name, self._valid_fields[name]) ad._from_raw(value) return raise TypeError('"%s" does not have a "%s" field' % (self.__class__.__name__, key)) def __getattr__(self, key): return self.__get(key) def __getitem__(self, key): return self.__get(key) def __get(self, key): if not isinstance(key, str): raise AttributeError("'%s' has no field '%s'" % (self._name, key)) name = key.lower() if self._d and name in self._d: if self._d[name]._leaf: return self._d[name]._d return self._d[name] if name in self._valid_fields: if self._valid_fields[name].leaf and not self._valid_fields[name].list: raise AttributeError("Optional field '%s' not found in '%s'" % (key, self._name)) if self._d is None: self._d = {} if self._valid_fields[name].list: return ListDelegate(self._d, name, self._valid_fields[name]) return AssignDelegate(self._d, name, self._valid_fields[name]) self.__field_error(key) def __delattr__(self, key): self.__del(key) def __delitem__(self, key): self.__del(key) def __del(self, key): name = key.lower() del self._d[name] def __iter__(self): for name in self._d: yield name def __repr__(self): return "<%s %s>" % (self.__class__.__name__, str(self._to_raw(strict=False))) def __eq__(self, other): if self._leaf: return self._d == other return repr(self._to_raw(strict=False)) == repr(other._to_raw(strict=False)) def __field_error(self, key): raise KeyError('"%s" does not have a "%s" field' % (self.__class__.__name__, key)) class Delegate(object): def __init__(self, d, key, field): self._d = d self._key = key self._field = field class AssignDelegate(Delegate): def _from_raw(self, raw): if any([True for t in self._field.types if isinstance(raw, t)]): self._d[self._key] = raw else: self._d[self._key] = self.__from_raw(raw) def __setattr__(self, key, value): return self.__set(key, value) def __set(self, key, value): if key.startswith('_'): return super(AssignDelegate, self).__setattr__(key, value) if self._key not in self._d: self._d[self._key] = None self._d[self._key] = self.__from_field(key, value) def __getattr__(self, key): return self.__get(key) def __get(self, key): if key.startswith('_'): return super(AssignDelegate, self).__getattribute__(key) if not isinstance(key, str): raise AttributeError("'%s' has no field '%s'" % (self._name, key)) name = key.lower() for _type in self._field.types: if name in _type._valid_fields: if _type._valid_fields[name].leaf and not _type._valid_fields[name].list: raise AttributeError("Optional field '%s' not found in '%s'" % (key, self._key)) self._d[self._key] = _type() self._d[self._key]._d = {} if _type._valid_fields[name].list: return ListDelegate(self._d[self._key]._d, name, _type._valid_fields[name]) return AssignDelegate(self._d[self._key]._d, name, _type._valid_fields[name]) self.__field_error(key) def __from_raw(self, raw): assert not self._field.list def upcast(cls, raw): try: value = cls() value._from_raw(raw) return value._from_raw_found(), value except TypeError as e: return -1, e candidates = [upcast(cls, raw) for cls in self._field.types] best = None rank = -1 for r, v in candidates: if r > rank: best = v rank = r if best is None: raise TypeError('None of %s accepted: %s : %s' % (self._field.types, raw, candidates)) return best def __from_field(self, key, value): last_exception = None for cls in self._field.types: try: v = cls() setattr(v, key, value) return v except TypeError as e: last_exception = e raise last_exception # pylint: disable=raising-bad-type def __field_error(self, key): raise KeyError('"%s" does not have a "%s" field' % (self.__class__.__name__, key)) class ListDelegate(Delegate): def __init__(self, d, key, field): super(ListDelegate, self).__init__(d, key, field) self._l = [] if self._key not in self._d: self._d[self._key] = self def append(self, value): t = self._field.types[0]() t._from_raw(value) self._l.append(t) def extend(self, values): for value in values: self.append(value) @property def _leaf(self): return False # return self._field.leaf def _to_raw(self, strict=True): ret = [] for i in range(len(self._l)): v = self._l[i] if v: ret.append(v._to_raw(strict)) elif strict: raise IndexError('Index [%d] of list "%s" not set' % (i, self._key)) return ret def _from_raw_dropped(self): ret = [] for i in range(len(self._l)): v = self._l[i] if v: d = v._from_raw_dropped() if d: ret.append(d) return ret def __setitem__(self, index, value): t = self._field.types[0]() t._from_raw(value) self._l[index] = t def __getitem__(self, index): try: v = self._l[index] if v is None: v = self._field.types[0]() self._l[index] = v return v except IndexError: pass from itertools import count for i in count(len(self._l)): if i == index: v = self._field.types[0]() self._l.append(v) return v else: self._l.append(None) def __iter__(self): for value in self._l: yield value def __len__(self): return len(self._l) __all__ = ['Type']
StarcoderdataPython
1664839
<reponame>ndrewl/neoml<gh_stars>0 """ Copyright (c) 2017-2021 ABBYY Production LLC 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 numpy from .Utils import convert_data, get_data from scipy.sparse import csr_matrix, issparse import neoml.PythonWrapper as PythonWrapper class SvmClassificationModel : """Support-vector machine (SVM) classification model. """ def __init__(self, internal): self.internal = internal def classify(self, X): """Gets the classification results for the input sample. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Return values ------- predictions : generator of ndarray of shape (n_samples, n_classes) The predictions of the input samples. """ x = convert_data( X ) return self.internal.classify(*get_data(x)) class SvmClassifier(PythonWrapper.Svm) : """Support-vector machine algorithm translates the input data into vectors in a high-dimensional space and searches for a maximum-margin dividing hyperplane. Parameters ---------- kernel : {'linear', 'poly', 'rbf', 'sigmoid'}, default='linear' The kernel function to be used. max_iteration_count : int, default=1000 The maximum number of iterations. error_weight : float, default=1.0 The error weight relative to the regularization function. degree : int, default=1 The degree for the gaussian kernel. gamma : float, default=1.0 The kernel coefficient (for 'poly', 'rbf', 'sigmoid'). coeff0 : float, default=1.0 The kernel free term (for 'poly, 'sigmoid'). tolerance : float, default=0.1 The algorithm precision. thread_count : int, default=1 The number of processing threads to be used while training the model. """ def __init__(self, kernel='linear', max_iteration_count=1000, error_weight=1.0, degree=1, gamma=1.0, coeff0=1.0, tolerance=0.1, thread_count=1): if kernel != 'linear' and kernel != 'poly' and kernel != 'rbf' and kernel != 'sigmoid': raise ValueError('The `kernel` must be one of: `linear`, `poly`, `rbf`, `sigmoid`.') if max_iteration_count <= 0: raise ValueError('The `max_iteration_count` must be > 0.') if error_weight <= 0: raise ValueError('The `error_weight` must be >= 0.') if thread_count <= 0: raise ValueError('The `thread_count` must be > 0.') super().__init__(kernel, float(error_weight), int(max_iteration_count), int(degree), float(gamma), float(coeff0), float(tolerance), int(thread_count)) def train(self, X, Y, weight=None): """Trains the SVM classification model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training sample. The values will be converted to ``dtype=np.float32``. If a sparse matrix is passed in, it will be converted to a sparse ``csr_matrix``. Y : array-like of shape (n_samples,) Correct class labels (``int``) for the training set vectors. weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Return values ------- model : object The trained ``SvmClassificationModel``. """ x = convert_data( X ) y = numpy.array( Y, dtype=numpy.int32, copy=False ) if x.shape[0] != y.size: raise ValueError('The `X` and `Y` inputs must be the same length.') if weight is None: weight = numpy.ones(y.size, numpy.float32) else: weight = numpy.array( weight, dtype=numpy.float32, copy=False ) if numpy.any(y < 0): raise ValueError('All `Y` elements must be >= 0.') if numpy.any(weight < 0): raise ValueError('All `weight` elements must be >= 0.') return SvmClassificationModel(super().train_classifier(*get_data(x), int(x.shape[1]), y, weight))
StarcoderdataPython
3116
import pandas as pd import ta from app.common import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option("display.max_columns", None) pd.set_option("display.width", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = "buy_signal" SELL_SIGNAL = "sell_signal" def calculate_indicators(self): df = self.load_df(limit=1000) _ = df["close_3_ema"] _ = df["boll"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df["high"], low=df["low"]) df["AO"] = ao.ao() return df def can_sell(self, df): prev_candle = self.candle(df) last_ema = prev_candle["close_3_ema"] last_bb = prev_candle["boll"] return [ last_ema < last_bb, (self.candle(df, rewind=-2)["AO"] > 0) & (self.candle(df, rewind=-1)["AO"] < 0), prev_candle["volume"] > 0, ] def can_buy(self, df): prev_candle = self.candle(df) last_ema = prev_candle["close_3_ema"] last_bb = prev_candle["boll"] return [ last_ema > last_bb, (self.candle(df, rewind=-2)["AO"] < 0) & (self.candle(df, rewind=-1)["AO"] > 0), prev_candle["volume"] > 0, ] def alert_message(self, df): prev_candle = self.candle(df) last_close = prev_candle["close"] last_ao = prev_candle["AO"] return ( "Close: {:.2f}, Awesome Oscillator value: {:.2f}".format( last_close, last_ao ), )
StarcoderdataPython
1607547
<reponame>beyucel/gpytorch #!/usr/bin/env python3 import math import torch import gpytorch import unittest import warnings from gpytorch.lazy import CachedCGLazyTensor, NonLazyTensor from gpytorch.utils.gradients import _ensure_symmetric_grad from test.lazy._lazy_tensor_test_case import LazyTensorTestCase from unittest.mock import MagicMock, patch class TestCachedCGLazyTensorNoLogdet(LazyTensorTestCase, unittest.TestCase): seed = 0 def create_lazy_tensor(self, with_solves=False, with_logdet=False): mat = torch.randn(5, 6) mat = mat.matmul(mat.transpose(-1, -2)) mat.requires_grad_(True) lazy_tensor = NonLazyTensor(mat) eager_rhs = torch.randn(5, 10).detach() if with_solves: with gpytorch.settings.num_trace_samples(1000 if with_logdet else 1): # For inv_quad_logdet tests solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms( lazy_tensor, eager_rhs.detach(), logdet_terms=with_logdet ) eager_rhss = [eager_rhs.detach(), eager_rhs[..., -2:-1].detach()] solves = [solve.detach(), solve[..., -2:-1].detach()] else: eager_rhss = [eager_rhs] solves = [] probe_vecs = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_norms = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_solves = torch.tensor([], dtype=mat.dtype, device=mat.device) tmats = torch.tensor([], dtype=mat.dtype, device=mat.device) return CachedCGLazyTensor(lazy_tensor, eager_rhss, solves, probe_vecs, probe_vec_norms, probe_vec_solves, tmats) def evaluate_lazy_tensor(self, lazy_tensor): return lazy_tensor.base_lazy_tensor.tensor def _test_inv_matmul(self, rhs, lhs=None, cholesky=False): if cholesky: # These tests don't make sense for CachedCGLazyTensor return lazy_tensor = self.create_lazy_tensor(with_solves=True).requires_grad_(True) lazy_tensor_copy = lazy_tensor.clone().detach_().requires_grad_(True) evaluated = self.evaluate_lazy_tensor(lazy_tensor_copy) evaluated.register_hook(_ensure_symmetric_grad) # Rather than the supplied rhs and lhs, # we'll replace them with ones that we've precomputed solves for rhs_orig = rhs if rhs_orig.dim() == 1: rhs = lazy_tensor.eager_rhss[0][..., -1].squeeze(-1).clone().detach().requires_grad_(True) # Make sure we're setting this test up correctly self.assertEqual(rhs_orig.shape, rhs.shape) else: if lhs is not None: rhs = lazy_tensor.eager_rhss[0][..., 2:].clone().detach().requires_grad_(True) else: rhs = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True) # Make sure we're setting this test up correctly self.assertEqual(rhs_orig.shape[:-1], rhs.shape[:-1]) lhs = lhs if lhs is not None: lhs_orig = lhs if rhs_orig.dim() == 1: lhs = lazy_tensor.eager_rhss[0][..., :-1].transpose(-1, -2).clone().detach().requires_grad_(True) else: lhs = lazy_tensor.eager_rhss[0][..., :2].transpose(-1, -2).clone().detach().requires_grad_(True) # Make sure we're setting this test up correctly self.assertEqual(lhs_orig.shape[:-2], lhs.shape[:-2]) # Create a test right hand side and left hand side rhs.requires_grad_(True) rhs_copy = rhs.clone().detach().requires_grad_(True) if lhs is not None: lhs.requires_grad_(True) lhs_copy = lhs.clone().detach().requires_grad_(True) _wrapped_cg = MagicMock(wraps=gpytorch.utils.linear_cg) with patch("gpytorch.utils.linear_cg", new=_wrapped_cg) as linear_cg_mock: with gpytorch.settings.max_cholesky_size(math.inf if cholesky else 0), \ gpytorch.settings.cg_tolerance(1e-4): with warnings.catch_warnings(record=True) as w: # Perform the inv_matmul if lhs is not None: res = lazy_tensor.inv_matmul(rhs, lhs) actual = lhs_copy @ evaluated.inverse() @ rhs_copy else: res = lazy_tensor.inv_matmul(rhs) actual = evaluated.inverse().matmul(rhs_copy) self.assertAllClose(res, actual, rtol=0.02, atol=1e-5) self.assertEqual(len(w), 0) with warnings.catch_warnings(record=True) as w: # Perform backward pass grad = torch.randn_like(res) res.backward(gradient=grad) actual.backward(gradient=grad) for arg, arg_copy in zip(lazy_tensor.representation(), lazy_tensor_copy.representation()): if arg_copy.grad is not None: self.assertAllClose(arg.grad, arg_copy.grad, rtol=0.03, atol=1e-5) self.assertAllClose(rhs.grad, rhs_copy.grad, rtol=0.03, atol=1e-5) if lhs is not None: self.assertAllClose(lhs.grad, lhs_copy.grad, rtol=0.03, atol=1e-5) # Determine if we've called CG or not # We shouldn't if we supplied a lhs if lhs is None: self.assertEqual(len(w), 1) if not cholesky and self.__class__.should_call_cg: self.assertTrue(linear_cg_mock.called) else: self.assertEqual(len(w), 0) self.assertFalse(linear_cg_mock.called) def test_inv_matmul_vector(self): # Skipping this test because it's not really necessary for CachedCGLazyTensor # We'll only ever be performing inv_matmul against matrices ,r owhen a left hand side is supplied pass def test_inv_matmul_matrix_broadcast(self): pass def test_inv_quad_logdet(self): pass def test_inv_quad_logdet_no_reduce(self): pass def test_root_inv_decomposition(self): lazy_tensor = self.create_lazy_tensor() root_approx = lazy_tensor.root_inv_decomposition() test_mat = lazy_tensor.eager_rhss[0].clone().detach() res = root_approx.matmul(test_mat) actual = lazy_tensor.inv_matmul(test_mat) self.assertLess(torch.norm(res - actual) / actual.norm(), 0.1) class TestCachedCGLazyTensor(TestCachedCGLazyTensorNoLogdet): seed = 0 def test_inv_quad_logdet(self): # Forward lazy_tensor = self.create_lazy_tensor(with_solves=True, with_logdet=True) evaluated = self.evaluate_lazy_tensor(lazy_tensor) flattened_evaluated = evaluated.view(-1, *lazy_tensor.matrix_shape) vecs = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True) vecs_copy = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True) with gpytorch.settings.num_trace_samples(128), warnings.catch_warnings(record=True) as w: res_inv_quad, res_logdet = lazy_tensor.inv_quad_logdet(inv_quad_rhs=vecs, logdet=True) self.assertEqual(len(w), 0) res = res_inv_quad + res_logdet actual_inv_quad = evaluated.inverse().matmul(vecs_copy).mul(vecs_copy).sum(-2).sum(-1) actual_logdet = torch.cat( [torch.logdet(flattened_evaluated[i]).unsqueeze(0) for i in range(lazy_tensor.batch_shape.numel())] ).view(lazy_tensor.batch_shape) actual = actual_inv_quad + actual_logdet diff = (res - actual).abs() / actual.abs().clamp(1, math.inf) self.assertLess(diff.max().item(), 15e-2) def test_inv_quad_logdet_no_reduce(self): # Forward lazy_tensor = self.create_lazy_tensor(with_solves=True, with_logdet=True) evaluated = self.evaluate_lazy_tensor(lazy_tensor) flattened_evaluated = evaluated.view(-1, *lazy_tensor.matrix_shape) vecs = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True) vecs_copy = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True) with gpytorch.settings.num_trace_samples(128), warnings.catch_warnings(record=True) as w: res_inv_quad, res_logdet = lazy_tensor.inv_quad_logdet( inv_quad_rhs=vecs, logdet=True, reduce_inv_quad=False ) self.assertEqual(len(w), 0) res = res_inv_quad.sum(-1) + res_logdet actual_inv_quad = evaluated.inverse().matmul(vecs_copy).mul(vecs_copy).sum(-2).sum(-1) actual_logdet = torch.cat( [torch.logdet(flattened_evaluated[i]).unsqueeze(0) for i in range(lazy_tensor.batch_shape.numel())] ).view(lazy_tensor.batch_shape) actual = actual_inv_quad + actual_logdet diff = (res - actual).abs() / actual.abs().clamp(1, math.inf) self.assertLess(diff.max().item(), 15e-2) class TestCachedCGLazyTensorNoLogdetBatch(TestCachedCGLazyTensorNoLogdet): seed = 0 def create_lazy_tensor(self, with_solves=False, with_logdet=False): mat = torch.randn(3, 5, 6) mat = mat.matmul(mat.transpose(-1, -2)) mat.requires_grad_(True) lazy_tensor = NonLazyTensor(mat) eager_rhs = torch.randn(3, 5, 10).detach() if with_solves: with gpytorch.settings.num_trace_samples(1000 if with_logdet else 1): # For inv_quad_logdet tests solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms( lazy_tensor, eager_rhs.detach(), logdet_terms=with_logdet ) eager_rhss = [eager_rhs.detach(), eager_rhs[..., -2:-1].detach()] solves = [solve.detach(), solve[..., -2:-1].detach()] else: eager_rhss = [eager_rhs] solves = [] probe_vecs = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_norms = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_solves = torch.tensor([], dtype=mat.dtype, device=mat.device) tmats = torch.tensor([], dtype=mat.dtype, device=mat.device) return CachedCGLazyTensor( lazy_tensor, eager_rhss, solves, probe_vecs, probe_vec_norms, probe_vec_solves, tmats ) class TestCachedCGLazyTensorBatch(TestCachedCGLazyTensor): seed = 0 def create_lazy_tensor(self, with_solves=False, with_logdet=False): mat = torch.randn(3, 5, 6) mat = mat.matmul(mat.transpose(-1, -2)) mat.requires_grad_(True) lazy_tensor = NonLazyTensor(mat) eager_rhs = torch.randn(3, 5, 10).detach() if with_solves: with gpytorch.settings.num_trace_samples(1000 if with_logdet else 1): # For inv_quad_logdet tests solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms( lazy_tensor, eager_rhs.detach(), logdet_terms=with_logdet ) eager_rhss = [eager_rhs.detach(), eager_rhs[..., -2:-1].detach()] solves = [solve.detach(), solve[..., -2:-1].detach()] else: eager_rhss = [eager_rhs] solves = [] probe_vecs = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_norms = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_solves = torch.tensor([], dtype=mat.dtype, device=mat.device) tmats = torch.tensor([], dtype=mat.dtype, device=mat.device) return CachedCGLazyTensor( lazy_tensor, eager_rhss, solves, probe_vecs, probe_vec_norms, probe_vec_solves, tmats ) class TestCachedCGLazyTensorMultiBatch(TestCachedCGLazyTensor): seed = 0 # Because these LTs are large, we'll skil the big tests should_test_sample = False skip_slq_tests = True def create_lazy_tensor(self, with_solves=False, with_logdet=False): mat = torch.randn(2, 3, 5, 6) mat = mat.matmul(mat.transpose(-1, -2)) mat.requires_grad_(True) lazy_tensor = NonLazyTensor(mat) eager_rhs = torch.randn(2, 3, 5, 10).detach() if with_solves: with gpytorch.settings.num_trace_samples(1000 if with_logdet else 1): # For inv_quad_logdet tests solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms( lazy_tensor, eager_rhs.detach(), logdet_terms=with_logdet ) eager_rhss = [eager_rhs.detach(), eager_rhs[..., -2:-1].detach()] solves = [solve.detach(), solve[..., -2:-1].detach()] else: eager_rhss = [eager_rhs] solves = [] probe_vecs = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_norms = torch.tensor([], dtype=mat.dtype, device=mat.device) probe_vec_solves = torch.tensor([], dtype=mat.dtype, device=mat.device) tmats = torch.tensor([], dtype=mat.dtype, device=mat.device) return CachedCGLazyTensor( lazy_tensor, eager_rhss, solves, probe_vecs, probe_vec_norms, probe_vec_solves, tmats )
StarcoderdataPython
76526
<filename>tests/test_protocol_implements_decorator.py from protocol_implements_decorator import implements from typing import Protocol def test(): """Run some tests on the functionality of the decorators.""" class Printable(Protocol): """A test protocol that requires a to_string method.""" def to_string(self) -> str: return "" class Otherable(Protocol): """Another example.""" def other(self) -> str: return "" fail: bool = False try: @implements(Printable) class Example: # type: ignore """Test class that should implement printable but doesn't.""" except NotImplementedError: fail = True pass assert fail @implements(Printable) class Example2: # type: ignore """Test class that does implement Printable.""" def to_string(self) -> str: return str(self) fail = False @implements(Printable, Otherable) class Example4: """Test class that uses multiple protocols.""" def to_string(self) -> str: return str(self) def other(self) -> str: return str(self) test = Example4() print(test.get_protocols_implemented())
StarcoderdataPython
1753678
<reponame>xotonic/netconfessor<filename>gen/tools/jnc_plugin/java_value.py import collections import context import util from .ordered_set import OrderedSet class JavaValue(object): """A Java value, typically representing a field or a method in a Java class and optionally a javadoc comment. A JavaValue can have its attributes set using the optional keyword arguments of the constructor, or by using the add and set methods. Each instance of this class has an 'as_list' method which is used to get a list of strings representing lines of code that can be written to a Java file once all the attributes have been set set. """ def __init__(self, exact=None, javadocs=None, modifiers=None, name=None, value=None, imports=None, indent=4): """Initializes the attributes of a new Java value. Keyword arguments: exact (String list) -- If supplied, the 'as_list' method will return this list until something has been added to this Java value. javadocs (String list) -- A list of the lines in the javadoc declaration for this Java Value. modifiers (String list) -- A list of Java modifiers such as 'public' and 'static'. Also used to specify the type of fields. name (String) -- The identifier used for this value. value (String) -- Not used by methods, this is placed after the assignment operator in a field declaration. imports (String list) -- A (possibly redundant) set of classes to import in the class declaring this value. This list is typically filtered by other classes so nothing gets imported unless it is required to for the Java class to compile. indent (Integer) -- The indentation in the 'as_list' representation. Defaults to 4 spaces. """ self.value = value self.indent = ' ' * indent self.default_modifiers = True self.javadocs = OrderedSet() if javadocs is not None: for javadoc in javadocs: self.add_javadoc(javadoc) self.modifiers = [] if modifiers is not None: for modifier in modifiers: self.add_modifier(modifier) self.name = None if name is not None: self.set_name(name) self.imports = set([]) if imports is not None: for import_ in imports: self.imports.add(import_) self.exact = exact self.default_modifiers = True def __eq__(self, other): """Returns True iff self and other represents an identical value""" for attr, value in vars(self).items(): try: if getattr(other, attr) != value: return False except AttributeError: return False return True def __ne__(self, other): """Returns True iff self and other represents different values""" return not self.__eq__(other) def _set_instance_data(self, attr, value): """Adds or assigns value to the attr attribute of this Java value. attr (String) -- The attribute to add or assign value to. If this Java value does not have an attribute with this name, a warning is printed with the msg "Unknown attribute" followed by the attribute name. The value is added, appended or assigned, depending on if the attribute is a MutableSet, a list or something else, respectively. value -- Typically a String, but can be anything, really. The 'exact' cache is invalidated is the attribute exists. """ try: data = getattr(self, attr) if isinstance(data, list): data.append(value) elif isinstance(data, collections.MutableSet): data.add(value) else: setattr(self, attr, value) except AttributeError: util.print_warning(msg='Unknown attribute: ' + attr, key=attr) else: self.exact = None # Invalidate cache def set_name(self, name): """Sets the identifier of this value""" self._set_instance_data('name', name) def set_indent(self, indent=4): """Sets indentation used in the as_list methods""" self._set_instance_data('indent', ' ' * indent) def add_modifier(self, modifier): """Adds modifier to end of list of modifiers. Overwrites modifiers set in constructor the first time it is invoked, to enable subclasses to have default modifiers. """ if self.default_modifiers: self.modifiers = [] self.default_modifiers = False self._set_instance_data('modifiers', modifier) def add_javadoc(self, line): """Adds line to javadoc comment, leading ' ', '*' and '/' removed""" self._set_instance_data('javadocs', line.lstrip(' */')) def add_dependency(self, import_, this_class_name=''): """Adds import_ to list of imports needed for value to compile.""" _, sep, class_name = import_.rpartition('.') if sep: if class_name not in context.java_built_in | {this_class_name}: self.imports.add(import_) return class_name elif not any(x in context.java_built_in | {this_class_name} for x in (import_, import_[:-2])): self.imports.add(import_) return import_ def javadoc_as_string(self): """Returns a list representing javadoc lines for this value""" lines = [] if self.javadocs: lines.append(self.indent + '/**') lines.extend([self.indent + ' * ' + line for line in self.javadocs]) lines.append(self.indent + ' */') return lines def as_list(self): """String list of code lines that this Java value consists of""" if self.exact is None: assert self.name is not None assert self.indent is not None self.exact = self.javadoc_as_string() declaration = self.modifiers + [self.name] if self.value is not None: declaration.append('=') declaration.append(self.value) self.exact.append(''.join([self.indent, ' '.join(declaration), ';'])) return self.exact def __hash__(self): return hash(str(self.as_list()))
StarcoderdataPython
1692848
<reponame>suyanan/vioser<filename>1.0/VIOS/ngs/scripts/db_nt_process.py #-*- coding:utf-8 -*- from .config_paras import * if __name__ == '__main__': sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) os.environ['DJANGO_SETTINGS_MODULE'] = 'VIOS.settings' django.setup() ##index the nt file : 20170614(download) def nt_database_pre_process(ntFile): os.system('makeblastdb -dbtype nucl -input_type fasta -in %s' %(ntFile)) #ntVirusesLen1000File_dir = os.path.dirname(ntVirusesLen1000File) #os.system('bowtie2-build -f -q --threads %d %s %s/%s' %(numThreads,ntVirusesLen1000File,ntVirusesLen1000File_dir,bt2_index_base)) #%s %s%s : ref bt2_index_base os.system('samtools faidx %s'%(ntFile)) #nt_database_pre_process(nt_file) ##index the nt_index_title #def nt_index_title() #the nt file is too large, so in big_server to get the log/ouput by using "print .." def nt_viruses_onceforall(numThreads,ntVirusesFamilyNameList): """index the nt_viruses _family and generate index_header file""" nt_viruses_family_file_list,nt_viruses_family_path_list,bt2_index_base_name_list,nt_viruses_family_index_header_file_list = get_nt_viruses_family_results(ntVirusesFamilyNameList) #print nt_viruses_family_file_list for i in range(len(ntVirusesFamilyNameList)): print '===========%s'%(ntVirusesFamilyNameList[i]) #format the local nt_ file to blastn , maxFileSize = '2GB' #BLAST options error: max_file_sz must be < 2 GiB #os.system('makeblastdb -dbtype nucl -input_type fasta -max_file_sz 2GB -in %s' %(nt_viruses_family_file_list[i])) os.system('makeblastdb -dbtype nucl -input_type fasta -in %s' %(nt_viruses_family_file_list[i])) os.system('bowtie2-build -f -q --threads %d %s %s/%s' %(numThreads,nt_viruses_family_file_list[i],nt_viruses_family_path_list[i],bt2_index_base_name_list[i])) os.system('samtools faidx %s'%(nt_viruses_family_file_list[i])) #generate nt_index_header file nt_viruses_family_file_obj = open(nt_viruses_family_file_list[i], 'r') nt_viruses_family_index_header_file_obj = open(nt_viruses_family_index_header_file_list[i],'w+') try: while True: eachLine = nt_viruses_family_file_obj.readline() if eachLine == '': #read the end of file : EOF break; if eachLine[0] == '>': #header = eachLine.split('>')[-1] # >V01351.1 Sea urchin fragment, 3' to the actin gene in <SPAC01> header = eachLine[1:-1] assession = header.split(' ')[0] annotation = header[header.index(' ') + 1:] for i in range(len(annotation) - 1): if not (re.compile(r'\w|,|\'|<|>|\.|-|_|\(|\)|\+|:')).match(annotation[i]): annotation = annotation.replace(annotation[i], ' ') nt_viruses_family_index_header_file_obj.write(assession+'\t'+annotation+'\n') finally: nt_viruses_family_file_obj.close() nt_viruses_family_index_header_file_obj.close() #nt_viruses_family_name_list = ['viruses_final','viruses_full','bacterias_full','viruses_Adenoviridae','viruses_Coronaviridae','viruses_Filoviridae','viruses_Flaviviridae','viruses_Orthomyxoviridae'] #0 means viruses full database max_target_seqs_nt_viruses_list = [120211, 3817, 6224600, 9894, 2462, 65183, 420380] #while employ nt_viruses_onceforall , you can change it. max_target_seqs_nt_viruses = max(max_target_seqs_nt_viruses_list) #420380, use the max as the paras of 'blastn -max_target_seqs' def genome_hosts_onceforall(numThreads,genomeHostsNameList): """index the genome_hosts""" genome_hosts_file_list,genome_hosts_path_list,bt2_index_base_name_list = get_genome_hosts_results(genomeHostsNameList) for i in range(len(genomeHostsNameList)): print '===========%s'%(genomeHostsNameList[i]) genome_hosts_fasta_file = os.path.join(genome_hosts_path_list[i],genomeHostsNameList[i]+'.fa') #print genome_hosts_fasta_file if os.path.getsize(genome_hosts_file_list[i]): #some genome not in USCS with 2bit format, but can find in Genome browser and ftp download fasta format os.system('twoBitToFa %s %s' %(genome_hosts_file_list[i],genome_hosts_fasta_file)) os.system('bowtie2-build -f -q --threads %d %s %s/%s'%(numThreads,genome_hosts_fasta_file,genome_hosts_path_list[i],bt2_index_base_name_list[i])) def genome_host_adder(numThreads,genomeHostName,genomeHostNameReadable): path_name = genomeHostName file_name = '%s.2bit'%(genomeHostName) genome_host_path = genomesDB_path+path_name if not os.path.exists(genome_host_path): os.system('mkdir %s'%(genome_host_path)) genome_host_file = os.path.join(genome_host_path,file_name) bt2_index_base_name = 'bt2_index_%s'%(genomeHostName) print '===========%s'%(genomeHostName) genome_host_adder_file = os.path.join(db_path,'genome_host_adder.log') genome_hosts_name_adder_list = [] if os.path.exists(genome_host_adder_file):#if file exists,check. if no exists just pass with open(genome_host_adder_file,'r') as genome_host_adder_file_obj: genome_hosts_adder_list = genome_host_adder_file_obj.readlines() for i in range(len(genome_hosts_adder_list)): each_genome_host = genome_hosts_adder_list[i].strip('\n') each_genome_host_name = each_genome_host.split('\t')[0] genome_hosts_name_adder_list.append(each_genome_host_name) ###no repeate submit the genome name by users genome_hosts_name_updated_list = genome_hosts_name_list+genome_hosts_name_adder_list if not genomeHostName in genome_hosts_name_updated_list: os.system('rsync -aP rsync://hgdownload.soe.ucsc.edu/goldenPath/%s/bigZips/%s.2bit %s' %(genomeHostName,genomeHostName,genome_host_path)) genome_host_fasta_file = os.path.join(genome_host_path,genomeHostName+'.fa') ##rsync download fail, there is no user's host name in USCS if not os.path.exists(genome_host_file): os.rmdir(genome_host_path) if os.path.exists(genome_host_path) and os.path.getsize(genome_host_file):#file exists and not empty os.system('twoBitToFa %s %s' %(genome_host_file,genome_host_fasta_file)) os.system('bowtie2-build -f -q --threads %d %s %s/%s'%(numThreads,genome_host_fasta_file,genome_host_path,bt2_index_base_name)) #if all is successful,remember the genome_host_name_readable genome_host_adder_file = os.path.join(db_path,'genome_host_adder.log') with open(genome_host_adder_file,'a+') as genome_host_adder_file_obj: genome_hosts_adder_list = [genomeHostName+'\t',genomeHostNameReadable+'\n'] genome_host_adder_file_obj.writelines(genome_hosts_adder_list)
StarcoderdataPython
3301637
<reponame>sbutler/spacescout_web """ Copyright 2013 Board of Trustees, University of Illinois 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. Description ================================================================= Modifies the search arguments before send it to spotseeker_server. """ from spacescout_web.org_filters import SearchFilter import sys class Filter(SearchFilter): def filter_args(self, args): if 'shibboleth' in sys.modules and self.request.user.is_authenticated(): args['eppn'] = self.request.user.username return args
StarcoderdataPython
1628243
<gh_stars>1-10 """ Generate the right type of host object and return it or run commands against it """ import logging from dsi.common.local_host import LocalHost from dsi.common.log import IOLogAdapter from dsi.common.remote_ssh_host import RemoteSSHHost LOG = logging.getLogger(__name__) # This stream only log error or above messages ERROR_ONLY = logging.getLogger("error_only") INFO_ADAPTER = IOLogAdapter(LOG, logging.INFO) WARN_ADAPTER = IOLogAdapter(LOG, logging.WARN) def make_host(host_info, mongodb_auth_settings=None, use_tls=False): """ Create a host object based off of host_ip_or_name. The code that receives the host is responsible for calling close on the host instance. Each RemoteHost instance can have 2*n+1 open sockets (where n is the number of exec_command calls with Pty=True) otherwise n is 1 so there is a max of 3 open sockets. :param mongodb_auth_settings: MongoDB auth settings dictionary :param namedtuple host_info: Public IP address or the string localhost, category and offset :rtype: Host """ host = None if host_info.public_ip in ["localhost", "127.0.0.1", "0.0.0.0"]: LOG.debug("Making localhost for %s", host_info.public_ip) host = LocalHost(mongodb_auth_settings, use_tls) else: LOG.debug("Making remote host for %s using ssh", host_info.public_ip) host = RemoteSSHHost( host_info.public_ip, host_info.ssh_user, host_info.ssh_key_file, mongodb_auth_settings, use_tls, ) host.alias = "{category}.{offset}".format(category=host_info.category, offset=host_info.offset) return host
StarcoderdataPython
3265780
<filename>naa_csv_reader.py<gh_stars>1-10 import csv def csv_reader(csv_filename): """ This module reads the csv file for a specified spectrum that contains the peak information in a single column. This module will extract the peak energies as well as their associated net area with uncertainty and FWHM. """ file = open(csv_filename,'r') read_file = csv.reader(file) raw_data = list(read_file) energies = [] net_area = [] net_area_unc = [] peak_cps = [] fwhm = [] for i in range(len(raw_data[2:])): energies.append(raw_data[2+i][0]) net_area.append(raw_data[2+i][1]) net_area_unc.append(raw_data[2+i][2]) peak_cps.append(raw_data[2+i][3]) fwhm.append(raw_data[2+i][4]) energies = [float(x) for x in energies] net_area = [float(x) for x in net_area] net_area_unc = [float(x) for x in net_area_unc] peak_cps = [float(x) for x in peak_cps] fwhm = [float(x) for x in fwhm] peak_info = {'energies':energies,'net_area':net_area,'net_area_unc':net_area_unc,'peak_cps':peak_cps,'fwhm':fwhm,'csv_filename':csv_filename} return(peak_info)
StarcoderdataPython
3208616
#Ler dois vetores de dimensão 5 e calcular o produto interno deles. vetor1 = [] vetor2 = [] produtoInterno = 0.0 print("insira as componentes do primeiro vetor: ") for i in range(5): vetor1.append(float(input(f'Entre com o {i+1}-ésimo valor do vetor 1: '))) print("insira as componentes do segundo vetor: ") for i in range(5): vetor2.append(float(input(f'Entre com o {i+1}-ésimo valor do vetor 1: '))) #cálculo do produto interno for i in range(5): produtoInterno += vetor1[i]*vetor2[i] print(f'o produto interno é {produtoInterno:.2f}')
StarcoderdataPython
3229911
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython Una empresa de servicios públicos desea liquidar el total de la factura teniendo en cuenta: +---------+------------------+---------------+ | Estrato | Nivel de Consumo | Tarifa Básica | +---------+------------------+---------------+ | 1 | <= 10 | $5000 | +---------+------------------+---------------+ | 2 | <= 25 | $10000 | +---------+------------------+---------------+ | 3 | <= 35 | $15000 | +---------+------------------+---------------+ | 4 | <= 40 | $20000 | +---------+------------------+---------------+ Si el nivel de consumo se excede, debe pagar por cada punto adicional en el nivel de consumo $800, en cualquiera de los 4 estratos. Ejemplo: Si el estrato es 3 y el nivel de consumo 45 entonces el valor de la factura es de: Valor factura = 15000 + (10*800) = 23000 pesos Realizar: a. Una función que tenga como parámetros de entrada el estrato y el nivel de consumo, y debe retornar el valor de la factura a pagar. """ tabla = { 1: (5000, 10), 2: (10000, 25), 3: (15000, 35), 4: (20000, 40), } def calcular(estrato: float, consumo: float) -> float: """Calcula el valor de la factura a pagar. :param estrato: Estrato del cliente. :estrato type: float :param consumo: Nivel de consumo del cliente. :consumo type: float :return: Valor de la factura a pagar. :rytpe: float >>> calcular(3, 45) 23000 """ tarifa_basica, limite = tabla[estrato] if consumo <= limite: return tarifa_basica else: return tarifa_basica + (consumo - limite) * 800 if __name__ == "__main__": import doctest doctest.testmod()
StarcoderdataPython
1730582
# Configuration file for jupyterhub. ## The public facing URL of the whole JupyterHub application. # # This is the address on which the proxy will bind. # Sets protocol, ip, base_url # Default: 'http://:8000' c.JupyterHub.bind_url = 'http://:8000' ## The URL the single-user server should start in. # # `{username}` will be expanded to the user's username # # Example uses: # # - You can set `notebook_dir` to `/` and `default_url` to `/tree/home/{username}` to allow people to # navigate the whole filesystem from their notebook server, but still start in their home directory. # - Start with `/notebooks` instead of `/tree` if `default_url` points to a notebook instead of a directory. # - You can set this to `/lab` to have JupyterLab start by default, rather than Jupyter Notebook. # Default: '' c.Spawner.default_url = '/lab'
StarcoderdataPython
1748616
from card_lookup import process_exact_match def test_exact_match_found(db_cursor): test_inputs = ["Goblin", "cerberus", "Puppet", "Ceres of the Night", "Ta-G, Katana Unsheathed", "Marionette//Tre", "XII. Wolfraud, Hanged Man", "XXI. Zelgenea, The World" ] for i in test_inputs: assert process_exact_match(i, db_cursor) is not None def test_exact_match_not_found(db_cursor): test_inputs = ["wisp", "Hades", "elanas prayer", "erntz", " ", "" ] for i in test_inputs: assert process_exact_match(i, db_cursor) is None # for cards reprinted into newer sets, # the bot returns card from original released set def test_exact_match_card_reprint(db_cursor): result = process_exact_match("summit temple", db_cursor) assert result["card_set_id"] == 10007 # == chronogenesis
StarcoderdataPython
1738780
# given 2 integer, determin weather # or not they differ by one bit # link : https://www.youtube.com/watch?v=LqxtPV8xKeI&list=PLNmW52ef0uwvkul_e_wLD525jbTfMKLIJ&index=3 def grayNumber(a, b): x = a ^ b while x > 0: if x % 2 == 1 and x >> 1 > 0: return False x >>= 1 return True def main(): a = int(input()) b = int(input()) print(grayNumber(a, b)) if __name__ == "__main__": main()
StarcoderdataPython
1777719
<reponame>malva28/Cat-Jump-2D<filename>codigo/controller.py import glfw import sys class Controller: def __init__(self): self.mc = None def set_model(self, m): self.mc = m def on_key(self, window, key, scancode, action, mods): if self.mc.game_over: print("The game is over!" "\nRerun the program to start again") return if not (action == glfw.PRESS or action == glfw.RELEASE): return if key == glfw.KEY_ESCAPE: sys.exit() elif key == glfw.KEY_A and action == glfw.PRESS: self.mc.direc = -1 elif key == glfw.KEY_D and action == glfw.PRESS: self.mc.direc = 1 elif (key == glfw.KEY_A or key == glfw.KEY_D) and action == glfw.RELEASE: self.mc.direc = 0 elif key == glfw.KEY_W: self.mc.jump() else: print('Unknown key')
StarcoderdataPython
3376598
<filename>test_project/test_project/settings.py """ Django settings for test_project project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'NOT_SECRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True USE_DEBUG_TOOLBAR = DEBUG TEMPLATE_DEBUG = True ACCEPT_FEEDBACK = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'brambling', 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'zenaida', 'zenaida.contrib.hints', 'floppyforms', 'django_filters', 'daguerre', 'compressor', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", 'brambling.context_processors.current_site', ) ROOT_URLCONF = 'test_project.urls' WSGI_APPLICATION = 'test_project.wsgi.application' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static') import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media') from django.core.urlresolvers import reverse_lazy LOGIN_REDIRECT_URL = '/' LOGIN_URL = reverse_lazy('login') AUTH_USER_MODEL = 'brambling.Person' # These IDs are used for Stripe Connect and Dwolla facilitation # respectively. STRIPE_APPLICATION_ID = os.environ.get('STRIPE_APPLICATION_ID', '') STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY', '') STRIPE_PUBLISHABLE_KEY = os.environ.get('STRIPE_PUBLISHABLE_KEY', '') STRIPE_TEST_APPLICATION_ID = os.environ.get('STRIPE_TEST_APPLICATION_ID', '') STRIPE_TEST_SECRET_KEY = os.environ.get('STRIPE_TEST_SECRET_KEY', '') STRIPE_TEST_PUBLISHABLE_KEY = os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY', '') DWOLLA_APPLICATION_KEY = os.environ.get('DWOLLA_APPLICATION_KEY', '') DWOLLA_APPLICATION_SECRET = os.environ.get('DWOLLA_APPLICATION_SECRET', '') DWOLLA_TEST_APPLICATION_KEY = os.environ.get('DWOLLA_TEST_APPLICATION_KEY', '') DWOLLA_TEST_APPLICATION_SECRET = os.environ.get('DWOLLA_TEST_APPLICATION_SECRET', '') STRIPE_TEST_ORGANIZATION_ACCESS_TOKEN = os.environ.get('STRIPE_TEST_ORGANIZATION_ACCESS_TOKEN', '') STRIPE_TEST_ORGANIZATION_PUBLISHABLE_KEY = os.environ.get('STRIPE_TEST_ORGANIZATION_PUBLISHABLE_KEY', '') STRIPE_TEST_ORGANIZATION_REFRESH_TOKEN = os.environ.get('STRIPE_TEST_ORGANIZATION_REFRESH_TOKEN', '') STRIPE_TEST_ORGANIZATION_USER_ID = os.environ.get('STRIPE_TEST_ORGANIZATION_USER_ID', '') DWOLLA_TEST_ORGANIZATION_ACCESS_TOKEN = os.environ.get('DWOLLA_TEST_ORGANIZATION_ACCESS_TOKEN', '') DWOLLA_TEST_ORGANIZATION_REFRESH_TOKEN = os.environ.get('DWOLLA_TEST_ORGANIZATION_REFRESH_TOKEN', '') DWOLLA_TEST_ORGANIZATION_USER_ID = os.environ.get('DWOLLA_TEST_ORGANIZATION_USER_ID', '') DWOLLA_TEST_ORGANIZATION_PIN = os.environ.get('DWOLLA_TEST_ORGANIZATION_PIN', '') DWOLLA_TEST_USER_ACCESS_TOKEN = os.environ.get('DWOLLA_TEST_USER_ACCESS_TOKEN', '') DWOLLA_TEST_USER_REFRESH_TOKEN = os.environ.get('DWOLLA_TEST_USER_REFRESH_TOKEN', '') DWOLLA_TEST_USER_USER_ID = os.environ.get('DWOLLA_TEST_USER_USER_ID', '') DWOLLA_TEST_USER_PIN = os.environ.get('DWOLLA_TEST_USER_PIN', '') GRAPPELLI_ADMIN_TITLE = "Dancerfly" STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) _BOOTSTRAP_SASS_SUBPATH = "/gems/bootstrap-sass-3.3.4.1/assets/stylesheets/" STATICFILES_DIRS = [x + _BOOTSTRAP_SASS_SUBPATH for x in os.environ['GEM_PATH'].split(":") if os.path.isdir(x + _BOOTSTRAP_SASS_SUBPATH)] COMPRESS_PRECOMPILERS = ( ('text/sass', 'django_libsass.SassCompiler'), ) from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert alert-info', messages.INFO: 'alert alert-info', messages.SUCCESS: 'alert alert-success', messages.WARNING: 'alert alert-warning', messages.ERROR: 'alert alert-danger' } if USE_DEBUG_TOOLBAR: INSTALLED_APPS += ( 'debug_toolbar.apps.DebugToolbarConfig', 'template_timings_panel', ) DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', 'template_timings_panel.panels.TemplateTimings.TemplateTimings', ] if ACCEPT_FEEDBACK: MIDDLEWARE_CLASSES += ( 'talkback.middleware.TalkbackMiddleware', ) INSTALLED_APPS += ( 'talkback', )
StarcoderdataPython
148801
#!/usr/bin/env python from setuptools import setup, find_packages version = None exec(open('dagr_revamped/version.py').read()) with open('README.md', 'r') as fh: long_description = fh.read() setup( name='dagr_revamped', version=version, description='A deviantArt Ripper script written in Python', author='<NAME>', url='https://github.com/phillmac/dagr_revamped', packages=find_packages(), package_data={'dagr_revamped': ['builtin_plugins/*']}, install_requires=[ 'MechanicalSoup >= 0.10.0', 'docopt == 0.6.2', 'pluginbase == 1.0.0', 'portalocker == 2.3.0', 'python-dateutil == 2.7.5', 'pybreaker == 0.6.0', 'requests-toolbelt==0.9.1', 'deviantart @ git+https://github.com/phillmac/deviantart@c21ce195b466618ae16a9146412b3b713be71ef5' ], extras_require={ 'calmjs': ['calmjs==3.3.1'], 'selenium': ['selenium==3.141.0'], 'easywebdav': ['easywebdav==1.2.0'], 'full': ['calmjs', 'selenium', 'easywebdav'] }, classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], entry_points={ 'console_scripts': [ 'dagr.py=dagr_revamped.cli:main', 'dagr-bulk.py=dagr_revamped.bulk:main', 'dagr-utils.py=dagr_revamped.utils_cli:main', 'dagr-config.py=dagr_revamped.config:main' ] } )
StarcoderdataPython
2756
<filename>languages/pt-br.py # coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não é possível atualizar ou excluir os resultados de uma junção', '# of International Staff': '# De equipe internacional', '# of National Staff': '# De equipe nacional', '# of Vehicles': '# De Veículos', '%(msg)s\nIf the request type is "%(type)s", please enter the %(type)s on the next screen.': '%(msg)s\nSe o tipo de pedido é "%(type)s", digite a %(type)s na próxima tela.', '%(system_name)s - Verify Email': '%(system_name)s - Verificar E-Mail', '%.1f km': '%.1f km', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%m-%d-%Y': '%m-%d-%Y', '%m-%d-%Y %H:%M:%S': '%m-%d-%Y %H:%M:%S', '%s Create a new site or ensure that you have permissions for an existing site.': '%s Cria um novo site ou garante que você tenha permissões para um site existente.', '%s rows deleted': '%s linhas excluídas', '%s rows updated': '%s linhas atualizadas', '& then click on the map below to adjust the Lat/Lon fields': 'Em seguida selecione o mapa abaixo para ajustar os campos Lat/Lon', "'Cancel' will indicate an asset log entry did not occur": "'cancelar' irá indicar que a entrada de log de ativo não ocorreu", '* Required Fields': '* campos obrigatórios', '0-15 minutes': '0-15 minutos', '1 Assessment': '1 Avaliação', '1 location, shorter time, can contain multiple Tasks': '1 Local, menos tempo, pode conter várias Tarefas', '1-3 days': '1 a 3 dias', '15-30 minutes': '15 a 30 minutos', '2 different options are provided here currently:': '2 opções diferentes são fornecidos aqui atualmente:', '2x4 Car': 'Carro 2x4', '30-60 minutes': '30-60 minutos', '4-7 days': '4-7 Dias', '4x4 Car': 'Carro 4x4', '8-14 days': '8-14 Dias', 'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.': 'Um marcador assinalado para um local individual é configurado se há a necessidade de substituir um marcador assinalado para o Recurso Classe.', 'A Reference Document such as a file, URL or contact person to verify this data.': 'A Reference Document such as a file, URL or contact person to verify this data.', 'A Reference Document such as a file, URL or contact person to verify this data. You can type the 1st few characters of the document name to link to an existing document.': 'Um documento de referência como um arquivo, URL ou contacto pessoal para verificar esses dados. Pode inserir as primeiras letras do nome dum documento para chegar a esse documento.', 'A brief description of the group (optional)': 'Uma descrição breve do grupo (opcional)', 'A file downloaded from a GPS containing a series of geographic points in XML format.': 'Um ficheiro descarregado de um GPS contendo uma série de pontos geográficos em formato XML.', 'A file in GPX format taken from a GPS whose timestamps can be correlated with the timestamps on the photos to locate them on the map.': 'Um ficheiro em formato GPX retirado de um GPS cujas datas e horas podem ser correlacionadas com as de fotografias para localização num mapa.', 'A file in GPX format taken from a GPS.': 'A file in GPX format taken from a GPS.', 'A library of digital resources, such as photos, documents and reports': 'Uma biblioteca de recursos digitais, como fotos, documentos e relatórios', 'A location group can be used to define the extent of an affected area, if it does not fall within one administrative region.': 'Um grupo local pode ser usado para definir a extensão de uma área afetada, se não cair dentro de uma região administrativa.', 'A location group is a set of locations (often, a set of administrative regions representing a combined area).': 'Um grupo de localização é um conjunto de locais (muitas vezes, um conjunto de regiões administrativas que representam uma área Combinada).', 'A location group is a set of locations (often, a set of administrative regions representing a combined area). Member locations are added to a location group here. Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group. A location group can be used to define the extent of an affected area, if it does not fall within one administrative region. Location groups can be used in the Regions menu.': 'Um grupo de localização é um conjunto de locais (muitas vezes, um conjunto de regiões administrativas que representam uma área Combinada). Membros locais são adicionados em grupos locais aqui. Grupos locais podem ser utilizados para filtrar o que é mostrado no mapa e nos resultados da procura apenas as entidades locais abrangidas no grupo. Um grupo local pode ser usado para definir a extensão de uma área afetada, se não cair dentro de uma região administrativa. Grupos local pode ser utilizado no menu Regiões.', 'A location group must have at least one member.': 'Um grupo de localização deve ter, pelo menos, um membro.', "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": 'Um local que especifica a área geográfica dessa região. Este pode ser um local a partir da hierarquia local, ou um "grupo local", ou um local que tem um limite para a área.', 'A survey series with id %s does not exist. Please go back and create one.': 'Id% não foi encontrado na pesquisa. Por favor voltar e crie um.', 'A task is a piece of work that an individual or team can do in 1-2 days': 'A task is a piece of work that an individual or team can do in 1-2 days', 'ABOUT THIS MODULE': 'SOBRE ESTE MÓDULO', 'ACCESS DATA': 'Dados de Acesso', 'ANY': 'Todos', 'API Key': 'API Key', 'API is documented here': 'API está documentado aqui', 'ATC-20 Rapid Evaluation modified for New Zealand': 'ATC-20 Rápida Avaliação modificado para a Nova Zelândia', 'Abbreviation': 'Abreviatura', 'Ability to Fill Out Surveys': 'Capacidade para preencher Inquéritos', 'Ability to customize the list of details tracked at a Shelter': 'Capacidade de Customizar a lista de detalhes rastreados em um Abrigo', 'Ability to customize the list of human resource tracked at a Shelter': 'Capacidade de Customizar a lista de recursos humanos Rastreados em um Abrigo', 'Ability to customize the list of important facilities needed at a Shelter': 'Capacidade de Customizar a lista das instalações importante necessária em um Abrigo', 'Ability to view Results of Completed and/or partially filled out Surveys': 'Capacidade para visualizar resultados de Concluída e/ou parcialmente preenchido Pesquisas', 'About': 'sobre', 'About Sahana': 'Sobre Sahana', 'Access denied': 'Acesso negado', 'Access to Shelter': 'Acesso a Abrigo', 'Access to education services': 'Acesso a serviços de educação', 'Accessibility of Affected Location': 'Acessibilidade do Local Afectado', 'Accompanying Relative': 'Accompanying Relative', 'Account Registered - Please Check Your Email': 'Conta registrada - verifique seu e-mail', 'Account registered, however registration is still pending approval - please wait until confirmation received.': 'Conta registrada, mas registro pende aprovação - por favor aguarde até confirmação ser recebida.', 'Acronym': 'Iniciais', "Acronym of the organization's name, eg. IFRC.": 'Acrônimo do nome da organização, por exemplo, FICV.', 'Actionable by all targeted recipients': 'Acionáveis por todos os destinatários de destino', 'Actionable only by designated exercise participants; exercise identifier SHOULD appear in <note>': 'Acionáveis apenas pelos participantes exercício designado; Identificação do excercício deve aparecer em', 'Actioned?': 'Acionado?', 'Actions': 'Ações', 'Actions taken as a result of this request.': 'Ações tomadas como resultado desse pedido.', 'Activate Events from Scenario templates for allocation of appropriate Resources (Human, Assets & Facilities).': 'Ativar eventos dos templates de cenário para alocação adequada de recursos (humanos, ativos e equipamentos)', 'Active': 'ativo', 'Active Problems': 'Problemas ativos', 'Activities': 'atividades', 'Activities matching Assessments:': 'Atividades correspondentes a Avaliações:', 'Activities of boys 13-17yrs before disaster': 'Atividades de garotos 13-17 anos antes do desastre', 'Activities of boys 13-17yrs now': 'Atividades de garotos 13-17yrs agora', 'Activities of boys <12yrs before disaster': 'Atividades de garotos <12 anos antes do desastre', 'Activities of boys <12yrs now': 'Atividades de garotos <12 anos agora', 'Activities of children': 'Atividades de crianças', 'Activities of girls 13-17yrs before disaster': 'Atividades de meninas 13-17yrs antes de desastres', 'Activities of girls 13-17yrs now': 'Atividades de meninas 13-17yrs agora', 'Activities of girls <12yrs before disaster': 'Atividades de meninas <12yrs antes de desastres', 'Activities of girls <12yrs now': 'Agora atividades de meninas de menos de 12 anos', 'Activities:': 'Atividades:', 'Activity': 'atividade', 'Activity Added': 'Atividade Incluída', 'Activity Deleted': 'Atividade Apagada', 'Activity Details': 'Detalhes da Atividade', 'Activity Report': 'Relatório de atividades', 'Activity Reports': 'Relatório de Atividades', 'Activity Type': 'Tipo de atividade', 'Activity Updated': 'Atividade Atualizada', 'Activity added': 'Activity added', 'Activity removed': 'Activity removed', 'Activity updated': 'Activity updated', 'Add': 'incluir', 'Add Activity': 'Incluir Atividade', 'Add Activity Report': 'Incluir Relatório de atividade', 'Add Activity Type': 'Incluir tipo de atividade', 'Add Address': 'Incluir Endereço', 'Add Alternative Item': 'Adicionar item alternativo', 'Add Assessment': 'Incluir Avaliação', 'Add Assessment Summary': 'Incluir Avaliação De Resumo', 'Add Asset': 'Incluir ativo', 'Add Asset Log Entry - Change Label': 'Incluir recurso de entrada de entrada - trocar a Etiqueta', 'Add Availability': 'Incluir Disponibilidade', 'Add Baseline': 'Incluir Linha', 'Add Baseline Type': 'Incluir Linha De Tipo', 'Add Bed Type': 'Incluir Tipo De Cama', 'Add Brand': 'Incluir Marca', 'Add Budget': 'Incluir Orçamento', 'Add Bundle': 'Incluir Pacote Configurável', 'Add Camp': 'Incluir acampamento', 'Add Camp Service': 'Incluir acampamento de serviço', 'Add Camp Type': 'Incluir tipo de acampamento', 'Add Catalog': 'Incluir Catálogo', 'Add Catalog Item': 'Incluir Item de Catálogo', 'Add Certificate': 'Incluir certificado', 'Add Certification': 'Adicionar Certificação', 'Add Cholera Treatment Capability Information': 'Incluir Informação sobre capacidade para tratamento de cólera', 'Add Cluster': 'Incluir cluster', 'Add Cluster Subsector': 'Incluir Subsetor de Cluster', 'Add Competency': 'incluir competência', 'Add Competency Rating': 'Incluir Classificação da Competência', 'Add Contact': 'Incluir contato', 'Add Contact Information': 'Incluir informações de contato', 'Add Course': 'Incluir curso', 'Add Course Certificate': 'Incluir Certificado de Curso', 'Add Credential': 'Incluir referência', 'Add Credentials': 'Incluir Referências', 'Add Dead Body Report': 'Incluir Relatório de Cadáver', 'Add Disaster Victims': 'Incluir Vítimas de Desastre', 'Add Distribution.': 'Incluir distribuição.', 'Add Document': 'Add Document', 'Add Donor': 'Incluir doador', 'Add Facility': 'Incluir Recurso', 'Add Feature Class': 'Incluir classe de recurso', 'Add Feature Layer': 'Incluir camada de recurso', 'Add Flood Report': 'Incluir Relatório Enchente', 'Add GPS data': 'Add GPS data', 'Add Group': 'Incluir Grupo', 'Add Group Member': 'Incluir Membro do Grupo', 'Add Hospital': 'Incluir Hospital', 'Add Human Resource': 'Incluir Recurso Humano', 'Add Identification Report': 'Incluir Identificação Relatório', 'Add Identity': 'Incluir Identidade', 'Add Image': 'Incluir Imagem', 'Add Impact': 'Adicionar Impacto', 'Add Impact Type': 'Incluir Tipo De Impacto', 'Add Incident': 'Adicionar Incidente', 'Add Incident Report': 'Incluir relatório de incidente', 'Add Inventory Item': 'Inclúir item de inventário', 'Add Item': 'Incluir item', 'Add Item Category': 'Incluir categoria de item', 'Add Item Pack': 'Incluir pacote de itens', 'Add Item to Catalog': 'Incluir Item no Catálogo', 'Add Item to Commitment': 'Incluir Item no Compromisso', 'Add Item to Inventory': 'Incluir Item de Inventário', 'Add Item to Request': 'Incluir Item para pedido', 'Add Item to Shipment': 'Adicionar Item para Embarque', 'Add Job Role': 'Incluir tarefa Função', 'Add Key': 'Incluir Chave', 'Add Kit': 'Adicionar Kit', 'Add Layer': 'Incluir Camada', 'Add Level 1 Assessment': 'Incluir nível de Avaliação 1', 'Add Level 2 Assessment': 'Incluir nível de Avaliação 2', 'Add Location': 'Incluir Local', 'Add Log Entry': 'Adicionar Entrada de Log', 'Add Map Configuration': 'Incluir Mapa de configuração', 'Add Marker': 'Incluir Marcador', 'Add Member': 'Incluir membro', 'Add Membership': 'Incluir Associação', 'Add Message': 'Incluir Mensagem', 'Add Mission': 'Incluir Missão', 'Add Need': 'Incluir o necessário', 'Add Need Type': 'Adicionar o tipo Necessário', 'Add New': 'Incluir novo', 'Add New Activity': 'Incluir Nova Atividade', 'Add New Address': 'Incluir Novo Endereço', 'Add New Alternative Item': 'Incluir novo Item Alternativo', 'Add New Assessment': 'Adicionar Nova Avaliação', 'Add New Assessment Summary': 'Incluir novo Resumo de Avaliação', 'Add New Asset': 'Incluir Novo Ativo', 'Add New Baseline': 'Incluir nova linha de base', 'Add New Baseline Type': 'Incluir novo tipo de linha de base', 'Add New Brand': 'Adicionar Nova Marca', 'Add New Budget': 'Adicionar Novo Orçamento', 'Add New Bundle': 'Incluir Novo Pacote', 'Add New Camp': 'Incluir novo Campo', 'Add New Camp Service': 'Inlcuir Novo Campo de Serviço', 'Add New Camp Type': 'Incluir Novo Campo de Tipo', 'Add New Catalog': 'Incluir Novo Catálogo', 'Add New Catalog Item': 'Incluir novo Item de catálogo', 'Add New Cluster': 'Adicionar novo grupo', 'Add New Cluster Subsector': 'Adicionar novo subgrupo', 'Add New Commitment Item': 'Incluir novo item de compromisso', 'Add New Contact': 'Incluir novo contato', 'Add New Credential': 'Incluir nova credencial', 'Add New Document': 'Incluir Novo Documento', 'Add New Donor': 'Adicionar novo doador', 'Add New Entry': 'Incluir Nova Entrada', 'Add New Event': 'Adicionar novo evento', 'Add New Facility': 'Incluir novo Recurso', 'Add New Feature Class': 'Incluir nova classe do recurso', 'Add New Feature Layer': 'Adicionar nova camada de características', 'Add New Flood Report': 'Adicionar novo relatório de cheias', 'Add New Group': 'Adicionar novo grupo', 'Add New Home': 'Add New Home', 'Add New Hospital': 'Adicionar novo hospital', 'Add New Human Resource': 'Incluir novos recursos humanos', 'Add New Identity': 'Adicionar nova identidade', 'Add New Image': 'Adicionar nova imagem', 'Add New Impact': 'Adicionar novo impacto', 'Add New Impact Type': 'Incluir novo Tipo De Impacto', 'Add New Incident Report': 'Adicionar novo relatório de incidentes', 'Add New Inventory Item': 'Incluir novo Item De Inventário', 'Add New Item': 'Incluir novo item', 'Add New Item Category': 'Incluir nova categoria de itens', 'Add New Item Pack': 'Incluir novo pacote de itens', 'Add New Item to Kit': 'Incluir novo Item de Kit', 'Add New Key': 'Adicionar Nova Chave', 'Add New Kit': 'Incluir novo Kit', 'Add New Layer': 'Adicionar Nova Camada', 'Add New Level 1 Assessment': 'Incluir novo nível 1 avaliação', 'Add New Level 2 Assessment': 'Incluir novo nível 2 avaliação', 'Add New Location': 'Incluir Novo Local', 'Add New Log Entry': 'Incluir nova entrada de Log', 'Add New Map Configuration': 'Incluir Novo Mapa de Configuração', 'Add New Marker': 'Incluir novo Marcador', 'Add New Member': 'Incluir Novo Membro', 'Add New Membership': 'Incluir novo membro', 'Add New Need': 'Adicionar novas necessidades', 'Add New Need Type': 'Incluir novo Tipo Necessário', 'Add New Note': 'Adicionar NOVA NOTA', 'Add New Office': 'Adicionar novo escritório', 'Add New Organization': 'Incluir nova Organização', 'Add New Patient': 'Add New Patient', 'Add New Person to Commitment': 'Add New Person to Commitment', 'Add New Photo': 'Adicionar Nova Foto', 'Add New Population Statistic': 'Incluir nova População De Estatística', 'Add New Problem': 'Incluir novo Problema', 'Add New Project': 'Incluir novo projeto', 'Add New Projection': 'Adicionar Nova Projecção', 'Add New Rapid Assessment': 'Incluir nova Avaliação Rápida', 'Add New Received Item': 'Incluir novo Item Recebido', 'Add New Record': 'Incluir Novo Registro', 'Add New Relative': 'Add New Relative', 'Add New Report': 'Incluir Novo Relatório', 'Add New Request': 'Incluir novo pedido', 'Add New Request Item': 'Incluir novo Item de Pedido', 'Add New Resource': 'Incluir Novo Recurso', 'Add New River': 'Incluir novo Rio', 'Add New Role': 'INCLUIR NOVA FUNÇÃO', 'Add New Role to User': 'Incluir nova função para o usuário', 'Add New Room': 'Adicionar nova sala', 'Add New Scenario': 'Adicionar Novo cenário', 'Add New Sector': 'Incluir novo Sector', 'Add New Sent Item': 'Incluir novo Item Enviado', 'Add New Setting': 'Adicionar Nova Configuração', 'Add New Shelter': 'Incluir Novo Abrigo', 'Add New Shelter Service': 'Incluir Novo Serviço de Abrigo', 'Add New Shelter Type': 'Incluir Novo Tipo de Abrigo', 'Add New Skill': 'Adicionar nova habilidade', 'Add New Solution': 'Adicionar nova solução', 'Add New Staff': 'Adicionar Nova Equipe', 'Add New Staff Member': 'Incluir novo equipe do membro', 'Add New Staff Type': 'Incluir novo tipo de equipe.', 'Add New Subsector': 'Incluir novo Subsector', 'Add New Survey Answer': 'Incluir nova resposta na pesquisa.', 'Add New Survey Question': 'Incluir nova pergunta na pesquisa.', 'Add New Survey Section': 'Incluir nova seção na pesquisa.', 'Add New Survey Series': 'Incluir nova série na pesquisa.', 'Add New Survey Template': 'Incluir novo Modelo De Pesquisa', 'Add New Task': 'Incluir Nova Tarefa', 'Add New Team': 'Adicionar nova equipe', 'Add New Theme': 'Incluir novo tema', 'Add New Ticket': 'Incluir nova permissão', 'Add New Track': 'Adicionar Nova Pista', 'Add New User': 'Incluir Novo Usuário', 'Add New User to Role': 'Adicionar Novo usuário para Função', 'Add New Vehicle': 'Add New Vehicle', 'Add New Volunteer': 'Incluir novo Voluntário', 'Add New Warehouse': 'Adicionar novo armazém', 'Add Note': 'Incluir nota', 'Add Office': 'Adicionar Office', 'Add Organization': 'Incluir Organização', 'Add Peer': 'Incluír Par', 'Add Person': 'incluir pessoa', 'Add Person to Commitment': 'Add Person to Commitment', 'Add Personal Effects': 'Incluir efeitos pessoais', 'Add Photo': 'Incluir Foto', 'Add Population Statistic': 'Incluir População Estatística', 'Add Position': 'Adicionar Posição', 'Add Problem': 'Adicionar Problema', 'Add Project': 'Adicionar Projeto', 'Add Projection': 'Adicionar Projeção', 'Add Question': 'Adicionar Pergunta', 'Add Rapid Assessment': 'Adicionar Avaliação Rápida', 'Add Record': 'Incluir Registro', 'Add Reference Document': 'Incluir documento de referência', 'Add Report': 'Incluir Relatório', 'Add Request': 'Incluir Pedido', 'Add Resource': 'Incluir Recurso', 'Add River': 'Incluir Rio', 'Add Role': 'Incluir Função', 'Add Room': 'Incluir Sala', 'Add Section': 'Incluir Secção', 'Add Sector': 'Incluir Sector', 'Add Service Profile': 'Incluir Perfil de Serviço', 'Add Setting': 'Adicionar Definição', 'Add Shelter': 'Incluir Abrigo', 'Add Shelter Service': 'Incluir Serviço de Abrigo', 'Add Shelter Type': 'Incluir Tipo de Abrigo', 'Add Skill': 'Incluir Habilidade', 'Add Skill Equivalence': 'Incluir equivalência de habilidades', 'Add Skill Provision': 'Incluir provisão de habilidades', 'Add Skill Type': 'Incluir Tipo de Habilidade', 'Add Skill to Request': 'Add Skill to Request', 'Add Solution': 'Incluir Solução', 'Add Staff': 'Incluir equipe', 'Add Staff Member': 'Adicionar membro da equipe', 'Add Staff Type': 'Incluir tipo de equipe', 'Add Status': 'Incluir Status', 'Add Subscription': 'Incluir Assinatura', 'Add Subsector': 'Incluir Subsetor', 'Add Survey Answer': 'Incluir resposta de pesquisa', 'Add Survey Question': 'Adicionar pergunta da pesquisa', 'Add Survey Section': 'Incluir seção da pesquisa', 'Add Survey Series': 'Incluir série da pesquisa', 'Add Survey Template': 'Incluir Modelo De Pesquisa', 'Add Task': 'Incluir Tarefa', 'Add Team': 'Incluir equipe', 'Add Theme': 'Incluir Tema', 'Add Ticket': 'Adicionar Bilhete', 'Add Training': 'Incluir Treinamento', 'Add Unit': 'Incluir Unidade', 'Add User': 'Incluir Usuário', 'Add Vehicle': 'Add Vehicle', 'Add Vehicle Detail': 'Add Vehicle Detail', 'Add Vehicle Details': 'Add Vehicle Details', 'Add Volunteer': 'Incluir Voluntário', 'Add Volunteer Availability': 'Incluir disponibilidade do voluntário', 'Add Warehouse': 'Adicionar Data Warehouse', 'Add a Person': 'Incluir uma pessoa', 'Add a Reference Document such as a file, URL or contact person to verify this data. If you do not enter a Reference Document, your email will be displayed instead.': 'Adicionar um documento de referência como um arquivo, URL ou contacto pessoal para verificar esses dados. Se você não inserir um documento de referência, seu e-mail será exibido no lugar.', 'Add a Volunteer': 'Incluir um Voluntário', 'Add a new certificate to the catalog.': 'Incluir um novo certificado no catálogo.', 'Add a new competency rating to the catalog.': 'Adicionar uma classificação nova competência para o catálogo.', 'Add a new course to the catalog.': 'Adicionar um novo rumo para o catálogo.', 'Add a new job role to the catalog.': 'Incluir uma função nova tarefa para o catálogo.', 'Add a new skill provision to the catalog.': 'Incluir uma disposição nova habilidade para o catálogo.', 'Add a new skill to the catalog.': 'Incluir uma nova habilidade para o catálogo.', 'Add a new skill type to the catalog.': 'Incluir um tipo novo de hailidade para o catálogo.', 'Add new Group': 'Adicionar novo grupo', 'Add new Individual': 'Incluir novo indivíduo', 'Add new Patient': 'Add new Patient', 'Add new project.': 'Adicionar novo projeto.', 'Add new staff role.': 'Incluir função de novos funcionários.', 'Add staff members': 'Incluir membros da equipe', 'Add to Bundle': 'Incluir no Pacote Configurável', 'Add to budget': 'Incluir no orçamento', 'Add volunteers': 'Incluir voluntários', 'Add/Edit/Remove Layers': 'Incluir/editar/remover camadas', 'Additional Beds / 24hrs': 'Camas adicionais / 24 horas', 'Address': 'endereços', 'Address Details': 'Detalhes do Endereço', 'Address Type': 'Tipo de Endereço', 'Address added': 'Endereço incluído', 'Address deleted': 'Endereço excluído', 'Address updated': 'Endereço actualizado', 'Addresses': 'Endereços', 'Adequate': 'adequar', 'Adequate food and water available': 'Comida e água adequado disponível', 'Admin Email': 'email do administrador', 'Admin Name': 'nome do administrador', 'Admin Tel': 'Telefone do administrador', 'Administration': 'administração', 'Admissions/24hrs': 'admissões/24 horas', 'Adolescent (12-20)': 'adolescente (12-20)', 'Adolescent participating in coping activities': 'Adolescente participando em actividades de superação', 'Adult (21-50)': 'Adulto (21-50)', 'Adult ICU': 'UTI para adultos', 'Adult Psychiatric': 'Psiquiátrico para adultos', 'Adult female': 'Mulher adulta', 'Adult male': 'Homem adulto', 'Adults in prisons': 'Adultos em prisões', 'Advanced:': 'Avançado:', 'Advisory': 'Aconselhamento', 'After clicking on the button, a set of paired items will be shown one by one. Please select the one solution from each pair that you prefer over the other.': 'Depois de pressionar o botão será mostrado um conjunto de dois elementos, um de cada vez. Por favor selecione a uma solução de cada par de sua preferência sobre o outro.', 'Age Group': 'Grupo etário', 'Age group': 'Grupo etário', 'Age group does not match actual age.': 'Grupo etário não corresponde à idade real.', 'Aggravating factors': 'Fatores agravantes', 'Agriculture': 'Agricultura', 'Air Transport Service': 'Serviço de Transporte Aéreo', 'Air tajin': 'Tajin AR', 'Aircraft Crash': 'Despenho de Avião', 'Aircraft Hijacking': 'Sequestro de Avião', 'Airport Closure': 'Encerramento de Aeroporto', 'Airspace Closure': 'Encerramento de Espaço Aéreo', 'Alcohol': 'álcool', 'Alert': 'Alertar', 'All': 'Tudo', 'All Inbound & Outbound Messages are stored here': 'Todas as mensagens enviadas e recebidas são armazenados aqui', 'All Resources': 'Todos os recursos', 'All data provided by the Sahana Software Foundation from this site is licenced under a Creative Commons Attribution licence. However, not all data originates here. Please consult the source field of each entry.': 'Todos os dados fornecidos pelos Sahana Software Foundation a partir deste site é licenciado sob uma Licença Atribuição Comuns criativos. No entanto, nem todos os dados se origina aqui. Por favor consulte o campo de origem de cada entrada.', 'Allowed to push': 'Permissão para pressionar', 'Allows a Budget to be drawn up': 'Permite que um orçamento seja estabelecido', 'Allows authorized users to control which layers are available to the situation map.': 'Permite usuários autorizados a controlar quais camadas estão disponíveis no mapa de situação.', 'Alternative Item': 'Item Alternativo', 'Alternative Item Details': 'Detalhes do Item alternativo', 'Alternative Item added': 'Item alternativo incluído', 'Alternative Item deleted': 'Item alternativo excluído', 'Alternative Item updated': 'Item Alternativo atualizado', 'Alternative Items': 'Itens alternativos', 'Alternative places for studying': 'Locais alternativos para estudo', 'Ambulance Service': 'Serviço de Ambulância', 'An asset must be assigned to a person, site OR location.': 'Um ATIVO deve ser designado a uma pessoa, local ou site.', 'An intake system, a warehouse management system, commodity tracking, supply chain management, procurement and other asset and resource management capabilities.': 'Um sistema de admissão, um sistema de gestão de depósitos, tracking and commodity, gestão da cadeia de fornecimentos, aquisições de ativos e outros e os recursos de gerenciamento de recurso.', 'An item which can be used in place of another item': 'Um item que pode ser utilizado no lugar de outro item', 'Analysis of Completed Surveys': 'Análise das Pesquisas Concluídas', 'Analysis of assessments': 'Analysis of assessments', 'Animal Die Off': 'Morte Animal', 'Animal Feed': 'Alimentação Animal', 'Answer Choices (One Per Line)': 'Resposta opções (Um por linha)', 'Anthropolgy': 'Anthropolgy', 'Antibiotics available': 'Antibióticos disponíveis', 'Antibiotics needed per 24h': 'Antibióticos necessário por H', 'Apparent Age': 'Idade aparente', 'Apparent Gender': 'Género aparente', 'Application Deadline': 'Prazo Final da aplicação', 'Applications': 'Requisições', 'Approve': 'Aprovar', 'Approved': 'aprovado', 'Approver': 'Aprovador', 'Arabic': 'Arabic', 'Arctic Outflow': 'Árctico Exfluxo', 'Area': 'Área', 'Areas inspected': 'Inspeccionados áreas', 'As of yet, no sections have been added to this template.': 'As of yet, no sections have been added to this template.', 'Assessment': 'Avaliação', 'Assessment Details': 'Detalhes da Avaliação', 'Assessment Reported': 'Avaliação Relatada', 'Assessment Summaries': 'Sumário de Avaliações', 'Assessment Summary Details': 'Detalhes do sumário de avaliação', 'Assessment Summary added': 'Anexado sumário de avaliações', 'Assessment Summary deleted': 'Avaliação de resumo apagado', 'Assessment Summary updated': 'Sumário de avaliação atualizado', 'Assessment added': 'Avaliação incluída', 'Assessment admin level': 'Avaliação de nível administrativo', 'Assessment deleted': 'Avaliação excluída', 'Assessment timeline': 'sequência temporal de avaliação', 'Assessment updated': 'Avaliação atualizada', 'Assessments': 'avaliações', 'Assessments Needs vs. Activities': 'Necessidades de Avaliações vs. Atividades', 'Assessments and Activities': 'Avaliações e Atividades', 'Assessments:': 'Avaliações', 'Assessor': 'Avaliador', 'Asset': 'Recurso', 'Asset Assigned': 'Ativo Designado', 'Asset Assignment Details': 'Detalhes da Designação de Recursos', 'Asset Assignment deleted': 'Designação De ativo excluído', 'Asset Assignment updated': 'Atribuição de Ativo atualizada', 'Asset Assignments': 'Designações de Ativo', 'Asset Details': 'Detalhes do Ativo', 'Asset Log': 'Log de ATIVOS', 'Asset Log Details': 'Detalhes do Log de ativos', 'Asset Log Empty': 'Log de Ativos vazio', 'Asset Log Entry Added - Change Label': 'Adicionada uma entrada no Log de ativos -Alterar Etiqueta', 'Asset Log Entry deleted': 'Apagada uma entrada no Log de ativos', 'Asset Log Entry updated': 'Atualizada uma entrada no Log de Ativos', 'Asset Management': 'gerenciamento de recursos', 'Asset Number': 'número do recurso', 'Asset added': 'Ativo Incluído', 'Asset deleted': 'ativo excluído', 'Asset removed': 'Ativo Removido', 'Asset updated': 'recurso atualizado', 'Assets': 'recursos', 'Assets are resources which are not consumable but are expected back, so they need tracking.': 'Os ativos são recursos que não são consumíveis e serão devolvidos, portanto precisam de rastreamento.', 'Assign': 'Designar', 'Assign Asset': 'designar recurso', 'Assign Group': 'Designar Grupo', 'Assign Staff': 'Atribuir Equipe', 'Assign to Org.': 'Designar para Org.', 'Assign to Organisation': 'Atribuir para Organização', 'Assign to Organization': 'Atribuir para Organização', 'Assign to Person': 'Atribuir uma Pessoa', 'Assign to Site': 'Atribuir um Site', 'Assigned': 'Designado', 'Assigned By': 'Designado por', 'Assigned To': 'Designado Para', 'Assigned to': 'Designado para', 'Assigned to Organisation': 'Designado para Organização', 'Assigned to Person': 'Designado para a Pessoa', 'Assigned to Site': 'Designado para o Site', 'Assignments': 'Designações', 'At/Visited Location (not virtual)': 'Em/Visitou Local (não virtual)', 'Attend to information sources as described in <instruction>': 'Participar de fontes de informação, conforme descrito em<instruction>', 'Attribution': 'Atribuição', "Authenticate system's Twitter account": 'Sistema de Autenticação para conta de Twitter', 'Author': 'autor', 'Availability': 'Disponibilidade', 'Available Alternative Inventories': 'Alternativas de Inventário disponíveis', 'Available Alternative Inventory Items': 'Itens alternativos de Inventário disponíveis', 'Available Beds': 'camas disponíveis', 'Available Forms': 'Available Forms', 'Available Inventories': 'Inventários disponíveis', 'Available Inventory Items': 'Itens de inventário disponíveis', 'Available Messages': 'Mensagens disponíveis', 'Available Records': 'Registros disponíveis', 'Available databases and tables': 'Banco de Dados e Tabelas disponíveis', 'Available for Location': 'Disponível para locação', 'Available from': 'disponível de', 'Available in Viewer?': 'Disponível no visualizador?', 'Available until': 'Disponível até', 'Avalanche': 'Avalanche', 'Avoid the subject event as per the <instruction>': 'Evitar o assunto do evento de acordo com a', 'Background Color': 'Background Color', 'Background Color': 'Cor de Plano de Fundo', 'Background Color for Text blocks': 'Cor de segundo plano para blocos de texto', 'Bahai': 'Bahai', 'Baldness': 'Calvície', 'Banana': 'Banana', 'Bank/micro finance': 'banco/micro finanças', 'Barricades are needed': 'Barricadas são necessárias', 'Base Layer?': 'Camada De Base?', 'Base Location': 'Local da Base', 'Base Site Set': 'Conjunto de Site básico', 'Baseline Data': 'Dados básicos', 'Baseline Number of Beds': 'Numero de camadas base de camas', 'Baseline Type': 'Tipo de Linha Base', 'Baseline Type Details': 'Detalhes de Tipo de Linha Base', 'Baseline Type added': 'Tipo de Linha Base adicionado', 'Baseline Type deleted': 'Tipo de Linha Base removido', 'Baseline Type updated': 'Tipo de Linha Base actualizado', 'Baseline Types': 'Tipos de Linha Base', 'Baseline added': 'Camada Base incluída', 'Baseline deleted': 'Camada Base Excluída', 'Baseline number of beds of that type in this unit.': 'Numero de camadas base de camas desse tipo nesta unidade.', 'Baseline updated': 'Linha Base actulizada', 'Baselines': 'Camadas Base', 'Baselines Details': 'Detalhes de Camadas Base', 'Basic Assessment': 'Avaliação Básica', 'Basic Assessment Reported': 'Avaliação Básica Relatada', 'Basic Details': 'Detalhes Básicos', 'Basic reports on the Shelter and drill-down by region': 'Relatórios básicos sobre o Abrigo e abertura por região', 'Baud': 'Transmissão', 'Baud rate to use for your modem - The default is safe for most cases': 'Taxa de transmissão para ser usada pelo seu modem - O padrão é seguro para a maioria dos casos', 'Beam': 'feixe', 'Bed Capacity': 'Capacidade de leitos', 'Bed Capacity per Unit': 'Capacidade cama por Unidade', 'Bed Type': 'Tipo de cama', 'Bed type already registered': 'Tipo de cama já registrado', 'Below ground level': 'Abaixo do nível do solo', 'Beneficiary Type': 'Tipo de beneficiário', "Bing Layers cannot be displayed if there isn't a valid API Key": "Bing Layers cannot be displayed if there isn't a valid API Key", 'Biological Hazard': 'Risco Biológico', 'Biscuits': 'Biscoitos', 'Blizzard': 'Nevasca', 'Blood Type (AB0)': 'Tipo sanguíneo (AB0)', 'Blowing Snow': 'Soprando neve', 'Boat': 'Barco', 'Bodies': 'Bodies', 'Bodies found': 'Corpos encontrados', 'Bodies recovered': 'corpos recuperados', 'Body': 'corpo', 'Body Recovery': 'Body Recovery', 'Body Recovery Request': 'Pedido de recuperação de corpos', 'Body Recovery Requests': 'Pedidos de recuperação de corpos', 'Bomb': 'Bomba', 'Bomb Explosion': 'Explosão de bomba', 'Bomb Threat': 'Ameaça de bomba', 'Border Color for Text blocks': 'Cor da borda para blocos de texto', 'Bounding Box Insets': 'Delimitadora Inserções Caixa', 'Bounding Box Size': 'CAIXA delimitadora Tamanho', 'Brand': 'Marca', 'Brand Details': 'Detalhes da Marca', 'Brand added': 'Marca incluída', 'Brand deleted': 'Marca excluída', 'Brand updated': 'marca atualizada', 'Brands': 'marcas', 'Bricks': 'Tijolos', 'Bridge Closed': 'PONTE FECHADA', 'Bucket': 'Balde', 'Buddhist': 'Budista', 'Budget': 'Orçamento', 'Budget Details': 'Detalhes de Orçamento', 'Budget Updated': 'Orçamento Atualizado', 'Budget added': 'Orçamento incluído', 'Budget deleted': 'Orçamento excluído', 'Budget updated': 'Orçamento atualizado', 'Budgeting Module': 'Módulo de Orçamento', 'Budgets': 'Orçamentos', 'Buffer': 'buffer', 'Bug': 'erro', 'Building Assessments': 'Avaliações de construção', 'Building Collapsed': 'Construção Fechada', 'Building Name': 'Nome do edifício', 'Building Safety Assessments': 'Regras de Segurança do Edifício', 'Building Short Name/Business Name': 'Nome curto/Nome completo do Edifício', 'Building or storey leaning': 'Edifício ou andar em inclinação', 'Built using the Template agreed by a group of NGOs working together as the': 'Construído de acordo com o formulário acordado por um grupo de ONGs', 'Bulk Uploader': 'Carregador em massa', 'Bundle': 'Pacote', 'Bundle Contents': 'Conteúdo do Pacote', 'Bundle Details': 'Detalhes do Pacote', 'Bundle Updated': 'Pacote configurável ATUALIZADO', 'Bundle added': 'Pacote incluído', 'Bundle deleted': 'Pacote Excluído', 'Bundle updated': 'Pacote atualizado', 'Bundles': 'Pacotes', 'Burn': 'Gravar', 'Burn ICU': 'Queimar ICU', 'Burned/charred': 'Queimados/carbonizados', 'By Facility': 'Por Facilidade', 'By Inventory': 'Por Inventário', 'By Person': 'Por pessoa', 'By Site': 'Por Site', 'CBA Women': 'CBA Mulheres', 'CLOSED': 'CLOSED', 'CN': 'CN', 'CSS file %s not writable - unable to apply theme!': 'Arquivo CSS %s não é gravável - Impossível aplicar o tema!', 'Calculate': 'calcular', 'Camp': 'Acampamento', 'Camp Coordination/Management': 'Campo Coordenação/gestão', 'Camp Details': 'Detalhes do Alojamento', 'Camp Service': 'Serviço de Alojamento', 'Camp Service Details': 'Detalhe do Serviço de Campo', 'Camp Service added': 'Serviço de Alojamento incluído', 'Camp Service deleted': 'Serviço de Alojamento excluído', 'Camp Service updated': 'Serviço de campo atualizado', 'Camp Services': 'Serviço de campo', 'Camp Type': 'Tipo de Campo', 'Camp Type Details': 'Detalhes do tipo de campo', 'Camp Type added': 'Tipo de Campo incluso.', 'Camp Type deleted': 'Tipo de campo excluído.', 'Camp Type updated': 'Tipo De acampamento atualizado', 'Camp Types': 'TIPOS DE acampamento', 'Camp Types and Services': 'Tipos e serviços de acampamentos', 'Camp added': 'Alojamento incluído', 'Camp deleted': 'Alojamento excluído', 'Camp updated': 'Acampamento atualizado', 'Camps': 'Alojamentos', 'Can only disable 1 record at a time!': 'Pode desativar apenas 1 registro por vez!', 'Can only enable 1 record at a time!': 'Can only enable 1 record at a time!', "Can't import tweepy": 'Não pode importar tweepy', 'Cancel': 'Cancelar', 'Cancel Log Entry': 'Cancelar Registro De Entrada', 'Cancel Shipment': 'Cancelar Embarque', 'Canceled': 'cancelado', 'Candidate Matches for Body %s': 'Candidato Corresponde ao Corpo %s', 'Canned Fish': 'Conservas de Peixe', 'Cannot be empty': 'Não pode ser vazio', 'Cannot disable your own account!': 'Voce não pode desativar sua própria conta!', 'Capacity (Max Persons)': 'Capacidade (Máximo De pessoas)', 'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)': 'CAPTURA informações sobre grupos Desastre Vítima (Turistas, passageiros, Famílias, etc. ).', 'Capture Information on each disaster victim': 'Informações de captura em cada vítima Desastre', 'Capturing organizational information of a relief organization and all the projects they have in the region': 'Capturando informações organizacionais de uma organização de ajuda e todos os projetos têm na região', 'Capturing the projects each organization is providing and where': 'Capturando os projetos que cada organização está fornecendo e onde', 'Cardiology': 'Cardiologia', 'Cassava': 'Mandioca', 'Casual Labor': 'Trabalho Casual', 'Casualties': 'Acidentes', 'Catalog': 'catálogo', 'Catalog Details': 'Detalhes do Catálogo', 'Catalog Item': 'Item do catálogo de', 'Catalog Item added': 'Item incluído no catálogo', 'Catalog Item deleted': 'Catálogo de Item excluído', 'Catalog Item updated': 'Item do catálogo de atualização', 'Catalog Items': 'Itens do Catálogo', 'Catalog added': 'Catálogo Incluído', 'Catalog deleted': 'Catálogo excluído', 'Catalog updated': 'Catálogo Atualizado', 'Catalogs': 'Catálogos', 'Categories': 'Categorias', 'Category': 'category', "Caution: doesn't respect the framework rules!": 'Cuidado: não respeitar as regras de enquadramento!', 'Ceilings, light fixtures': 'Tetos, luminarias', 'Cell Phone': 'Cell Phone', 'Central point to record details on People': 'Ponto Central para registrar detalhes sobre pessoas', 'Certificate': 'Certificate', 'Certificate Catalog': 'Catálogo de Certificados', 'Certificate Details': 'Detalhes do Certificado', 'Certificate Status': 'Status do Certificado', 'Certificate added': 'Certificado incluído', 'Certificate deleted': 'Certificado Removido', 'Certificate updated': 'Certificado Actualizado', 'Certificates': 'Certificados', 'Certification': 'Certificação', 'Certification Details': 'Detalhes da Certificação', 'Certification added': 'Certificação incluída', 'Certification deleted': 'Certificação excluída', 'Certification updated': 'Certificação atualizada', 'Certifications': 'Certificações', 'Certifying Organization': 'Certificação da Organização', 'Change Password': '<PASSWORD>ar <PASSWORD>ha', 'Check': 'Verifique', 'Check Request': 'Verificar Pedido', 'Check for errors in the URL, maybe the address was mistyped.': 'Verifique se há erros na URL, talvez o endereço foi digitado incorretamente.', 'Check if the URL is pointing to a directory instead of a webpage.': 'Verifique se a URL está apontando para um diretório em vez de uma página da Web.', 'Check outbox for the message status': 'Outbox para verificar o status da mensagem', 'Check to delete': 'Verificar para Excluir', 'Check-in': 'Registrar Entrada', 'Check-in at Facility': 'Check-in at Facility', 'Check-out': 'Registrar Saída', 'Checked': 'verificado', 'Checklist': 'lista de verificação', 'Checklist created': 'Lista de verificação criada', 'Checklist deleted': 'Lista de verificação excluída', 'Checklist of Operations': 'Lista de Verificação das Operações', 'Checklist updated': 'Lista de verificação atualizado', 'Chemical Hazard': 'Risco Químico', 'Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack': 'Ameaça ou ataque Químico, Biológico, Radiológico, Nuclear ou de alto concentração Explosiva', 'Chicken': 'Frango', 'Child': 'Criança', 'Child (2-11)': 'Criança (2-11)', 'Child (< 18 yrs)': 'Criança (< 18 anos)', 'Child Abduction Emergency': 'Emergência de Rapto De Criança', 'Child headed households (<18 yrs)': 'Famílias chefiadas por Filho (<18 anos)', 'Children (2-5 years)': 'Crianças (2 a 5 anos)', 'Children (5-15 years)': 'Crianças (5 a 15 anos)', 'Children (< 2 years)': 'Crianças (< 2 anos)', 'Children in adult prisons': 'Crianças nas prisões para adultos', 'Children in boarding schools': 'Crianças em internatos', 'Children in homes for disabled children': 'Crianças em lares para crianças deficientes', 'Children in juvenile detention': 'Crianças em detenção juvenil', 'Children in orphanages': 'Crianças nos orfanatos', 'Children living on their own (without adults)': 'Crianças vivendo por conta própria (sem adultos)', 'Children not enrolled in new school': 'Crianças não matriculadas em Nova Escola', 'Children orphaned by the disaster': 'Crianças órfãs pela catástrofe', 'Children separated from their parents/caregivers': 'Crianças SEPARADAS de seus pais/responsáveis', 'Children that have been sent to safe places': 'Crianças que foram enviadas para locais seguros', 'Children who have disappeared since the disaster': 'Crianças que desapareceram desde o desastre', 'Chinese (Simplified)': 'Chinese (Simplified)', 'Chinese (Taiwan)': 'Chinês (Taiwan)', 'Cholera Treatment': 'Tratamento da cólera', 'Cholera Treatment Capability': 'Capacidade de Tratamento da Cólera', 'Cholera Treatment Center': 'Centro de Tratamento de Cólera', 'Cholera-Treatment-Center': 'Centro de tratamento de cólera', 'Choose a new posting based on the new evaluation and team judgement. Severe conditions affecting the whole building are grounds for an UNSAFE posting. Localised Severe and overall Moderate conditions may require a RESTRICTED USE. Place INSPECTED placard at main entrance. Post all other placards at every significant entrance.': 'Escolha uma nova alocação baseada na nova avaliação e julgamento do time. Condições severas que afetem o prédio inteiro são base para uma colocação INSEGURA. Grave localizada e no geral condições moderadas podem exigir um USO RESTRITO. Local INSPECCIONADO cartaz na entrada principal. Coloque todos os outros cartazes em cada entrada importante.', 'Christian': 'Cristão', 'Church': 'Igreja', 'Circumstances of disappearance, other victims/witnesses who last saw the missing person alive.': 'Circunstâncias do desaparecimento, outras vítimas/testemunhas quais viram pela última vez a pessoa desaparecida viva.', 'City': 'CIDADE', 'Civil Emergency': 'Emergência Civil', 'Cladding, glazing': 'Revestimentos, vidros', 'Click on the link': 'Clique no link', 'Client IP': 'Client IP', 'Climate': 'Climate', 'Clinical Laboratory': 'Laboratório clínico', 'Clinical Operations': 'operações clinicas', 'Clinical Status': 'estado clínico', 'Close map': 'Close map', 'Closed': 'fechado', 'Clothing': 'vestuário', 'Cluster': 'agrupamento', 'Cluster Details': 'Detalhes do Grupo', 'Cluster Distance': 'Distância entre Grupos', 'Cluster Subsector': 'Subsector de Grupos', 'Cluster Subsector Details': 'Detalhes do sub-setor do cluster', 'Cluster Subsector added': 'Subsector de Grupos incluído', 'Cluster Subsector deleted': 'Subsector de Grupos removido', 'Cluster Subsector updated': 'Sub-setores do cluster atualizado', 'Cluster Subsectors': 'Sub-setores do cluster', 'Cluster Threshold': 'Limite do Cluster', 'Cluster added': 'adicionar agrupamento', 'Cluster deleted': 'Grupo removido', 'Cluster updated': 'Cluster atualizado', 'Cluster(s)': 'Grupo(s)', 'Clusters': 'clusters', 'Code': 'Código', 'Cold Wave': 'onda fria', 'Collapse, partial collapse, off foundation': 'Reduzir, reduzir parciais, off foundation', 'Collective center': 'Centro coletivo', 'Color for Underline of Subheadings': 'Cor para Sublinhar de Subposições', 'Color of Buttons when hovering': 'Cor dos botões quando erguidos', 'Color of bottom of Buttons when not pressed': 'Cor da parte inferior dos botões quando não for pressionado', 'Color of bottom of Buttons when pressed': 'Cor da parte de baixo dos botões quando pressionados', 'Color of dropdown menus': 'Cor de menus DROP-', 'Color of selected Input fields': 'Cor dos campos de entrada selecionados', 'Color of selected menu items': 'cor dos ítens selecionados do menu', 'Column Choices (One Per Line': 'Coluna de opções (uma por linha)', 'Columns, pilasters, corbels': 'Colunas, pilastras , cavaletes', 'Combined Method': 'Método combinado', 'Come back later.': 'Volte mais tarde.', 'Come back later. Everyone visiting this site is probably experiencing the same problem as you.': 'Volte mais tarde. Todos que visitam este site esta, provavelmente, enfrentando o mesmo problema que você.', 'Comments': 'Comentários', 'Commercial/Offices': 'Comercial/Escritórios', 'Commit': 'Consolidar', 'Commit Date': 'Commit Data', 'Commit from %s': 'Consolidação de s%', 'Commit. Status': 'Commit. Status', 'Commiting a changed spreadsheet to the database': 'Consolidando uma planilha alterada no banco de dados', 'Commitment': 'Comprometimento', 'Commitment Added': 'Compromisso Incluído', 'Commitment Canceled': 'Compromisso cancelado', 'Commitment Details': 'Detalhes do compromisso', 'Commitment Item': 'Item do compromisso', 'Commitment Item Details': 'Detalhes do item de compromisso', 'Commitment Item added': 'Item de compromisso incluído', 'Commitment Item deleted': 'Item do compromisso excluído', 'Commitment Item updated': 'Compromisso Item atualizado', 'Commitment Items': 'Itens compromisso', 'Commitment Status': 'Empenhamento Status', 'Commitment Updated': 'Compromisso Atualizado', 'Commitments': 'Compromissos', 'Committed': 'Comprometido', 'Committed By': 'Cometido por', 'Committed People': 'Committed People', 'Committed Person Details': 'Committed Person Details', 'Committed Person updated': 'Committed Person updated', 'Committing Inventory': 'Confirmando Inventário', 'Committing Organization': 'Committing Organization', 'Committing Person': 'Committing Person', 'Communication problems': 'Problemas de Comunicação', 'Community Centre': 'Comunidade Centro', 'Community Health Center': 'Centro Comunitário de Saúde', 'Community Member': 'Membro da Comunidade', 'Competencies': 'Competências', 'Competency': 'Competência', 'Competency Details': 'Competência Detalhes', 'Competency Rating Catalog': 'Catálogo de Classificação de Competências', 'Competency Rating Details': 'Detalhes da classificação de competências', 'Competency Rating added': 'Classificação de Habilidades incluída', 'Competency Rating deleted': 'Classificação de competência excluída', 'Competency Rating updated': 'Atualização da classificação de competências', 'Competency Ratings': 'Classificação de competências', 'Competency added': 'Competência incluída', 'Competency deleted': 'Competência excluído', 'Competency updated': 'Competência atualizada', 'Complete': 'Concluir', 'Completed': 'Concluído', 'Complexion': 'Compleição', 'Compose': 'Redigir', 'Compromised': 'Comprometida', 'Concrete frame': 'Quadro concreto', 'Concrete shear wall': 'Muro de corteconcreto', 'Condition': 'Condição', 'Configurations': 'Configurações', 'Configure Run-time Settings': 'Configurar as configurações de tempo de execução', 'Confirm Shipment Received': 'Confirmar Remessa Recebida', 'Confirmed': 'Confirmado', 'Confirming Organization': 'Confirmando Organização', 'Conflict Details': 'Detalhes Do conflito', 'Conflict Resolution': 'Resolução de Conflito', 'Consignment Note': 'NOTA REMESSA', 'Constraints Only': 'Somente restrições', 'Consumable': 'Consumível', 'Contact': 'contato', 'Contact Data': 'Dados contato', 'Contact Details': 'Detalhes do contato', 'Contact Info': 'Informações de Contato', 'Contact Information': 'Informações de Contato', 'Contact Information Added': 'Informação de contato incluída', 'Contact Information Deleted': 'Informação de contato excluída', 'Contact Information Updated': 'Informações de contato atualizadas', 'Contact Method': 'Método de Contato', 'Contact Name': 'Nome do contato', 'Contact Person': 'Pessoa de Contato', 'Contact Phone': 'Telefone para Contato', 'Contact details': 'Detalhes do contato', 'Contact information added': 'Informações de contato incluídas', 'Contact information deleted': 'Informações de contato excluídas', 'Contact information updated': 'Informações de contato atualizadas', 'Contact person(s) in case of news or further questions (if different from reporting person). Include telephone number, address and email as available.': 'Pessoa(s) a contactar em caso de notícias ou mais perguntas (se for diferente da pessoa que reportou). Incluir número de telefone, endereço e correio electrónico se disponível.', 'Contact us': 'F<NAME>', 'Contacts': 'contatos', 'Contents': 'Conteúdo', 'Contributor': 'Contribuidor', 'Conversion Tool': 'Ferramenta de Conversão', 'Cooking NFIs': 'Cozinhando NFIs', 'Cooking Oil': 'Cozinhando Óleo', 'Coordinate Conversion': 'COORDENAR a Conversão', 'Coping Activities': 'Atividades de lida', 'Copy': 'copiar', 'Corn': 'Milho', 'Cost Type': 'Tipo de custo', 'Cost per Megabyte': 'Custo por megabyte', 'Cost per Minute': 'Custo por Minuto', 'Country': 'País', 'Country of Residence': 'País de Residência', 'County': 'Município', 'Course': 'Curso', 'Course Catalog': 'Catálogo de Cursos', 'Course Certificate Details': 'Detalhes do Certificado do Curso', 'Course Certificate added': 'Certificado do Curso adicionado', 'Course Certificate deleted': 'Certificado do Curso excluído', 'Course Certificate updated': 'Certificado do Curso atualizado', 'Course Certificates': 'Certificados de Curso', 'Course Certificates': 'Certificados de Curso', 'Course Details': 'Detalhes do curso', 'Course added': 'Curso incluído', 'Course deleted': 'Curso excluído', 'Course updated': 'Curso atualizado', 'Courses': 'Cursos', 'Create & manage Distribution groups to receive Alerts': 'Criar & GERENCIAR grupos de distribuição de receber alertas', 'Create Checklist': 'Criar Lista de Verificação', 'Create Group Entry': 'Criar Grupo De Entrada', 'Create Impact Assessment': 'Criar Avaliação de Impacto', 'Create Mobile Impact Assessment': 'Criar Avaliação de Impacto Movel', 'Create New Asset': 'Criar Novo Recurso', 'Create New Catalog Item': 'Criar Novo Item de Catálogo', 'Create New Event': 'Criar Novo Evento', 'Create New Item Category': 'Criar Nova Categoria de Item', 'Create New Request': 'Criar Novo Pedido', 'Create New Scenario': 'Criar Novo cenário', 'Create New Vehicle': 'Create New Vehicle', 'Create Rapid Assessment': 'Criar Avaliação Rápida', 'Create Request': 'Criar solicitação', 'Create Task': 'Criar Tarefa', 'Create a group entry in the registry.': 'Criar uma entrada de grupo no registro.', 'Create new Office': 'Criar novo escritório', 'Create new Organization': 'Criar nova organização', 'Create, enter, and manage surveys.': 'Criar, digitar e gerenciar pesquisas.', 'Creation of Surveys': 'Criação de Pesquisas', 'Creation of assessments': 'Creation of assessments', 'Credential Details': 'Detalhes da Credencial', 'Credential added': 'Credencial incluída', 'Credential deleted': 'Credencial Excluída', 'Credential updated': 'Credencial ATUALIZADA', 'Credentialling Organization': 'Organização acreditada', 'Credentials': 'credenciais', 'Credit Card': 'Cartão de crédito', 'Crime': 'crime', 'Criteria': 'Critério', 'Currency': 'moeda', 'Current Entries': 'Entradas Atuais', 'Current Group Members': 'Membros do Grupo atual', 'Current Identities': 'Identidades atuais', 'Current Location': 'Posição Atual', 'Current Location Country': 'Current Location Country', 'Current Location Phone Number': 'Current Location Phone Number', 'Current Location Treating Hospital': 'Current Location Treating Hospital', 'Current Log Entries': 'Entradas de Log atuais', 'Current Memberships': 'Participações atuais', 'Current Mileage': 'Current Mileage', 'Current Notes': 'Notes atual', 'Current Records': 'Registros atuais', 'Current Registrations': 'Registros atuais', 'Current Status': 'Status atual', 'Current Team Members': 'Os atuais membros da equipe', 'Current Twitter account': 'Conta atual no Twitter', 'Current community priorities': 'Atuais prioridades da comunidade', 'Current general needs': 'Atuais necessidades gerais', 'Current greatest needs of vulnerable groups': 'Maiores necessidades atuais dos grupos vulneráveis', 'Current health problems': 'Problemas de saúde atuais', 'Current number of patients': 'Número atual de pacientes', 'Current problems, categories': 'Problemas atuais, categorias', 'Current problems, details': 'Problemas atuais, detalhes', 'Current request': 'Pedido atual', 'Current response': 'Resposta atual', 'Current session': 'Sessão atual', 'Currently no Certifications registered': 'Nenhuma certificação registrada atualmente', 'Currently no Competencies registered': 'Nenhuma competência registrada atualmente', 'Currently no Course Certificates registered': 'Nenhum Curso Certificado registrado atualmente', 'Currently no Credentials registered': 'Nenhuma credencial registrada atualmente', 'Currently no Missions registered': 'Nenhuma missão registrada atualmente', 'Currently no Skill Equivalences registered': 'Nenhuma equivelência de habilidade registrada atualmente', 'Currently no Skills registered': 'Currently no Skills registered', 'Currently no Trainings registered': 'Atualmente não há treinamentos registrados', 'Currently no entries in the catalog': 'Nenhuma entrada no catálogo atualmente', 'Custom Database Resource (e.g., anything defined as a resource in Sahana)': 'Bnaco de Dados customizado de Recursos (por exemplo, nada definido como recurso no Sahana)', 'DC': 'DC', 'DNA Profile': 'Perfil de DNA', 'DNA Profiling': 'Perfil de DNA', 'DVI Navigator': 'Navegador DVI', 'Dam Overflow': 'Barragem ESTOURO', 'Damage': 'dano', 'Dangerous Person': 'Pessoa perigosa', 'Dashboard': 'Painel', 'Data': 'Dados', 'Data Type': 'Data Type', 'Data uploaded': 'Dados carregados', 'Database': 'DATABASE', 'Date': 'date', 'Date & Time': 'Date & Time', 'Date Available': 'Data Disponível', 'Date Received': 'Data do recebimento', 'Date Requested': 'Data do pedido', 'Date Required': 'Necessária', 'Date Sent': 'Data de Envio', 'Date Until': 'Data Até', 'Date and Time': 'Data e Hora', 'Date and time this report relates to.': 'Data e hora relacionadas a este relatório.', 'Date of Birth': 'Data de Nascimento', 'Date of Latest Information on Beneficiaries Reached': 'Data da última informação sobre Beneficiários Alcançado', 'Date of Report': 'Data do relatório', 'Date of Treatment': 'Date of Treatment', 'Date/Time': 'data/hora', 'Date/Time of Find': 'Pesquisa de data/hora', 'Date/Time of disappearance': 'Data/hora do desaparecimento', 'Date/Time when found': 'Data/hora quando foi encontrado', 'Date/Time when last seen': 'Data/ hora em que foi visto pela última vez', 'De-duplicator': 'Anti duplicador', 'Dead Bodies': 'Dead Bodies', 'Dead Body': 'Cadáver', 'Dead Body Details': 'Detalhes do Cadáver', 'Dead Body Reports': 'Relatórios de Cadáver', 'Dead body report added': 'Relatório de cadaver incluso.', 'Dead body report deleted': 'Relatório de cadáver excluído.', 'Dead body report updated': 'Relatório de cadáver atualizado', 'Deaths in the past 24h': 'Mortes nas últimas 24 horas', 'Deaths/24hrs': 'Mortes/24hrs', 'Decimal Degrees': 'Graus decimais', 'Decision': 'DECISÃO', 'Decomposed': 'Decomposto', 'Default Height of the map window.': 'Altura Padrão da janela do mapa.', 'Default Location': 'Default Location', 'Default Map': 'Mapa padrão', 'Default Marker': 'Padrão de mercado', 'Default Width of the map window.': 'Padrão de largura da janela do mapa.', 'Default synchronization policy': 'Política de sincronização de padrão', 'Defecation area for animals': 'Área de defecação para animais', 'Define Scenarios for allocation of appropriate Resources (Human, Assets & Facilities).': 'Cenários De definir para alocação adequado de recursos (humanos, Ativos & instalações).', 'Defines the icon used for display of features on handheld GPS.': 'Define o ícone utilizado para exibição de recursos no GPS portátil.', 'Defines the icon used for display of features on interactive map & KML exports.': 'Define o ícone utilizado para exibição de recursos no mapa interativo & exportações KML.', 'Defines the marker used for display & the attributes visible in the popup.': 'Define o marcador utilizado para exibir & os atributos visíveis no pop-up.', 'Degrees must be a number between -180 and 180': 'Os graus devem ser um número entre -180 e 180', 'Dehydration': 'Desidratação', 'Delete': 'Excluir', 'Delete Alternative Item': 'EXCLUIR Item Alternativo', 'Delete Assessment': 'Excluir Avaliação', 'Delete Assessment Summary': 'Excluir Resumo da Avaliação', 'Delete Asset': 'Excluir Ativo', 'Delete Asset Assignment': 'Excluir o recurso designado', 'Delete Asset Log Entry': 'EXCLUIR recurso de entrada de Log', 'Delete Baseline': 'apagar linha base', 'Delete Baseline Type': 'apagar tipo de linha base', 'Delete Brand': 'apagar marca', 'Delete Budget': 'apagar orçamento', 'Delete Bundle': 'apagar pacote', 'Delete Catalog': 'Excluir o Catálogo', 'Delete Catalog Item': 'apagar item do catálogo', 'Delete Certificate': 'Excluir Certificado', 'Delete Certification': 'Excluir Certificação', 'Delete Cluster': 'Exclui Cluster', 'Delete Cluster Subsector': 'EXCLUIR Cluster Subsector', 'Delete Commitment': 'Excluir Compromisso', 'Delete Commitment Item': 'Excluir Item de Compromisso', 'Delete Competency': 'Excluir Competência', 'Delete Competency Rating': 'Excluir Classificação da Competência', 'Delete Contact Information': 'Excluir Informações de Contato', 'Delete Course': 'Excluir Curso', 'Delete Course Certificate': 'Excluir Certificado do Curso', 'Delete Credential': 'Excluir Credencial', 'Delete Document': 'Excluir documento', 'Delete Donor': 'EXCLUIR Dador', 'Delete Entry': 'Excluir Entrada', 'Delete Event': 'Excluir Evento', 'Delete Feature Class': 'Excluir Classe de Recurso', 'Delete Feature Layer': 'Excluir Camada de Componentes', 'Delete GPS data': 'Delete GPS data', 'Delete Group': 'Excluir Grupo', 'Delete Home': 'Delete Home', 'Delete Hospital': 'Excluir Hospital', 'Delete Image': 'Excluir Imagem', 'Delete Impact': 'Excluir Impacto', 'Delete Impact Type': 'Excluir Tipo De Impacto', 'Delete Incident Report': 'Excluir Relatório de Incidentes', 'Delete Inventory Item': 'EXCLUIR Item De Inventário', 'Delete Item': 'Excluir Item', 'Delete Item Category': 'EXCLUIR categoria de Itens', 'Delete Item Pack': 'EXCLUIR Pacote de Itens', 'Delete Job Role': 'Excluir Cargo', 'Delete Key': 'Tecla de exclusão', 'Delete Kit': 'EXCLUIR Kit', 'Delete Layer': 'Excluir Camada', 'Delete Level 1 Assessment': 'EXCLUIR Nível 1 Avaliação', 'Delete Level 2 Assessment': 'EXCLUIR Nível 2 Avaliação', 'Delete Location': 'Excluir locação', 'Delete Map Configuration': 'EXCLUIR Mapa de configuração', 'Delete Marker': 'EXCLUIR Marcador', 'Delete Membership': 'Excluir membro', 'Delete Message': 'Excluir mensagem', 'Delete Mission': 'EXCLUIR Missão', 'Delete Need': 'Excluir necessidades', 'Delete Need Type': 'Excluir tipos de necessidades', 'Delete Office': 'Excluir escritório', 'Delete Organization': 'Excluir organização', 'Delete Patient': 'Delete Patient', 'Delete Peer': 'Excluir par', 'Delete Person': 'excluir pessoa', 'Delete Photo': 'Excluir Foto', 'Delete Population Statistic': 'EXCLUIR População Estatística', 'Delete Position': 'EXCLUIR Posição', 'Delete Project': 'Excluir Projeto', 'Delete Projection': 'Excluir Projeção', 'Delete Rapid Assessment': 'Excluir Avaliação Rápida', 'Delete Received Item': 'Excluir Item Recebido', 'Delete Received Shipment': 'Excluir Embarque Recebido', 'Delete Record': 'Excluir Registro', 'Delete Relative': 'Delete Relative', 'Delete Report': 'Excluir Relatório', 'Delete Request': 'Excluir Solicitação', 'Delete Request Item': 'Excluir item de solicitação', 'Delete Resource': 'Excluir Recurso', 'Delete Room': 'Excluir Sala', 'Delete Scenario': 'Excluir Cenário', 'Delete Section': 'Excluir seção', 'Delete Sector': 'Excluir Setor', 'Delete Sent Item': 'Excluir Item Enviado', 'Delete Sent Shipment': 'Excluir Embarque Enviado', 'Delete Service Profile': 'Excluir perfil de serviço', 'Delete Setting': 'Excluir Definição', 'Delete Skill': 'Excluir habilidade', 'Delete Skill Equivalence': 'Excluir equivalência de habilidade', 'Delete Skill Provision': 'Excluir Provisão de Habilidade', 'Delete Skill Type': 'Excluir Tipo de Habilidade', 'Delete Staff Type': 'Excluir Tipo De Equipe', 'Delete Status': 'Excluir Posição/Estado', 'Delete Subscription': 'Excluir assinatura', 'Delete Subsector': 'Excluir subsetor', 'Delete Survey Answer': 'Excluir reposta da pesquisa', 'Delete Survey Question': 'Excluir pergunta da pesquisa', 'Delete Survey Section': 'Excluir seção da pesquisa', 'Delete Survey Series': 'Excluir série da pesquisa', 'Delete Survey Template': 'Excluir modelo da pesquisa', 'Delete Training': 'Excluir Treinamento', 'Delete Unit': 'Excluir Unidade', 'Delete User': 'Excluir usuário', 'Delete Vehicle': 'Delete Vehicle', 'Delete Vehicle Details': 'Delete Vehicle Details', 'Delete Volunteer': 'EXCLUIR Voluntário', 'Delete Warehouse': 'Excluír Armazém', 'Delete from Server?': 'Excluir do Servidor?', 'Delphi Decision Maker': 'tomador de decisão Delphi', 'Demographic': 'Demográfico', 'Demonstrations': 'Demonstrações', 'Dental Examination': 'Exame Dentário', 'Dental Profile': 'Perfil Dentário', 'Deployment Location': 'Deployment Location', 'Describe the condition of the roads to your hospital.': 'Descreva as condições da estrada até o seu hospital.', 'Describe the procedure which this record relates to (e.g. "medical examination")': 'Descreva o procedimento ao qual este registro está relacionado (Ex: "exame médico")', 'Description': 'Descrição', 'Description of Contacts': 'Descrição dos Contatos', 'Description of defecation area': 'Descrição da área de defecação', 'Description of drinking water source': 'Descrição da fonte de água potável', 'Description of sanitary water source': 'Descrição da fonte de água sanitária', 'Description of water source before the disaster': 'Descrição da fonte de água antes do desastre', 'Descriptive Text (e.g., Prose, etc)': 'Texto Descritivo (por exemplo, Prosa, etc.)', 'Desire to remain with family': 'O desejo de permanecer com a família', 'Destination': 'destino', 'Destroyed': 'Destruído', 'Details': 'detalhes', 'Details field is required!': 'Campo de detalhes é obrigatório!', 'Dialysis': 'Diálise', 'Diaphragms, horizontal bracing': 'Diafragmas, interditará horizontal', 'Diarrhea': 'Diarréia', 'Dignitary Visit': 'Visita de Dignatários', 'Direction': 'Endereço', 'Disable': 'Desativar', 'Disabled': 'desativado', 'Disabled participating in coping activities': 'Deficiente participando de enfrentamento', 'Disabled?': 'Desativado?', 'Disaster Victim Identification': 'Identificação de Vítima de Desastre', 'Disaster Victim Registry': 'Registro de Vítima de Desastre', 'Disaster clean-up/repairs': 'Desastre limpeza/reparos', 'Discharge (cusecs)': 'Quitação (cusecs)', 'Discharges/24hrs': 'Descargas/24horas', 'Discussion Forum': 'Fórum de Discussão', 'Discussion Forum on item': 'Fórum de discussão do item', 'Disease vectors': 'Vectores doença', 'Dispensary': 'Dispensário', 'Displaced': 'Deslocadas', 'Displaced Populations': 'Populações deslocadas', 'Display Polygons?': 'exibir Polígonos?', 'Display Routes?': 'Exibir Rotas?', 'Display Tracks?': 'exibir Trilhas?', 'Display Waypoints?': 'Exibir Rota?', 'Distance between defecation area and water source': 'Distância entre área de esgoto e fonte de água', 'Distance from %s:': 'Distância de %s:', 'Distance(Kms)': 'Distância(Kms)', 'Distribution': 'Distribuição de', 'Distribution groups': 'Grupos de distribuição', 'District': 'Distrito', 'Do you really want to delete these records?': 'Você realmente deseja excluir esses registros?', 'Do you want to cancel this received shipment? The items will be removed from the Inventory. This action CANNOT be undone!': 'Você deseja cancelar este carregamento que foi recebido? Os itens serão removidos do inventário. Esta ação não pode ser desfeita!', 'Do you want to cancel this sent shipment? The items will be returned to the Inventory. This action CANNOT be undone!': 'Você deseja cancelar esse carregamento enviado? Os itens serão retornados para o inventário. Esta ação não pode ser desfeita!', 'Do you want to receive this shipment?': 'Você deseja receber esse carregamento?', 'Do you want to send these Committed items?': 'Você deseja enviar esses itens Consolidados?', 'Do you want to send this shipment?': 'Você deseja enviar este carregamento?', 'Document': 'documento', 'Document Details': 'Detalhes do Documento', 'Document Scan': 'Scanear Documento', 'Document added': 'Documento incluído', 'Document deleted': 'Documento excluído', 'Document removed': 'Document removed', 'Document updated': 'Documento Atualizado', 'Documents': 'Documentos', 'Documents and Photos': 'Documentos e Fotos', 'Does this facility provide a cholera treatment center?': 'Esta facilidade proporciona um centro de tratamento da cólera?', 'Doing nothing (no structured activity)': 'Fazendo nada (sem atividade estruturada)', 'Dollars': 'dólares', 'Domain': 'domínio', 'Domestic chores': 'Afazeres domésticos', 'Donated': 'Doado', 'Donation Certificate': 'Certificado de doaçao', 'Donation Phone #': 'Número de Telefone de doaçao', 'Donor': 'Dador', 'Donor Details': 'Doador Detalhes', 'Donor added': 'Doador incluído', 'Donor deleted': 'Doador excluído', 'Donor updated': 'Doador ATUALIZADO', 'Donors': 'Doadores', 'Donors Report': 'Relatório de Doadores', 'Door frame': 'Quadro de porta', 'Download PDF': 'Fazer download do PDF', 'Download Template': 'Download Template', 'Draft': 'rascunho', 'Drainage': 'Drenagem', 'Drawing up a Budget for Staff & Equipment across various Locations.': 'Elaborar um orçamento para Equipe & Equipamento de vários locais.', 'Drill Down by Group': 'Detalhar por grupo', 'Drill Down by Incident': 'Detalhar por incidente', 'Drill Down by Shelter': 'Detalhar por abrigo', 'Driving License': 'Carteira de Motorista', 'Drought': 'Seca', 'Drugs': 'Drogas', 'Dug Well': 'Cavaram Bem', 'Duplicate?': 'Duplicado?', 'Duration': 'Duração', 'Dust Storm': 'Tempestade de Poeira', 'Dwelling': 'Habitação', 'Dwellings': 'Habitações', 'E-mail': 'Correio eletrônico', 'EMS Reason': 'Razão EMS', 'EMS Status': 'EMS Status', 'ER Status': 'ER Status', 'ER Status Reason': 'Razão ER Status', 'EXERCISE': 'EXERCISE', 'Early Recovery': 'Início De Recuperação', 'Earth Enabled?': 'Earth Enabled?', 'Earthquake': 'Terremotos', 'Edit': 'Editar', 'Edit Activity': 'Editar Atividade', 'Edit Address': 'Editar Endereço', 'Edit Alternative Item': 'Editar Item Alternativo', 'Edit Application': 'Editar Aplicação', 'Edit Assessment': 'Editar avaliação', 'Edit Assessment Summary': 'Editar resumo da avaliação', 'Edit Asset': 'Editar recurso', 'Edit Asset Assignment': 'Editar designação do recurso', 'Edit Asset Log Entry': 'EDITAR ENTRADA DE Log de ATIVOs', 'Edit Baseline': 'Editar base de avaliação', 'Edit Baseline Type': 'Editar tipo de base de avaliação', 'Edit Brand': 'Editar marca', 'Edit Budget': 'Editar orçamento', 'Edit Bundle': 'Editar Pacote', 'Edit Camp': 'EDITAR acampamento', 'Edit Camp Service': 'EDITAR Serviço de acampamento', 'Edit Camp Type': 'Editar Tipo de Campo', 'Edit Catalog': 'Editar catálogo', 'Edit Catalog Item': 'Editar item do catálogo', 'Edit Certificate': 'Editar Certificado', 'Edit Certification': 'Editar Certificação', 'Edit Cluster': 'Editar grupo', 'Edit Cluster Subsector': 'Editar subgrupo', 'Edit Commitment': 'Editar compromisso', 'Edit Commitment Item': 'Editar Item De Compromisso', 'Edit Committed Person': 'Edit Committed Person', 'Edit Competency': 'Editar Competência', 'Edit Competency Rating': 'Editar Classificação da Competência', 'Edit Contact': 'Editar Contato', 'Edit Contact Information': 'Editar Informações de Contato', 'Edit Contents': 'Editar Conteúdo', 'Edit Course': 'Editar Curso', 'Edit Course Certificate': 'Editar Certificado de Curso', 'Edit Credential': 'Editar Credencial', 'Edit Dead Body Details': 'Editar Detalhes do Cadáver', 'Edit Description': 'Editar Descrição', 'Edit Details': 'Editar detalhes', 'Edit Disaster Victims': 'Editar vítimas do desastre', 'Edit Document': 'Editar documento', 'Edit Donor': 'Editar Doador', 'Edit Email Settings': 'Editar As Configurações De E-Mail', 'Edit Entry': 'Editar Entrada', 'Edit Event': 'Editar evento', 'Edit Facility': 'Editar recurso', 'Edit Feature Class': 'EDITAR CLASSE DE RECURSO', 'Edit Feature Layer': 'Editar Recurso Camada', 'Edit Flood Report': 'Editar Relatório de Enchente', 'Edit GPS data': 'Edit GPS data', 'Edit Gateway Settings': 'Editar Configurações de Gateway', 'Edit Group': 'Grupo de edição', 'Edit Home': 'Edit Home', 'Edit Hospital': 'Editar Hospital', 'Edit Human Resource': 'Editar Recursos Humanos', 'Edit Identification Report': 'Editar Relatório de identificação', 'Edit Identity': 'Editar Identidade', 'Edit Image': 'Editar Imagem', 'Edit Image Details': 'Editar Detalhes da Imagem', 'Edit Impact': 'Editar Impacto', 'Edit Impact Type': 'Editar Tipo De Impacto', 'Edit Import File': 'Edit Import File', 'Edit Incident Report': 'Editar Relatório de Incidente', 'Edit Inventory Item': 'Editar Item De Inventário', 'Edit Item': 'Editar Item', 'Edit Item Category': 'Editar Item de categoria', 'Edit Item Pack': 'Editar Pacote de Itens', 'Edit Job Role': 'Editar cargo', 'Edit Key': 'Editar Tecla', 'Edit Kit': 'Editar Kit', 'Edit Layer': 'Editar Camada', 'Edit Level %d Locations?': 'Editar Locais Nível d% ?', 'Edit Level 1 Assessment': 'Editar Avaliação Nível 1', 'Edit Level 2 Assessment': 'Editar nível 2 de acesso', 'Edit Location': 'Local de edição', 'Edit Log Entry': 'EDITAR ENTRADA DE Log', 'Edit Map Configuration': 'Editar Mapa de configuração', 'Edit Map Services': 'Editar mapa de serviços', 'Edit Marker': 'Marcador de Edição', 'Edit Membership': 'Editar inscrição', 'Edit Message': 'Editar mensagem', 'Edit Messaging Settings': 'Editar Configurações De Mensagens', 'Edit Mission': 'Editar Missão', 'Edit Modem Settings': 'Editar Configurações Do Modem', 'Edit Need': 'Ediçao Necessária', 'Edit Need Type': 'Editar tipo de necessidade', 'Edit Note': 'Editar nota', 'Edit Office': 'Escritório de edição', 'Edit Options': 'Opções de edição', 'Edit Organization': 'Organizar edições', 'Edit Parameters': 'Parametros de edição', 'Edit Patient': 'Edit Patient', 'Edit Peer Details': 'Detalhes do par editado', 'Edit Person Details': 'Editar detalhes pessoais', 'Edit Personal Effects Details': 'Editar detalhes de objectos pessoais', 'Edit Photo': 'Editar Foto', 'Edit Population Statistic': 'Editar Estatística da População', 'Edit Position': 'Editar Posição', 'Edit Problem': 'Editar Problema', 'Edit Project': 'Editar Projecto', 'Edit Projection': 'Editar Projeção', 'Edit Rapid Assessment': 'Editar Rápida Avaliação', 'Edit Received Item': 'Editar Item Recebido', 'Edit Received Shipment': 'Editar Embarque Recebido', 'Edit Record': 'Editar Registro', 'Edit Registration': 'Editar Registro', 'Edit Registration Details': 'Editar Detalhes De Registro', 'Edit Relative': 'Edit Relative', 'Edit Report': 'Editar Relatório', 'Edit Request': 'Editar Pedido', 'Edit Request Item': 'Editar Item Pedido', 'Edit Requested Skill': 'Edit Requested Skill', 'Edit Resource': 'Editar Recurso', 'Edit River': 'EDITAR RIO', 'Edit Role': 'Editar Função', 'Edit Room': 'Editar Sala', 'Edit SMS Settings': 'Edit SMS Settings', 'Edit SMTP to SMS Settings': 'Edit SMTP to SMS Settings', 'Edit Scenario': 'Editar cenário', 'Edit Sector': 'Editar Setor', 'Edit Sent Item': 'Editar Item Enviado', 'Edit Setting': 'Editar Definição', 'Edit Settings': 'Editar Configurações', 'Edit Shelter': 'EDITAR ABRIGO', 'Edit Shelter Service': 'Editar Serviço de Abrigo', 'Edit Shelter Type': 'EDITAR Tipo De Abrigo', 'Edit Skill': 'editar competência', 'Edit Skill Equivalence': 'Editar Equivalência de Habilidade', 'Edit Skill Provision': 'Editar Habilidade de Fornecimento', 'Edit Skill Type': 'editar tipo de competência', 'Edit Solution': 'editar solução', 'Edit Staff': 'editar pessoal', 'Edit Staff Member Details': 'Editar detalhes do membro da equipe', 'Edit Staff Type': 'EDITAR Tipo De Equipe', 'Edit Subscription': 'Editar assinatura', 'Edit Subsector': 'EDITAR Subsector', 'Edit Survey Answer': 'Editar resposta da pesquisa', 'Edit Survey Question': 'Editar pergunta da pesquisa', 'Edit Survey Section': 'EDITAR Seção de Pesquisa', 'Edit Survey Series': 'EDITAR Pesquisa de Série', 'Edit Survey Template': 'EDITAR MODELO DE PESQUISA', 'Edit Task': 'Editar Tarefa', 'Edit Team': 'Editar equipe', 'Edit Theme': 'Editar tema', 'Edit Themes': 'EDITAR TEMAs', 'Edit Ticket': 'EDITAR Bilhete', 'Edit Track': 'EDITAR RASTREAMENTO', 'Edit Training': 'Editar Treinamento', 'Edit Tropo Settings': 'Editar Configurações Tropo', 'Edit User': 'Editar Usuário', 'Edit Vehicle': 'Edit Vehicle', 'Edit Vehicle Details': 'Edit Vehicle Details', 'Edit Volunteer Availability': 'Editar Disponibilidade de Voluntário', 'Edit Volunteer Details': 'Editar Detalhes de Voluntário', 'Edit Warehouse': 'Editar Armazém', 'Edit Web API Settings': 'Edit Web API Settings', 'Edit current record': 'Editar Registro Atual', 'Edit message': 'Editar mensagem', 'Edit the Application': 'Editar a Aplicação', 'Editable?': 'Editável?', 'Education': 'Educação', 'Education materials received': 'Materiais de educação recebido', 'Education materials, source': 'materiais de Educação, origem', 'Effects Inventory': 'Inventário de efeitos', 'Eggs': 'Ovos', 'Either a shelter or a location must be specified': 'Um abrigo ou um local deve ser especificado', 'Either file upload or document URL required.': 'Um arquivo de upload ou URL do documento são necessários.', 'Either file upload or image URL required.': 'Um arquivo de upload ou URL de imagem são necessárias.', 'Elderly person headed households (>60 yrs)': 'Chefes de Familia de idade avançada (>60 anos)', 'Electrical': 'Elétrico', 'Electrical, gas, sewerage, water, hazmats': 'Elétrica, gás, esgotos, água, hazmats', 'Elevated': 'Elevado', 'Elevators': 'Elevadores', 'Email': 'E-MAIL', 'Email Address': 'Endereço de e-mail', 'Email Address to which to send SMS messages. Assumes sending to <EMAIL>': 'Email Address to which to send SMS messages. Assumes sending to <EMAIL>', 'Email Settings': 'Configurações de e-mail', 'Email settings updated': 'As configurações de e-mail atualizado', 'Embalming': 'Embalsamento', 'Embassy': 'Embaixada', 'Emergency Capacity Building project': 'Plano de emergência de capacidade dos prédios', 'Emergency Department': 'Departamento de Emergência', 'Emergency Shelter': 'Abrigo de Emergência', 'Emergency Support Facility': 'Recurso De Suporte de emergência', 'Emergency Support Service': 'Suporte do Serviço de Emergência', 'Emergency Telecommunications': 'Emergência De Telecomunicações', 'Enable': 'Enable', 'Enable/Disable Layers': 'Ativar/Desativar Camadas', 'Enabled': 'Habilitado', 'Enabled?': 'Enabled?', 'Enabling MapMaker layers disables the StreetView functionality': 'Enabling MapMaker layers disables the StreetView functionality', 'End Date': 'Data de encerramento', 'End date': 'Data de Término', 'End date should be after start date': 'Data Final deve ser maior do que a data de início', 'End of Period': 'Fim de Período', 'English': 'Inglês', 'Enter Coordinates:': 'Entre as coordenadas:', 'Enter a GPS Coord': 'Digite uma Coordada GPS', 'Enter a name for the spreadsheet you are uploading (mandatory).': 'Digite um nome para a planilha que está fazendo Upload (obrigatório).', 'Enter a name for the spreadsheet you are uploading.': 'Enter a name for the spreadsheet you are uploading.', 'Enter a new support request.': 'Digite um pedido novo de suporte.', 'Enter a unique label!': 'Digite um rótulo exclusivo!', 'Enter a valid date before': 'Digite uma data válida antes de', 'Enter a valid email': 'Insira um email válido', 'Enter a valid future date': 'Digite uma data futura válida', 'Enter a valid past date': 'Enter a valid past date', 'Enter some characters to bring up a list of possible matches': 'Digite alguns caracteres para trazer uma lista de correspondências possíveis', 'Enter some characters to bring up a list of possible matches.': 'Digite alguns caracteres para trazer uma lista de correspondências possíveis.', 'Enter tags separated by commas.': 'Insira as tags separadas por vírgulas.', 'Enter the data for an assessment': 'Enter the data for an assessment', 'Enter the same password as above': 'Digite a mesma senha acima', 'Enter your firstname': 'Enter your firstname', 'Enter your organization': 'Enter your organization', 'Entered': 'Inserido', 'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.': 'Digitar um número de telefone é opcional, mas ao fazer isto permite a voçe se registrar para receber mensagens SMS.', 'Entry deleted': 'Entrada removida', 'Environment': 'Ambiente do', 'Equipment': 'Equipamento', 'Error encountered while applying the theme.': 'Erro encontrado ao aplicar o tema.', 'Error in message': 'Erro na mensagem', 'Error logs for "%(app)s"': 'Registro de erros de "%(app)s"', 'Error: no such record': 'Erro: nenhum registro', 'Errors': 'Erros', 'Est. Delivery Date': 'Est. Data de entrega', 'Estimated # of households who are affected by the emergency': '# estimado das famílias que são afetados pela emergência', 'Estimated # of people who are affected by the emergency': '# estimado de pessoas que são afetados pela emergência', 'Estimated Overall Building Damage': 'Dano total de construção estimado', 'Estimated total number of people in institutions': 'Número total estimado de pessoas em instituições', 'Euros': 'Euros', 'Evacuating': 'abandono', 'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)': 'Valide as informações desta mensagem. (Este valor não deve ser utilizado em aplicações de aviso público. ).', 'Event': 'Evento', 'Event Details': 'Detalhes do evento', 'Event added': 'Evento incluído', 'Event deleted': 'Evento excluído', 'Event updated': 'Evento atualizado', 'Events': 'eventos', 'Example': 'Exemplo:', 'Exceeded': 'Excedido', 'Excellent': 'Excelente', 'Exclude contents': 'Excluir conteúdo', 'Excreta disposal': 'Eliminação de dejetos', 'Execute a pre-planned activity identified in <instruction>': 'Executar uma atividade pré-planejada identificada no', 'Exercise': 'Excercício', 'Exercise?': 'Exercício ?', 'Exercises mean all screens have a watermark & all notifications have a prefix.': "Exercícios significa que todas as telas têm uma marca d'água & todas as comunicações têm um prefixo.", 'Existing Placard Type': 'Cartaz existente Tipo', 'Existing Sections': 'Existing Sections', 'Existing food stocks': 'Estoques de alimentos existente', 'Existing location cannot be converted into a group.': 'Local Existente não pode ser convertido em um grupo.', 'Exits': 'Saídas', 'Expected Return Home': 'Expected Return Home', 'Experience': 'Experiência', 'Expiry Date': 'Data de expiração', 'Explosive Hazard': 'Perigo explosivo', 'Export': 'Exportar', 'Export Data': 'Exportar dados.', 'Export Database as CSV': 'Exportar o banco de dados como CSV', 'Export in GPX format': 'Exportar no formato GPX', 'Export in KML format': 'Exportar no formato KML', 'Export in OSM format': 'Exportar no formato OSM', 'Export in PDF format': 'Exportar no formato PDF', 'Export in RSS format': 'Exportar no formato RSS', 'Export in XLS format': 'Exportar no formato XLS', 'Exterior Only': 'Exterior Apenas', 'Exterior and Interior': 'Exterior e Interior', 'Eye Color': 'Cor dos Olhos', 'Facebook': 'Facebook', 'Facial hair, color': 'Cabelo Facial, cor', 'Facial hair, type': 'Cabelo Facial, digite', 'Facial hear, length': 'Facial ouvir, COMPRIMENTO', 'Facilities': 'Instalações', 'Facility': 'Instalação', 'Facility Details': 'Detalhes da Instalação', 'Facility Operations': 'Facilidades nas Operações', 'Facility Status': 'Status Facility', 'Facility Type': 'Tipo de Instalação', 'Facility added': 'Instalação incluída', 'Facility or Location': 'Instalação ou Local', 'Facility removed': 'Recurso removido', 'Facility updated': 'Recurso atualizado', 'Fail': 'Falha', 'Failed!': 'Falha!', 'Fair': 'Razoável', 'Falling Object Hazard': 'Queda Objeto Risco', 'Families/HH': 'Famílias/HH', 'Family': 'Familia', 'Family tarpaulins received': 'lonas de familia recebidas', 'Family tarpaulins, source': 'lonas de familia, fuente', 'Family/friends': 'Família/amigos', 'Farmland/fishing material assistance, Rank': 'TERRAS/assistência de material de Pesca, posição', 'Fatalities': 'Fatalidades', 'Fax': 'Número do Fax', 'Feature Class': 'Classe de Recursos', 'Feature Class Details': 'Detalhes da classe de recurso', 'Feature Class added': 'Classe de Recurso incluída', 'Feature Class deleted': 'Classe de recurso excluída', 'Feature Class updated': 'Classe De recurso atualizada', 'Feature Classes': 'Classes de Recursos', 'Feature Classes are collections of Locations (Features) of the same type': 'Classes De recurso são grupos de localidades (recursos) do mesmo tipo', 'Feature Layer Details': 'Recurso Camada Detalhes', 'Feature Layer added': 'Recurso Camada incluída', 'Feature Layer deleted': 'Recurso Camada excluído', 'Feature Layer updated': 'Recurso Camada atualizada', 'Feature Layers': 'Camadas recurso', 'Feature Namespace': 'Espaço De recurso', 'Feature Request': 'Pedido de Componente', 'Feature Type': 'Tipo de Componente', 'Features Include': 'Componentes Incluidos', 'Female': 'Sexo Feminino', 'Female headed households': 'Famílias chefiadas por mulheres', 'Few': 'Poucos', 'Field': 'Campo', 'Field Hospital': 'Campo Hospital', 'File': 'arquivo', 'File Imported': 'File Imported', 'File Importer': 'File Importer', 'File name': 'File name', 'Fill in Latitude': 'Preencher na Latitude', 'Fill in Longitude': 'Preencher na Longitude', 'Filter': 'Filtro', 'Filter Field': 'Filtro de Campo', 'Filter Value': 'Filtro de Valor', 'Find': 'Localizar', 'Find All Matches': 'Localizar todos os equivalentes', 'Find Dead Body Report': 'Localizar Relatório de Cadáver', 'Find Hospital': 'Localizar Hospital', 'Find Person Record': 'Localizar registro de pessoa', 'Find Volunteers': 'Localizar Voluntários', 'Find a Person Record': 'Localizar um Registro de Pessoa', 'Finder': 'Localizador', 'Fingerprint': 'Impressão digital', 'Fingerprinting': 'Impressões digitais', 'Fingerprints': 'Impressões Digitais', 'Finish': 'Terminar', 'Finished Jobs': 'Tarefa Terminada', 'Fire': 'Fogo', 'Fire suppression and rescue': 'Supressão e salvamento de incêndio', 'First Name': '<NAME>', 'First name': '<NAME>', 'Fishing': 'Pesca', 'Flash Flood': 'Enchente', 'Flash Freeze': 'congelar o momento', 'Flexible Impact Assessments': 'Flexibilidade no Impacto de avaliações', 'Flood': 'Enchente', 'Flood Alerts': 'Alertas de Enchente', 'Flood Alerts show water levels in various parts of the country': 'Os alertas de inundação mostram o nível da água em várias partes do país', 'Flood Report': 'Relatório de Inundação', 'Flood Report Details': 'Detalhes do Relatório de Inundação', 'Flood Report added': 'Relatório de Inundação incluído', 'Flood Report deleted': 'Relatório de Inundação removido', 'Flood Report updated': 'Relatório de Inundação actualizado', 'Flood Reports': 'Relatórios de Inundação', 'Flow Status': 'posição de fluxo', 'Focal Point': 'Ponto Central', 'Fog': 'Nevoeiro', 'Food': 'Food', 'Food Supply': 'Alimentação', 'Food assistance': 'Ajuda alimentar', 'Footer': 'Rodapé', 'Footer file %s missing!': '% Arquivo rodapé ausente!', 'For': 'Por', 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).': 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).', 'For a country this would be the ISO2 code, for a Town, it would be the Airport Locode.': 'Para um país este seria o código ISO2, para uma cidade, este seria o codigo do aeroporto (UNE/Locode).', 'For each sync partner, there is a default sync job that runs after a specified interval of time. You can also set up more sync jobs which could be customized on your needs. Click the link on the right to get started.': 'Para cada parceiro de sincronização, há uma tarefa de sincronização padrão que é executada após um intervalo de tempo especificado. Você também pode configurar mais tarefas de sincronização que podem ser customizadas de acordo com as suas necessidades. Clique no link à direita para começar.', 'For enhanced security, you are recommended to enter a username and password, and notify administrators of other machines in your organization to add this username and password against your UUID in Synchronization -> Sync Partners': 'Para segurança reforçada, é recomendável digitar um nome de usuário e senha, e notificar os administradores de outras máquinas em sua organização para incluir esse usuário e senha no UUID em Sincronização -> Parceiros De Sincronização', 'For live help from the Sahana community on using this application, go to': 'Para ajuda ao vivo da comunidade do Sahana sobre como utilizar esse aplicativo, vá para', 'For messages that support alert network internal functions': 'Para mensagens que suportam funções internas de alertas de rede', 'For more details on the Sahana Eden system, see the': 'Para obter mais detalhes sobre o sistema Sahana Eden, consulte o', 'For more information, see': 'Para obter mais informações, consulte o', 'For more information, see ': 'For more information, see ', 'For other types, the next screen will allow you to enter the relevant details...': 'Para outros tipos, a próxima tela permitirá que você digite os detalhes relevantes.', 'Forest Fire': 'Incêndios florestais', 'Formal camp': 'Acampamento formal', 'Format': 'Formato', "Format the list of attribute values & the RGB value to use for these as a JSON object, e.g.: {Red: '#FF0000', Green: '#00FF00', Yellow: '#FFFF00'}": "Formatar a lista de valores de atributos & o valor RGB a ser usado para esses como o objeto JSON, Exemplo: {Red: '#FF0000, Green: '#00FF00', Yellow: '#FFFF00'}", 'Forms': 'formulários', 'Found': 'localizado', 'Foundations': 'Fundações', 'Freezing Drizzle': 'Garoa gelada', 'Freezing Rain': 'Chuva Gelada', 'Freezing Spray': 'Spray Gelado', 'French': 'Francês', 'Friday': 'sexta-feira', 'From': 'from', 'From Facility': 'From Facility', 'From Inventory': 'A partir do Inventário', 'From Location': 'Do Local', 'From Organisation': 'Da organização', 'From Organization': 'Da Organização', 'From Person': 'Da Pessoa', 'Frost': 'Geada', 'Fulfil. Status': 'Encher. Status', 'Fulfillment Status': 'Status de preenchimento', 'Full': 'Cheio', 'Full beard': 'Barba completa', 'Fullscreen Map': 'Mapa em tela cheia', 'Functions available': 'Funções disponíveis', 'Funding Organization': 'Financiar a Organização', 'Funeral': 'Funeral', 'Further Action Recommended': 'Mais Acção Recomendada', 'GIS Reports of Shelter': 'Relatórios GIS de abrigos', 'GIS integration to view location details of the Shelter': 'Integration GIS para visualizar detalhes do local do Abrigo', 'GPS': 'GPS', 'GPS Data': 'GPS Data', 'GPS ID': 'GPS ID', 'GPS Marker': 'Marcador De GPS', 'GPS Track': 'Rastrear por GPS', 'GPS Track File': 'Rastrear Arquivo GPS', 'GPS data': 'GPS data', 'GPS data added': 'GPS data added', 'GPS data deleted': 'GPS data deleted', 'GPS data updated': 'GPS data updated', 'GPX Track': 'GPX RASTREAR', 'GRN': 'NRG', 'GRN Status': 'Status GRN', 'Gale Wind': 'Temporal', 'Gap Analysis': 'Análise de Falhas', 'Gap Analysis Map': 'Mapa de Análise de Falhas', 'Gap Analysis Report': 'Relatório de Análise de Falhas', 'Gap Map': 'Mapa de Falhas', 'Gap Report': 'Relatório de Falhas', 'Gateway': 'Portão', 'Gateway Settings': 'Configurações de Gateway', 'Gateway settings updated': 'Configurações de Gateway atualizadas', 'Gender': 'Sexo', 'General': 'geral', 'General Comment': 'Comentário Geral', 'General Medical/Surgical': 'Médico/Cirúrgico Geral', 'General emergency and public safety': 'Geral de emergência e segurança pública', 'General information on demographics': 'Informações gerais sobre demografia', 'Generator': 'Gerador', 'Geocode': 'Geocodificar', 'Geocoder Selection': 'Seleção De geocodificador', 'Geometry Name': 'Nome da geometria', 'Geophysical (inc. landslide)': 'Geofísica (inc. deslizamento)', 'Geotechnical': 'Geotécnica', 'Geotechnical Hazards': 'RISCOS geotécnicos', 'Geraldo module not available within the running Python - this needs installing for PDF output!': 'Geraldo não disponíveis no módulo a execução Python- é necessário instalar para saída PDF!', 'Geraldo not installed': 'Geraldo não instalado', 'German': 'German', 'Get incoming recovery requests as RSS feed': 'Obter pedidos recebidos de recuperação como feed RSS', 'Give a brief description of the image, e.g. what can be seen where on the picture (optional).': 'Fornecer uma descrição breve da imagem, por exemplo, o que pode ser visto no local da imagem (opcional).', 'Give information about where and when you have seen them': 'Fornecer informações sobre onde e quando você os viu', 'Global Messaging Settings': 'Configurações Globais de Menssagem', 'Go': 'ir', 'Go to Request': 'Ir para Pedido', 'Goatee': 'Barbicha', 'Good': 'Válido', 'Good Condition': 'Boa Condição', 'Goods Received Note': 'Nota de Recebimento de Mercadorias', "Google Layers cannot be displayed if there isn't a valid API Key": "Google Layers cannot be displayed if there isn't a valid API Key", 'Government': 'Governamental', 'Government UID': 'GOVERNO UID', 'Government building': 'Prédios Públicos', 'Grade': 'Grau', 'Greek': 'grego', 'Green': 'verde', 'Ground movement, fissures': 'Movimento do solo terrestre, fissuras', 'Ground movement, settlement, slips': 'Movimento do solo terrestre, assentamentos, escorregões', 'Group': 'Grupo', 'Group Description': 'Descrição do Grupo', 'Group Details': 'Detalhes do grupo', 'Group ID': 'Group ID', 'Group Member added': 'Membro do grupo incluído', 'Group Members': 'membros do grupo', 'Group Memberships': 'Associados do Grupo', 'Group Name': 'Nome do grupo', 'Group Title': 'Título do grupo', 'Group Type': 'Tipo de grupo', 'Group added': 'Grupo adicionado', 'Group deleted': 'Grupo Excluído', 'Group description': 'Descrição do Grupo', 'Group updated': 'GRUPO ATUALIZADO', 'Groups': 'Grupos do', 'Groups removed': 'Grupos Removido', 'Guest': 'Convidado', 'HR Data': 'Dados de RH', 'HR Manager': 'Responsável de RH', 'Hail': 'granizo', 'Hair Color': 'Cor do Cabelo', 'Hair Length': 'Comprimento do cabelo', 'Hair Style': 'Estilo do Cabelo', 'Has additional rights to modify records relating to this Organization or Site.': 'Tem direitos adicionais para modificar os registros relativos a esta organização ou site.', 'Has data from this Reference Document been entered into Sahana?': 'Os dados deste documento de referência foi digitado no Sahana?', 'Has only read-only access to records relating to this Organization or Site.': 'Tem apenas acesso de leitura para os registros relativos a esta organização ou site.', 'Has the Certificate for receipt of the shipment been given to the sender?': 'O certificado de recepção do carregamento foi dado para o remetente?', 'Has the GRN (Goods Received Note) been completed?': 'O GRN (nota de mercadorias recebidas) foi concluído?', 'Hazard Pay': 'Pagar Risco', 'Hazardous Material': 'Material perigoso', 'Hazardous Road Conditions': 'Estradas em Condições de Risco', 'Header Background': 'Conhecimento de Chefia', 'Header background file %s missing!': 'Arquivo de Cabeçalho de Base %s ausente!', 'Headquarters': 'Matriz', 'Health': 'Saúde', 'Health care assistance, Rank': 'Assistência Saúde, Classificação', 'Health center': 'Centro de Saúde', 'Health center with beds': 'Centro de saúde com camas', 'Health center without beds': 'Centro de saúde sem camas', 'Health services status': 'Situação dos serviços de saúde', 'Healthcare Worker': 'Profissional de Saúde', 'Heat Wave': 'Onda de calor', 'Heat and Humidity': 'Calor e Umidade', 'Height': 'Altura', 'Height (cm)': 'Altura (cm)', 'Height (m)': 'Altura (m)', 'Help': 'Ajuda', 'Helps to monitor status of hospitals': 'Ajuda para monitorar status de hospitais', 'Helps to report and search for Missing Persons': 'Ajuda a reportar e procurar pessoas desaparecidas.', 'Helps to report and search for missing persons': 'Ajuda a reportar e procurar pessoas desaparecidas.', 'Here are the solution items related to the problem.': 'Aqui estão as soluções relacionadas ao problema.', 'Heritage Listed': 'Património Listado', 'Hierarchy Level %d Name': 'Hierarquia de Nível% de d Nome', 'Hierarchy Level 0 Name (e.g. Country)': 'Hierarquia Nível 0 Nome (por exemplo, País)', 'Hierarchy Level 0 Name (i.e. Country)': 'Hierarquia Nível 0 nome (por exemplo País)', 'Hierarchy Level 1 Name (e.g. Province)': 'Hierarquia Nível 1 Nome (por exemplo, Província)', 'Hierarchy Level 1 Name (e.g. State or Province)': 'Hierarquia Nível 1 nome (por exemplo, Estado ou Província)', 'Hierarchy Level 2 Name (e.g. District or County)': 'Hierarquia de Nível 2 Nome (por exemplo, Região ou Município)', 'Hierarchy Level 3 Name (e.g. City / Town / Village)': 'Hierarquia Nível 3 Nome (por exemplo, Cidade / Municipio / Vila)', 'Hierarchy Level 4 Name (e.g. Neighbourhood)': 'Hierarquia de Nível 4 Nome (por exemplo, Bairro)', 'Hierarchy Level 5 Name': 'Nome de Nível 5 na Hierarquia', 'High': 'Alta', 'High Water': "d'água alta", 'Hindu': 'Hindu', 'History': 'História', 'Hit the back button on your browser to try again.': 'Clique no ícone de voltar em seu navegador para tentar novamente.', 'Holiday Address': 'Endereço durante Feriado', 'Home': 'Residência', 'Home Address': 'Endereço Residencial', 'Home City': 'Home City', 'Home Country': 'País natal', 'Home Crime': 'Crime Doméstico', 'Home Details': 'Home Details', 'Home Phone Number': 'Home Phone Number', 'Home Relative': 'Home Relative', 'Home added': 'Home added', 'Home deleted': 'Home deleted', 'Home updated': 'Home updated', 'Homes': 'Homes', 'Hospital': 'Hospital', 'Hospital Details': 'Detalhes do Hospital', 'Hospital Status Report': 'Relatório de Status do Hospital', 'Hospital information added': 'Informações do hospital inclusas.', 'Hospital information deleted': 'Informações do hospital excluídas', 'Hospital information updated': 'informações do Hospital atualizadas', 'Hospital status assessment.': 'Avaliação de status do Hospital.', 'Hospitals': 'Hospitais', 'Hot Spot': 'ponto de acesso', 'Hour': 'Hora', 'Hours': 'Horas', 'Household kits received': 'Kits caseiros recebidos', 'Household kits, source': 'Kit de família, origem', 'How does it work?': 'Como funciona?', 'How is this person affected by the disaster? (Select all that apply)': 'Como esta pessoa é afetada pelo desastre? (selecione todos que se aplicam)', 'How long will the food last?': 'Quanto tempo irá durar a comida?', 'How many Boys (0-17 yrs) are Dead due to the crisis': 'Quantos rapazes (0-17 anos) estão Mortos devido à crise', 'How many Boys (0-17 yrs) are Injured due to the crisis': 'Quantos rapazes (0-17 anos) estão Feridos devido à crise', 'How many Boys (0-17 yrs) are Missing due to the crisis': 'Quantos rapazes (0-17 anos) estão Desaparecidos devido à crise', 'How many Girls (0-17 yrs) are Dead due to the crisis': 'Quantas garotas (0-17 anos) morreram devido à crise', 'How many Girls (0-17 yrs) are Injured due to the crisis': 'Quantas garotas (0-17 anos) estão feridas devido à crise', 'How many Girls (0-17 yrs) are Missing due to the crisis': 'Quantas garotas (0-17 anos) estão perdidas devido à crise', 'How many Men (18 yrs+) are Dead due to the crisis': 'Quantos homens (18 anos+) estão mortos devido à crise', 'How many Men (18 yrs+) are Injured due to the crisis': 'Quantos homens (18 anos +) são feridos devido à crise', 'How many Men (18 yrs+) are Missing due to the crisis': 'Quantos homens (18 anos +) estão ausentes devido à crise', 'How many Women (18 yrs+) are Dead due to the crisis': 'Quantas mulheres (+18 anos) estão mortas devido à crise', 'How many Women (18 yrs+) are Injured due to the crisis': 'Quantas mulheres (+18 anos) estão feridas devido à crise', 'How many Women (18 yrs+) are Missing due to the crisis': 'Quantas mulheres acima de 18 anos estão ausentes devido à crise', 'How many days will the supplies last?': 'Quantos dias irão durar os abastecimentos?', 'How many new cases have been admitted to this facility in the past 24h?': 'Quantos novos casos tenham sido admitidos a esta facilidade nas últimas 24 horas?', 'How many of the patients with the disease died in the past 24h at this facility?': 'Como muitos dos pacientes com a doença morreram nas últimas 24 horas nesta unidade?', 'How many patients with the disease are currently hospitalized at this facility?': 'Quantos pacientes com a doença estão atualmente internados nesta instalação?', 'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.': 'Quanto detalhe é visto. Um nível alto de Zoom mostra muitos detalhes, mas não uma grande área. Um nível de Zoom baixo significa ver uma grande área, mas não com um alto nível de detalhe.', 'Human Resource': 'Recursos humanos', 'Human Resource Details': 'Detalhes de Recursos Humanos', 'Human Resource Management': 'Gerenciamento de recursos humanos', 'Human Resource added': 'Recurso humano adicionado', 'Human Resource removed': 'Recursos Humanos removido', 'Human Resource updated': 'Recursos Humanos atualizado', 'Human Resources': 'Recursos Humanos', 'Human Resources Management': 'Gerenciamento de Recursos Humanos', 'Humanitarian NGO': 'ONG humanitária', 'Hurricane': 'Furacão', 'Hurricane Force Wind': 'Furacão Força Vento', 'Hybrid Layer': 'Hybrid Layer', 'Hygiene': 'Higiene', 'Hygiene NFIs': 'Higiene NFIs', 'Hygiene kits received': 'Kits de higiene recebido', 'Hygiene kits, source': 'Kits de higiene, origem', 'Hygiene practice': 'Prática de higiene', 'Hygiene problems': 'PROBLEMAS DE HIGIENE', 'I accept. Create my account.': 'I accept. Create my account.', 'I am available in the following area(s)': 'Estou disponível na(s) seguinte(s) área(s)', 'ID Tag': 'Etiqueta de Identificação', 'ID Tag Number': 'Número da Etiqueta de Identificação', 'ID type': 'Tipo de ID', 'Ice Pressure': 'Pressão de gelo', 'Iceberg': 'Icebergue', 'Identification': 'Identification', 'Identification Report': 'Identificação Relatório', 'Identification Reports': 'Relatórios de Identificação', 'Identification Status': 'Status da Identificação', 'Identified as': 'Identificado como', 'Identified by': 'Identificado por', 'Identity': 'Identidade', 'Identity Details': 'Detalhes da identidade', 'Identity added': 'Identidade incluída', 'Identity deleted': 'Identidade excluída', 'Identity updated': 'Identidade atualizada', 'If Staff have login accounts then they are given access to edit the details of the': 'Se o pessoal tiver contas de login, então lhes é dado acesso para editar os detalhes do', 'If a ticket was issued then please provide the Ticket ID.': 'Se um bilhete foi emitido então por favor forneça o ID do bilhete.', 'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.': 'Se um usuário verifica que eles possuem um endereço de email com este domínio, o campo Aprovador é utilizado para determinar se e por quem aprovação adicional é necessária.', 'If it is a URL leading to HTML, then this will downloaded.': 'Se for uma URL levando a HTML, então este será baixado.', 'If neither are defined, then the Default Marker is used.': 'Se nem são definidos, então o Marcador Padrão é utilizado.', 'If no marker defined then the system default marker is used': 'Se nenhum marcador definido, o marcador padrão do sistema é utilizada', 'If no, specify why': 'Se não, especifique por que', 'If none are selected, then all are searched.': 'Se nenhuma for selecionada, então todos são procurados.', "If selected, then this Asset's Location will be updated whenever the Person's Location is updated.": 'Se selecionado, esta localização do ativo será atualizado sempre que a localização da pessoa é atualizada.', 'If the location is a geographic area, then state at what level here.': 'Se o local é uma área geográfica, então defina em que nível aqui.', 'If the request is for %s, please enter the details on the next screen.': 'If the request is for %s, please enter the details on the next screen.', 'If the request is for type "Other", you should enter a summary of the request here.': 'Se o pedido for para o tipo \ " Outro", você deve digitar um resumo do pedido aqui.', 'If the request type is "Other", please enter request details here.': 'Se o tipo de pedido é "other", por favor, digite aqui detalhes do pedido.', "If this configuration represents a region for the Regions menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.": 'Se esta configuração representa uma região para o menu regiões, dê-lhe um nome a ser utilizado no menu. O nome de uma configuração pessoal do mapa será configurado para o nome do usuário.', "If this field is populated then a user who specifies this Organization when signing up will be assigned as a Staff of this Organization unless their domain doesn't match the domain field.": 'Se esse campo for Preenchido, então, um usuário que especificar esta organização quando se registrar será designado como um agente desta organização a menos que seu domínio não corresponde ao campo de domínio.', 'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organization': 'Se esse campo for preenchido, o usuário de um específico Domain será automaticamente registrado como funcionário desta organização.', 'If this is set to True then mails will be deleted from the server after downloading.': 'Se isso for ajustado para “True”, as correspondências serão deletadas do servidor depois que o downloading for feito.', "If this is ticked, then this will become the user's Base Location & hence where the user is shown on the Map": 'Se isso for ticado, se tornará a base geográfica do usuário e, consequentemente onde este aparece no mapa.', 'If this record should be restricted then select which role is required to access the record here.': 'Se esse registro deve ser restrito, selecione qual regra é necessária para acessar o record aqui.', 'If this record should be restricted then select which role(s) are permitted to access the record here.': 'Se esse registro deve ser restrito, selectione qual (is) regra (s) serão permitidas para assessá-lo aqui.', 'If yes, specify what and by whom': 'Se SIM, Especifique o quê e por quem', 'If yes, which and how': 'Se sim, quais e como', 'If you do not enter a Reference Document, your email will be displayed to allow this data to be verified.': 'Se você não inserir um documento de referência, seu e-mail será exibido para permitir que esses dados sejam verificados.', "If you don't see the Hospital in the list, you can add a new one by clicking link 'Add Hospital'.": "Se você não vê o Hospital na lista, você pode incluir um novo clicando no link 'incluir Hospital'.", "If you don't see the Office in the list, you can add a new one by clicking link 'Add Office'.": "Se você não vê o escritório na lista, você pode incluir um novo clicando no link 'incluir escritório'.", "If you don't see the Organization in the list, you can add a new one by clicking link 'Add Organization'.": 'Se voce não vê a Organização na lista, voce poderá adicionar uma nova clicando no link "Incluir Organização"', 'If you know what the Geonames ID of this location is then you can enter it here.': 'Se voce conhecer o Geonames ID desta localização então voce poderá inserí-lo aqui.', 'If you know what the OSM ID of this location is then you can enter it here.': 'Se voce conhecer o OSM ID desta localização, então voce pode inserí-lo aqui.', 'If you need to add a new document then you can click here to attach one.': 'Se houver necessidade de incluir um novo documento então voce poderá clicar aqui para anexá-lo.', 'If you want several values, then separate with': 'Se voce deseja varios valores, separe com', 'If you would like to help, then please': 'Se você gostaria de ajudar, então por favor', 'Illegal Immigrant': 'Imigrante Ilegal', 'Image': 'Imagem', 'Image Details': 'Detalhes da Imagem', 'Image File(s), one image per page': 'Image File(s), one image per page', 'Image Tags': 'Imagem Tags', 'Image Type': 'Tipo de Imagem', 'Image Upload': 'Fazer atualizacao Da imagem', 'Image added': 'Imagem Adicionada', 'Image deleted': 'Imagem excluída', 'Image updated': 'Imagem atualizada', 'Imagery': 'Imagens', 'Images': 'Imagens', 'Impact Assessments': 'Avaliações de impacto', 'Impact Details': 'Detalhes de impacto', 'Impact Type': 'Tipo de impacto', 'Impact Type Details': 'Detalhes dos tipos de impacto', 'Impact Type added': 'Tipo de impacto incluído', 'Impact Type deleted': 'Tipo de impacto excluído', 'Impact Type updated': 'Atualização dos tipos de impacto', 'Impact Types': 'Tipos de impactos', 'Impact added': 'Impacto incluído', 'Impact deleted': 'Impacto excluído', 'Impact updated': 'Atualização de impacto', 'Impacts': 'Impactos', 'Import': 'Importação', 'Import & Export Data': 'Importar & Exportar Dados', 'Import Data': 'Importar Dados', 'Import File': 'Import File', 'Import File Details': 'Import File Details', 'Import File deleted': 'Import File deleted', 'Import Files': 'Import Files', 'Import Job Count': 'Import Job Count', 'Import Jobs': 'Importar Tarefas', 'Import New File': 'Import New File', 'Import and Export': 'Importação e Exportação', 'Import from Ushahidi Instance': 'Importação da Instância Ushahidi', 'Import if Master': 'Importar se Mestre', 'Import multiple tables as CSV': 'Importar tabelas multiplas como CSV', 'Import/Export': 'Importar/Exportar', 'Important': 'Importante', 'Importantly where there are no aid services being provided': 'Importante onde não há serviços de apoio a ser prestado', 'Imported': 'Imported', 'Importing data from spreadsheets': 'Importar dados de planilhas', 'Improper decontamination': 'Descontaminação Imprópria', 'Improper handling of dead bodies': 'Manipulação inadequada de cadáveres', 'In Catalogs': 'Em Catálogos', 'In Inventories': 'Em Inventários', 'In Process': 'Em Processo', 'In Progress': 'Em Progresso', 'In Window layout the map maximises to fill the window, so no need to set a large value here.': 'Maximize o ajuste da janela para preenche-la toda, desta forma não será necessário configurar para uso de fonte grande.', 'Inbound Mail Settings': 'Definições de correio de entrada', 'Incident': 'Incidente', 'Incident Categories': 'Categorias Incidente', 'Incident Report': 'Relatório de Incidente', 'Incident Report Details': 'Detalhes do relatório de incidentes', 'Incident Report added': 'Relatório de Incidente incluído', 'Incident Report deleted': 'Relatório de Incidente excluído', 'Incident Report updated': 'Relatório de incidente atualizado', 'Incident Reporting': 'Relatório de incidentes', 'Incident Reporting System': 'Sistema de relatórios de incidentes', 'Incident Reports': 'Relatório de incidentes', 'Incidents': 'incidentes', 'Include any special requirements such as equipment which they need to bring.': 'Include any special requirements such as equipment which they need to bring.', 'Incoming': 'Entrada', 'Incoming Shipment canceled': 'Chegada da encomenda cancelada', 'Incoming Shipment updated': 'Chegada de encomenda actualizada.', 'Incomplete': 'Incompleto', 'Individuals': 'Individuais', 'Industrial': 'Industrial', 'Industrial Crime': 'Crime Industrial', 'Industry Fire': 'Indústria Fogo', 'Infant (0-1)': 'Criança (0-1)', 'Infectious Disease': 'Doença INFECCIOSA', 'Infectious Disease (Hazardous Material)': 'Doenças infecciosas (Material perigoso)', 'Infectious Diseases': 'Doenças infecciosas', 'Infestation': 'Infestação', 'Informal Leader': 'Líder Informal', 'Informal camp': 'Acampamento Informal', 'Information gaps': 'problemas de informação', 'Infusion catheters available': 'Cateteres de infusão disponível', 'Infusion catheters need per 24h': 'Cateteres infusão necessário por 24 H', 'Infusion catheters needed per 24h': 'Cateteres infusão necessário por H', 'Infusions available': 'Infusões disponíveis', 'Infusions needed per 24h': 'Infusões necessário por 24H', 'Inspected': 'Inspecionado', 'Inspection Date': 'Data de Inspeção', 'Inspection date and time': 'Data e hora de inspeção', 'Inspection time': 'Hora da inspeção', 'Inspector ID': 'ID do Inspetor', 'Instant Porridge': 'Mingau Instantâneo', "Instead of automatically syncing from other peers over the network, you can also sync from files, which is necessary where there's no network. You can use this page to import sync data from files and also export data to sync files. Click the link on the right to go to this page.": 'Em vez de sincronizar automaticamente com outros pares pela rede, voce também pode sincronizar com arquivos, o que é necessário quando não há rede. Você pode utilizar esta página para importar dados de sincronização de arquivos e também exportar dados para arquivos de Sincronização. Clique no link à direita para ir para esta página.', 'Institution': 'Instituição', 'Insufficient': 'insuficiente', 'Insufficient privileges': 'Insufficient privileges', 'Insufficient vars: Need module, resource, jresource, instance': 'Variaveis insuficientes: necessario modulo, recurso, jrecurso, instância', 'Insurance Renewal Due': 'Insurance Renewal Due', 'Intake Items': 'Itens de admissão', 'Intergovernmental Organization': 'Organização Intergovernamental', 'Interior walls, partitions': 'Do Interior das paredes, partições', 'Internal State': 'Estado Interno', 'International NGO': 'ONG internacional', 'International Organization': 'Organização Internacional', 'Interview taking place at': 'Entrevista em', 'Invalid': 'Inválido', 'Invalid Query': 'Consulta inválida', 'Invalid email': 'Invalid email', 'Invalid phone number': 'Invalid phone number', 'Invalid phone number!': 'Invalid phone number!', 'Invalid request!': 'Pedido inválido!', 'Invalid ticket': 'Bilhete Inválido', 'Inventories': 'Inventários.', 'Inventory': 'Inventário', 'Inventory Item': 'Item do inventário', 'Inventory Item Details': 'Detalhes do Item de inventário', 'Inventory Item added': 'Item incluído no inventário', 'Inventory Item deleted': 'Item do inventário excluído', 'Inventory Item updated': 'Item de Inventário atualizado', 'Inventory Items': 'Itens do Inventário', 'Inventory Items Available for Request Item': 'Itens de inventário disponíveis para Pedir um Item', 'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.': 'Itens de invenrário incluem ambos suprimentos consumíveis & aqueles que se transformarão em Ativos no seu destino.', 'Inventory Management': 'Gerenciamento de Inventário', 'Inventory Stock Position': 'Inventory Stock Position', 'Inventory functionality is available for:': 'Inventário de funcionalidades esta disponível para:', 'Inventory of Effects': 'Inventário de Efeitos', 'Is editing level L%d locations allowed?': 'É permitido editar o nível dos locais L%d?', 'Is it safe to collect water?': 'É seguro coletar água?', 'Is this a strict hierarchy?': 'Esta é uma hierarquia rigorosa?', 'Issuing Authority': 'Autoridade emissora', 'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'Ele captura não apenas os locais onde elas estão ativas, mas também captura informações sobre o conjunto de projetos que está fornecendo em cada região.', 'Italian': 'Italian', 'Item': 'Item', 'Item Added to Shipment': 'Item Incluído para Embarque', 'Item Catalog Details': 'Detalhes do item do catálogo', 'Item Categories': 'Categorias do Item', 'Item Category': 'Categoria do Item', 'Item Category Details': 'Detalhes da categoria de item', 'Item Category added': 'Categoria de item incluída', 'Item Category deleted': 'Categoria de item excluída', 'Item Category updated': 'Atualização da categoria de item', 'Item Details': 'Detalhes do item', 'Item Pack Details': 'Detalhes do pacote de itens', 'Item Pack added': 'Pacote de itens', 'Item Pack deleted': 'Pacote de itens excluído', 'Item Pack updated': 'Itens de Pacote atualizados', 'Item Packs': 'Item de Pacotes', 'Item added': 'Item incluído', 'Item added to Inventory': 'Itens adicionados ao Inventário', 'Item added to shipment': 'Item incluído para embarque', 'Item already in Bundle!': 'Item já no pacote configurável!', 'Item already in Kit!': 'Item já no Kit!', 'Item already in budget!': 'Item já no Orçamento!', 'Item deleted': 'Item Excluído', 'Item removed from Inventory': 'Item removido do Inventário', 'Item updated': 'Item atualizado', 'Items': 'Itens', 'Items in Category can be Assets': 'itens na categoria podem ser ativos', 'Japanese': 'japonês', 'Jerry can': 'Jerry pode', 'Jew': 'Judeu', 'Job Market': 'Mercado de trabalho', 'Job Role': 'Função de trabalho', 'Job Role Catalog': 'Catalogo de Funçao de trabalho', 'Job Role Details': 'Detalhes da Função', 'Job Role added': 'funçao de trabalho inclusa', 'Job Role deleted': 'Funçao de trabalho excluida', 'Job Role updated': 'Função actualizada', 'Job Roles': 'Funções', 'Job Title': 'Título do Cargo', 'Jobs': 'Tarefas', 'Journal': 'Diário', 'Journal Entry Details': 'Detalhes da Entrada de Diário', 'Journal entry added': 'Entrada de diário incluída', 'Journal entry deleted': 'Entrada de diário removida', 'Journal entry updated': 'Entrada de diário atualizado', 'Key': 'Tecla', 'Key Details': 'Detalhes da Chave', 'Key added': 'Chave adicionada', 'Key deleted': 'Chave removida', 'Key updated': 'Chave actualizada', 'Keys': 'Teclas', 'Kit': 'kit', 'Kit Contents': 'Conteúdo Kit', 'Kit Details': 'Detalhes do Kit', 'Kit Updated': 'Kit de Atualização', 'Kit added': 'Pacote adicionado', 'Kit deleted': 'Kit excluído', 'Kit updated': 'Kit de atualização', 'Kits': 'Kits', 'Known Identities': 'Identidades conhecido', 'Known incidents of violence against women/girls': 'Incidentes de violência conhecidos contra mulheres/garotas', 'Known incidents of violence since disaster': 'Incidentes de violência conhecidos desde o desastre', 'Korean': 'Korean', 'LICENSE': 'LICENÇA', 'Lack of material': 'Falta de material', 'Lack of school uniform': 'Falta de uniforme escolar', 'Lack of supplies at school': 'Falta de suprimentos na escola', 'Lack of transport to school': 'Falta de transporte escolar', 'Lactating women': 'Mulheres lactantes', 'Lahar': 'Lahar', 'Landslide': 'Deslizamento', 'Language': 'Linguagem', 'Last Name': 'sobrenome', 'Last known location': 'Último local conhecido', 'Last name': 'Last name', 'Last synchronization time': 'Horário da última sincronização', 'Last updated': 'Última atualização', 'Last updated ': 'Last updated ', 'Last updated by': 'Última atualização por', 'Last updated on': 'Última Atualização em', 'Latitude': 'Latitude', 'Latitude & Longitude': 'Latitude & Longitude', 'Latitude is North-South (Up-Down).': 'Latitude é sentido norte-sul (emcima-embaixo).', 'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Latitude é zero na linha do Equador, positiva no hemisfério norte e negativa no hemisfério sul.', 'Latitude of Map Center': 'Latitude DO MAPA Centro', 'Latitude of far northern end of the region of interest.': 'Latitude do extremo Norte longe do Região de interesse.', 'Latitude of far southern end of the region of interest.': 'Latitude da extremidade sul longe do Região de interesse.', 'Latitude should be between': 'Latitude deve estar entre', 'Latrines': 'Privadas', 'Law enforcement, military, homeland and local/private security': 'Execução da lei militar, interna e segurança local/privada', 'Layer': 'Camada', 'Layer Details': 'Detalhes de Camada', 'Layer ID': 'Layer ID', 'Layer Name': 'Layer Name', 'Layer Type': 'Layer Type', 'Layer added': 'Camada incluída', 'Layer deleted': 'Camada excluída', 'Layer has been Disabled': 'Layer has been Disabled', 'Layer has been Enabled': 'Layer has been Enabled', 'Layer updated': 'Camada atualizada', 'Layers': 'Camadas', 'Layers updated': 'Camadas atualizadas', 'Layout': 'Modelo', 'Leader': 'guia', 'Leave blank to request an unskilled person': 'Leave blank to request an unskilled person', 'Legend Format': 'Formato da Legenda', 'Length (m)': 'Comprimento (m)', 'Level': 'Nível', 'Level 1': 'Nível 1', 'Level 1 Assessment Details': 'Detalhes da Avaliação Nível 1', 'Level 1 Assessment added': 'Avaliação Nível 1 incluído', 'Level 1 Assessment deleted': 'Avaliação Nível 1 excluído', 'Level 1 Assessment updated': 'Avaliação Nível 1 atualizada', 'Level 1 Assessments': 'Avaliações Nível 1', 'Level 2': 'nível 2', 'Level 2 Assessment Details': 'Nível 2 de avaliação Detalhado', 'Level 2 Assessment added': 'Nível 2 avaliação incluído', 'Level 2 Assessment deleted': 'Nível 2 de avaliação excluído', 'Level 2 Assessment updated': 'Nível 2 de avaliação atualizada', 'Level 2 Assessments': 'Nível 2 de Avaliações', 'Level 2 or detailed engineering evaluation recommended': 'Nível 2 ou engenharia detalhada de avaliação recomendado', "Level is higher than parent's": 'Nível superior ao dos pais', 'Library support not available for OpenID': 'Apoio de biblioteca não está disponível para OpenID', 'License Number': 'License Number', 'License Plate': 'License Plate', 'LineString': 'cadeia-de-linhas', 'List': 'Listar', 'List / Add Baseline Types': 'Lista / Incluir Linha de Tipos', 'List / Add Impact Types': 'Lista / Incluir Tipos de Impacto', 'List / Add Services': 'Lista / Incluir Serviços', 'List / Add Types': 'Lista / Incluir Tipos', 'List Activities': 'listar atividades', 'List All': 'Mostrar Tudo', 'List All Assets': 'Lista todos os ativos', 'List All Catalog Items': 'Lista todos os Itens Do Catálogo', 'List All Commitments': 'Lista todos os compromissos', 'List All Entries': 'Listar todas as entradas', 'List All Item Categories': 'Lista todos os itens Categorias', 'List All Memberships': 'Listar Todas As Associações', 'List All Received Shipments': 'Lista todas as transferências Recebidas', 'List All Records': 'Lista todos os registros', 'List All Reports': 'Listar todos os Relatórios', 'List All Requested Items': 'Lista Todos Os itens solicitados', 'List All Requested Skills': 'List All Requested Skills', 'List All Requests': 'Lista Todos Os Pedidos', 'List All Sent Shipments': 'Listar todos os embarques enviados', 'List All Vehicles': 'List All Vehicles', 'List Alternative Items': 'Listar Itens Alternativos', 'List Assessment Summaries': 'Listar Resumos das Avaliações', 'List Assessments': 'Listar as Avaliações', 'List Asset Assignments': 'Listar Atribuições de Ativos', 'List Assets': 'Listar Ativos', 'List Availability': 'Listar Disponibilidade', 'List Baseline Types': 'Lista de Tipos De Linha', 'List Baselines': 'Lista de Linhas', 'List Brands': 'Lista de Marcas', 'List Budgets': 'Listar Orçamentos', 'List Bundles': 'Listar Pacotes', 'List Camp Services': 'Listar Serviços de Acampamento', 'List Camp Types': 'Listar Tipos de Acampamentos', 'List Camps': 'Listar Acampamentos', 'List Catalog Items': 'Lista de Itens Do Catálogo', 'List Catalogs': 'Listar catálogos', 'List Certificates': 'Listar certificados', 'List Certifications': 'Listar certificações', 'List Checklists': 'Lista Listas de Verificação.', 'List Cluster Subsectors': 'Lista Subsetores de Cluster', 'List Clusters': 'Lista Clusters', 'List Commitment Items': 'Lista Itens de Compromisso', 'List Commitments': 'Lista Compromissos', 'List Committed People': 'List Committed People', 'List Competencies': 'Listar competencias', 'List Competency Ratings': 'Listar classificações de competencias', 'List Conflicts': 'Lista Conflitos', 'List Contact Information': 'Listar informações do contato', 'List Contacts': 'Listar contatos', 'List Course Certificates': 'Listar certificados de cursos', 'List Courses': 'Listar Cursos', 'List Credentials': 'Listar credenciais', 'List Current': 'Lista Atual', 'List Documents': 'Listar documentos', 'List Donors': 'Listar doadores', 'List Events': 'Lista de Eventos', 'List Facilities': 'Lista de Facilidades', 'List Feature Classes': 'Listar Classes De Recursos', 'List Feature Layers': 'LISTAr Camadas DE RECURSOS', 'List Flood Reports': 'Listar Relatórios de Inundações', 'List GPS data': 'List GPS data', 'List Groups': 'Listar grupos', 'List Groups/View Members': 'Listar Grupos/visualizar membros', 'List Homes': 'List Homes', 'List Hospitals': 'Listar de Hospitais', 'List Human Resources': 'Lista de Recursos Humanos', 'List Identities': 'Lista de Identidades', 'List Images': 'Lista de Imagens', 'List Impact Assessments': 'Lista de Avaliações De Impacto', 'List Impact Types': 'Lista de Tipos De Impacto', 'List Impacts': 'Lista de impactos', 'List Import Files': 'List Import Files', 'List Incident Reports': 'Lista de relatórios de incidentes', 'List Inventory Items': 'Listar ítens de inventário', 'List Item Categories': 'Listar categorias de ítens', 'List Item Packs': 'Lista pacotes de itens', 'List Items': 'Listar itens', 'List Items in Inventory': 'Lista de Itens no inventário', 'List Job Roles': 'Listar cargos', 'List Keys': 'Listar Chaves', 'List Kits': 'LISTAR Kits', 'List Layers': 'Listar Camadas', 'List Level 1 Assessments': 'Listar avaliações nível 1', 'List Level 1 assessments': 'Listar avaliação nível 1', 'List Level 2 Assessments': 'Listar avaliações nível 2', 'List Level 2 assessments': 'Listar avaliações nível 2', 'List Locations': 'Listar Localizações', 'List Log Entries': 'Listar as entradas de log', 'List Map Configurations': 'Listar configurações de mapa', 'List Markers': 'Listar marcadores', 'List Members': 'Lista de membros', 'List Memberships': 'Lista de associados', 'List Messages': 'Listar Mensagens', 'List Missing Persons': 'Lista de pessoas desaparecidas', 'List Missions': 'Listar Missões', 'List Need Types': 'Listar tipos de necessidades', 'List Needs': 'Lista de Necessidades', 'List Notes': 'Lista de Notas', 'List Offices': 'Lista de Escritórios', 'List Organizations': 'Listar Organizações', 'List Patients': 'List Patients', 'List Peers': 'LISTA DE PARES', 'List Personal Effects': 'Lista de objetos pessoais', 'List Persons': 'LISTA DE PESSOAS', 'List Photos': 'Lista de Fotos', 'List Population Statistics': 'Lista das Estatisticas da População', 'List Positions': 'Lista de Posições', 'List Problems': 'Lista de Problemas', 'List Projections': 'Lista de Projeções', 'List Projects': 'Listar Projectos', 'List Rapid Assessments': 'Listar Avaliações Rápidas', 'List Received Items': 'Listar Elementos Recebidos', 'List Received Shipments': 'Listar Carga Recebida', 'List Records': 'Listar Registros', 'List Registrations': 'Listar Registrações', 'List Relatives': 'List Relatives', 'List Reports': 'Relatórios de Listas', 'List Request Items': 'Pedido de Itens de lista', 'List Requested Skills': 'List Requested Skills', 'List Requests': 'LISTA DE PEDIDOS', 'List Resources': 'Listar Recursos', 'List Rivers': 'Lista de Rios', 'List Roles': 'Listar Funções', 'List Rooms': 'Listar Salas', 'List Scenarios': 'Listar cenários', 'List Sections': 'lista de Seções', 'List Sectors': 'Lista de Sectores', 'List Sent Items': 'Os itens da lista Enviada', 'List Sent Shipments': 'Embarques lista Enviada', 'List Service Profiles': 'Lista de serviços Perfis', 'List Settings': 'Lista de configurações', 'List Shelter Services': 'Lista de serviços de abrigo', 'List Shelter Types': 'Lista de Tipos De Abrigo', 'List Shelters': 'Lista de Abrigos', 'List Skill Equivalences': 'LISTA DE HABILIDADE Equivalências', 'List Skill Provisions': 'Listar suprimento de habilidades', 'List Skill Types': 'Lista de Tipos De Habilidade', 'List Skills': 'LISTA DE HABILIDADES', 'List Solutions': 'Listar Soluções', 'List Staff': 'Listar Pessoal', 'List Staff Members': 'Listar funcionários', 'List Staff Types': 'Listar Tipos De Equipe', 'List Status': 'Listar Status', 'List Subscriptions': 'Lista de Assinaturas', 'List Subsectors': 'Listar Subsetores', 'List Support Requests': 'Listar Pedidos de Suporte', 'List Survey Answers': 'Listar Respostas de Pesquisa', 'List Survey Questions': 'Listar Perguntas da Pesquisa', 'List Survey Sections': 'Listar Seções da Pesquisa', 'List Survey Series': 'Listar Séries de Pesquisa', 'List Survey Templates': 'Listar Modelos de Pesquisa', 'List Tasks': 'Lista de Tarefas', 'List Teams': 'Lista de Equipes', 'List Themes': 'Lista de Temas', 'List Tickets': 'lista de Bilhetes', 'List Tracks': 'Rastreia lista', 'List Trainings': 'Listar Treinamentos', 'List Units': 'Lista de Unidades', 'List Users': 'Mostrar usuários', 'List Vehicle Details': 'List Vehicle Details', 'List Vehicles': 'List Vehicles', 'List Volunteers': 'Mostrar Voluntários', 'List Warehouses': 'Mostrar Depósitos', 'List all': 'Mostrar tudo', 'List available Scenarios': 'Listar Cenários Disponíveis', 'List of CSV files': 'List of CSV files', 'List of CSV files uploaded': 'List of CSV files uploaded', 'List of Items': 'Lista de Itens', 'List of Missing Persons': 'Lista de pessoas desaparecidas', 'List of Peers': 'Lista de pares', 'List of Reports': 'Lista de Relatórios', 'List of Requests': 'Lista de Pedidos', 'List of Spreadsheets': 'Lista de Folhas de Cálculo', 'List of Spreadsheets uploaded': 'Lista de Folhas de Cálculo transferidas', 'List of Volunteers': 'Lista de Voluntários', 'List of Volunteers for this skill set': 'Lista de Voluntários para este conjunto de competências', 'List of addresses': 'Lista de endereços', 'List unidentified': 'Lista não identificada', 'List/Add': 'Lista/incluir', 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities': 'Lista "quem está fazendo o que & aonde". Permite a agências humanitárias coordenar suas atividades', 'Live Help': 'Ajuda ao vivo', 'Livelihood': 'Subsistência', 'Load Cleaned Data into Database': 'Carregue Informações Claras no Banco de Dados', 'Load Raw File into Grid': 'Carregamento de arquivo bruto na Grid', 'Loading': 'Carregando', 'Local Name': 'Nome local', 'Local Names': 'Nomes locais', 'Location': 'Localização', 'Location 1': 'Local 1', 'Location 2': 'Local 2', 'Location Details': 'Detalhes da Localização', 'Location Hierarchy Level 0 Name': 'Nivel Local de hierarquia 0 nome', 'Location Hierarchy Level 1 Name': 'Nivel local de hierarquia 1 nome', 'Location Hierarchy Level 2 Name': 'Nivel local de hierarquia 2 nome', 'Location Hierarchy Level 3 Name': 'Hierarquia local Nível 3 Nome', 'Location Hierarchy Level 4 Name': 'Hierarquia local Nível 4 Nome', 'Location Hierarchy Level 5 Name': 'Hierarquia local Nível 5 Nome', 'Location added': 'Local incluído', 'Location cannot be converted into a group.': 'Local não pode ser convertido em um grupo.', 'Location deleted': 'Localidade excluída', 'Location details': 'Detalhes do Local', 'Location group cannot be a parent.': 'Localização de grupo não pode ser um pai.', 'Location group cannot have a parent.': 'Localização de grupo não tem um pai.', 'Location groups can be used in the Regions menu.': 'Grupos local pode ser utilizado no menu Regiões.', 'Location groups may be used to filter what is shown on the map and in search results to only entities covered by locations in the group.': 'Grupos locais podem ser utilizados para filtrar o que é mostrado no mapa e nos resultados da procura apenas as entidades locais abrangidas no grupo.', 'Location updated': 'Local atualizado', 'Location:': 'Localização:', 'Location: ': 'Location: ', 'Locations': 'Localizações', 'Locations of this level need to have a parent of level': 'Locais de esse nível precisa ter um pai de nível', 'Lockdown': 'BLOQUEIO', 'Log': 'registro', 'Log Entry Details': 'detalhes da entrada de registro', 'Log entry added': 'Entrada de Log incluída', 'Log entry deleted': 'Entrada de Log Excluída', 'Log entry updated': 'Entrada de Log de atualização', 'Login': 'login', 'Logistics': 'Logística', 'Logistics Management System': 'Sistema de Gestão de Logística', 'Logo': 'Logotipo', 'Logo file %s missing!': 'Arquivo de logotipo %s ausente!', 'Logout': 'Deslogar', 'Long Text': 'Texto Longo', 'Longitude': 'Longitude', 'Longitude is West - East (sideways).': 'Longitude é Oeste - Leste (lateral).', 'Longitude is West-East (sideways).': 'Longitude é leste-oeste (direções).', 'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Longitude é zero no primeiro meridiano (Greenwich Mean Time) e é positivo para o leste, em toda a Europa e Ásia. Longitude é negativo para o Ocidente, no outro lado do Atlântico e nas Américas.', 'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Longitude é zero no primeiro meridiano (por meio de Greenwich, Reino Unido) e é positivo para o leste, em toda a Europa e Ásia. Longitude é negativo para o Ocidente, no outro lado do Atlântico e nas Américas.', 'Longitude of Map Center': 'Longitude do Centro do Mapa', 'Longitude of far eastern end of the region of interest.': 'Longitude longe do Oeste no final da região de interesse.', 'Longitude of far western end of the region of interest.': 'Longitude de oeste longínquo no final da Região de interesse.', 'Longitude should be between': 'Longitude deve estar entre', 'Looting': 'Saques', 'Lost': 'Perdido', 'Lost Password': '<PASSWORD>', 'Low': 'Baixo', 'Magnetic Storm': 'Tempestade magnética', 'Major Damage': 'Grandes danos', 'Major expenses': 'Despesas principais', 'Major outward damage': 'Danos exteriores principais', 'Make Commitment': 'Ter obrigação', 'Make New Commitment': 'Fazer Novo Compromisso', 'Make Request': 'Fazer Pedido', 'Make preparations per the <instruction>': 'Fazer Preparações por', 'Male': 'masculino', 'Manage': 'Gerenciar', 'Manage Events': 'Manage Events', 'Manage Relief Item Catalogue': 'Gerenciar Catálogo de Item de Alívio', 'Manage Users & Roles': 'GERENCIAR Usuários & Funções', 'Manage Vehicles': 'Manage Vehicles', 'Manage Warehouses/Sites': 'GERENCIAR Armazéns/Sites', 'Manage Your Facilities': 'Gerenciar suas instalações', 'Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.': 'Gerenciar pedidos de suprimentos, patrimônio, pessoal ou outros recursos. Corresponde aos estoques onde os suprimentos são solicitados.', 'Manage requests of hospitals for assistance.': 'GERENCIAR Pedidos de hospitais para obter assistência.', 'Manage volunteers by capturing their skills, availability and allocation': 'GERENCIAR voluntários por captura sua capacidade, Alocação e disponibilidade', 'Manager': 'Gerente', 'Managing Office': 'Gerenciando Office', 'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Obrigatório. Em GeoServer, este é o nome Da Camada. No getCapabilities WFS, este é o nome da parte FeatureType após os dois pontos (:).', 'Mandatory. The URL to access the service.': 'Obrigatório. A URL para acessar o serviço.', 'Manual': 'Manual', 'Manual Synchronization': 'Sincronização Manual', 'Many': 'Muitos', 'Map': 'Mapa', 'Map Center Latitude': 'Latitude do Centro do Mapa', 'Map Center Longitude': 'Longitude do centro do mapa', 'Map Configuration': 'Configuração de Mapa', 'Map Configuration Details': 'Detalhes de configuração de mapa', 'Map Configuration added': 'Configuração de mapa incluído', 'Map Configuration deleted': 'Configuração de mapa excluído', 'Map Configuration removed': 'Configuração de mapa removido', 'Map Configuration updated': 'Configuração de mapa atualizada', 'Map Configurations': 'Configuracões de mapa', 'Map Height': 'Altura do Mapa', 'Map Service Catalog': 'Catálogo do serviço de mapas', 'Map Settings': 'Configurações do Mapa', 'Map Viewing Client': 'Cliente de visualização do mapa', 'Map Width': 'Largura do mapa', 'Map Zoom': 'Zoom do mapa', 'Map of Hospitals': 'Mapa de Hospitais', 'MapMaker Hybrid Layer': 'MapMaker Hybrid Layer', 'MapMaker Layer': 'MapMaker Layer', 'Maps': 'Maps', 'Marine Security': 'Segurança da marina', 'Marital Status': 'Estado Civil', 'Marker': 'Marcador', 'Marker Details': 'Detalhes do Marcador', 'Marker added': 'Marcador incluído', 'Marker deleted': 'Marcador removido', 'Marker updated': 'Marcador atualizado', 'Markers': 'Marcadores', 'Master': 'Master', 'Master Message Log': 'Mensagem de Log principal', 'Master Message Log to process incoming reports & requests': 'Log de Mensagem Principal para processar relatórios de entrada e pedidos', 'Match Percentage': 'Porcentagem de correspondência', 'Match Requests': 'Corresponder Pedidos', 'Match percentage indicates the % match between these two records': 'Porcentagem idêntica indica a % idêntica entre estes dois registros.', 'Match?': 'Combina?', 'Matching Catalog Items': 'Catálogo de itens correspondentes', 'Matching Items': 'Itens correspondentes', 'Matching Records': 'Registros de correspondência', 'Matrix of Choices (Multiple Answers)': 'Matrix de Opções (Respostas Múltiplas)', 'Matrix of Choices (Only one answer)': 'Matrix de Opções (Apenas uma resposta)', 'Matrix of Text Fields': 'Matriz de campos de texto', 'Max Persons per Dwelling': 'Máx. Pessoas por Habitação', 'Maximum Location Latitude': 'Latitude máxima local', 'Maximum Location Longitude': 'Longitude máxima local', 'Medical and public health': 'Saúde Médica e Pública', 'Medium': 'Médio', 'Megabytes per Month': 'Megabytes por mês', 'Members': 'membros', 'Membership': 'Membresia', 'Membership Details': 'Detalhes de Associação', 'Membership added': 'Associação incluído', 'Membership deleted': 'Associação Excluída', 'Membership updated': 'Associação ATUALIZADO', 'Memberships': 'Parcelas', 'Message': 'message', 'Message Details': 'deatlhes de mesagens', 'Message Variable': 'Mensagem variável', 'Message added': 'Mensagem incluída', 'Message deleted': 'Mensagem Excluída', 'Message field is required!': 'Campo mensagem é obrigatório!', 'Message updated': 'Mensagem atualizada', 'Message variable': 'Mensagem variável', 'Messages': 'mensagens.', 'Messaging': 'sistema de mensagens', 'Messaging settings updated': 'Configurações de mensagens atualizadas', 'Meteorite': 'Meteorito', 'Meteorological (inc. flood)': 'Meteorológico (inc. Enchente)', 'Method used': 'Método utilizado', 'Middle Name': 'Nome do meio', 'Migrants or ethnic minorities': 'Imigrantes ou minorias étnicas', 'Mileage': 'Mileage', 'Military': 'Militares', 'Minimum Bounding Box': 'Caixa Delimitadora Mínima', 'Minimum Location Latitude': 'Mínimo Latitude de Localidade', 'Minimum Location Longitude': 'Longitude de Localização Mínima', 'Minimum shift time is 6 hours': 'tempo mínimo de Shift é de 6 horas', 'Minor Damage': 'Dano secundário', 'Minor/None': 'Secundária/Nenhum', 'Minorities participating in coping activities': 'Minorias participando em atividades de cópia', 'Minute': 'Minuto', 'Minutes must be a number between 0 and 60': 'Minutos devem ser um número entre 0 e 60', 'Minutes per Month': 'Minutos por Mês', 'Minutes should be a number greater than 0 and less than 60': 'Minutos devem ser um número maior que 0 e menor que 60', 'Miscellaneous': 'Variados', 'Missing': 'Perdido', 'Missing Person': 'Pessoa desaparecida', 'Missing Person Details': 'Detalhes da pessoa perdida', 'Missing Person Registry': 'Faltando Registro da Pessoa', 'Missing Person Reports': 'Relatórios da pessoa desaparecida', 'Missing Persons': 'Pessoas desaparecidas', 'Missing Persons Registry': 'Registro de pessoas desaparecidas', 'Missing Persons Report': 'Relatório de pessoas desaparecidas', 'Missing Report': 'Relatório de desaparecimento', 'Missing Senior Citizen': 'Cidadão sênior desaparecido', 'Missing Vulnerable Person': 'Pessoa vulnerável desaparecida', 'Mission Details': 'Detalhes da Missão', 'Mission Record': 'Registro da Missão', 'Mission added': 'Missão incluída', 'Mission deleted': 'Missão excluída', 'Mission updated': 'Missão atualizada', 'Missions': 'Missões', 'Mobile': 'telefone celular', 'Mobile Basic Assessment': 'Taxação básica móvel', 'Mobile Phone': 'Telefone celular', 'Mode': 'modo', 'Model/Type': 'Modelo/Tipo', 'Modem': 'Modem', 'Modem Settings': 'Configurações do Modem', 'Modem settings updated': 'Configurações de modem atualizadas', 'Moderate': 'moderate', 'Moderator': 'moderator', 'Modify Information on groups and individuals': 'Modificar Informações sobre grupos e pessoas', 'Modifying data in spreadsheet before importing it to the database': 'Modificando dados na planilha antes de importá-los para o banco de dados', 'Module': 'Módulo', 'Module disabled!': 'Módulo desativado!', 'Module provides access to information on current Flood Levels.': 'Módulo fornece acesso a informações na atual Onda níveis.', 'Monday': 'segunda-feira', 'Monthly Cost': 'Custo mensal', 'Monthly Salary': 'Salário mensal', 'Months': 'meses', 'Morgue': 'Morgue', 'Morgue Details': 'Morgue Details', 'Morgue Status': 'Situação do necrotério', 'Morgue Units Available': 'Unidades disponíveis no necrotério', 'Morgues': 'Morgues', 'Mosque': 'Mesquita', 'Motorcycle': 'Motocicleta', 'Moustache': 'Bigode', 'MultiPolygon': 'multipolygon', 'Multiple': 'Múltiplos', 'Multiple Choice (Multiple Answers)': 'Múltipla escolha (Várias Respostas)', 'Multiple Choice (Only One Answer)': 'Múltipla Escolha (Apenas uma resposta)', 'Multiple Matches': 'Múltiplas Correspondências', 'Multiple Text Fields': 'Vários campos de texto', 'Muslim': 'Muçulmano', 'Must a location have a parent location?': 'Um local deve ter uma posição pai?', 'My Current function': 'Minha função Atual', 'My Details': 'My Details', 'My Tasks': 'Minhas tarefas', 'My Volunteering': 'My Volunteering', 'N/A': 'n/d', 'NO': 'no', 'NZSEE Level 1': 'NZSEE Nível 1', 'NZSEE Level 2': 'NZSEE Nível 2', 'Name': 'nome', 'Name and/or ID': 'Nome E/OU ID', 'Name of the file (& optional sub-path) located in static which should be used for the background of the header.': 'O nome do arquivo (& sub OPCIONAL-path) localizado no estáticamente que deve ser utilizado para o segundo plano do Cabeçalho.', 'Name of the file (& optional sub-path) located in static which should be used for the top-left image.': 'Nome do arquivo (e sub-caminho opcional) localizado estático que deveria ser utilizado para a imagem superior esquerda.', 'Name of the file (& optional sub-path) located in views which should be used for footer.': 'Nome do arquivo (e sub-caminho opcional) localizado nas visualizações que deve ser utilizado no rodapé.', 'Name of the person in local language and script (optional).': 'Nome da pessoa no idioma local e script local (opcional).', 'Name or Job Title': 'Nome ou cargo', 'Name, Org and/or ID': 'Nome, organização e/ou ID.', 'Name/Model/Type': 'Nome/Modelo/Tipo', 'Names can be added in multiple languages': 'Nomes podem ser adicionados em múltiplos idiomas', 'National': 'Nacional', 'National ID Card': 'Cartão de ID Nacional', 'National NGO': 'Nacional ONG', 'Nationality': 'Nacionalidade', 'Nationality of the person.': 'Nacionalidade da pessoa.', 'Nautical Accident': 'Acidente Náutico', 'Nautical Hijacking': 'Sequestro Náutico', 'Need Type': 'Precisa de Tipo', 'Need Type Details': 'Tipo precisa de Detalhes', 'Need Type added': 'Precisa de tipo incluído', 'Need Type deleted': 'Precisa de Tipo excluído', 'Need Type updated': 'Tipo de necessidade atualizada', 'Need Types': 'Tipos de necessidade', "Need a 'url' argument!": "Precisa de um argumento ' url!", 'Need added': 'Necessidade incluída', 'Need deleted': 'Necessidade excluída', 'Need to be logged-in to be able to submit assessments': 'Precisa estar conectado ao programa para conseguir submeter avaliações', 'Need to configure Twitter Authentication': 'Precisa configurar a autenticação do Twitter', 'Need to specify a Budget!': 'É necessário especificar um orçamento!', 'Need to specify a Kit!': 'É necessário especificar um Kit!', 'Need to specify a Resource!': 'É necessário especificar um recurso!', 'Need to specify a bundle!': 'É necessário especificar um pacote!', 'Need to specify a group!': 'É necessário especificar um grupo!', 'Need to specify a location to search for.': 'É necessário especificar um local para procurar.', 'Need to specify a role!': 'Será necessário especificar um papel!', 'Need to specify a table!': 'Será necessário especificar uma tabela!', 'Need to specify a user!': 'Será necessário especificar um usuário!', 'Need updated': 'Precisa de atualização', 'Needs': 'necessidades', 'Needs Details': 'detalhes necessarios', 'Needs Maintenance': 'Necessita Manutenção', 'Needs to reduce vulnerability to violence': 'Necessidade de reduzir a vulnerabilidade à violência.', 'Negative Flow Isolation': 'NEGATIVO Fluxo ISOLAMENTO', 'Neighborhood': 'Bairro', 'Neighbouring building hazard': 'Risco de construção vizinhos', 'Neonatal ICU': 'Neonatal ICU', 'Neonatology': 'Neonatologia', 'Network': 'rede', 'Neurology': 'Neurologia', 'New': 'Novo(a)', 'New Assessment reported from': 'Nova Avaliação relatada a partir de', 'New Certificate': 'Novo Certificado', 'New Checklist': 'Nova Verificação', 'New Entry': 'Nova Entrada', 'New Event': 'Novo Evento', 'New Home': 'New Home', 'New Item Category': 'Nova Categoria de Ítem', 'New Job Role': 'Novo Papel', 'New Location': 'Novo Local', 'New Location Group': 'Novo Grupo de Locais', 'New Patient': 'New Patient', 'New Peer': 'Novo Par', 'New Record': 'Novo Registro', 'New Relative': 'New Relative', 'New Request': 'Nova Requisição', 'New Scenario': 'Novo Cenário', 'New Skill': 'Nova Habilidade', 'New Solution Choice': 'Escolha nova solução', 'New Staff Member': 'Novo membro da equipe', 'New Support Request': 'Novo pedido de suporte', 'New Synchronization Peer': 'Novo par de sincronização', 'New Team': 'Nova equipe', 'New Ticket': 'New Ticket', 'New Training Course': 'Novo Curso de Treinamento', 'New Volunteer': 'Novo Voluntário', 'New cases in the past 24h': 'Novos casos nas últimas 24H', 'News': 'Notícias', 'Next': 'Seguinte', 'No': 'no', 'No Activities Found': 'Não há actividades', 'No Activities currently registered in this event': 'No Activities currently registered in this event', 'No Alternative Items currently registered': 'Nenhum item alternativo atualmente registrado', 'No Assessment Summaries currently registered': 'Nenhum Sumário De Avaliação actualmente registrado', 'No Assessments currently registered': 'Nenhuma Avaliação actualmente registrada', 'No Asset Assignments currently registered': 'Nenhum ativo designado encontra-se atualmente registrado', 'No Assets currently registered': 'Sem Ativos registrados atualmente', 'No Assets currently registered in this event': 'Sem ativos atualmente registrados neste evento', 'No Assets currently registered in this scenario': 'Sem ativos atualmente registrados neste cenário', 'No Baseline Types currently registered': 'Nenhum tipo de base line registrado atualmente', 'No Baselines currently registered': 'Nenhuma linha base registrada atualmente', 'No Brands currently registered': 'Sem Marcas atualmente registrado', 'No Budgets currently registered': 'Nenhum Dos Orçamentos registrados atualmente', 'No Bundles currently registered': 'Nenhum pacote atualmente registrado', 'No Camp Services currently registered': 'Nenhum serviço de acampamento atualmente registrado', 'No Camp Types currently registered': 'Nenhum tipo de acampamento atualmente registrado', 'No Camps currently registered': 'Sem Acampamentos atualmente registrados', 'No Catalog Items currently registered': 'Nenhum itens do catálogo registrado atualmente', 'No Catalogs currently registered': 'Nenhum catálogo atualmente registrado', 'No Checklist available': 'Checklist não disponível', 'No Cluster Subsectors currently registered': 'Nenhum sub-setor de cluster registrado atualmente', 'No Clusters currently registered': 'Nenhum Cluster registrado atualmente', 'No Commitment Items currently registered': 'Nenhum Item de Compromisso registrado atualmente', 'No Commitments': 'Sem Compromissos', 'No Credentials currently set': 'Nenhuma credencial atualmente configurada', 'No Details currently registered': 'Nenhum detalhes registrado atualmente', 'No Documents currently attached to this request': 'No Documents currently attached to this request', 'No Documents found': 'Nenhum Documento encontrado', 'No Donors currently registered': 'Sem doadores registrados atualmente', 'No Events currently registered': 'Não há eventos atualmente registrados', 'No Facilities currently registered in this event': 'Não há Recursos atualmente registrado nesse evento', 'No Facilities currently registered in this scenario': 'Não há recursos atualmente registrados neste cenário', 'No Feature Classes currently defined': 'Nenhuma Classe de Componentes atualmente definidos', 'No Feature Layers currently defined': 'Nenhuma Camada de Componentes atualmente definidos', 'No Flood Reports currently registered': 'Nenhum relatório de Inundação atualmente registrado', 'No GPS data currently registered': 'No GPS data currently registered', 'No Groups currently defined': 'Não há Grupos definidos atualmente', 'No Groups currently registered': 'Nenhum Grupo atualmente registrado', 'No Homes currently registered': 'No Homes currently registered', 'No Hospitals currently registered': 'Nenhum hospital atualmente registrado', 'No Human Resources currently registered in this event': 'Nao há recursos humanos atualmente registrados nesse evento', 'No Human Resources currently registered in this scenario': 'Sem recursos humanos atualmente registrados neste cenário', 'No Identification Report Available': 'Nenhum Relatório de Identificação Disponível', 'No Identities currently registered': 'Nenhuma Identidade atualmente registrada', 'No Image': 'Nenhuma Imagem', 'No Images currently registered': 'Nenhuma Imagem atualmente registrada', 'No Impact Types currently registered': 'Nenhum tipo de impacto atualmente registrado', 'No Impacts currently registered': 'Nenhum Impacto atualmente registrado', 'No Import Files currently uploaded': 'No Import Files currently uploaded', 'No Incident Reports currently registered': 'Nenhum relatório de incidente registrado atualmente', 'No Incoming Shipments': 'Nenhum Embarque de Entrada', 'No Inventories currently have suitable alternative items in stock': 'No Inventories currently have suitable alternative items in stock', 'No Inventories currently have this item in stock': 'No Inventories currently have this item in stock', 'No Inventory Items currently registered': 'Nenhum Item de Inventário registrado atualmente', 'No Item Categories currently registered': 'Nenhuma Categoria de Item atualmente registrada', 'No Item Packs currently registered': 'Nenhum Pacote de Itens atualmente registrado', 'No Items currently registered': 'Nenhum item registrado atualmente', 'No Items currently registered in this Inventory': 'Sem itens registrados atualmente neste inventário', 'No Keys currently defined': 'Nenhuma chave definida no momento', 'No Kits currently registered': 'Nenhum kit registrado no momento', 'No Level 1 Assessments currently registered': 'Nenhuma avaliação nível 1 registrada no momento', 'No Level 2 Assessments currently registered': 'Nenhum nível 2 Avaliações atualmente registrado', 'No Locations currently available': 'Locais Não disponíveis atualmente', 'No Locations currently registered': 'Locais Não registrados atualmente', 'No Map Configurations currently defined': 'Nenhuma configuração de Mapa estão atualmente definidos', 'No Map Configurations currently registered in this event': 'Nenhuma configuração de Mapa esta atualmente registrado nesse evento', 'No Map Configurations currently registered in this scenario': 'Nenhuma configuração de Mapa está atualmente registrado neste cenário', 'No Markers currently available': 'Não há marcadores atualmente disponíveis', 'No Match': 'Sem correspondência', 'No Matching Catalog Items': 'Nenhum Item de Catálogo Correspondente', 'No Matching Items': 'Sem itens correspondentes', 'No Matching Records': 'Sem registros correspondentes', 'No Members currently registered': 'Sem membros registrados atualmente', 'No Memberships currently defined': 'Sem Associações definidas atualmente', 'No Memberships currently registered': 'Sem Associações registradas atualmente', 'No Messages currently in Outbox': 'Nenhuma mensagem na Caixa de saída', 'No Need Types currently registered': 'Sem necessidade, Tipos atualmente registrados', 'No Needs currently registered': 'Sem necessidade, atualmente registrado', 'No Offices currently registered': 'Nenhum Escritório registrado atualmente', 'No Offices found!': 'Menhum Escritório localizado!', 'No Organizations currently registered': 'Número de Organizações atualmente registradas', 'No Packs for Item': 'No Packs for Item', 'No Patients currently registered': 'No Patients currently registered', 'No People currently committed': 'No People currently committed', 'No People currently registered in this camp': 'Nenhuma pessoa registrada atualmente neste campo', 'No People currently registered in this shelter': 'Nenhuma pessoa registrada atualmente neste abrigo', 'No Persons currently registered': 'Nenhuma pessoa atualmente registrada', 'No Persons currently reported missing': 'nenhuma pessoa reportada atualmente como perdida', 'No Persons found': 'Nenhuma pessoa localizada', 'No Photos found': 'Nenhuma Foto localizada', 'No Picture': 'Nenhuma imagem', 'No Population Statistics currently registered': 'Nenhuma estatística populacional atualmente registrada', 'No Presence Log Entries currently registered': 'Nenhuma entrada no log Presença atualmente registrado', 'No Problems currently defined': 'Nenhum Problema atualmente definido', 'No Projections currently defined': 'Nenhuma projeção atualmente definida', 'No Projects currently registered': 'Nenhum projeto atualmente registrado', 'No Rapid Assessments currently registered': 'Nenhuma Tributação Rápida atualmente registrada', 'No Ratings for Skill Type': 'No Ratings for Skill Type', 'No Received Items currently registered': 'Nenhum item recebido atualmente registrado', 'No Received Shipments': 'Entregas/Despachos não recebidos', 'No Records currently available': 'Registros atualmente não disponíveis', 'No Relatives currently registered': 'No Relatives currently registered', 'No Request Items currently registered': 'Não há items de Pedidos registados', 'No Requests': 'Não há pedidos', 'No Rivers currently registered': 'Não Rios atualmente registrado', 'No Roles currently defined': 'Nenhumas funções atualmente definidas', 'No Rooms currently registered': 'Nenhuma sala atualmente registrada', 'No Scenarios currently registered': 'Nenhum cenário atualmente registrado', 'No Sections currently registered': 'Sem seções atualmente registradas', 'No Sectors currently registered': 'setores nao atualmente registrados', 'No Sent Items currently registered': 'Nenhum item Enviado atualmente registrado', 'No Sent Shipments': 'Nenhum carregamento enviado', 'No Settings currently defined': 'configuraçoes atualmente nao definida', 'No Shelter Services currently registered': 'nenhum serviço de abrigo atualmente registrado', 'No Shelter Types currently registered': 'Nenhum tipo de abrigo registrado atualmente', 'No Shelters currently registered': 'abrigos atualmente nao registrados', 'No Skills currently requested': 'No Skills currently requested', 'No Solutions currently defined': 'Sem Soluções actualmente definidas', 'No Staff Types currently registered': 'Sem Tipos de Funcionários actualmente registrados', 'No Staff currently registered': 'Sem Funcionários actualmente registrados', 'No Subscription available': 'Nenhuma assinatura disponível', 'No Subsectors currently registered': 'Nenhum sub setor atualmente registrado', 'No Support Requests currently registered': 'Nenhum suporte a pedido atualmente registrado', 'No Survey Answers currently entered.': 'Nenhuma resposta de pesquisa atualmente inscrita.', 'No Survey Answers currently registered': 'Nenhuma resposta a pesquisa atualmente registrada', 'No Survey Questions currently registered': 'Nenhuma pergunta de pesquisa atualmente registrada', 'No Survey Sections currently registered': 'Nenhuma seção de pesquisa atualmente registrada', 'No Survey Series currently registered': 'Nenhuma série de pesquisa atualmente registrada', 'No Survey Template currently registered': 'Nenhum Modelo de Pesquisa atualmente registrado', 'No Tasks currently registered in this event': 'No Tasks currently registered in this event', 'No Tasks currently registered in this scenario': 'No Tasks currently registered in this scenario', 'No Tasks with Location Data': 'Nenhuma tarefa com local de dados', 'No Teams currently registered': 'Nenhuma equipe atualmente registrada', 'No Themes currently defined': 'Nenhum Tema atualmente definido', 'No Tickets currently registered': 'Sem ingressos atualmente registrados', 'No Tracks currently available': 'nenhum rastreamento atualmente disponível', 'No Users currently registered': 'Nenhum Usuário actualmente registrado', 'No Vehicle Details currently defined': 'No Vehicle Details currently defined', 'No Vehicles currently registered': 'No Vehicles currently registered', 'No Volunteers currently registered': 'Nenhum Voluntário actualmente registrado', 'No Warehouses currently registered': 'Nenhum Armazém actualmente registrado', 'No access at all': 'Nenhum acesso', 'No access to this record!': 'Não há acesso a esta entrada!', 'No action recommended': 'Nenhuma acção recomendada', 'No conflicts logged': 'Nenhum conflito registrado', 'No contact information available': 'Nenhuma informações de contato disponível', 'No contact method found': 'No contact method found', 'No contacts currently registered': 'Nenhum contato atualmente registrado', 'No data in this table - cannot create PDF!': 'Nenhum dado nesta tabela- PDF não pode ser criado!', 'No databases in this application': 'Nenhum banco de dados neste aplicativo', 'No dead body reports available': 'Nenhum relatório de óbito disponível', 'No entries found': 'Nenhum artigo encontrado', 'No entries matching the query': 'Nenhuma entrada correspondente a consulta', 'No entry available': 'Nenhuma entrada disponível', 'No forms to the corresponding resource have been downloaded yet.': 'No forms to the corresponding resource have been downloaded yet.', 'No location known for this person': 'Nenhum local conhecido para essa pessoa', 'No locations found for members of this team': 'Locais não localizado para membros deste equipe', 'No log entries matching the query': 'Nenhuma entrada de log correspondente a consulta', 'No match': 'No match', 'No matching records found': 'No matching records found', 'No messages in the system': 'Nenhuma mensagem no sistema', 'No notes available': 'Notas não disponíveis', 'No peers currently registered': 'Não há pares registrados atualmente', 'No pending registrations found': 'Não foram encontrados registros pendentes', 'No pending registrations matching the query': 'Não foram encontrados registros pendentes correspondentes à consulta efetuada', 'No person record found for current user.': 'Nenhum registro de pessoa localizado para o usuário atual.', 'No problem group defined yet': 'Nenhum grupo problema definido ainda', 'No records matching the query': 'Sem registros correspondentes a consulta', 'No report available.': 'Nenhum Relatório disponível.', 'No reports available.': 'Não há relatórios disponíveis.', 'No reports currently available': 'Não há relatórios disponíveis actualmente', 'No requests found': 'Não foram foram encontrados pedidos', 'No resources currently reported': 'Recursos não reportados actualmente', 'No service profile available': 'Nenhum perfil de serviço disponível', 'No skills currently set': 'Não há habilidades atualmente configuradas', 'No staff members currently registered': 'Nenhum membro da equipe atualmente registrado', 'No staff or volunteers currently registered': 'Nenhum funcionário ou voluntário atualmente registrado', 'No status information available': 'Informação não está disponível', 'No synchronization': 'Sem Sincronização', 'No tasks currently assigned': 'No tasks currently assigned', 'No tasks currently registered': 'Nenhuma tarefa atualmente registrada', 'No template found!': 'Nenhum modelo localizado!', 'No units currently registered': 'Nenhuma unidade actualmente registrada', 'No volunteer availability registered': 'Sem disponibilidade de voluntário registrada', 'No volunteers currently registered': 'Nenhum Voluntário actualmente registrado', 'Non-structural Hazards': 'Riscos não-estruturais', 'None': 'Nenhum', 'None (no such record)': 'Nenhum (sem registro )', 'Noodles': 'Macarrão', 'Normal': 'Normal', 'Not Applicable': 'Não se aplica', 'Not Authorised!': 'Não Autorizado!', 'Not Possible': 'Impossível', 'Not Set': 'não configurado', 'Not authorised!': 'Não autorizado!', 'Not installed or incorrectly configured.': 'Não instalado ou Configurado Incorretamente.', 'Note': 'Nota', 'Note Details': 'Detalhes da Nota', 'Note Status': 'Status da Nota', 'Note Type': 'Tipo de nota', 'Note added': 'Nota Incluída', 'Note deleted': 'NOTA Excluída', 'Note that this list only shows active volunteers. To see all people registered in the system, search from this screen instead': 'Observer que essa lista mostra apenas voluntários ativos. Para ver todas as pessoas registradas no sistema, procure a partir deste ecrã em vez de', 'Note updated': 'Nota atualizada', 'Notes': 'Observações', 'Notice to Airmen': 'Aviso ao piloto', 'Number': 'número', 'Number of Columns': 'Número de colunas', 'Number of Patients': 'Número de Pacientes', 'Number of People Required': 'Number of People Required', 'Number of Rows': 'Número de Linhas', 'Number of additional beds of that type expected to become available in this unit within the next 24 hours.': 'Número de camas adicionais de tipo esperado tornar disponível nesta unidade nas próximas 24 horas.', 'Number of alternative places for studying': 'Número de locais alternativos para estudar', 'Number of available/vacant beds of that type in this unit at the time of reporting.': 'Número de camas disponíveis/livre desse tipo nesta unidade no momento do relatório.', 'Number of bodies found': 'Number of bodies found', 'Number of deaths during the past 24 hours.': 'Número de mortes durante as últimas 24 horas.', 'Number of discharged patients during the past 24 hours.': 'Número de pacientes Descarregados durante as últimas 24 horas.', 'Number of doctors': 'Número de médicos', 'Number of in-patients at the time of reporting.': 'Número de pacientes internos na hora do relatório.', 'Number of newly admitted patients during the past 24 hours.': 'Número de pacientes admitidos durante as últimas 24 horas.', 'Number of non-medical staff': 'Número de funcionários não-médico', 'Number of nurses': 'Número de enfermeiras', 'Number of private schools': 'Número de escolas privadas', 'Number of public schools': 'Número de escolas públicas', 'Number of religious schools': 'Número de escolas religiosas', 'Number of residential units': 'Número de unidades residenciais', 'Number of residential units not habitable': 'Unidades de número residencial não habitáveis', 'Number of vacant/available beds in this hospital. Automatically updated from daily reports.': 'Número de leitos vagos/disponíveis nesse hospital. Atualizado automaticamente a partir de relatórios diários.', 'Number of vacant/available units to which victims can be transported immediately.': 'Número de unidades vagas/disponíveis em que vítimas podem ser transportadas imediatamente.', 'Number or Label on the identification tag this person is wearing (if any).': 'Número ou código na etiqueta de identificação que a pessoa está usando (se houver).', 'Number or code used to mark the place of find, e.g. flag code, grid coordinates, site reference number or similar (if available)': 'Número ou código utilizado para marcar o local de localização, por exemplo, código de bandeira, grade de coordenadas, número de referência do site ou similar (se disponível)', 'Number/Percentage of affected population that is Female & Aged 0-5': 'Número/percentagem da população afetada que é uma mulher entre 0 e 5 anos', 'Number/Percentage of affected population that is Female & Aged 13-17': 'Número/percentagem da população afetadas do sexo feminino entre 13 e 17 anos', 'Number/Percentage of affected population that is Female & Aged 18-25': 'Número/percentagem da população afetada que é Mulher com 18-25 anos', 'Number/Percentage of affected population that is Female & Aged 26-60': 'Número/percentagem da população afetada que é Mulher com 26-60 anos', 'Number/Percentage of affected population that is Female & Aged 6-12': 'Número/percentagem da população afetada que é Mulher com 6-12 anos', 'Number/Percentage of affected population that is Female & Aged 61+': 'Número/percentagem da população afetada que é Mulher > 61 anos', 'Number/Percentage of affected population that is Male & Aged 0-5': 'Número/percentagem da população afetada que é Homem com 0-5 anos', 'Number/Percentage of affected population that is Male & Aged 13-17': 'Número/percentagem da população afetada que é Homem com 13-17 anos', 'Number/Percentage of affected population that is Male & Aged 18-25': 'Número/percentagem da população afetada que é Homem com 18-25 anos', 'Number/Percentage of affected population that is Male & Aged 26-60': 'Número/percentagem de população afetada que é do sexo masculino & Idade 26-60', 'Number/Percentage of affected population that is Male & Aged 6-12': 'Número/percentagem de população afectada que é do sexo masculino & Idade 6-12', 'Number/Percentage of affected population that is Male & Aged 61+': 'Número/percentagem da população afetada que é do sexo masculino & Idade 61+', 'Nursery Beds': 'Camas de berçario', 'Nutrition': 'Nutrição', 'Nutrition problems': 'Problemas nutricionais', 'OK': 'OK', 'OR Reason': 'Ou Razão', 'OR Status': 'Ou Status', 'OR Status Reason': 'Ou razão do status', 'OR a site OR a location': 'OU um site OU um local', 'Observer': 'observador', 'Obsolete': 'Obsoleto', 'Obstetrics/Gynecology': 'Obstetrícia/Ginecologia', 'Office': 'escritório', 'Office Address': 'Endereço do escritório', 'Office Details': 'Detalhes do Escritório.', 'Office Phone': 'Telefone do escritório', 'Office added': 'Escritório', 'Office deleted': 'Escritório excluído', 'Office updated': 'Escritório atualizado', 'Offices': 'Escritórios', 'Offices & Warehouses': 'Escritórios & Armazéns', 'Offline Sync': 'Sincronização desconectada.', 'Offline Sync (from USB/File Backup)': 'Off-line (Sync a partir do USB/arquivo de Backup)', 'Older people as primary caregivers of children': 'Pessoas mais velhas como responsáveis primárias de crianças', 'Older people in care homes': 'Pessoas mais velhas em casas de cuidados', 'Older people participating in coping activities': 'Pessoas mais antigos participantes em lidar atividades', 'Older person (>60 yrs)': 'Idosos (>60 anos)', 'On by default?': 'Por padrão?', 'On by default? (only applicable to Overlays)': 'Por padrão? (apenas aplicável para Sobreposições)', 'One Time Cost': 'Custo Único', 'One time cost': 'Custo único', 'One-time': 'Único', 'One-time costs': 'Custos únicos', 'Oops! Something went wrong...': 'Oops! Algo deu errado...', 'Oops! something went wrong on our side.': 'Oops! algo deu errado do nosso lado.', 'Opacity (1 for opaque, 0 for fully-transparent)': 'Opacidade (1 para opaco, 0 para totalmente transparente)', 'Open': 'Abrir', 'Open area': 'Abrir área', 'Open recent': 'Abrir recente', 'Operating Rooms': 'Salas operacionais', 'Optional': 'Optional', 'Optional Subject to put into Email - can be used as a Security Password by the service provider': 'Optional Subject to put into Email - can be used as a Security Password by the service provider', 'Optional link to an Incident which this Assessment was triggered by.': 'Link opcional para um incidente que esta avaliação foi desencadeada por.', 'Optional selection of a MapServer map.': 'Optional selection of a MapServer map.', 'Optional selection of a background color.': 'Optional selection of a background color.', 'Optional selection of an alternate style.': 'Optional selection of an alternate style.', 'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.': 'opcional Se você desejar apresenta o estilo com base nos valores de um atributo, Selecione o atributo a ser utilizado aqui.', 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).': 'opcional Em GeoServer, esta é a área de trabalho Namespace URI (não o nome!). Dentro do getCapabilities WFS, este é parte do nome FeatureType antes dos dois pontos (:).', 'Optional. In GeoServer, this is the Workspace Namespace URI. Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).': 'optional. Em GeoServer, este é o espaço de Nomes URI. No getCapabilities WFS, este é o nome da parte FeatureType antes de os dois pontos (:).', 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.': 'opcional O nome de um elemento cujo conteúdo deve ser uma URL de um arquivo de imagem para Popups.', 'Optional. The name of an element whose contents should be put into Popups.': 'opcional O nome de um elemento cujo conteúdo deve ser adicionado em Popups.', "Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.": "opcional O nome da coluna de geometria. Em PostGIS padroniza para 'the_geom'.", 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.': 'opcional O nome do esquema. Em Geoserver isto tem o formato http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.', 'Options': 'opções', 'Organisation': 'Organização', 'Organization': 'Organização', 'Organization Details': 'Detalhes da Organização', 'Organization Registry': 'Registro de Organização', 'Organization added': 'Organização incluída', 'Organization deleted': 'Organização excluída', 'Organization updated': 'Organização atualizada', 'Organizations': 'Organizações', 'Origin': 'Origem', 'Origin of the separated children': 'Origem das crianças separadas', 'Other': 'outro', 'Other (describe)': 'Outros (descreva)', 'Other (specify)': 'Outros motivos (especifique)', 'Other Evidence': 'outras evidencias', 'Other Faucet/Piped Water': 'Outras Torneiras /Agua Encanada', 'Other Isolation': 'Outro Isolamento', 'Other Name': 'outro nome', 'Other activities of boys 13-17yrs': 'Outras atividades de garotos 13-17anos', 'Other activities of boys 13-17yrs before disaster': 'Outras atividades de garotos 17-13anos antes do desastre', 'Other activities of boys <12yrs': 'Outras atividades de garotos <12 anos', 'Other activities of boys <12yrs before disaster': 'Outras atividades de garotos <12anos antes do desastre', 'Other activities of girls 13-17yrs': 'Outras atividades de meninas 13-17anos', 'Other activities of girls 13-17yrs before disaster': 'Outras atividades de meninas 13-17anos antes do desastre', 'Other activities of girls<12yrs': 'Outras atividades de garotas<12anos', 'Other activities of girls<12yrs before disaster': 'Outras atividades de garotas<12anos antes do desastre', 'Other alternative infant nutrition in use': 'Nutrição infantil alternativa em uso', 'Other alternative places for study': 'Outros locais alternativos para estudo', 'Other assistance needed': 'Outra assistência necessária', 'Other assistance, Rank': 'Outra assistência, Número', 'Other current health problems, adults': 'Outros problemas actuais de saúde, adultos', 'Other current health problems, children': 'Outros problemas actuais de saúde, crianças', 'Other events': 'outros eventos', 'Other factors affecting school attendance': 'Outros fatores que afetam a frequencia escolar', 'Other major expenses': 'outras despesas importantes', 'Other non-food items': 'Outros itens não alimentícios', 'Other recommendations': 'Outras recomendações', 'Other residential': 'Outros residentes', 'Other school assistance received': 'Assistência de outra escola recebida', 'Other school assistance, details': 'Assistência de outra escola, detalhes', 'Other school assistance, source': 'Assistência de outra escola, origem', 'Other settings can only be set by editing a file on the server': 'Outras configurações só podem ser definidas editando um arquivo no servidor', 'Other side dishes in stock': 'Pratos outro lado em ações', 'Other types of water storage containers': 'Outros tipos de recipientes de armazenamento de água', 'Other ways to obtain food': 'Outras maneiras de obter alimentos', 'Outbound Mail settings are configured in models/000_config.py.': 'Definições de correio de saída são configurados em modelos/000_config..py', 'Outbox': 'Caixa de Saída', 'Outgoing SMS Handler': 'Saída do Manipulador SMS', 'Outgoing SMS handler': 'Manipulador de SMS de saída', 'Overall Hazards': 'Riscos gerais', 'Overhead falling hazard': 'Risco de queda sobrecarga', 'Overland Flow Flood': 'Por via terrestre Fluxo de Enchente', 'Owned Resources': 'Recursos Próprios', 'PAHO UID': 'OPS UID', 'PDAM': 'PDAM', 'PDF File': 'PDF File', 'PIN': 'alfinete', 'PIN number': 'Número do pino', 'PIN number ': 'PIN number ', 'PL Women': 'Mulheres PL', 'Pack': 'Pacote', 'Packs': 'Pacotes', 'Page': 'Page', 'Parameters': 'Parâmetros de Monitoramento', 'Parapets, ornamentation': 'Passarelas, ornamentação', 'Parent': 'parent', 'Parent Office': 'Escritório Principal', "Parent level should be higher than this record's level. Parent level is": 'Nível dos pais deve ser maior que o nível do registro. Nível do Pai é', 'Parent needs to be of the correct level': 'Pai precisa ser do nível correto', 'Parent needs to be set': 'Principal precisa ser configurado', 'Parent needs to be set for locations of level': 'Principal precisa ser configurado para locais de nível', 'Parents/Caregivers missing children': 'Pais/cuidadores de crianças desaparecidas', 'Parking Area': 'Parking Area', 'Partial': 'Parcial', 'Participant': 'Participante', 'Pashto': '<PASSWORD>', 'Pass': '<PASSWORD>', 'Passport': 'passaporte', 'Password': '<PASSWORD>', "Password fields don't match": 'Os campos de senha não são iguais.', 'Path': 'Caminho', 'Pathology': 'Patologia', 'Patient': 'Patient', 'Patient Details': 'Patient Details', 'Patient Tracking': 'Patient Tracking', 'Patient added': 'Patient added', 'Patient deleted': 'Patient deleted', 'Patient updated': 'Patient updated', 'Patients': 'Pacientes', 'Pediatric ICU': 'UTI Pediatrica', 'Pediatric Psychiatric': 'Psiquiátrico Pediátra', 'Pediatrics': 'Pediatria', 'Peer': 'Membro', 'Peer Details': 'Detalhes do Membro', 'Peer Registration': 'Registro de par', 'Peer Registration Details': 'Detalhes de Registro do Par', 'Peer Registration Request': 'Requerido Registro do Par', 'Peer Type': 'Por Tipo', 'Peer UID': 'Por UID', 'Peer added': 'Membro adicionado', 'Peer deleted': 'Membro excluído', 'Peer not allowed to push': 'Peer não permitido para envio', 'Peer registration request added': 'Registro Requerido do Par adicionado', 'Peer registration request deleted': 'Registro requerido do par excluído', 'Peer registration request updated': 'Registro requerido do par atualizado', 'Peer updated': 'PAR ATUALIZADO', 'Peers': 'Pares', 'Pending': 'pendente', 'Pending Requests': 'PEDIDOS PENDENTES', 'People': 'pessoas', 'People Needing Food': 'Pessoas precisando de alimento', 'People Needing Shelter': 'Pessoas precisando de abrigo', 'People Needing Water': 'Pessoas precisando de água', 'People Trapped': 'Pessoas presas', 'Performance Rating': 'Classificação da Performance', 'Person': 'pessoa', 'Person 1': 'Pessoa 1', 'Person 1, Person 2 are the potentially duplicate records': 'Pessoa 1, Pessoa 2 são os registros potencialmente duplicados', 'Person 2': 'Pessoa 2', 'Person De-duplicator': 'Anti-duplicador de Pessoas', 'Person Details': 'Detalhes Pessoais', 'Person Finder': 'Buscador de pessoas', 'Person Registry': 'Registro De Pessoa', 'Person added': 'Pessoa Incluída', 'Person added to Commitment': 'Person added to Commitment', 'Person deleted': 'Pessoa removida', 'Person details updated': 'Detalhes pessoais actualizados', 'Person interviewed': 'Pessoa entrevistada', 'Person missing': 'Pessoa perdida', 'Person must be specified!': 'Person must be specified!', 'Person removed from Commitment': 'Person removed from Commitment', 'Person reporting': 'Pessoa relatando', 'Person who has actually seen the person/group.': 'Pessoa que tenha realmente visto a pessoa/Grupo.', 'Person/Group': 'Pessoa/Grupo', 'Personal': 'Pessoal', 'Personal Data': 'Dados pessoais', 'Personal Effects': 'Efeitos pessoal', 'Personal Effects Details': 'Detalhes dos Efeitos Pessoais', 'Personal Map': 'Mapa De Pessoal', 'Personal Profile': 'Perfil pessoal', 'Personal impact of disaster': 'Impacto de desastre pessoal', 'Persons': 'Pessoas', 'Persons in institutions': 'Pessoas em instituições', 'Persons with disability (mental)': 'Pessoas com deficiência (mental)', 'Persons with disability (physical)': 'Pessoas com deficiência (física)', 'Phone': 'telefone', 'Phone 1': 'Telefone 1', 'Phone 2': 'Telefone 2', "Phone number to donate to this organization's relief efforts.": 'Número de telefone para doar ao serviço de assistência social desta organização', 'Phone/Business': 'Telefone comercial', 'Phone/Emergency': 'Telefone de emergência', 'Phone/Exchange': 'Telefone/Exchange', 'Phone/Exchange (Switchboard)': 'Telefone/Câmbio (Central)', 'Photo': 'foto', 'Photo Details': 'Foto com detalhes', 'Photo Taken?': 'Foto tomada?', 'Photo added': 'Foto adicionada (ou incluída)', 'Photo deleted': 'Foto deletada (apagada, excluída em definitivo)', 'Photo updated': 'Foto ATUALIZADA', 'Photograph': 'Fotografia ou Arte Fotográfica', 'Photos': 'fotos, imagens fotográficas', 'Physical Description': 'Descrição física', 'Physical Safety': 'Segurança Física', 'Picture': 'Imagem', 'Picture upload and finger print upload facility': 'Fazer upload de imagem e impressão dedo upload facility', 'Place': 'Local', 'Place of Recovery': 'Local de recuperação', 'Places for defecation': 'Locais para a defecação', 'Places the children have been sent to': 'Lugares que as crianças foram enviadas para', 'Planner': 'Planejador', 'Playing': 'Reproduzindo', "Please come back after sometime if that doesn't help.": 'Por favor, volte após algum tempo se isso não ajuda.', 'Please correct all errors.': 'Por favor CORRIJA todos os erros.', 'Please enter a First Name': 'Por favor insira um primeiro nome', 'Please enter a first name': 'Por favor insira um primeiro nome', 'Please enter a number only': 'Please enter a number only', 'Please enter a person': 'Insira uma pessoa', 'Please enter a site OR a location': 'Por favor digite um site ou um local', 'Please enter a valid email address': 'Please enter a valid email address', 'Please enter the first few letters of the Person/Group for the autocomplete.': 'Por favor Digite as primeiras letras do Pessoa/Grupo para o AutoCompletar.', 'Please enter the recipient': 'Por favor Digite o destinatário', 'Please fill this!': 'Por favor preencha isso!', 'Please give an estimated figure about how many bodies have been found.': 'Please give an estimated figure about how many bodies have been found.', 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.': 'Por favor Forneça a URL da página que você está fazendo referência à, uma descrição do que você esperava que acontecesse & O que realmente aconteceu.', 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened. If a ticket was issued then please provide the Ticket ID.': 'Por favor Forneça a URL da página que você está fazendo referência à, uma descrição do que você esperava que acontecesse & O que realmente aconteceu. Se um bilhete foi emitido então por favor forneça o ID do bilhete.', 'Please report here where you are:': 'Por favor informe aqui onde você está:', 'Please select': 'Por favor Selecione', 'Please select another level': 'Por favor selecione outro nível', 'Please sign-up with your Cell Phone as this allows us to send you Text messages. Please include full Area code.': 'Por favor inscrever-se com seu celular como isso nos permite lhe enviar mensagens de texto. Por favor inclua código de Área total.', 'Please specify any problems and obstacles with the proper handling of the disease, in detail (in numbers, where appropriate). You may also add suggestions the situation could be improved.': 'Por favor especifique quaisquer problemas e obstáculos com a manipulação correcta da doença, em detalhes (em números, se for o caso). Pode também dar sugestões - a situação pode ser melhorada.', 'Please use this field to record any additional information, including a history of the record if it is updated.': 'Por favor utilize esse campo para registrar quaisquer informações adicionais, incluindo um histórico do registro se ele estiver sendo atualizado.', 'Please use this field to record any additional information, including any Special Needs.': 'Por favor utilize esse campo para registrar quaisquer informações adicionais, incluindo quaisquer necessidades especiais.', 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.': 'Por favor utilize esse campo para registrar quaisquer informações adicionais, como IDs de instância Ushahidi. Incluir o histórico do registo se este fôr actualizado.', 'Pledge Support': 'Suporte da promessa', 'Point': 'Ponto', 'Poisoning': 'Envenenamento', 'Poisonous Gas': 'Gás venenoso', 'Police': 'Polícia', 'Pollution and other environmental': 'Poluição ambiental e outras', 'Polygon': 'Polígono', 'Polygon reference of the rating unit': 'Polígono de referência da unidade de classificação', 'Poor': 'Pobre', 'Population': 'População', 'Population Statistic Details': 'População Estatística Detalhes', 'Population Statistic added': 'População Estatística incluída', 'Population Statistic deleted': 'População Estatística excluído', 'Population Statistic updated': 'População De Estatística atualizada', 'Population Statistics': 'Estatísticas De população', 'Population and number of households': 'população e número de residentes', 'Popup Fields': 'Pop-up Campos', 'Popup Label': 'Rótulo do pop-up', 'Porridge': 'mingau', 'Port': 'porta', 'Port Closure': 'Porta Encerramento', 'Portuguese': 'Português', 'Portuguese (Brazil)': 'Português (Brasil)', 'Position': 'Posição', 'Position Catalog': 'Catálogo de posições', 'Position Details': 'detalhamento do cargo', 'Position added': 'Cargo inserido', 'Position deleted': 'Cargo excluído', 'Position updated': 'Posição atualizada', 'Positions': 'cargos', 'Postcode': 'Código Postal', 'Poultry': 'Aves', 'Poultry restocking, Rank': 'Reabastecimento de aves domésticas, posição', 'Pounds': 'Libras', 'Power Failure': 'Falha de Energia', 'Powered by Sahana Eden': 'Desenvolvido pela Sahana Eden', 'Pre-cast connections': 'Conexões-cast pré', 'Preferred Name': 'Nome Preferido', 'Pregnant women': 'Mulheres grávidas', 'Preliminary': 'Preliminar', 'Presence': 'Presença', 'Presence Condition': 'Condição de Presença', 'Presence Log': 'Log de Presença', 'Previous': 'Anterior', 'Primary Name': 'Nome Principal', 'Primary Occupancy': 'Principal Ocupação', 'Priority': 'priority', 'Priority from 1 to 9. 1 is most preferred.': 'Prioridade de 1 a 9. 1 é preferível', 'Private': 'Privado', 'Problem': 'Problema do', 'Problem Administration': 'Gestão de problema', 'Problem Details': 'Detalhes do Problema', 'Problem Group': 'Grupo do Problema', 'Problem Title': 'Título do Problema', 'Problem added': 'Problema incluído', 'Problem connecting to twitter.com - please refresh': 'Problema ao conectar-se ao twitter.com, tente novamente', 'Problem deleted': 'Problema Excluído', 'Problem updated': 'Problema Atualizado', 'Problems': 'Problemas', 'Procedure': 'Procedimento', 'Process Received Shipment': 'Processo recebeu embarque', 'Process Shipment to Send': 'Processar remessa a enviar', 'Profile': 'profile', 'Project': 'projeto', 'Project Details': 'Detalhes do Projeto', 'Project Status': 'Status do Projeto', 'Project Tracking': 'Acompanhamento do Projeto', 'Project added': 'Projeto incluído', 'Project deleted': 'Projeto Excluído', 'Project has no Lat/Lon': 'Projeto não possui Latitude/Longitude', 'Project updated': 'Projeto ATUALIZADO', 'Projection': 'Projeção', 'Projection Details': 'Detalhes da Projeção', 'Projection Type': 'Projection Type', 'Projection added': 'Projeção incluída', 'Projection deleted': 'Projeção excluída', 'Projection updated': 'Projecção atualizada', 'Projections': 'projeções', 'Projects': 'projetos', 'Property reference in the council system': 'Referência de propriedade no sistema do conselho', 'Protected resource': 'Recurso protegido', 'Protection': 'Protecção', 'Provide Metadata for your media files': 'Fornecer Metadados para os seus ficheiros media', 'Provide a password': 'Provide a password', 'Provide an optional sketch of the entire building or damage points. Indicate damage points.': 'Fornecer um retrato opcional de todo o edifício ou áreas danificadas. Pontos danos indicar.', 'Proxy-server': 'Servidor Proxy', 'Psychiatrics/Adult': 'Psiquiatras/Adulto', 'Psychiatrics/Pediatric': 'Psiquiatras/Pediátrica', 'Public': 'Público', 'Public Event': 'Evento público', 'Public and private transportation': 'Transporte Público e Privado', 'Public assembly': 'Assembléia Pública', 'Pull tickets from external feed': 'Pull de bilhetes alimentação externa', 'Punjabi': 'Punjabi', 'Purchase Date': 'Data de aquisição', 'Push tickets to external system': 'BILHETES Push PARA sistema externo', 'Pyroclastic Flow': 'Pyroclastic FLuxo', 'Pyroclastic Surge': 'Pyroclastic Aumento', 'Python Serial module not available within the running Python - this needs installing to activate the Modem': 'Módulo Serial Python não disponíveis no a execução Python-isto tem de instalar para ativar o Modem', 'Quantity': 'Quantidade', 'Quantity Committed': 'Quantidade Comprometida', 'Quantity Fulfilled': 'Quantidade Preenchida', "Quantity in %s's Inventory": 'Quantidade de %s do Inventário', 'Quantity in Transit': 'Quantidade em Trânsito', 'Quarantine': 'Quarentena', 'Queries': 'Buscas', 'Query': 'Busca', 'Queryable?': 'Consultável?', 'RC frame with masonry infill': 'Quadro de RC com aterros de alvenaria', 'RECORD A': 'Registro A', 'RECORD B': 'REGISTRO B', 'Race': 'Corrida', 'Radio': 'Radio', 'Radio Callsign': 'Rádio Chamada', 'Radio Details': 'Radio Details', 'Radiological Hazard': 'Risco Radiológico', 'Radiology': 'Radiologia', 'Railway Accident': 'Acidente Ferroviário', 'Railway Hijacking': 'Sequestro Ferroviário', 'Rain Fall': 'Queda de Chuva', 'Rapid Assessment': 'Avaliação Rápida', 'Rapid Assessment Details': 'Rápida Avaliação Detalhes', 'Rapid Assessment added': 'Rapid Avaliação incluído', 'Rapid Assessment deleted': 'Rápida Avaliação excluído', 'Rapid Assessment updated': 'Rapid avaliação atualizada', 'Rapid Assessments': 'Rapid Avaliações', 'Rapid Assessments & Flexible Impact Assessments': 'Rapid Avaliações & Flexível Impacto Avaliações', 'Rapid Close Lead': 'Fechamento Lead rápido', 'Rapid Data Entry': 'Entrada de dados rápida', 'Rating Scale': 'Escala de avaliação', 'Raw Database access': 'Acesso bruto a Base de dados', 'Read-Only': 'somente para leitura', 'Read-only': 'somente para leitura', 'Receive': 'Receber', 'Receive Items': 'Aceitar itens', 'Receive New Shipment': 'Receber Novos Embarques', 'Receive Shipment': 'Receber carregamento', 'Receive this shipment?': 'Receber esse embarque?', 'Received': 'Recebido', 'Received By': 'Recebido Por', 'Received By Person': 'Recebido Por Pessoa', 'Received Item Details': 'Detalhes do item recebido', 'Received Item deleted': 'Recebido item excluído', 'Received Item updated': 'Item recebido atualizado', 'Received Shipment Details': 'Lista de remessa de mercadorias/produtos', 'Received Shipment canceled': 'Remessa de produtos cancelada', 'Received Shipment canceled and items removed from Inventory': 'Recebido carregamento cancelado e itens removidos do inventário', 'Received Shipment updated': 'Carregamento Recebido Atualizado', 'Received Shipments': 'Carregamento de produtos recebido', 'Receiving and Sending Items': 'Receber e enviar Itens', 'Recipient': 'destinatário', 'Recipients': 'destinatários', 'Recommendations for Repair and Reconstruction or Demolition': 'Recomendações para reparo e reconstrução ou demolição', 'Record': 'registro', 'Record Details': 'Detalhes do Registro', 'Record Saved': 'Registro Gravado', 'Record added': 'Registro incluído', 'Record any restriction on use or entry': 'Registro de qualquer restrição à utilização ou entrada', 'Record deleted': 'Registro excluído', 'Record last updated': 'Último registro atualizado', 'Record not found': 'Registro não encontrado', 'Record not found!': 'Registro não encontrado!', 'Record updated': 'registro atualizado', 'Recording and Assigning Assets': 'Ativos de Gravação e Designação', 'Records': 'Registros', 'Recovery': 'recuperação', 'Recovery Request': 'pedido de recuperação', 'Recovery Request added': 'Pedido de recuperação adicionado', 'Recovery Request deleted': 'Pedido de recuperação apagado', 'Recovery Request updated': 'Pedido de recuperação atualizado', 'Recovery Requests': 'Pedidos de recuperação', 'Recruitment': 'Recrutamento', 'Recurring': 'Recorrente', 'Recurring Cost': 'Custo recorrente', 'Recurring cost': 'Custo recorrente', 'Recurring costs': 'Custos recorrentes', 'Red': 'vermelho', 'Red Cross / Red Crescent': 'Cruz Vermelha / Red Crescent', 'Reference Document': 'Documento de referência', 'Refresh Rate (seconds)': 'Taxa de Atualização (Segundos)', 'Region Location': 'Localizaçao da regiao', 'Regional': 'regional', 'Regions': 'Regiões', 'Register': 'registro', 'Register Person': 'REGISTRAR PESSOA', 'Register Person into this Camp': 'Registrar Pessoa neste Acampamento', 'Register Person into this Shelter': 'REGISTRAR PESSOA PARA ESTE Abrigo', 'Register them as a volunteer': 'Registrá-los como voluntários', 'Registered People': 'Pessoas Registradas', 'Registered users can': 'Os usuários registrados podem', 'Registration': 'Inscrição', 'Registration Details': 'Detalhes da Inscrição', 'Registration added': 'Inscrição adicionada', 'Registration entry deleted': 'Inscrição excluída', 'Registration is still pending approval from Approver (%s) - please wait until confirmation received.': 'Registro ainda está pendente de aprovação do Aprovador (%s) - Por favor, aguarde até a confirmação recebida.', 'Registration key': 'Registration key', 'Registration updated': 'Inscrição atualizada', 'Rehabilitation/Long Term Care': 'Reabilitação/Cuidados de Longo Termo', 'Reinforced masonry': 'Alvenaria reforçada', 'Rejected': 'rejeitado', 'Relative Details': 'Relative Details', 'Relative added': 'Relative added', 'Relative deleted': 'Relative deleted', 'Relative updated': 'Relative updated', 'Relatives': 'Relatives', 'Relief': 'Alivio', 'Relief Team': 'Equipe de socorro', 'Religion': 'Religião', 'Religious': 'Religiosas', 'Religious Leader': 'Líder religioso', 'Relocate as instructed in the <instruction>': 'Relocalizar conforme instruído no', 'Remove': 'remover', 'Remove Activity from this event': 'Remove Activity from this event', 'Remove Asset from this event': 'Remover ativo deste evento', 'Remove Asset from this scenario': 'Remover ativo deste cenário', 'Remove Document from this request': 'Remove Document from this request', 'Remove Facility from this event': 'Remover recurso deste evento', 'Remove Facility from this scenario': 'Remover recurso deste cenário', 'Remove Human Resource from this event': 'REMOVER RECURSOS HUMANOS A partir deste evento', 'Remove Human Resource from this scenario': 'REMOVER RECURSOS HUMANOS A partir deste cenário', 'Remove Item from Inventory': 'Remover Item do Inventário', 'Remove Map Configuration from this event': 'REMOVER Mapa de configuração a partir deste evento', 'Remove Map Configuration from this scenario': 'REMOVER Mapa de configuração a partir deste cenário', 'Remove Person from Commitment': 'Remove Person from Commitment', 'Remove Skill': 'Remove Skill', 'Remove Skill from Request': 'Remove Skill from Request', 'Remove Task from this event': 'Remove Task from this event', 'Remove Task from this scenario': 'Remove Task from this scenario', 'Remove this asset from this event': 'REMOVER este recurso a partir deste evento', 'Remove this asset from this scenario': 'Remover este recurso deste cenário', 'Remove this facility from this event': 'Remove this facility from this event', 'Remove this facility from this scenario': 'Remove this facility from this scenario', 'Remove this human resource from this event': 'Remove this human resource from this event', 'Remove this human resource from this scenario': 'Remove this human resource from this scenario', 'Remove this task from this event': 'Remove this task from this event', 'Remove this task from this scenario': 'Remove this task from this scenario', 'Repair': 'REPARO', 'Repaired': 'Reparado', 'Repeat your password': '<PASSWORD>', 'Replace': 'TROCAR', 'Replace if Master': 'Substituir se Principal', 'Replace if Newer': 'Substituir se o Mais Recente', 'Report': 'Relatório', 'Report Another Assessment...': 'Adicionar Outro Relatório De Avaliação....', 'Report Details': 'Detalhes do Relatório', 'Report Resource': 'Reportar Recursos', 'Report Types Include': 'Tipos de relatório incluem', 'Report added': 'Relatório incluído', 'Report deleted': 'Relatório removido', 'Report my location': 'Relate meu local', 'Report the contributing factors for the current EMS status.': 'Reportar os factores que contribuem para a situação EMS actual.', 'Report the contributing factors for the current OR status.': 'Reportar os factores que contribuem para a situação OR actual.', 'Report them as found': 'Reportar como encontrados', 'Report them missing': 'Reportar como perdidos', 'Report updated': 'Relatório atualizado', 'ReportLab module not available within the running Python - this needs installing for PDF output!': 'O módulo de ReportLab não disponíveis na execução Python - isto requer a instalação para a entrega em PDF!', 'ReportLab not installed': 'ReportLab não instalado', 'Reporter': 'Relator', 'Reporter Name': 'Nome do Relator', 'Reporting on the projects in the region': 'Relatórios sobre os projetos na região', 'Reports': 'Relatórios', 'Request': 'Pedido', 'Request Added': 'Pedido Incluído', 'Request Canceled': 'Pedido Cancelado', 'Request Details': 'Detalhes do Pedido', 'Request From': 'Pedido De', 'Request Item': 'Item de pedido', 'Request Item Details': 'Detalhes do item de pedido', 'Request Item added': 'Item incluído no pedido', 'Request Item deleted': 'Item de pedido excluído', 'Request Item from Available Inventory': 'PEDIDO DE Item de Inventário Disponível', 'Request Item updated': 'Pedido actualizado', 'Request Items': 'Itens de pedido', 'Request New People': 'Request New People', 'Request Status': 'Status do Pedido', 'Request Type': 'Tipo de Pedido', 'Request Updated': 'Solicitação atualizada', 'Request added': 'Pedido adicionado', 'Request deleted': 'Solicitação excluída', 'Request for Role Upgrade': 'Pedido de upgrade de função', 'Request updated': 'Pedido actualizado', 'Request, Response & Session': 'Pedido, Resposta & Sessão', 'Requested': 'solicitado', 'Requested By': 'Solicitado Por', 'Requested By Facility': 'Solicitado Pela Instalação', 'Requested By Site': 'Solicitado Por Site', 'Requested From': 'Solicitada a Partir de', 'Requested Items': 'Itens solicitados', 'Requested Skill': 'Requested Skill', 'Requested Skill Details': 'Requested Skill Details', 'Requested Skill updated': 'Requested Skill updated', 'Requested Skills': 'Requested Skills', 'Requested by': 'Solicitado Por', 'Requested on': 'Em solicitada', 'Requester': 'Solicitante', 'Requests': 'Pedidos', 'Requests Management': 'Gerenciamento de Pedidos', 'Required Skill': 'Required Skill', 'Requires Login!': 'É necessário fazer login!', 'Rescue and recovery': 'Resgate e recuperação', 'Reset': 'Restaurar', 'Reset Password': '<PASSWORD>', 'Resolve': 'Resolver', 'Resolve Conflict': 'Resolver Conflito', 'Resolve link brings up a new screen which helps to resolve these duplicate records and update the database.': 'Resolva link que levará até uma nova tela que ajudará a resolver esses registros duplicados e atualizar o banco de dados.', 'Resource': 'Recurso', 'Resource Details': 'Detalhes do recurso', 'Resource added': 'Recurso incluído', 'Resource deleted': 'Recurso Excluído', 'Resource updated': 'Recurso atualizado', 'Resources': 'Recursos', 'Respiratory Infections': 'Infecções respiratórias', 'Response': 'Resposta', 'Restricted Access': 'Acesso Restrito', 'Restricted Use': 'Uso restrito', 'Results': 'results', 'Retail Crime': 'Crime a varejo', 'Retrieve Password': '<PASSWORD>', 'Return': 'Retorno', 'Return to Request': 'Retornar ao pedido', 'Returned': 'Retornado', 'Returned From': 'Retornado a partir de', 'Returned Status': 'Retornado Status', 'Review Incoming Shipment to Receive': 'Revisão da Remessa de Entrada para Receber', 'Rice': 'Arroz', 'Riot': 'Motim', 'River': 'Rio', 'River Details': 'Detalhes do Rio', 'River added': 'Rio adicionado', 'River deleted': 'Rio deletado', 'River updated': 'Rio atualizado', 'Rivers': 'Rios', 'Road Accident': 'Acidente na rua/estrada', 'Road Closed': 'Rua/Estrada fechada', 'Road Conditions': 'Condições da Estrada', 'Road Delay': 'Atraso de Estrada', 'Road Hijacking': 'Sequestro de Estrada', 'Road Usage Condition': 'Condição de Uso de Estrada', 'Roads Layer': 'Roads Layer', 'Role': 'Função', 'Role Details': 'Detalhes da Função', 'Role Required': 'Função requerida', 'Role Updated': 'Funções atualizadas', 'Role added': 'Regra incluída', 'Role deleted': 'Função excluída', 'Role updated': 'Funções atualizadas', 'Role-based': 'Baseada em regra', 'Roles': 'Funções', 'Roles Permitted': 'Funções Permitidas', 'Roof tile': 'Telhado lado a lado', 'Roofs, floors (vertical load)': 'Telhados, pisos (carga vertical)', 'Room': 'Sala', 'Room Details': 'Detalhes da sala', 'Room added': 'Sala incluída', 'Room deleted': 'Sala excluída', 'Room updated': 'Sala atualizada', 'Rooms': 'Salas', 'Roster': 'Lista', 'Row Choices (One Per Line)': 'Opções da linha (Um por linha)', 'Rows in table': 'Linhas na tabela', 'Rows selected': 'Linhas Selecionadas', 'Run Functional Tests': 'Executar testes funcionais', 'Run Interval': 'Intervalo de execução', 'Running Cost': 'Custo corrente', 'Russian': 'Russian', 'SMS Modems (Inbound & Outbound)': 'SMS Modems (Inbound & Outbound)', 'SMS Outbound': 'SMS Outbound', 'SMS Settings': 'SMS Settings', 'SMS settings updated': 'SMS settings updated', 'SMTP to SMS settings updated': 'SMTP to SMS settings updated', 'Safe environment for vulnerable groups': 'Ambiente seguro para grupos vulneráveis', 'Safety Assessment Form': 'Formulário de avaliação de segurança', 'Safety of children and women affected by disaster?': 'Segurança das crianças e mulheres afetadas pela catástrofe?', 'Sahana Administrator': 'Sahana AdmiNistrador', 'Sahana Agasti': 'Sahana Agasti', 'Sahana Blue': 'Sahana Azul', 'Sahana Community Chat': 'Sahana COMUNIDADE de BATE-PAPO', 'Sahana Eden': 'Sahana Eden', 'Sahana Eden <=> Other': 'Sahana Eden <=> Outros', 'Sahana Eden <=> Sahana Eden': 'Sahana Éden <=> Sahana Éden', 'Sahana Eden Humanitarian Management Platform': 'plataforma de gerenciamento humanitário Sahana Éden', 'Sahana Eden Website': 'SITE Sahana Éden', 'Sahana Green': 'Sahana Verde', 'Sahana Steel': 'Sahana Steel', 'Sahana access granted': 'Acesso Sahana CONCEDIDO', 'Salted Fish': 'Peixe Salgado', 'Sanitation problems': 'Problemas de saneamento', 'Satellite': 'satélite', 'Satellite Layer': 'Satellite Layer', 'Satellite Office': 'Escritório experimental', 'Saturday': 'SAturday', 'Save': 'armazenar', 'Saved.': 'armazenado.', 'Saving...': 'Guardando...', 'Scale of Results': 'Nível de Resultados', 'Scanned Copy': 'Scanned Copy', 'Scanned Forms Upload': 'Scanned Forms Upload', 'Scenario': 'Cenário', 'Scenario Details': 'Detalhes do Cenário', 'Scenario added': 'Cenário incluído', 'Scenario deleted': 'Cenário excluído', 'Scenario updated': 'Cenário atualizado', 'Scenarios': 'Cenários', 'Schedule': 'Horário', 'Schema': 'Esquema', 'School': 'Escola', 'School Closure': 'Encerramento Escolar', 'School Lockdown': 'Bloqueio escolar', 'School Teacher': 'Professor de escola', 'School activities': 'Actividades escolares', 'School assistance': 'Assistência escolar', 'School attendance': 'Presença escolar', 'School destroyed': 'Escola Destruída', 'School heavily damaged': 'Escola fortemente danificada', 'School tents received': 'Tendas da escola recebidas', 'School tents, source': 'Tendas de escolha, origem', 'School used for other purpose': 'Escola utilizada para outros fins', 'School/studying': 'Escola/estudando', 'Schools': 'Escolas', 'Search': 'Pesquisar', 'Search Activities': 'procurar atividades', 'Search Activity Report': 'Relatório de pesquisa de atividades', 'Search Addresses': 'procurar endereços', 'Search Alternative Items': 'Procurar itens alternativos', 'Search Assessment Summaries': 'Procura De Avaliação De RESUMOS', 'Search Assessments': 'Avaliações de procura', 'Search Asset Assignments': 'Procurar ATIVO Designações', 'Search Asset Log': 'Procurar log de ativo', 'Search Assets': 'Procurar Recursos', 'Search Baseline Type': 'Procurar Typo de Base', 'Search Baselines': 'Procurar Bases', 'Search Brands': 'Procurar Marcas', 'Search Budgets': 'Procura Orçamentos', 'Search Bundles': 'PACOTES Configuráveis de procura', 'Search Camp Services': 'Procurar Serviços de Acampamento', 'Search Camp Types': 'Procurar Tipos De Acampamento', 'Search Camps': 'Procurar acampamentos', 'Search Catalog Items': 'Itens de procura De Catálogo', 'Search Catalogs': 'Procurar nos Catálogos', 'Search Certificates': 'Procurar Certificados', 'Search Certifications': 'Procurar Certificações', 'Search Checklists': 'Listas De procura', 'Search Cluster Subsectors': 'Procura De Cluster Subsectores', 'Search Clusters': 'Clusters de procura', 'Search Commitment Items': 'Itens de procura Compromisso', 'Search Commitments': 'Compromissos de procura', 'Search Committed People': 'Search Committed People', 'Search Competencies': 'Procurar Competências', 'Search Competency Ratings': 'Procurar Indices de Competência', 'Search Contact Information': 'Procurar informações de contato', 'Search Contacts': 'Buscar contatos', 'Search Course Certificates': 'procura Certificados de Curso', 'Search Courses': 'Procurar Cursos', 'Search Credentials': 'Credenciais de busca', 'Search Documents': 'Pesquisar documentos', 'Search Donors': 'Procura de Doadores', 'Search Entries': 'Pesquisar Entradas', 'Search Events': 'Pesquisar Eventos', 'Search Facilities': 'Pesquisar Instalações', 'Search Feature Class': 'Pesquisar classe de dispositivos', 'Search Feature Layers': 'Pesquisar camadas do dispositivo', 'Search Flood Reports': 'Pesquisar relatórios de inundação', 'Search GPS data': 'Search GPS data', 'Search Groups': 'Buscar Grupos', 'Search Homes': 'Search Homes', 'Search Human Resources': 'Pesquise recursos humanos.', 'Search Identity': 'Buscar Identidade', 'Search Images': 'Procurar Imagens', 'Search Impact Type': 'Procurar Tipo de Impacto', 'Search Impacts': 'Procurar Impactos', 'Search Import Files': 'Search Import Files', 'Search Incident Reports': 'Procurar Relatórios de Incidentes', 'Search Inventory Items': 'Procurar Entradas De Inventário', 'Search Inventory items': 'Procurar Entradas De Inventário', 'Search Item Categories': 'Buscar categorias de Item', 'Search Item Packs': 'Buscar pocotes de itens', 'Search Items': 'Buscar Itens', 'Search Job Roles': 'Pesquise papéis de trabalho', 'Search Keys': 'Procurar chaves', 'Search Kits': 'Procurar kits', 'Search Layers': 'Procurar camadas', 'Search Level': 'Search Level', 'Search Level 1 Assessments': 'Procurar Avaliações Nível 1', 'Search Level 2 Assessments': 'Procurar Avaliações Nível 2', 'Search Locations': 'Procurar Localidades', 'Search Log Entry': 'Procura de entrada de Log', 'Search Map Configurations': 'Pesquise mapa de configurações.', 'Search Markers': 'Marcadores De procura', 'Search Member': 'Procurar Membro', 'Search Membership': 'Procurar filiação', 'Search Memberships': 'Pesquisar Associações', 'Search Missions': 'Procurar Missões', 'Search Need Type': 'Procura Precisa De Tipo', 'Search Needs': 'Procura precisa', 'Search Notes': 'Notes procura', 'Search Offices': 'Escritórios de procura', 'Search Organizations': 'Pesquisar Organizações', 'Search Patients': 'Search Patients', 'Search Peer': 'PROCURA Par', 'Search Personal Effects': 'Procura objetos pessoais', 'Search Persons': 'Buscar Membros', 'Search Photos': 'Procura Fotos', 'Search Population Statistics': 'Procurar Estatística de População', 'Search Positions': 'Procura de Posições', 'Search Problems': 'Procura de Problemas', 'Search Projections': 'Projeções de procura', 'Search Projects': 'Procura de Projetos', 'Search Rapid Assessments': 'Procura de Avaliações Rápidas', 'Search Received Items': 'Procura de Itens Recebidos', 'Search Received Shipments': 'Embarques de procura Recebidos', 'Search Records': 'registros de procura', 'Search Registations': 'Registations procura', 'Search Registration Request': 'Pedido de registro de procura', 'Search Relatives': 'Search Relatives', 'Search Report': 'Procurar Relatório', 'Search Reports': 'Procurar Relatórios', 'Search Request': 'pedido de pesquisa', 'Search Request Items': 'Pedido de procura de Itens', 'Search Requested Items': 'Procura de itens solicitados', 'Search Requested Skills': 'Search Requested Skills', 'Search Requests': 'Procura de solicitações', 'Search Resources': 'Pesquisa de recursos', 'Search Rivers': 'Rios procura', 'Search Roles': 'Pesquisa de papéis', 'Search Rooms': 'Procurar Salas', 'Search Scenarios': 'Procurar cenários', 'Search Sections': 'As Seções de procura', 'Search Sectors': 'Procurar Setores', 'Search Sent Items': 'Procurar Itens Enviados', 'Search Sent Shipments': 'Procurar Despachos Enviados', 'Search Service Profiles': 'Serviço de procura Perfis', 'Search Settings': 'Definições de Pesquisa', 'Search Shelter Services': 'Procura Abrigo de serviços', 'Search Shelter Types': 'Procura tipos de Abrigo', 'Search Shelters': 'Procurar Abrigos', 'Search Skill Equivalences': 'Procurar equivalencias de habilidades', 'Search Skill Provisions': 'Procurar Disposições de habilidade', 'Search Skill Types': 'Pesquisar Tipos de Habilidades', 'Search Skills': 'Pesquisar Habilidades', 'Search Solutions': 'Pesquisar Soluções', 'Search Staff': 'Busca de pessoal', 'Search Staff Types': 'Busca de tipo de pessoal', 'Search Staff or Volunteer': 'Procurar Funcionário ou Voluntário', 'Search Status': 'Busca de status', 'Search Subscriptions': 'Busca de assinaturas', 'Search Subsectors': 'Buscar subsetores', 'Search Support Requests': 'Pedidos de suporte a pesquisa', 'Search Tasks': 'Tarefa de Pesquisa', 'Search Teams': 'Times de pesquisa', 'Search Themes': 'Temas de pesquisa', 'Search Tickets': 'Buscar Bilhetes', 'Search Tracks': 'Procurar Trilhas', 'Search Trainings': 'Buscar Treinamentos', 'Search Twitter Tags': 'Procurar Twitter Tags', 'Search Units': 'Procura Unidades', 'Search Users': 'Procurar Usuários', 'Search Vehicle Details': 'Search Vehicle Details', 'Search Vehicles': 'Search Vehicles', 'Search Volunteer Availability': 'Buscar Disponibilidade para Voluntáriado', 'Search Volunteers': 'Procura Voluntários', 'Search Warehouses': 'procura Warehouses', 'Search and Edit Group': 'Procurar e editar GRUPO', 'Search and Edit Individual': 'Procurar e Editar Individual', 'Search for Staff or Volunteers': 'Pesquise por funcionários ou voluntários', 'Search for a Location by name, including local names.': 'Pesquisar local por nome, incluindo nomes locais.', 'Search for a Person': 'Procurar Pessoa', 'Search for a Project': 'Procurar Projecto', 'Search for a shipment by looking for text in any field.': 'Procurar carga fazendo uma pesquisa de texto em qualquer campo.', 'Search for a shipment received between these dates': 'Procurar carga recebida entre estas datas', 'Search for a vehicle by text.': 'Search for a vehicle by text.', 'Search for an Organization by name or acronym': 'Procurar por uma Organização por nome ou iniciais', 'Search for an Organization by name or acronym.': 'Procurar por uma organização por nome ou iniciais.', 'Search for an asset by text.': 'Pesquisar um recurso por texto.', 'Search for an item by category.': 'Procurar por categoria.', 'Search for an item by Year of Manufacture.': 'Search for an item by Year of Manufacture.', 'Search for an item by brand.': 'Search for an item by brand.', 'Search for an item by catalog.': 'Search for an item by catalog.', 'Search for an item by category.': 'Search for an item by category.', 'Search for an item by its code, name, model and/or comment.': 'Search for an item by its code, name, model and/or comment.', 'Search for an item by text.': 'Procurar por texto.', 'Search for asset by country.': 'Procurar bens por país.', 'Search for asset by location.': 'Search for asset by location.', 'Search for office by country.': 'Procurar escritórios por país.', 'Search for office by location.': 'Search for office by location.', 'Search for office by organization.': 'Procurar escritórios por organização.', 'Search for office by text.': 'Procura por texto do gabinete.', 'Search for vehicle by location.': 'Search for vehicle by location.', 'Search for warehouse by country.': 'Pesquise por depósito por país.', 'Search for warehouse by location.': 'Search for warehouse by location.', 'Search for warehouse by organization.': 'Pesquise por depósito por organização.', 'Search for warehouse by text.': 'Pesquise por depósito via campo-texto.', 'Search here for a person record in order to:': 'Buscar aqui por um registro de pessoa a fim de:', 'Search messages': 'Mensagens de Procura', 'Searching for different groups and individuals': 'Procurar diferentes grupos e indivíduos', 'Secondary Server (Optional)': 'Servidor secundário (opcional)', 'Seconds must be a number between 0 and 60': 'Segundos deve ser um número entre 0 e 60', 'Section': 'Section', 'Section Details': 'Seção Detalhes', 'Section deleted': 'Seção excluído', 'Section updated': 'Seção atualizada', 'Sections': 'Seções', 'Sections that are part of this template': 'Sections that are part of this template', 'Sections that can be selected': 'Sections that can be selected', 'Sector': 'setor', 'Sector Details': 'Detalhes do Setor', 'Sector added': 'Sector incluído', 'Sector deleted': 'Sector apagado', 'Sector updated': 'Setor atualizado', 'Sector(s)': 'Setor(es)', 'Sectors': 'Setores', 'Security Status': 'Status de Segurança', 'Security problems': 'Problemas de Segurança', 'See All Entries': 'Ver todas as entradas', 'See all': 'Ver tudo', 'See unassigned recovery requests': 'Consulte Pedidos de recuperação designado', 'Seen': 'Visto', 'Select': 'select', 'Select Items from the Request': 'Selecionar itens do pedido', 'Select Items from this Inventory': 'Selecionar itens a partir deste Inventário', 'Select Organization': 'Selecionar Organização', 'Select Skills from the Request': 'Select Skills from the Request', "Select a Room from the list or click 'Add Room'": "Escolha uma sala da lista ou clique 'Incluir sala'", 'Select a location': 'Selecionar um local', "Select a manager for status 'assigned'": "Select a manager for status 'assigned'", "Select a person in charge for status 'assigned'": "Selecione uma pessoa responsável para status 'DESIGNADO'", 'Select a question from the list': 'Selecione uma pergunta a partir da lista', 'Select a range for the number of total beds': 'Selecione um intervalo para o número de camas total', 'Select all that apply': 'Selecione todas as que se applicam', 'Select an Organization to see a list of offices': 'Selecione uma organização para ver uma lista de escritórios', 'Select the overlays for Assessments and Activities relating to each Need to identify the gap.': 'Selecione as sobreposições de avaliação e actividades relacionadas com cada necessidade para identificar as lacunas.', 'Select the person assigned to this role for this project.': 'Selecione a pessoa designada para essa função neste projeto.', "Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.": "Selecione isto se todas as localidades especificas precisarem de um pai no nível mais alto da hierarquia. Por exemplo, se 'distrito' é a menor divisão na hierarquia e, em seguida, todos os locais específicos seriam obrigados a ter um distrito como um pai.", "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.": 'Selecione isto se todos os locais específicos de uma posição pai na hierarquia do local. Isso pode ajudar na configuração de uma "região" representando uma área afetada.', 'Select to show this configuration in the Regions menu.': 'Selecione para mostrar essa configuração no menu regiões.', 'Select to show this configuration in the menu.': 'Select to show this configuration in the menu.', 'Selected Jobs': 'Selected Jobs', 'Selects what type of gateway to use for outbound SMS': 'Selects what type of gateway to use for outbound SMS', 'Selects whether to use a Modem, Tropo or other Gateway for sending out SMS': 'Selecione se vau utilizar um Modem, Tropo ou outro Gateway para enviar SMS', 'Send': 'Envie', 'Send Alerts using Email &/or SMS': 'Envio de alertas usando e-mail e/ou SMS', 'Send Commitment as Shipment': 'Enviar compromisso como carregamento', 'Send New Shipment': 'Enviar nova remessa', 'Send Notification': 'Enviar notificação', 'Send Shipment': 'Enviar Carregamento', 'Send a message to this person': 'Enviar uma mensagem para esta pessoa', 'Send a message to this team': 'Enviar uma mensagem para essa equipe', 'Send from %s': 'Enviar de %s', 'Send message': 'Enviar mensagem', 'Send new message': 'Enviar nova mensagem', 'Sends & Receives Alerts via Email & SMS': 'Envia & Recebe Alertas via E-Mail & SMS', 'Senior (50+)': 'Sênior (50+)', 'Sent': 'Enviadas', 'Sent By': 'Enviado Por', 'Sent By Person': 'Enviado Por Pessoa', 'Sent Item Details': 'Detalhes do Item enviado', 'Sent Item deleted': 'Enviado Item excluído', 'Sent Item updated': 'Enviado Item atualizado', 'Sent Shipment Details': 'Enviado Detalhes de Embarque', 'Sent Shipment canceled': 'Enviado Carregamento cancelado', 'Sent Shipment canceled and items returned to Inventory': 'Enviado Carregamento cancelado e itens retornado ao Inventário', 'Sent Shipment updated': 'Enviado Embarque atualizado', 'Sent Shipments': 'Remessas Enviadas', 'Separated children, caregiving arrangements': 'Crianças separados, disposições caregiving', 'Serial Number': 'Numero de série', 'Series': 'serie', 'Server': 'servidor', 'Service': 'serviço', 'Service Catalog': 'Catálogo de Serviços', 'Service Due': 'Service Due', 'Service or Facility': 'Serviço ou facilidade', 'Service profile added': 'Perfil de serviço adicionado', 'Service profile deleted': 'Perfil de serviço Excluído', 'Service profile updated': 'Perfil de serviço atualizado', 'Services': 'Serviços', 'Services Available': 'Serviços Disponíveis', 'Set Base Site': 'Definir base de dados do site', 'Set By': 'Definido por', 'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.': 'Configure como True para permitir que este nível da hierarquia do local possa ser editado por usuários que não sejam administradores.', 'Setting Details': 'Detalhes de ajuste', 'Setting added': 'Configuração adicionada', 'Setting deleted': 'Configuração Excluída', 'Setting updated': 'Configuração atualizada', 'Settings': 'Ajustes', 'Settings updated': 'Ajustes atualizados', 'Settings were reset because authenticating with Twitter failed': 'As configurações foram redefinidas porque a autenticação com Twitter falhou', 'Settings which can be configured through the web interface are available here.': 'As configurações que podem ser definidas através da interface da web estão disponíveis aqui.', 'Severe': 'Severo', 'Severity': 'Gravidade', 'Share a common Marker (unless over-ridden at the Feature level)': 'Compartilhar um marcador comum (a não ser que abaixo-assinado ao nível de Componente)', 'Shelter': 'Abrigo', 'Shelter & Essential NFIs': 'Abrigo & NFIs Essenciais', 'Shelter Details': 'Detalhes de Abrigo', 'Shelter Name': 'Nome de Abrigo', 'Shelter Registry': 'Registro de Abrigo', 'Shelter Service': 'Serviço de Abrigo', 'Shelter Service Details': 'Detalhes do serviço de abrigo', 'Shelter Service added': 'Serviço de Abrigo incluído', 'Shelter Service deleted': 'Serviço de Abrigo excluído', 'Shelter Service updated': 'Atualização de serviços de abrigo', 'Shelter Services': 'Serviços de abrigo', 'Shelter Type': 'Tipo de abrigo', 'Shelter Type Details': 'Detalhes do tiipo de abrigo', 'Shelter Type added': 'Tipo de abrigo incluído', 'Shelter Type deleted': 'Tipo de abrigo excluído', 'Shelter Type updated': 'Abrigos Tipo De atualização', 'Shelter Types': 'Tipos De abrigo', 'Shelter Types and Services': 'Abrigo Tipos e serviços', 'Shelter added': 'Abrigo incluído', 'Shelter deleted': 'Abrigo excluído', 'Shelter updated': 'Abrigo atualizado', 'Shelter/NFI Assistance': 'Abrigo/ Assistência NFI', 'Shelters': 'Abrigos', 'Shipment Created': 'Embarque Criado', 'Shipment Items': 'Itens de Carregamento', 'Shipment Items received by Inventory': 'Itens de Remessa recebidos pelo Inventário', 'Shipment Items sent from Inventory': 'Itens de Remessa enviados pelo Inventário', 'Shipment to Send': 'Carga para Enviar', 'Shipments': 'Remessas', 'Shipments To': 'Remessas Para', 'Shooting': 'Tiroteio', 'Short Assessment': 'Curta Avaliação', 'Short Description': 'Breve Descrição', 'Show Checklist': 'Mostrar Lista De Verificação', 'Show Details': 'Mostrar detalhes', 'Show Map': 'Mostrar Mapa', 'Show Region in Menu?': 'Mostrar Região no Menu?', 'Show in Menu?': 'Show in Menu?', 'Show on Map': 'Mostrar no mapa', 'Show on map': 'Mostrar no mapa', 'Sign-up as a volunteer': 'Inscrever-se como um voluntário', 'Sign-up for Account': 'Inscrever-se para conta', 'Sign-up succesful - you should hear from us soon!': 'Sua inscriçao foi feita com sucesso - aguarde notícias em breve!', 'Sindhi': 'Sindi', 'Single PDF File': 'Single PDF File', 'Site': 'site', 'Site Administration': 'Administração do site', 'Site or Location': 'Sítio ou Local', 'Sites': 'sites', 'Situation': 'Situação', 'Situation Awareness & Geospatial Analysis': 'Situação Reconhecimento & Geoespaciais Análise', 'Sketch': 'Esboço', 'Skill': 'QUALIFICAÇÃO', 'Skill Catalog': 'Catálogo de Conhecimentos', 'Skill Details': 'Detalhes das habilidades', 'Skill Equivalence': 'Equivalência de Conhecimentos', 'Skill Equivalence Details': 'Detalhes da Equivalência de Habilidade', 'Skill Equivalence added': 'Equivalência de Habilidade incluída', 'Skill Equivalence deleted': 'Equivalência de Habilidade excluída', 'Skill Equivalence updated': 'Equivalência de Habilidade atualizada', 'Skill Equivalences': 'Equivalências de habilidade', 'Skill Provision': 'Provisão de Habilidade', 'Skill Provision Catalog': 'Catálogo de habilidades disponível', 'Skill Provision Details': 'Detalhes de habilidades disponível', 'Skill Provision added': 'Provisão de Habilidade incluída', 'Skill Provision deleted': 'Catalogo de habilidades excluído', 'Skill Provision updated': 'Catálogo de habilidades atualizado', 'Skill Provisions': 'Habilidades disponíveis', 'Skill Status': 'Status da Habilidade', 'Skill TYpe': 'Tipo de habilidade', 'Skill Type': 'Skill Type', 'Skill Type Catalog': 'Catálogo de tipos de habilidades', 'Skill Type Details': 'Detalhes do tipo de habilidade', 'Skill Type added': 'Tipo de habilidade incluído', 'Skill Type deleted': 'Tipo de habilidade excluído', 'Skill Type updated': 'Tipo de habilidade atualizado', 'Skill Types': 'Tipos de habilidade', 'Skill added': 'Habilidade incluída', 'Skill added to Request': 'Skill added to Request', 'Skill deleted': 'Habilidade Excluída', 'Skill removed': 'Skill removed', 'Skill removed from Request': 'Skill removed from Request', 'Skill updated': 'Habilidade ATUALIZADA', 'Skill/Training': 'Habilidades/Treinamento', 'Skills': 'Habilidades', 'Skills Catalog': 'Catálogo de habilidades', 'Skills Management': 'Gerenciamento das Habilidades', 'Skype': 'Skype', 'Skype ID': 'ID DO Skype', 'Slightly Damaged': 'Ligeiramente Danificado', 'Slope failure, debris': 'falha de inclinação, destroços', 'Small Trade': 'Pequeno Comércio', 'Smoke': 'Fumaça', 'Snapshot': 'snapshot', 'Snapshot Report': 'Relatório de snapshot', 'Snow Fall': 'Queda de neve , nevasca', 'Snow Squall': 'Rajada de neve', 'Soil bulging, liquefaction': 'abaulamento do solo, liquefação', 'Solid waste': 'Resíduos sólidos', 'Solution': 'Solução', 'Solution Details': 'Detalhes da Solução', 'Solution Item': 'Item de Solução', 'Solution added': 'Solução adicionada', 'Solution deleted': 'Solução excluída', 'Solution updated': 'Solução atualizada', 'Solutions': 'Soluções', 'Some': 'Algum', 'Sorry - the server has a problem, please try again later.': 'Sorry - the server has a problem, please try again later.', 'Sorry that location appears to be outside the area of the Parent.': 'Desculpe ! Essa localização está fora da área do Pai.', 'Sorry that location appears to be outside the area supported by this deployment.': 'Desculpe ! Essa localização parece estar fora da área suportada por esta implementação.', 'Sorry, I could not understand your request': 'Desculpe, eu não pude entender o seu pedido', 'Sorry, only users with the MapAdmin role are allowed to create location groups.': 'Desculpe, apenas usuários com o perfil MapAdmin tem permissão para criar locais dos grupos.', 'Sorry, only users with the MapAdmin role are allowed to edit these locations': 'Desculpe, apenas usuários com o perfil MapAdmin tem permissão para editar estes locais', 'Sorry, something went wrong.': 'Desculpe, algo deu errado.', 'Sorry, that page is forbidden for some reason.': 'Desculpe ! Esta página tem acesso restrito por alguma razão.', 'Sorry, that service is temporary unavailable.': 'Desculpe ! Este serviço está indisponível temporariamente.', 'Sorry, there are no addresses to display': 'Desculpe ! Não há endereços para visualizar.', "Sorry, things didn't get done on time.": 'Desculpe ! As tarefas não foram concluídas em tempo útil.', "Sorry, we couldn't find that page.": 'Desculpe, não foi possível localizar essa página.', 'Source': 'source', 'Source ID': 'ID de origem', 'Source Time': 'Origem do tempo', 'Sources of income': 'Fontes de rendimento', 'Space Debris': 'Destroços Espaciais', 'Spanish': 'espanhol', 'Special Ice': 'Gelo Especial', 'Special Marine': 'Marinha especial', 'Specialized Hospital': 'Hospital especializado.', 'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.': 'Área específica (exemplo: edifício/quarto) com a localização de onde essa pessoa/grupo é visto.', 'Specific locations need to have a parent of level': 'Locais específicos precisam ter um nível paterno.', 'Specify a descriptive title for the image.': 'Especifique um título descritivo para a imagem.', 'Specify the bed type of this unit.': 'Especifique o tipo de cama dessa unidade.', 'Specify the number of available sets': 'Especificar o número de conjuntos disponíveis', 'Specify the number of available units (adult doses)': 'Especifique o número de unidades disponíveis (doses para adultos)', 'Specify the number of available units (litres) of Ringer-Lactate or equivalent solutions': 'Especificar o número de unidades disponíveis (litros) de Ringer-Lactato ou soluções equivalentes', 'Specify the number of sets needed per 24h': 'Especificar o número de conjuntos necessários por 24h', 'Specify the number of units (adult doses) needed per 24h': 'Especificar o número de unidades (doses para adultos) necessário por 24h', 'Specify the number of units (litres) of Ringer-Lactate or equivalent solutions needed per 24h': 'Especificar o número de unidades (litros) de Ringer-Lactato ou soluções equivalentes necessárias para 24h', 'Speed': 'Speed', 'Spherical Mercator?': 'Mapa Mercator Esférico?', 'Spreadsheet Importer': 'PLANILHA IMPORTADOR', 'Spreadsheet uploaded': 'Planilha transferido por UPLOAD', 'Spring': 'Primavera', 'Squall': 'Rajada', 'Staff': 'Equipe', 'Staff & Volunteers': 'Colaboradores & Voluntários', 'Staff 2': 'Equipe 2', 'Staff Details': 'Equipe Detalhes', 'Staff ID': 'ID da equipe', 'Staff List': 'Lista de pessoal', 'Staff Member Details': 'Detalhes de membro da equipe', 'Staff Members': 'Membros da equipe', 'Staff Record': 'Registro de pessoal', 'Staff Type Details': 'Equipe Tipo Detalhes', 'Staff Type added': 'Equipe tipo incluído', 'Staff Type deleted': 'Tipo De equipe excluído', 'Staff Type updated': 'Equipe Tipo De atualização', 'Staff Types': 'Tipos de equipe', 'Staff added': 'Equipe incluída', 'Staff and Volunteers': 'Funcionários e Voluntários', 'Staff deleted': 'Equipe excluída', 'Staff member added': 'Membro da equipe incluído', 'Staff member updated': 'Membro da equipe atualizado', 'Staff present and caring for residents': 'Equipe presente e cuidando de moradores', 'Staff updated': 'Equipe atualizado', 'Staff2': 'staff2', 'Staffing': 'Equipe', 'Stairs': 'Escadas', 'Start Date': 'Data do início', 'Start date': 'Data Inicial', 'Start of Period': 'Início do Período', 'State': 'Status', 'Stationery': 'Papel de Carta', 'Status': 'Status', 'Status Report': 'Relatório de status', 'Status Updated': 'Status atualizado', 'Status added': 'Estado adicionado', 'Status deleted': 'Estado excluído', 'Status of clinical operation of the facility.': 'Estado da operação clínica da instalação.', 'Status of general operation of the facility.': 'Estado da operação geral da instalação.', 'Status of morgue capacity.': 'Estado da capacidade da morgue.', 'Status of operations of the emergency department of this hospital.': 'Estado das operações do Departamento de Emergência deste hospital.', 'Status of security procedures/access restrictions in the hospital.': 'Estado dos procedimentos de segurança/Restrições de Acesso no hospital.', 'Status of the operating rooms of this hospital.': 'Status das salas de operação deste hospital.', 'Status updated': 'Status atualizado', 'Steel frame': 'Estrutura de aço', 'Stolen': 'Roubado', 'Store spreadsheets in the Eden database': 'Arquivar as planilhas no banco de dados Eden', 'Storeys at and above ground level': 'Andares e no nível do solo acima', 'Storm Force Wind': 'Tempestade Força Vento', 'Storm Surge': 'ressaca', 'Stowaway': 'Penetra', 'Street Address': 'Endereço residencial', 'Streetview Enabled?': 'Streetview Enabled?', 'Strong Wind': 'vento forte', 'Structural': 'estrutural', 'Structural Hazards': 'riscos estruturais', 'Style': 'Style', 'Style Field': 'Estilo do Campo', 'Style Values': 'Estilo dos Valores', 'Sub-type': 'Subtipo', 'Subject': 'assunto', 'Submission successful - please wait': 'envio bem sucedido - por favor aguarde', 'Submission successful - please wait...': 'envio bem sucedido - por favor aguarde...', 'Submit New': 'Submeter Novamente', 'Submit New (full form)': 'Submeter Novo (formulário completo)', 'Submit New (triage)': 'Submeter novo (triagem)', 'Submit a request for recovery': 'envie um pedido de recuperação', 'Submit new Level 1 assessment (full form)': 'Submeter novo nível 1 de avaliação (formulário completo)', 'Submit new Level 1 assessment (triage)': 'Submeter novo nível 1 de avaliação (triagem)', 'Submit new Level 2 assessment': 'Submeter novo nível 2 de avaliação', 'Subscription Details': 'Detalhes da Assinatura', 'Subscription added': 'Assinatura Incluída', 'Subscription deleted': 'Assinatura Excluída', 'Subscription updated': 'Assinatura ATUALIZADO', 'Subscriptions': 'assinaturas', 'Subsector': 'Subsetor', 'Subsector Details': 'Detalhes de subsetor', 'Subsector added': 'Subsetor incluído', 'Subsector deleted': 'Subsetor excluído', 'Subsector updated': 'Subsetor atualizado', 'Subsectors': 'Subsetores', 'Subsistence Cost': 'custo de subsistencia', 'Suburb': 'Subúrbio', 'Suggest not changing this field unless you know what you are doing.': 'Sugerimos não alterar esse campo a menos que você saiba o que está fazendo.', 'Summary': 'Sumário', 'Summary by Administration Level': 'Resumo por Nível de Administração', 'Sunday': 'Domingo', 'Supervisor': 'Supervisor', 'Supplies': 'Suprimentos', 'Supply Chain Management': 'Supply Chain Management', 'Supply Item Categories': 'Supply Item Categories', 'Support Request': 'Pedido de Suporte', 'Support Requests': 'Pedidos de Suporte', 'Supports the decision making of large groups of Crisis Management Experts by helping the groups create ranked list.': 'Suporta a tomada de decisão de grandes grupos de Especialistas em Gestão de Crises ajudando os grupos a criar listas de classificados.', 'Sure you want to delete this object?': 'Tem certeza que você quer excluir este objeto?', 'Surgery': 'Cirurgia', 'Survey Answer': 'Resposta da Pesquisa', 'Survey Answer Details': 'Detalhes da Resposta da Pesquisa', 'Survey Answer added': 'Incluído Resposta da Pesquisa', 'Survey Answer deleted': 'Excluído a Resposta da Pesquisa', 'Survey Answer updated': 'Resposta da Pesquisa atualizada', 'Survey Module': 'Módulo de Pesquisa', 'Survey Name': 'Nome da Pesquisa', 'Survey Question': 'Questão de Pesquisa de Opinião', 'Survey Question Details': 'Detalhes da Pergunta de Pesquisa', 'Survey Question Display Name': 'Nome da pergunta de pesquisa', 'Survey Question added': 'Pergunta de pesquisa incluída', 'Survey Question deleted': 'Pergunta de pesquisa excluída', 'Survey Question updated': 'Pergunta de pesquisa atualizada', 'Survey Section': 'Seção da Pesquisa de Opinião', 'Survey Section Details': 'Detalhes de Seção de Pesquisa', 'Survey Section Display Name': 'Seção de pesquisa do nome de exibição', 'Survey Section added': 'Seção de Pesquisa incluída', 'Survey Section deleted': 'Seção de Pesquisa excluída', 'Survey Section updated': 'Seção de pesquisa atualizada', 'Survey Series': 'Série de Pesquisa', 'Survey Series Details': 'Série de Pesquisa Detalhes', 'Survey Series Name': 'Nome de Série de Pesquisa', 'Survey Series added': 'Série de Pesquisa incluída', 'Survey Series deleted': 'Série de Pesquisa excluída', 'Survey Series updated': 'Série de Pesquisa atualizada', 'Survey Template': 'Modelo de Pesquisa de Opinião', 'Survey Template Details': 'Definir detalhes do formulário', 'Survey Template added': 'Modelo de Pesquisa incluído', 'Survey Template deleted': 'Modelo de Pesquisa excluído', 'Survey Template updated': 'Definição de formulário actualizada', 'Survey Templates': 'Definir formulários', 'Symbology': 'Simbologia', 'Sync Conflicts': 'Conflitos de Sincronização', 'Sync History': 'Histórico de Sincronização', 'Sync Now': 'Sincronizar Agora', 'Sync Partners': 'Sincronizar parceiros', 'Sync Partners are instances or peers (SahanaEden, SahanaAgasti, Ushahidi, etc.) that you want to sync information with. Click on the link on the right to go the page where you can add sync partners, search for sync partners and modify them.': 'PARCEIROS DE Sincronização são instâncias ou PARES (SahanaEden, SahanaAgasti, Ushahidi, etc. ) que você deseja a informação de sincronização com. Clique no link sobre o direito de ir a página em que você pode incluir parceiros de sincronização, procurar por parceiros de sincronização e Modificá-las.', 'Sync Pools': 'Conjuntos de Sincronização', 'Sync Schedule': 'Planejamento de Sincronização', 'Sync Settings': 'Configurações de Sincronização', 'Sync process already started on': 'Processo de Sincronização já iniciado em', 'Sync process already started on ': 'Sync process already started on ', 'Synchronisation': 'Sincronização', 'Synchronization': 'Sincronização', 'Synchronization Conflicts': 'Conflitos de Sincronização', 'Synchronization Details': 'Detalhes de Sincronização', 'Synchronization History': 'Histórico de Sincronização', 'Synchronization Peers': 'Parceiros de Sincronização', 'Synchronization Settings': 'Configurações de sincronização', 'Synchronization allows you to share data that you have with others and update your own database with latest data from other peers. This page provides you with information about how to use the synchronization features of Sahana Eden': 'Sincronização permite compartilhar dados que você tenha com outros e Atualizar seu próprio banco de dados com informações recentes de outros parceiros. Esta página fornece informações sobre como utilizar os recursos de sincronização de Sahana Éden', 'Synchronization not configured.': 'Sincronização não Configurada.', 'Synchronization settings updated': 'Configurações de sincronização atualizadas', 'Syncronisation History': 'Histórico De Sincronização', "System's Twitter account updated": 'DO SISTEMA Chilreiam conta ATUALIZADO', 'Tags': 'Tags', 'Take shelter in place or per <instruction>': 'Abrigue-se no local ou por', 'Task': 'Task', 'Task Details': 'Detalhes da Tarefa', 'Task List': 'Lista de tarefas', 'Task Status': 'Status da tarefa', 'Task added': 'Task Inclusa', 'Task deleted': 'Tarefa excluída', 'Task removed': 'Task removed', 'Task updated': 'Tarefa atualizada', 'Tasks': 'Tarefas', 'Team': 'Equipe', 'Team Description': 'Descrição da Equipe', 'Team Details': 'Detalhes da Equipe', 'Team ID': 'ID da Equipe', 'Team Id': 'Id da Equipe', 'Team Leader': 'Líder de Equipe', 'Team Member added': 'Membro da equipe incluído', 'Team Members': 'Membros da equipe', 'Team Name': 'Nome da equipe', 'Team Type': 'Tipo de equipe', 'Team added': 'Equipe incluída', 'Team deleted': 'Equipe excluída', 'Team updated': 'Equipa actualizada', 'Teams': 'Equipes', 'Technical testing only, all recipients disregard': 'Apenas teste técnico, todos os recipientes ignorem', 'Telecommunications': 'Telecomunicações', 'Telephone': 'Telefone', 'Telephone Details': 'Telephone Details', 'Telephony': 'Telefonia', 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.': 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.', 'Temp folder %s not writable - unable to apply theme!': 'PASTA Temp%s não gravável-impossível aplicar tema!', 'Template Name': 'Template Name', 'Template file %s not readable - unable to apply theme!': 'Modelo% arquivo não é Legível-impossível aplicar tema!', 'Templates': 'modelos', 'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.': 'Termo para o 5º nível de divisão administrativa nacional (por exemplo, uma subdivisão de código postal ou de zona de votação). Este nível não é frequentemente utilizado.', 'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).': 'Termo para o 4º nível de divisão administrativa nacional(por exemplo, vila, bairro ou distrito).', 'Term for the primary within-country administrative division (e.g. State or Province).': 'Prazo para a principal divisão administrativa dentro do país (i.e. Estado ou Distrito).', 'Term for the secondary within-country administrative division (e.g. District or County).': 'Prazo para a Secundária divisão administrativa dentro do país (por exemplo, Bairro ou Município).', 'Term for the secondary within-country administrative division (e.g. District).': 'Prazo para a Secundária divisão administrativa dentro do país (i.e. Bairro).', 'Term for the third-level within-country administrative division (e.g. City or Town).': 'Prazo para o 3ᵉʳ nível de divisão administrativa dentro do país (por exemplo, Cidade ou Municipio).', 'Term for the top-level administrative division (i.e. Country).': 'Prazo para a divisão administrativa de nível superior (por exemplo País).', 'Term for the top-level administrative division (typically Country).': 'Prazo para a divisão administrativa de nível superior (geralmente País).', 'Terms of Service\n\nYou have to be eighteen or over to register as a volunteer.': 'Terms of Service\n\nYou have to be eighteen or over to register as a volunteer.', 'Terms of Service:': 'Terms of Service:', 'Territorial Authority': 'Autoridade territoriais', 'Terrorism': 'Terrorismo', 'Tertiary Server (Optional)': 'Servidor terciário (opcional)', 'Text': 'texto', 'Text Color for Text blocks': 'Cor de texto para os blocos de texto', 'Text before each Text Field (One per line)': 'Texto antes de cada campo de texto (um por linha)', 'Thank you for validating your email. Your user account is still pending for approval by the system administator (%s).You will get a notification by email when your account is activated.': 'Obrigado para validar seu e-mail. Sua conta de usuário ainda está pendente para aprovação pelo administrador do Sistema (%s). você receberá uma notificação por e-mail quando sua conta esteja ativada.', 'Thanks for your assistance': 'Obrigado por sua ajuda', 'The': 'O', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.': 'O "query" é uma condição como "db.table1.field1==\'value\'". Algo como "db.table1.field1 == db.table2.field2" resulta em uma junção SQL.', 'The Area which this Site is located within.': 'A área que este Site está localizado', 'The Assessments module allows field workers to send in assessments.': 'O Modulo Avaliações permite aos trabalhadores de campo que enviem avaliações.', 'The Author of this Document (optional)': 'O autor deste documento (opcional)', 'The Building Asssesments module allows building safety to be assessed, e.g. after an Earthquake.': 'O módulo avaliações De Construção permite a segurança edifício a ser avaliada, por exemplo, depois de um terremoto.', 'The Camp this Request is from': 'O Alojamento neste pedido é de', 'The Camp this person is checking into.': 'O Alojamento que esta pessoa está se registrando.', 'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'O local atual do Usuário/Grupo, que pode ser geral (para relatórios) ou precisa (para exibir em um mapa). Digite alguns caracteres para procurar nos locais disponíveis.', "The Donor(s) for this project. Multiple values can be selected by holding down the 'Control' key.": "O doador(s) para este projeto. Vários valores podem ser selecionados ao manter pressionado a chave 'control'", 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.': 'O endereço de e-mail para onde os pedidos de aprovação são enviados (normalmente seria um correio de Grupo ao invés de um individual). Se o campo estiver em branco, os pedidos são aprovados automaticamente se o domínio corresponder.', 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.': 'O Sistema de Comunicação de Incidentes permite o Público em Geral reportar incidentes & ter esses rastreados.', 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'A Localização da Pessoa vem do, que pode ser geral (para relatórios) ou precisa (para exibir em um mapa). Digite alguns caracteres para procurar nos locais disponíveis.', 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'O local que a pessoa vai, que pode ser genérico (para Relatórios) ou preciso (para exibir em um mapa). Digite alguns caracteres para procurar nos locais disponíveis.', 'The Media Library provides a catalog of digital media.': 'A Biblioteca de mídias fornece um catálogo de mídia digital.', 'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': 'O módulo de mensagens é o hub de comunicação principal do sistema Sahana. É utilizado para enviar alertas e/ou mensagens utilizando o SMS & e-mail para diferentes grupos e indivíduos antes, durante e após um desastre.', 'The Organization Registry keeps track of all the relief organizations working in the area.': 'O registro Da Organização mantém controle de todos as organizações de apoio que trabalham na área.', 'The Organization Registry keeps track of all the relief organizations working in the disaster region. It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'O registro da Organização mantém controle de todas organizações de ajuda trabalhando numa região de desastre. Ele captura não apenas os locais onde elas estão ativas, mas também captura informações sobre o conjunto de projetos que está fornecendo em cada região.', 'The Patient Tracking system keeps track of all the evacuated patients & their relatives.': 'The Patient Tracking system keeps track of all the evacuated patients & their relatives.', 'The Person currently filling this Role.': 'A pessoa atualmente preenchendo esta função.', 'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.': 'O módulo acompanhamento do projeto permite a criação de atividades para preencher Lacunas nas avaliações de necessidades.', 'The Requests Management System is a central online repository where all relief organizations, relief workers, government agents and camp sites for displaced personnel can coordinate the supply of aid with their demand. It allows users to allocate the available resources to fulfill the demands effectively and efficiently.': 'O sistema De Gerenciamento De Pedidos é um repositório online central em todas as organizações de ajuda, trabalhadores de assistência, agentes do governo e sites de acampamento para a equipe de refugiados pode coordenar o fornecimento da ajuda com seu pedido. Ela permite que usuários aloquem os recursos disponíveis para suprir as demandas de forma efetiva e eficiente.', 'The Role this person plays within this hospital.': 'A Função desta pessoa neste hospital.', 'The Role to which this Role reports.': 'A função à qual essa função responde.', 'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.': 'O registro do Abrigo rastreia todos os detalhes básicos abrigos e armazena sobre eles. Ele colabora com outros módulos para rastrear as pessoas associadas com um abrigo, os serviços disponíveis etc.', 'The Shelter this Request is from': 'O pedido deste abrigo é de', 'The Shelter this Request is from (optional).': 'O pedido este Abrigo é de (opcional).', 'The Shelter this person is checking into.': 'O abrigo esta pessoa está verificando no.', 'The URL for the GetCapabilities of a WMS Service whose layers you want accessible via the Map.': 'A URL para o GetCapabilities de um serviço WMS cujas camadas você deseja acessíveis através do mapa.', 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': 'A URL para a página do GetCapabilities de um Web Map Service (WMS), cujas camadas que você deseja disponíveis através do painel do navegador no Mapa.', "The URL of the image file. If you don't upload an image file, then you must specify its location here.": 'A URL do arquivo de imagem. Se voce não fizer o upload de um arquivo de imagem, então voce deverá especificar sua localização aqui.', 'The URL of your web gateway without the post parameters': 'A URL de seu gateway da web sem os parâmetros post', 'The URL to access the service.': 'A URL para acessar o serviço.', 'The Unique Identifier (UUID) as assigned to this facility by the government.': 'O Idenfificador Único (UUID) conforme designado pelo governo para esta filial.', 'The asset must be assigned to a site OR location.': 'O ativo deve ser assinalado para um site ou local.', 'The attribute which is used for the title of popups.': 'O atributo que é usado para o título de popups.', 'The attribute within the KML which is used for the title of popups.': 'O Atributo dentro do KML que é utilizado para o título dos pop-ups.', 'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)': 'O Atributo(s) no KML que são utilizados para o corpo dos pop-ups. ( utilizar um espaço entre atributos )', 'The body height (crown to heel) in cm.': 'A altura do corpo (cabeça até o calcanhar) em cm.', 'The contact person for this organization.': 'A pessoa de contato nessa organização.', 'The country the person usually lives in.': 'O país que a pessoa vive habitualmente', 'The default Facility for which this person is acting.': 'The default Facility for which this person is acting.', 'The default Facility for which you are acting.': 'The default Facility for which you are acting.', 'The default Organization for whom this person is acting.': 'A Organização padrão para quem esta pessoa está atuando.', 'The default Organization for whom you are acting.': 'A Organização padrão para quem você está atuando.', 'The duplicate record will be deleted': 'O registro duplicado será excluído', 'The first or only name of the person (mandatory).': 'O primeiro nome ou único nome da pessoa (obrigatório).', 'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.': 'O formulário da URL é http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service que representa o caminho da URL para o WMS.', 'The language you wish the site to be displayed in.': 'O idioma que você deseja que o site seja exibido.', 'The last known location of the missing person before disappearance.': 'A última localização conhecida da pessoa desaparecida antes do desaparecimento.', 'The level at which Searches are filtered.': 'The level at which Searches are filtered.', 'The list of Brands are maintained by the Administrators.': 'A lista de Marcas serão mantidas pelos administradores.', 'The list of Catalogs are maintained by the Administrators.': 'A lista de catálogos é mantida pelos administradores.', 'The list of Item categories are maintained by the Administrators.': 'A lista de categorias dos itens são mantidas pelos administradores.', 'The map will be displayed initially with this latitude at the center.': 'O mapa será exibido inicialmente com esta latitude no centro.', 'The map will be displayed initially with this longitude at the center.': 'O mapa será exibido inicialmente com esta longitude no centro.', 'The minimum number of features to form a cluster.': 'O número mínimo de recursos para formar um cluster.', 'The name to be used when calling for or directly addressing the person (optional).': 'O nome a ser usado ao chamar por ou diretamente endereçar a pessoa (opcional).', 'The next screen will allow you to detail the number of people here & their needs.': 'A próxima tela permitirá que você detalhe o número de pessoas aqui e as suas necessidades.', 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'O número de unidades de medida dos Itens alternativos é igual a uma unidade de medida do Item', 'The number of pixels apart that features need to be before they are clustered.': 'O número de separado de pixels de funcionalidades tem que ser antes que eles sejam agrupados.', 'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.': 'O número de títulos em torno do mapa visível para fazer download. Zero significa que a primeira página carrega mais rápido, números maiores que zero significam que as paginas seguintes são mais rápida.', 'The person at the location who is reporting this incident (optional)': 'A pessoa no local que está relatando este incidenten (opcional)', 'The person reporting the missing person.': 'A pessoa reportando o desaparecimento de alguem', 'The post variable containing the phone number': 'A variavel post contendo o numero de telefone', 'The post variable on the URL used for sending messages': 'A variável post no URL é utilizada para enviar mensagens', 'The post variables other than the ones containing the message and the phone number': 'As variáveis post diferentes das que contém a mensagem e o número de telefone', 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows': 'A porta serial no qual o modem está conectado-/dev/ttyUSB0, etc. No linux e com1, com2, etc. No Windows', 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.': 'O servidor não receber uma resposta oportuna de outro servidor que ele estava acessando para preencher o pedido pelo navegador.', 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.': 'O servidor recebeu uma resposta incorreta a partir de outro servidor que ele estava acessando para preencher o pedido pelo navegador.', 'The site where this position is based.': 'O local onde esta posição se baseia.', 'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.': 'O pessoal responsável pelas Instalações podem fazer pedidos de assistência. Compromissos podem ser feitas em relação a esses pedidos no entanto os pedidos permanecem abertas até o SOLICITANTE confirma que o pedido foi concluído.', 'The subject event no longer poses a threat or concern and any follow on action is described in <instruction>': 'O acontecimento já não representa uma ameaça ou preocupação e a ação a ser tomada é descrita em<instruction>', 'The time at which the Event started.': 'O momento em que o evento começou.', 'The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones.': 'The time difference between UTC and your timezone, specify as +HHMM for eastern or -HHMM for western timezones.', 'The title of the WMS Browser panel in the Tools panel.': 'O título do painel do navegador WMS em ferramentas.', 'The token associated with this application on': 'O token associado a este aplicativo em', 'The unique identifier which identifies this instance to other instances.': 'O indentificador único diferencia esta instância de outras.', 'The way in which an item is normally distributed': 'O modo em que um item é normalmente distribuído', 'The weight in kg.': 'O peso em quilogramas.', 'Theme': 'Tema', 'Theme Details': 'Detalhes do Tema', 'Theme added': 'Tema incluído', 'Theme deleted': 'Tema excluído', 'Theme updated': 'Tema atualizado', 'Themes': 'Temas', 'There are errors': 'Há erros', 'There are insufficient items in the Inventory to send this shipment': 'não há itens suficientes no armazém para o envio desse carregamento', 'There are multiple records at this location': 'Há vários registros neste local', 'There are not sufficient items in the Inventory to send this shipment': 'não há itens suficientes no inventário para enviar esse carregamento', 'There is no address for this person yet. Add new address.': 'Não há endereço para esta pessoa ainda. Adicionar novo endereço.', 'There was a problem, sorry, please try again later.': 'There was a problem, sorry, please try again later.', 'These are settings for Inbound Mail.': 'Estas são as configurações para Correio de entrada.', 'These are the Incident Categories visible to normal End-Users': 'Estes são as Categorias de incidentes visíveis para usuários finais normais.', 'These need to be added in Decimal Degrees.': 'estas precisam ser incluídas em graus decimais.', 'They': 'Eles', 'This appears to be a duplicate of': 'Isto parece ser duplicado de', 'This appears to be a duplicate of ': 'This appears to be a duplicate of ', 'This email address is already in use': 'This email address is already in use', 'This file already exists on the server as': 'Este arquivo já existe como no servidor', 'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.': 'Isso é apropriado se esse nível estiver em construção. Para evitar modificação acidental após esse nível estar concluído, pode ser configurado como False.', 'This is the way to transfer data between machines as it maintains referential integrity.': 'Este é o caminho para a transferência de dados entre máquinas que mantém a integridade referencial.', 'This is the way to transfer data between machines as it maintains referential integrity...duplicate data should be removed manually 1st!': 'Este é o caminho para a transferência de dados entre máquinas que mantém a integridade referencial...duplicado dados devem ser removidos manualmente 1ᵉʳ!', 'This level is not open for editing.': 'Este nível não é aberto para edição.', 'This might be due to a temporary overloading or maintenance of the server.': 'Isso pode ser devido a uma sobrecarga temporária ou manutenção do servidor.', 'This module allows Inventory Items to be Requested & Shipped between the Inventories of Facilities.': 'Este módulo permite que itens de inventário sejam Solicitados & Enviados entre os Inventários das instalações.', 'This module allows you to manage Events - whether pre-planned (e.g. exercises) or Live Incidents. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.': 'This module allows you to manage Events - whether pre-planned (e.g. exercises) or Live Incidents. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.', 'This module allows you to plan scenarios for both Exercises & Events. You can allocate appropriate Resources (Human, Assets & Facilities) so that these can be mobilized easily.': 'Este módulo permite que você planeje cenários para os Exercícios & Eventos. Você pode alocar apropriado recursos (humanos, Ativos e Recursos) para que estes possam ser mobilizados facilmente.', 'This page shows you logs of past syncs. Click on the link below to go to this page.': 'Esta página mostra as logs das sincronizações passadas. Clique no link abaixo para ir para essa página.', 'This screen allows you to upload a collection of photos to the server.': 'Esta tela permite que você faça upload de um conjunto de fotografias para o servidor.', 'This setting can only be controlled by the Administrator.': 'Esta definicão só pode ser controlado pelo administrador.', 'This shipment has already been received.': 'Este carregamento já foi recebido.', 'This shipment has already been sent.': 'Este carregamento já foi enviado.', 'This shipment has not been received - it has NOT been canceled because can still be edited.': 'Este carregamento não foi recebido-ele não foi cancelado porque ainda pode ser editado.', 'This shipment has not been sent - it has NOT been canceled because can still be edited.': 'Este carregamento não foi enviado- ele não foi cancelado porque ainda pode ser editado.', 'This shipment will be confirmed as received.': 'Este carregamento será confirmado como recebido.', 'This value adds a small mount of distance outside the points. Without this, the outermost points would be on the bounding box, and might not be visible.': 'Esse valor inclui um pequeno valor de distância fora dos pontos. Sem isto, os pontos mais afastados estariam na caixa delimitadora, e podem não estar visíveis.', 'This value gives a minimum width and height in degrees for the region shown. Without this, a map showing a single point would not show any extent around that point. After the map is displayed, it can be zoomed as desired.': 'Este valor fornece uma largura e altura minimas em graus para a região mostrada. Sem isto, um mapa que mostre um ponto único não mostraria nenhuma extensão ao redor desse ponto. Depois que o mapa for exibido, pode ser ampliado, conforme desejado.', 'Thunderstorm': 'Trovoada', 'Thursday': 'Quinta-feira', 'Ticket': 'Bilhete', 'Ticket Details': 'Detalhes do bilhete', 'Ticket ID': 'ID do Bilhete', 'Ticket added': 'Bilhete incluído', 'Ticket deleted': 'Bilhete removido', 'Ticket updated': 'Bilhete atualizado', 'Ticketing Module': 'Módulo de bilhetes', 'Tickets': 'Bilhetes', 'Tiled': 'Tiled', 'Tilt-up concrete': 'Inclinar concreto', 'Timber frame': 'Quadro de madeira', 'Timeline': 'Prazo', 'Timeline Report': 'Relatório de períodos de tempo', 'Timestamp': 'Timestamp', 'Timestamps can be correlated with the timestamps on the photos to locate them on the map.': 'Timestamps can be correlated with the timestamps on the photos to locate them on the map.', 'Title': 'título', 'Title to show for the Web Map Service panel in the Tools panel.': 'Título para mostrar o painel de serviço de Mapa da Web no painel de Ferramentas.', 'To': 'para', 'To Location': 'Localidade de destino', 'To Person': 'Para Pessoa', 'To begin the sync process, click the button on the right =>': 'Para iniciar o processo de Sincronização, clique no botão à direita.', 'To begin the sync process, click the button on the right => ': 'To begin the sync process, click the button on the right => ', 'To begin the sync process, click this button =>': 'Para iniciar o processo de Sincronização, clique neste botão.', 'To begin the sync process, click this button => ': 'To begin the sync process, click this button => ', 'To create a personal map configuration, click': 'Para criar uma configuração do mapa pessoal, clique', 'To create a personal map configuration, click ': 'To create a personal map configuration, click ', 'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in models/000_config.py': 'Para editar OpenStreetMap, você precisa editar as configurações do OpenStreetMap em models/000_config.py', 'To search by job title, enter any portion of the title. You may use % as wildcard.': 'Para pesquisar por título, digite qualquer parte do título. Pode utilizar o % como um substituto para qualquer caracter.', "To search by person name, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Para pesquisar por nome, digite qualquer do primeiro, meio ou últimos nomes, separados por espaços. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todas as pessoas.", "To search for a body, enter the ID tag number of the body. You may use % as wildcard. Press 'Search' without input to list all bodies.": "Para procurar um corpo, digite o número da ID do corpo. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todos os organismos.", "To search for a hospital, enter any of the names or IDs of the hospital, or the organization name or acronym, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.": "Para procurar um hospital, digite qualquer um dos nomes ou IDs do hospital, ou o nome da organização ou Acrônimo, separados por espaços. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todos os hospitais.", "To search for a hospital, enter any of the names or IDs of the hospital, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all hospitals.": "Para procurar um hospital, digite qualquer um dos nomes ou IDs do hospital, separados por espaços. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todos os hospitais.", "To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.": "Para procurar um local, digite o nome. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todos os locais.", "To search for a patient, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all patients.": "To search for a patient, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all patients.", "To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Para procurar por uma pessoa, digite qualquer do primeiro, meio ou últimos nomes e/ou um número de ID de uma pessoa, separados por espaços. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todas as pessoas.", "To search for a person, enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Para procurar por uma pessoa, digite ou o primeiro nome, ou o nome do meio ou sobrenome, separados por espaços. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todas as pessoas.", "To search for an assessment, enter any portion the ticket number of the assessment. You may use % as wildcard. Press 'Search' without input to list all assessments.": "Para procurar por uma avaliação, digite qualquer parte o número da permissão da avaliação. Pode utilizar o % como um substituto para qualquer caracter. PRESSIONE ' Search' sem entrada para listar todas as avaliações.", 'To variable': 'Para variável', 'Tools': 'ferramentas', 'Tornado': 'tornado', 'Total': 'Total', 'Total # of Target Beneficiaries': 'Nº Total de Beneficiários De Destino', 'Total # of households of site visited': 'Nº Total de famílias de site Visitado', 'Total Beds': 'Total de Camas', 'Total Beneficiaries': 'Total de Beneficiários', 'Total Cost per Megabyte': 'Custo Total por Megabyte', 'Total Cost per Minute': 'Custo Total por Minuto', 'Total Monthly': 'Total Mensal', 'Total Monthly Cost': 'Custo Total mensal', 'Total Monthly Cost:': 'Custo Total mensal:', 'Total Monthly Cost: ': 'Total Monthly Cost: ', 'Total One-time Costs': 'Total Um tempo de Custos', 'Total Persons': 'Totalizar Pessoas', 'Total Recurring Costs': 'Totalizar Custos Recorrentes', 'Total Unit Cost': 'Total do custo unitário', 'Total Unit Cost:': 'Custo Unitário Total:', 'Total Unit Cost: ': 'Total Unit Cost: ', 'Total Units': 'Total de unidades', 'Total gross floor area (square meters)': 'Total de área bruta (metros quadrados)', 'Total number of beds in this hospital. Automatically updated from daily reports.': 'Número Total de leitos neste hospital. Atualizado automaticamente a partir de relatórios diários.', 'Total number of houses in the area': 'Número Total de casas na área', 'Total number of schools in affected area': 'Número Total de escolas em área afetada', 'Total population of site visited': 'Totalizar População do site Visitado', 'Totals for Budget:': 'Total para Orçamento', 'Totals for Bundle:': 'Total do Pacote', 'Totals for Kit:': 'Totais para Kit', 'Tourist Group': 'Grupo turístico', 'Town': 'Urbano', 'Traces internally displaced people (IDPs) and their needs': 'Rastreia pessoas deslocadas internamente (PDI) e suas necessidades', 'Tracing': 'Rastreio', 'Track': 'Rastrear', 'Track Details': 'Detalhes do restraio', 'Track deleted': 'Rastreio excluído', 'Track updated': 'Rastreamento atualizado', 'Track uploaded': 'Rastreamento enviado', 'Track with this Person?': 'RASTREAR com esta pessoa?', 'Tracking of Patients': 'Tracking of Patients', 'Tracking of Projects, Activities and Tasks': 'Rastreamento de projetos, atividades e tarefas', 'Tracking of basic information on the location, facilities and size of the Shelters': 'Rastreamento de informações básicas sobre a localização, instalações e tamanho dos abrigos', 'Tracks': 'Tracks', 'Tracks the location, distibution, capacity and breakdown of victims in Shelters': 'Rastreia o local, distribuição, capacidade e discriminação da vítima em Abrigos', 'Traffic Report': 'Relatório de tráfego', 'Training': 'Treinamento', 'Training Course Catalog': 'Catálogo de cursos de treinamento', 'Training Details': 'Detalhes do treinamento', 'Training added': 'Treinamento incluído', 'Training deleted': 'Treinamento excluído', 'Training updated': 'Treinamento atualizado', 'Trainings': 'Treinamentos', 'Transit': 'Trânsito', 'Transit Status': 'Status do Transito', 'Transition Effect': 'Efeito de Transição', 'Transparent?': 'TRANSPARENTE?', 'Transportation assistance, Rank': 'Assistência de transporte, Classificação', 'Trauma Center': 'Centro de traumas', 'Travel Cost': 'Custo da Viagem', 'Tropical Storm': 'Tempestade Tropical', 'Tropo': 'substiuir, mudar', 'Tropo Messaging Token': '<PASSWORD>', 'Tropo Settings': 'Configurações esteja doido parceiro', 'Tropo Voice Token': '<PASSWORD>', 'Tropo settings updated': 'Configurações Tropo Atualizadas', 'Truck': 'Caminhão', 'Try checking the URL for errors, maybe it was mistyped.': 'Tente verificar se existem erros na URL, talvez tenha sido um erro de digitação', 'Try hitting refresh/reload button or trying the URL from the address bar again.': 'Tente apertar o botão atualizar/recarregar ou tente a URL a partir da barra de endereços novamente', 'Try refreshing the page or hitting the back button on your browser.': 'Tente atualizar a página ou apertar o botão voltar em seu navegador.', 'Tsunami': 'Tsunami', 'Tuesday': 'Terça-feira', 'Twitter': 'Twitter', 'Twitter ID or #hashtag': 'ID Twitter ou #hashtag', 'Twitter Settings': 'Configurações do Twitter', 'Type': 'type', 'Type of Construction': 'Tipo de Construção', 'Type of water source before the disaster': 'Tipo de fonte de água antes do desastre', "Type the first few characters of one of the Person's names.": 'Digite os primeiros caracteres de um dos nomes da pessoa.', 'UID': 'uid', 'UN': 'ONU', 'URL': 'Localizador-Padrão de Recursos', 'UTC Offset': 'UTC Offset', 'Un-Repairable': 'ONU-Reparáveis', 'Unable to parse CSV file!': 'Não é possível analisar Arquivo CSV!', 'Understaffed': 'Pessoal', 'Unidentified': 'Não identificado', 'Unit Cost': 'Custo por unidade', 'Unit added': 'Unidade incluída', 'Unit deleted': 'Unidade Excluída', 'Unit of Measure': 'Unidade de medida', 'Unit updated': 'Unidade Atualizados', 'Units': 'Unidades', 'Unknown': 'unknown', 'Unknown Peer': 'Peer desconhecido', 'Unknown type of facility': 'Tipo desconhecido de instalação', 'Unreinforced masonry': 'Alvenaria obras', 'Unresolved Conflicts': 'Conflitos não resolvidos', 'Unsafe': 'Inseguro', 'Unselect to disable the modem': 'Desmarcar para desativar o modem', 'Unselect to disable this API service': 'Unselect to disable this API service', 'Unselect to disable this SMTP service': 'Unselect to disable this SMTP service', 'Unsent': 'não enviado', 'Unsupported data format!': 'Formato de dados não Suportado!', 'Unsupported method!': 'Método não Suportado!', 'Update': 'atualização', 'Update Activity Report': 'Atualizar Relatório de atividade', 'Update Cholera Treatment Capability Information': 'Atualizar informações de capacidade de tratamento de Cólera', 'Update Request': 'Atualizar Pedido', 'Update Service Profile': 'Atualizar Perfil de Serviço', 'Update Status': 'Status da Atualização', 'Update Task Status': 'Atualizar Status da Tarefa', 'Update Unit': 'Atualizar Unidade', 'Update if Master': 'Atualizar se for o principal', 'Update if Newer': 'Atualizar se Mais Recente', 'Update your current ordered list': 'ATUALIZE a seu atual lista ordenada', 'Updated By': 'Atualizado por', 'Upload Comma Separated Value File': 'Upload Comma Separated Value File', 'Upload Format': 'Upload Format', 'Upload OCR Form': 'Upload OCR Form', 'Upload Photos': 'Fazer Upload de Fotos', 'Upload Spreadsheet': 'Fazer atualizacao de Planilha', 'Upload Track': 'Pista de carregamento', 'Upload a CSV file': 'Upload a CSV file', 'Upload a CSV file formatted according to the Template.': 'Upload a CSV file formatted according to the Template.', 'Upload a Spreadsheet': 'Fazer Upload de uma planilha', 'Upload an image file (bmp, gif, jpeg or png), max. 300x300 pixels!': 'Fazer Upload de um arquivo de imagem (bmp, gif, jpeg ou png), máx. 300x300 pixels!', 'Upload an image file here.': 'Fazer atualizacao de um arquivo de imagem aqui.', "Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.": 'Fazer atualizacao de um arquivo de imagem aqui. Se voce não fizer o upload de um arquivo de imagem, então voce deverá especificar sua localização no campo URL', 'Upload an image, such as a photo': 'Fazer Upload de uma imagem, como uma foto', 'Uploaded': 'Uploaded', 'Urban Fire': 'Incêndio urbano', 'Urban area': 'Zona Urbana', 'Urdu': 'Urdu', 'Urgent': 'Urgente', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Utilize (...)&(...) para e, (...)|(...) ou para, e ~(...) para não para construir consultas mais complexas.', 'Use Geocoder for address lookups?': 'Utiliza Geocodificador para consultas de endereços?', 'Use default': 'usar o padrão', 'Use these links to download data that is currently in the database.': 'Use estes links para fazer o download de dados actualmente na base de dados.', 'Use this to set the starting location for the Location Selector.': 'Use this to set the starting location for the Location Selector.', 'Used by IRS & Assess': 'Utilizado pela Receita Federal & Avaliar', 'Used in onHover Tooltip & Cluster Popups to differentiate between types.': 'Utilizado em onHover De Dicas & Cluster Popups para diferenciar entre tipos.', 'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.': 'Utilizado para construir onHover Dicas & primeiro campo também utilizado no Popups Cluster para diferenciar entre os registros.', 'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Usado para verificar latitude de locais inseridos é razoável. Pode ser utilizado para filtrar listas de recursos que possuem locais.', 'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Usado para verificar que longitude de locais inserido é razoável. Pode ser utilizado para filtrar listas de recursos que possuem locais.', 'Used to import data from spreadsheets into the database': 'Para importar dados utilizada a partir de planilhas no banco de dados', 'Used within Inventory Management, Request Management and Asset Management': 'Utilizado no gerenciamento de inventário, gerenciamento de Pedido e gerenciamento de ativos', 'User': 'usuário', 'User Account has been Disabled': 'Conta de Usuário foi Desativado', 'User Details': 'Detalhes do Usuário', 'User ID': 'User ID', 'User Management': 'gerenciamento do usuário', 'User Profile': 'Perfil do Utilizador', 'User Requests': 'Pedidos do Utilizador', 'User Updated': 'Utilizador actualizado', 'User added': 'Usuário Incluído', 'User already has this role': 'Usuário já tem essa função', 'User deleted': 'Usuário Excluído', 'User updated': 'Utilizador actualizado', 'Username': 'userName', 'Users': 'usuários', 'Users removed': 'Utilizadores removidos', 'Uses the REST Query Format defined in': 'Utiliza o formato de consulta REST definido em', 'Ushahidi': 'Ushahidi', 'Utilities': 'Serviços Públicos', 'Utility, telecommunication, other non-transport infrastructure': 'Serviços Públicos, telecomunicações, outra infra-estrutura não-transporte', 'Vacancies': 'Vagas', 'Value': 'value', 'Various Reporting functionalities': 'Diversas funcionalidades de relatório', 'Vehicle': 'veículo', 'Vehicle Crime': 'Roubo/Furto de veículo', 'Vehicle Details': 'Vehicle Details', 'Vehicle Details added': 'Vehicle Details added', 'Vehicle Details deleted': 'Vehicle Details deleted', 'Vehicle Details updated': 'Vehicle Details updated', 'Vehicle Management': 'Vehicle Management', 'Vehicle Types': 'Tipos de veículo', 'Vehicle added': 'Vehicle added', 'Vehicle deleted': 'Vehicle deleted', 'Vehicle updated': 'Vehicle updated', 'Vehicles': 'Vehicles', 'Vehicles are assets with some extra details.': 'Vehicles are assets with some extra details.', 'Verification Status': 'Status de verificação', 'Verified?': 'Verificado?', 'Verify password': '<PASSWORD>ha', 'Version': 'Version', 'Very Good': 'Muito bom', 'Very High': 'muito alto', 'View Alerts received using either Email or SMS': 'Visualizar alertas utilizando quer o correio electrónico quer SMS.', 'View All': 'Visualizar todos', 'View All Tickets': 'View All Tickets', 'View Error Tickets': 'Ver bilhetes de erro', 'View Fullscreen Map': 'Visualização Inteira Mapa', 'View Image': 'Visualizar imagem', 'View Items': 'Ver itens', 'View On Map': 'Visualizar no mapa', 'View Outbox': 'Visualização Outbox', 'View Picture': 'Visualização de imagem', 'View Results of completed and/or partially completed assessments': 'View Results of completed and/or partially completed assessments', 'View Settings': 'Ver Configurações', 'View Tickets': 'Visualizar Bilhetes', 'View and/or update their details': 'Visualizar e/ou actualizar os seus detalhes', 'View or update the status of a hospital.': 'VISUALIZAR ou atualizar o status de um hospital.', 'View pending requests and pledge support.': 'Visualizar pedidos pendentes e suporte promessa.', 'View the hospitals on a map.': 'Visualizar os hospitais em um mapa.', 'View/Edit the Database directly': 'Visualizar/Editar o banco de dados diretamente', "View/Edit the Database directly (caution: doesn't respect the framework rules!)": 'Visualizar/Alterar a base de dados directamente ( cuidado : não cumpre com as regras da infraestrutura ! ) ).', 'Village': 'Vila', 'Village Leader': 'Líder da Aldeia', 'Visible?': 'Visível?', 'Visual Recognition': 'Reconhecimento visual', 'Volcanic Ash Cloud': 'Nuvem de cinzas vulcânicas', 'Volcanic Event': 'Evento vulcânico', 'Volume (m3)': 'Volume (m3)', 'Volunteer Availability': 'Disponibilidade de Voluntário', 'Volunteer Details': 'Detalhes do voluntário', 'Volunteer Information': 'Voluntário Informações', 'Volunteer Management': 'Gestão de voluntário', 'Volunteer Project': 'Projeto voluntário', 'Volunteer Record': 'Voluntário Registro', 'Volunteer Request': 'Pedido voluntário', 'Volunteer added': 'Voluntário incluído', 'Volunteer availability added': 'Disponibilidade de voluntário incluída', 'Volunteer availability deleted': 'Disponibilidade de voluntário excluída', 'Volunteer availability updated': 'Disponibilidade de voluntário atualizada', 'Volunteer deleted': 'Voluntário excluído', 'Volunteer details updated': 'Atualização dos detalhes de voluntários', 'Volunteer updated': 'Voluntário atualizado', 'Volunteers': 'Voluntários', 'Volunteers List': 'Voluntários Lista', 'Volunteers were notified!': 'Voluntários foram notificados!', 'Vote': 'voto', 'Votes': 'votos', 'WASH': 'LAVAR', 'WMS Browser Name': 'WMS Nome do Navegador', 'WMS Browser URL': 'WMS Navegador URL', 'Walking Only': 'Apenas andando', 'Wall or other structural damage': 'Parede ou outros danos estruturais', 'Warehouse': 'Depósito', 'Warehouse Details': 'Detalhes do Armazém', 'Warehouse added': 'Warehouse incluído', 'Warehouse deleted': 'Deposito apagado', 'Warehouse updated': 'Warehouse ATUALIZADO', 'Warehouses': 'Armazéns', 'WatSan': 'WatSan', 'Water Sanitation Hygiene': 'Saneamento de água', 'Water collection': 'Coleta de água', 'Water gallon': 'Galão de água', 'Water storage containers in households': 'Recipientes de armazenamento de água nos domicílios', 'Water supply': 'Abastecimento de água', 'Waterspout': 'Waterspout', 'We have tried': 'We have tried', 'Web API settings updated': 'Web API settings updated', 'Web Map Service Browser Name': 'Nome do mapa da Web navegador de serviços', 'Web Map Service Browser URL': 'Web Mapa Do navegador de Serviços URL', 'Website': 'WebSite', 'Wednesday': 'Wednesday', 'Weight': 'peso', 'Weight (kg)': 'peso (kg)', 'Welcome to the Sahana Portal at': 'Bem-vindo ao Portal Sahana em', 'Well-Known Text': 'Texto bem conhecido', 'What order to be contacted in.': 'What order to be contacted in.', 'Wheat': 'Trigo', 'When a map is displayed that focuses on a collection of points, the map is zoomed to show just the region bounding the points.': 'Quando o mapa é que exibido incide sobre um conjunto de pontos, o mapa é aproximado para mostrar apenas a região delimitadora dos pontos.', 'When reports were entered': 'Quando os relatórios foram Digitados', "When syncing data with others, conflicts happen in cases when two (or more) parties want to sync information which both of them have modified, i.e. conflicting information. Sync module tries to resolve such conflicts automatically but in some cases it can't. In those cases, it is up to you to resolve those conflicts manually, click on the link on the right to go to this page.": 'Quando Sincronizando dados com outros, os conflitos acontecem em casos onde dois (ou mais) grupos desejam sincronizar informações que os dois tenham modificado, ou seja, informações conflitantes. Módulo de sincronização tenta resolver esses conflitos automaticamente mas em alguns casos isso não consegue. Nesses casos, cabe a si resolver esses conflitos manualmente, clique no link à direita para ir para esta página.', 'Whiskers': 'Bigodes', 'Who is doing what and where': 'Quem está a fazer o quê e onde', 'Who usually collects water for the family?': 'Quem habitualmente colecta água para a família ?', 'Width': 'width', 'Width (m)': 'Largura (m)', 'Wild Fire': 'Fogo Selvagem', 'Wind Chill': 'Vento Frio', 'Window frame': 'Esquadria de janela', 'Winter Storm': 'Tempestade de inverno', 'Women of Child Bearing Age': 'Mulheres da criança Tendo Idade', 'Women participating in coping activities': 'Mulheres que participam em lidar atividades', 'Women who are Pregnant or in Labour': 'Mulheres que esto grávidas ou no trabalho', 'Womens Focus Groups': 'Mulheres de Grupos Foco', 'Wooden plank': 'Tábua de madeira', 'Wooden poles': 'Postes de madeira', 'Working hours end': 'Horas de trabalho final', 'Working hours start': 'Horas de trabalho iniciar', 'Working or other to provide money/food': 'Trabalhando para outros para prover dinheiro / alimentos', 'X-Ray': 'Raio-X', 'XMPP': 'XMPP', 'YES': 'YES', "Yahoo Layers cannot be displayed if there isn't a valid API Key": "Yahoo Layers cannot be displayed if there isn't a valid API Key", 'Year': 'Year', 'Year built': 'Ano de construção', 'Year of Manufacture': 'Ano de fabricação', 'Yellow': 'amarelo', 'Yes': 'YES', 'You are a recovery team?': 'Você é uma equipe de recuperação?', 'You are attempting to delete your own account - are you sure you want to proceed?': 'Você está tentando excluir sua própria conta-Tem certeza de que deseja continuar?', 'You are currently reported missing!': 'Você está atualmente desaparecido!', 'You can change the configuration of synchronization module in the Settings section. This configuration includes your UUID (unique identification number), sync schedules, beacon service and so on. Click the following link to go to the Sync Settings page.': 'Você pode alterar a configuração do Módulo de Sincronização na seção configurações. Essa configuração inclui o seu UUID (número de identificação exclusivo), Planejamentos de Sincronização, serviço Farol e assim por diante. Clique no link a seguir para ir para a página Configurações de Sincronização.', 'You can click on the map below to select the Lat/Lon fields': 'Você pode clicar no mapa abaixo para selecionar os campos Lat/Lon', 'You can select the Draw tool': 'Pode selecionar a ferramenta Desenho', 'You can set the modem settings for SMS here.': 'Pode definir a configuração do modem SMS aqui.', 'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.': 'Você pode utilizar a ferramenta de conversão para converter coordenadas de GPS ou graus/minutos/segundos.', 'You do no have permission to cancel this received shipment.': 'Você não tem permissão para cancelar o recebimento deste carregamento.', 'You do no have permission to cancel this sent shipment.': 'Você não tem permissão para cancelar o envio desse carregamento.', 'You do no have permission to make this commitment.': 'Você não tem permissão de fazer este compromisso.', 'You do no have permission to receive this shipment.': 'Você não tem permissão para receber este carregamento.', 'You do no have permission to send this shipment.': 'Você não tem permissão para enviar este carregamento.', 'You do not have permission for any facility to make a commitment.': 'Você não tem permissão em qualquer instalação para estabelecer um compromisso.', 'You do not have permission for any facility to make a request.': 'Você não tem permissão em qualquer instalação para fazer um pedido.', 'You do not have permission for any facility to receive a shipment.': 'You do not have permission for any facility to receive a shipment.', 'You do not have permission for any facility to send a shipment.': 'You do not have permission for any facility to send a shipment.', 'You do not have permission for any site to add an inventory item.': 'Você não tem permissão em qualquer site para incluir um item de inventário.', 'You do not have permission for any site to make a commitment.': 'Você não tem permissão em qualquer site para assumir um compromisso.', 'You do not have permission for any site to make a request.': 'Você não tem permissão em qualquer site para fazer um pedido.', 'You do not have permission for any site to perform this action.': 'Você não tem permissão em qualquer site para executar esta ação.', 'You do not have permission for any site to receive a shipment.': 'Você não tem permissão para qualquer site para receber um carregamento.', 'You do not have permission for any site to send a shipment.': 'Você não tem permissão em qualquer site para enviar um carregamento.', 'You do not have permission to cancel this received shipment.': 'Você não tem permissão para cancelar este carregamento recebido.', 'You do not have permission to cancel this sent shipment.': 'Você não tem permissão para cancelar essa remessa enviada.', 'You do not have permission to make this commitment.': 'Você não tem permissão para assumir este compromisso.', 'You do not have permission to receive this shipment.': 'Você não tem permissão para receber esta remessa.', 'You do not have permission to send a shipment from this site.': 'Você não tem permissão para enviar um carregamento a partir deste site.', 'You do not have permission to send this shipment.': 'Você não tem permissão para enviar este carregamento.', 'You have a personal map configuration. To change your personal configuration, click': 'Você tem uma configuração de mapa pessoal. Para alterar a sua configuração pessoal, clique', 'You have a personal map configuration. To change your personal configuration, click ': 'You have a personal map configuration. To change your personal configuration, click ', 'You have found a dead body?': 'Descobriu um cadáver ?', "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.": "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.", "You haven't made any calculations": 'Não fez quaisquer cálculos.', 'You must be logged in to register volunteers.': 'Você deve estar com login efetuado para registrar voluntários.', 'You must be logged in to report persons missing or found.': 'Você deve estar registrado para informar pessoas desaparecidas ou localizadas.', 'You must provide a series id to proceed.': 'Você deve fornecer um número de série para continuar.', 'You should edit Twitter settings in models/000_config.py': 'Você deve editar as definições do Twitter em modelos/000_config.py', 'Your current ordered list of solution items is shown below. You can change it by voting again.': 'Seu lista de itens de solução pedidos aparece abaixo. Você pode alterá-lo ao votar novamente.', 'Your post was added successfully.': 'O post foi incluído com êxito.', 'Your system has been assigned a unique identification (UUID), which other computers around you can use to identify you. To view your UUID, you may go to Synchronization -> Sync Settings. You can also see other settings on that page.': 'Uma identificação exclusiva (UUID) foi designada para o seu sistema e poderá ser usada por outros computadores ao seu redor para identificá-lo. Para visualizar o seu UUID, você pode ir para Sincronização -> configurações Sync. Você também pode ver outras configurações nesta página.', 'ZIP Code': 'ZIP Code', 'Zero Hour': 'Hora Zero', 'Zinc roof': 'Telhado de Zinco', 'Zoom': 'Zoom', 'Zoom Levels': 'Níveis de Zoom', 'active': 'ativo', 'added': 'incluído', 'all records': 'todos os registros', 'allows a budget to be developed based on staff & equipment costs, including any admin overheads.': 'Permite que um orçamento seja desenvolvido com base em despesas com o pessoal e equipamento, incluindo quaisquer despesas gerais administrativas.', 'allows for creation and management of assessments.': 'allows for creation and management of assessments.', 'allows for creation and management of surveys to assess the damage following a natural disaster.': 'permite a criação e gerenciamento de pesquisas para avaliar os danos após um desastre natural.', 'an individual/team to do in 1-2 days': 'Uma pessoa/Equipe para fazer em 1 Dias-2', 'assigned': 'designado', 'average': 'Na média', 'black': 'Preto', 'blond': 'Loiro', 'blue': 'azul', 'brown': 'Marrom', 'business_damaged': 'business_damaged', 'by': 'por', 'c/o Name': 'c/o Nome', 'can be used to extract data from spreadsheets and put them into database tables.': 'Pode ser utilizado para extrair dados de planilhas e colocá-los em tabelas de dados.', 'cancelled': 'CANCELADO', 'caucasoid': 'Caucasoid', 'check all': 'Verificar Tudo', 'click for more details': 'Clique para mais detalhes', 'click here': 'click here', 'completed': 'Concluído', 'confirmed': 'Confirmado', 'consider': 'considerar', "couldn't be parsed so NetworkLinks not followed.": 'Não pôde ser analisado então o NetworkLinks não seguiu.', 'curly': 'Encaracolado', 'currently registered': 'Atualmente registrados', 'daily': 'Diariamente', 'dark': 'Escuro', 'data uploaded': 'dados carregados', 'database': 'DATABASE', 'database %s select': '% de dados s SELECIONE', 'db': 'dB', 'deceased': 'Falecido', 'delete all checked': 'excluir todos marcados', 'deleted': 'excluídos', 'design': 'projecto', 'diseased': 'Doentes', 'displaced': 'Deslocadas', 'divorced': 'Divorciado', 'done!': 'Pronto!', 'duplicate': 'duplicar', 'edit': 'Editar', 'eg. gas, electricity, water': 'Exemplo: Gás, eletricidade, água', 'embedded': 'integrado', 'enclosed area': 'Área anexada', 'enter a number between %(min)g and %(max)g': 'enter a number between %(min)g and %(max)g', 'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g', 'export as csv file': 'Exportar como arquivo cvs.', 'fat': 'Gordura', 'feedback': 'Retorno', 'female': 'Sexo Feminino', 'flush latrine with septic tank': 'esvaziar latrina com tanque séptico', 'food_sources': 'fuentes de alimento', 'forehead': 'testa', 'form data': 'form data', 'found': 'Localizado', 'from Twitter': 'do Twitter', 'getting': 'getting', 'green': 'verde', 'grey': 'cinza', 'here': 'aqui', 'high': 'Alta', 'hourly': 'Por hora', 'households': 'Membros da família', 'identified': 'identificado', 'ignore': 'Ignore', 'in Deg Min Sec format': 'GRAUS Celsius no formato Mín. Segundo', 'in GPS format': 'GPS no formato', 'in Inv.': 'in Inv.', 'inactive': 'inativo', "includes a GroundOverlay or ScreenOverlay which aren't supported in OpenLayers yet, so it may not work properly.": 'Inclui um GroundOverlay ou ScreenOverlay que não são ainda suportados em OpenLayuers, portanto poderá não funcionar na totalidade.', 'injured': 'Feridos', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'invalid': 'inválido', 'invalid request': 'PEDIDO INVÁLIDO', 'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.': 'É um repositório central de informações em tempo real onde vítimas de desastres e seus familiares, especialmente casos isolados, refugiados e pessoas deslocadas podem ser abrigados. Informações como nome, idade, Contate o número de Bilhete de Identidade número, localização Deslocadas, e outros detalhes são capturados. Detalhes de impressão Imagem e Dedo de as pessoas possam ser transferidos por upload para o sistema. As pessoas podem também ser capturados pelo grupo por eficiência e conveniência.', 'is envisioned to be composed of several sub-modules that work together to provide complex functionality for the management of relief and project items by an organization. This includes an intake system, a warehouse management system, commodity tracking, supply chain management, fleet management, procurement, financial tracking and other asset and resource management capabilities': 'tem como visão ser composto de vários sub-módulos que interagem juntos a fim de fornecer funcionalidade complexa para o gerenciamento de itens de ajuda e projeto de uma organização. Isso inclui um sistema de admissão, um sistema de gestão de depósitos, rastreamento de mercadorias, gestão da cadeia de fornecimentos, de gestão da frota, aquisições, recursos de rastreamento financeiro de ativos e outros e gerenciamento de recursos', 'keeps track of all incoming tickets allowing them to be categorised & routed to the appropriate place for actioning.': 'Mantém controle de todos os bilhetes de entrada permitindo que sejam classificados & direcionados ao local apropriado para atuação.', 'latrines': 'privadas', 'leave empty to detach account': 'deixar em branco para desconectar a conta', 'legend URL': 'Legenda URL', 'light': 'luz', 'login': 'login', 'long': 'Longo', 'long>12cm': 'comprimento>12cm', 'low': 'baixo', 'male': 'masculino', 'manual': 'Manual', 'married': 'casado', 'medium': 'médio.', 'medium<12cm': 'médio<12cm', 'meters': 'metros', 'missing': 'ausente', 'module allows the site administrator to configure various options.': 'Módulo permite que o administrador do site configure várias opções.', 'module helps monitoring the status of hospitals.': 'Módulo ajuda monitorando o status de hospitais.', 'module provides a mechanism to collaboratively provide an overview of the developing disaster, using online mapping (GIS).': 'Módulo fornece um mecanismo para colaboração fornecem uma visão geral do desastre de desenvolvimento, utilização de mapeamento online (SIG).', 'mongoloid': 'Mongolóide', 'more': 'Mais', 'n/a': 'n/d', 'negroid': 'Negróide', 'never': 'Nunca', 'new': 'Novo(a)', 'new record inserted': 'Novo registro inserido', 'next 100 rows': 'próximas 100 linhas', 'no': 'no', 'none': 'nenhum', 'normal': 'normal', 'not accessible - no cached version available!': 'Não acessível-nenhuma versão em cache disponível!', 'not accessible - using cached version from': 'Não acessível-Utilizando versão em Cache', 'not specified': 'não especificado', 'num Zoom Levels': 'Num níveis de Zoom', 'obsolete': 'Obsoleto', 'on': 'Ligar', 'once': 'uma vez', 'open defecation': 'Abrir evacuação', 'optional': 'Optional', 'or import from csv file': 'ou importar a partir do arquivo csv', 'other': 'outros', 'over one hour': 'Mais de uma hora', 'people': 'pessoas', 'piece': 'parte', 'pit': 'cova', 'pit latrine': 'cova de latrina', 'postponed': 'Adiado', 'preliminary template or draft, not actionable in its current form': 'Modelo ou rascunho preliminar, não acionável em sua forma atual', 'previous 100 rows': '100 linhas anteriores', 'record does not exist': 'Registro não existe', 'record id': 'ID do Registro', 'red': 'vermelho', 'reported': 'relatado', 'reports successfully imported.': 'relatórios importados com êxito.', 'representation of the Polygon/Line.': 'Representação do polígono /Linha.', 'retired': 'Aposentado', 'retry': 'retry', 'river': 'Rio', 'see comment': 'Veja o comentário', 'selected': 'Selecionado', 'separated': 'Separado', 'separated from family': 'Separados da família', 'shaved': 'raspado', 'short': 'pequeno', 'short<6cm': 'pequeno<6cm', 'sides': 'lados', 'sign-up now': 'Inscreva-se agora', 'single': 'único', 'slim': 'estreito', 'specify': 'Especifique.', 'staff': 'equipe', 'staff members': 'Membros da equipe', 'state': 'Estado', 'state location': 'Localização do Estado', 'straight': 'reto', 'suffered financial losses': 'Sofreram perdas financeiras', 'table': 'table', 'tall': 'Altura', 'this': 'isto', 'times and it is still not working. We give in. Sorry.': 'times and it is still not working. We give in. Sorry.', 'to access the system': 'Para acessar o sistema', 'to download a OCR Form.': 'to download a OCR Form.', 'to reset your password': 'Para Reconfigurar sua senha', 'to verify your email': 'Para verificar seu e-mail', 'tonsure': 'tonsura', 'total': 'Total', 'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!': 'Módulo tweepy não disponível com a execução Python-isto necessita da instalação para suporte a tropo Twitter!', 'unable to parse csv file': 'Não é possível analisar arquivo csv', 'uncheck all': 'Desmarcar Tudo', 'unidentified': 'IDENTIFICADO', 'unknown': 'unknown', 'unspecified': 'UNSPECIFIED', 'unverified': 'Não Verificado', 'updated': 'Atualizado', 'updates only': 'Apenas atualizações', 'verified': 'Verificado', 'volunteer': 'voluntário', 'volunteers': 'Voluntários', 'wavy': 'Serpentina', 'weekly': 'Semanalmente', 'white': 'branco', 'wider area, longer term, usually contain multiple Activities': 'maior área, maior prazo, contém usualmente múltiplas actividades', 'widowed': 'Viúvo', 'window': 'janela', 'within human habitat': 'Dentro do habitat humano', 'xlwt module not available within the running Python - this needs installing for XLS output!': 'Módulo Xlwt não disponível no módulo Python sendo executado - isto necessita ser instalado para saída XLS!', 'yes': 'YES', }
StarcoderdataPython
4837544
# SPDX-FileCopyrightText: 2019 <NAME> for Adafruit Industries # # SPDX-License-Identifier: MIT import time import array import board import audiobusio import simpleio import neopixel #---| User Configuration |--------------------------- SAMPLERATE = 16000 SAMPLES = 1024 THRESHOLD = 100 MIN_DELTAS = 5 DELAY = 0.2 FREQ_LOW = 520 FREQ_HIGH = 990 COLORS = ( (0xFF, 0x00, 0x00) , # pixel 0 (0xFF, 0x71, 0x00) , # pixel 1 (0xFF, 0xE2, 0x00) , # pixel 2 (0xAA, 0xFF, 0x00) , # pixel 3 (0x38, 0xFF, 0x00) , # pixel 4 (0x00, 0xFF, 0x38) , # pixel 5 (0x00, 0xFF, 0xA9) , # pixel 6 (0x00, 0xE2, 0xFF) , # pixel 7 (0x00, 0x71, 0xFF) , # pixel 8 (0x00, 0x00, 0xFF) , # pixel 9 ) #---------------------------------------------------- # Create a buffer to record into samples = array.array('H', [0] * SAMPLES) # Setup the mic input mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=SAMPLERATE, bit_depth=16) # Setup NeoPixels pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False) while True: # Get raw mic data mic.record(samples, SAMPLES) # Compute DC offset (mean) and threshold level mean = int(sum(samples) / len(samples) + 0.5) threshold = mean + THRESHOLD # Compute deltas between mean crossing points # (this bit by <NAME>) deltas = [] last_xing_point = None crossed_threshold = False for i in range(SAMPLES-1): sample = samples[i] if sample > threshold: crossed_threshold = True if crossed_threshold and sample < mean: if last_xing_point: deltas.append(i - last_xing_point) last_xing_point = i crossed_threshold = False # Try again if not enough deltas if len(deltas) < MIN_DELTAS: continue # Average the deltas mean = sum(deltas) / len(deltas) # Compute frequency freq = SAMPLERATE / mean print("crossings: {} mean: {} freq: {} ".format(len(deltas), mean, freq)) # Show on NeoPixels pixels.fill(0) pixel = round(simpleio.map_range(freq, FREQ_LOW, FREQ_HIGH, 0, 9)) pixels[pixel] = COLORS[pixel] pixels.show() time.sleep(DELAY)
StarcoderdataPython
4813584
<reponame>bsmsoft/bsm import os import click from bsm.cmd import Cmd from bsm.util.option import parse_lines @click.group(context_settings=dict(help_option_names=['-h', '--help'])) @click.option('--verbose', '-v', is_flag=True, help='Verbose mode, also print debug information') @click.option('--quiet', '-q', is_flag=True, help='Quiet mode, only print error information') @click.option('--app-root', type=str, hidden=True, help='Application configuration directory') @click.option('--shell', type=str, hidden=True, help='Type of shell script') @click.option('--config-user', type=str, help='User configuration file path') @click.option('--output-format', type=str, default='plain', help='Output format (json, yaml, python, plain)') @click.option('--output-env', is_flag=True, help='Also output environment') @click.pass_context def cli(ctx, verbose, quiet, app_root, shell, config_user, output_format, output_env): if verbose: ctx.obj['config_entry']['verbose'] = verbose if quiet: ctx.obj['config_entry']['quiet'] = quiet if config_user is not None: ctx.obj['config_entry']['config_user_file'] = config_user ctx.obj['output']['format'] = output_format ctx.obj['output']['env'] = output_env # app_root and shell could not be changed by arguments under shell command if 'app_root' not in ctx.obj['config_entry'] or ctx.obj['config_entry']['app_root'] is None: ctx.obj['config_entry']['app_root'] = app_root if 'shell' not in ctx.obj['output'] or ctx.obj['output']['shell'] is None: ctx.obj['output']['shell'] = shell @cli.command() @click.pass_context def version(ctx): '''Display version information''' cmd = Cmd() cmd.execute('version', ctx.obj) @cli.command() @click.pass_context def home(ctx): '''Display home directory of bsm''' cmd = Cmd() cmd.execute('home', ctx.obj) @cli.command() @click.argument('shell', type=str) @click.pass_context def setup(ctx, shell): '''Get the setup script''' cmd = Cmd() cmd.execute('setup', ctx.obj, shell) @cli.command() @click.option('--no-default', is_flag=True, help='Do not load default release') @click.option('--show-script', is_flag=True, help='Display the shell script') @click.pass_context def init(ctx, no_default, show_script): '''Initialize bsm environment''' cmd = Cmd() ctx.obj['config_entry']['default_scenario'] = not no_default cmd.execute('init', ctx.obj, no_default, show_script, ctx.obj['output']['shell']) @cli.command() @click.option('--show-script', is_flag=True, help='Display the shell script') @click.pass_context def exit(ctx, show_script): '''Exit bsm environment completely''' cmd = Cmd() cmd.execute('exit', ctx.obj, show_script, ctx.obj['output']['shell']) @cli.command() @click.pass_context def upgrade(ctx): '''Upgrade bsm to the latest version''' cmd = Cmd() cmd.execute('upgrade', ctx.obj) @cli.command() @click.option('--version', '-n', type=str, help='Release version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.argument('config-type', type=str, required=False) @click.argument('item-list', nargs=-1, type=str, required=False) @click.pass_context def config(ctx, version, option, config_type, item_list): '''Display configuration, mostly for debug purpose''' cmd = Cmd() ctx.obj['config_entry']['scenario'] = version ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('config', ctx.obj, config_type, item_list) @cli.command() @click.option('--release-repo', '-t', type=str, help='Repository with release information') @click.option('--all', '-a', 'list_all', is_flag=True, help='List all versions') @click.option('--tag', '-g', is_flag=True, help='List tags') @click.pass_context def ls_remote(ctx, release_repo, list_all, tag): '''List all available release versions''' cmd = Cmd() ctx.obj['release_repo'] = release_repo cmd.execute('ls-remote', ctx.obj, list_all, tag) @cli.command() @click.option('--software-root', '-r', type=str, help='Local installed software root directory') @click.pass_context def ls(ctx, software_root): '''List installed release versions''' cmd = Cmd() ctx.obj['software_root'] = software_root cmd.execute('ls', ctx.obj) @cli.command() @click.pass_context def default(ctx): '''List default release''' cmd = Cmd() cmd.execute('default', ctx.obj) @cli.command() @click.pass_context def current(ctx): '''List current release''' cmd = Cmd() cmd.execute('current', ctx.obj) @cli.command() @click.option('--software-root', '-r', type=str, help='Local installed software root directory') @click.option('--release-repo', type=str, help='Repository for retrieving release information') @click.option('--release-source', type=str, help='Directory for retrieving release information. ' 'This will take precedence over "release-repo". Use this option only for development') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.option('--reinstall', is_flag=True, help='Reinstall all packages') @click.option('--update', is_flag=True, help='Update version information before installation') @click.option('--without-package', is_flag=True, help='Do not install packages, only install the release') @click.option('--force', '-f', is_flag=True, help='Skip checking system requirements') @click.option('--yes', '-y', is_flag=True, help='Install without confirmation') @click.argument('version', type=str) @click.pass_context def install(ctx, software_root, release_repo, release_source, option, reinstall, update, without_package, force, yes, version): '''Install specified release version''' cmd = Cmd() ctx.obj['config_entry']['software_root'] = software_root ctx.obj['config_entry']['release_repo'] = release_repo ctx.obj['config_entry']['release_source'] = release_source ctx.obj['config_entry']['option'] = parse_lines(option) ctx.obj['config_entry']['scenario'] = version ctx.obj['config_entry']['reinstall'] = reinstall cmd.execute('install', ctx.obj, update, without_package, force, yes) @cli.command() @click.option('--software-root', '-r', type=str, help='Local installed software root directory') @click.option('--default', '-d', is_flag=True, help='Also set the version as default') @click.option('--option', '-o', type=str, multiple=True, help='Options for the release') @click.option('--without-package', '-p', is_flag=True, help='Do not include packages environment') @click.argument('version', type=str) @click.pass_context def use(ctx, software_root, default, option, without_package, version): '''Switch environment to given release version''' cmd = Cmd() ctx.obj['config_entry']['software_root'] = software_root ctx.obj['config_entry']['option'] = parse_lines(option) ctx.obj['config_entry']['scenario'] = version cmd.execute('use', ctx.obj, default, without_package) @cli.command() @click.option('--option', '-o', type=str, multiple=True, help='Options for the release') @click.pass_context def refresh(ctx, option): '''Refresh the current release version environment''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('refresh', ctx.obj) @cli.command() @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.argument('command', nargs=-1, type=str, required=True) @click.pass_context def run(ctx, option, command): '''Run release command''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('run', ctx.obj, command) @cli.command() @click.pass_context def clean(ctx): '''Clean the current release version environment''' cmd = Cmd() cmd.execute('clean', ctx.obj) @cli.command() @click.option('--all', '-a', 'list_all', is_flag=True, help='List all available packages') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.argument('package', type=str, required=False) @click.pass_context def pkg_ls(ctx, list_all, option, package): '''List all packages of the current release versions''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-ls', ctx.obj, list_all, package) @cli.command() @click.option('--package-root', '-p', type=str, help='Package root directory for initialization, default to current directory') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.option('--yes', '-y', is_flag=True, help='Install without confirmation') @click.pass_context def pkg_init(ctx, package_root, option, yes): '''Initialize a new package from directory''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-init', ctx.obj, package_root, yes) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--category-origin', type=str, help='Find reference package from category') @click.option('--subdir-origin', type=str, help='Find reference package from sub directory') @click.option('--version-origin', type=str, help='Find reference package from package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.option('--reinstall', is_flag=True, help='Reinstall all packages') @click.option('--yes', '-y', is_flag=True, help='Install without confirmation') @click.argument('package', type=str) @click.pass_context def pkg_install(ctx, category, subdir, version, category_origin, subdir_origin, version_origin, package, option, reinstall, yes): '''Install specified package''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) ctx.obj['config_entry']['reinstall'] = reinstall cmd.execute('pkg-install', ctx.obj, category, subdir, version, category_origin, subdir_origin, version_origin, package, yes) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.argument('package', type=str, required=False) @click.pass_context def pkg_use(ctx, category, subdir, version, option, package): '''Load a package''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-use', ctx.obj, category, subdir, version, package) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.option('--rebuild', is_flag=True, help='Rebuild the package') @click.argument('package', type=str, required=False) @click.pass_context def pkg_build(ctx, category, subdir, version, option, rebuild, package): '''Build a package''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-build', ctx.obj, category, subdir, version, rebuild, package) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.option('--force', '-f', is_flag=True, help='Do not prompt for confirmation') @click.argument('package', type=str, required=False) @click.pass_context def pkg_remove(ctx, category, subdir, version, option, force, package): '''Remove a package''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-remove', ctx.obj, category, subdir, version, force, package) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.argument('package', type=str, required=False) @click.pass_context def pkg_config(ctx, category, subdir, version, option, package): '''List package config''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-config', ctx.obj, category, subdir, version, package) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.option('--all', '-a', 'list_all', is_flag=True, help='List all available packages') @click.argument('package', type=str, required=False) @click.pass_context def pkg_path(ctx, category, subdir, version, option, list_all, package): '''List package path''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-path', ctx.obj, category, subdir, version, list_all, package) @cli.command() @click.argument('package', type=str) @click.pass_context def pkg_clean(ctx, package): '''Clean a package''' cmd = Cmd() cmd.execute('pkg-clean', ctx.obj, package) @cli.command() @click.option('--category', type=str, help='Category to be installed') @click.option('--subdir', type=str, help='Sub directory for package') @click.option('--version', type=str, help='Package version') @click.option('--option', '-o', type=str, multiple=True, help='Options for release') @click.argument('package', type=str, required=False) @click.pass_context def pkg_edit(ctx, category, subdir, version, option, package): '''Edit package configuration''' cmd = Cmd() ctx.obj['config_entry']['option'] = parse_lines(option) cmd.execute('pkg-edit', ctx.obj, category, subdir, version, package) def main(cmd_name=None, app_root=None, output_shell=None, check_cli=False): '''The app_root and output_shell here take precedence over cli arguments''' cli(prog_name=cmd_name, obj={'config_entry': {'app_root': app_root}, 'output': {'shell': output_shell}, 'check_cli': check_cli})
StarcoderdataPython
3272939
# implementing my own class, continent class class Continent: def __init__(self, name, population): self.name = name self.population = population def set_continent_name(self, name): self.name = name def set_continent_population(self, population): self.population = population def get_continent_name(self): return self.name def get_continent_population(self): return self.population def display_info(self): print(f"Name of continent: {self.get_continent_name}") print(f"Population of continent: {self.get_continent_population}") class Africa(Continent): def print_complexity(self): print("Complexity Dark") africa = Africa("", 0) africa.set_continent_name("African") africa.set_continent_population(1200000) africa.display_info() africa.print_complexity()
StarcoderdataPython
3346074
<gh_stars>1-10 import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) gncdir = os.path.dirname(parentdir) docdir = os.path.dirname(gncdir) sys.path.insert(0,parentdir) sys.path.insert(0, gncdir) sys.path.insert(0, docdir) import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import BoundaryNorm from matplotlib.ticker import MaxNLocator import numpy as np import math import pyIGRF import magnetic_field_cpp ### Setting up parameters to run sweep alt = 400 year = 2015 min_lat = -90 max_lat = 90 min_lon = -180 max_lon = 180 delta = 2 lat_range = np.arange(min_lat, max_lat, delta) lon_range = np.arange(min_lon, max_lon, delta) mag_field_strength_cpp = np.zeros((np.size(lat_range), np.size(lon_range))) mag_field_strength_igrf = np.zeros((np.size(lat_range), np.size(lon_range))) err = np.zeros((np.size(lat_range), np.size(lon_range))) for i, lat in enumerate(lat_range): for j, lon in enumerate(lon_range): B_vec = magnetic_field_cpp.get_magnetic_field(lat, lon, alt, year, 10) mag_field_strength_cpp[i, j] = np.linalg.norm(B_vec) D, I, H, Bx, By, Bz, F = pyIGRF.igrf_value(lat, lon, alt, year) mag_field_strength_igrf[i, j] = F err[i, j] = abs(mag_field_strength_cpp[i, j] - mag_field_strength_igrf[i, j]) X, Y = np.meshgrid(lon_range, lat_range) fig1, ax = plt.subplots() CS = ax.contour(X, Y, mag_field_strength_cpp, 30) CB = fig1.colorbar(CS, shrink=0.8, extend='both') ax.set_title('5th Order IGRF (Our Model)') # plt.show() fig2, ax2 = plt.subplots() CS = ax2.contour(X, Y, mag_field_strength_igrf, 30) CB = fig2.colorbar(CS, shrink=0.8, extend='both') ax2.set_title('Full IGRF (True Model)') plt.show() fig2, ax2 = plt.subplots() CS = ax2.contour(X, Y, err, 30) CB = fig2.colorbar(CS, shrink=0.8, extend='both') ax2.set_title('Error') plt.show()
StarcoderdataPython
4824817
<filename>bugs/PENDING_SUBMIT/0433-BAD-IMAGE-Pixel5-29b7a44e-no-opt-test/generate_cts_test.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 The GraphicsFuzz Project 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 # # https://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. """Generate a CTS test. This module/script is copied next to a specific test in your repository of bugs to generate an Amber script test suitable for adding to the CTS. In particular, the Amber script test is suitable for use with |add_amber_tests_to_cts.py|. """ from pathlib import Path from gfauto import tool, util def main() -> None: # Checklist: # - check output_amber # - check short_description # - check comment_text # - check copyright_year # - check extra_commands bug_dir = util.norm_path(Path(__file__).absolute()).parent tool.glsl_shader_job_crash_to_amber_script_for_google_cts( source_dir=bug_dir / "reduced_1", # Look at the "derived_from" field in `reduced_1/test.json` to find the original shader name. # If the shader was stable (e.g. "stable_quicksort") then you must prefix the .amber file name # with the name of the shader (using dashes instead of underscores). # The rest of the test name should describe the DIFFERENCE between the reference and variant shaders. # E.g. "stable-quicksort-composite-insert-with-constant.amber". # If the original shader was not stable then you should probably not add this test (with a few exceptions). # If you still want to add the test then the test name should approximately describe the contents of the variant # shader. E.g. "loop-with-early-return-and-function-call.amber". output_amber=bug_dir / "stable-sampler-polar-warp-do-discard-false-if.amber", work_dir=bug_dir / "work", # One sentence, 58 characters max., no period, no line breaks. # Describe the difference between the shaders, as described above for the .amber file name. # E.g. Two shaders with diff: composite insert with constant short_description="Two shaders with diff: do while discard in always false if", comment_text=""" The test renders two images using semantically equivalent shaders, and then checks that the images are similar. The test passes because the shaders have the same semantics and so the images should be the same.""", copyright_year="2021", # Pass |tool.AMBER_COMMAND_EXPECT_RED| to check that the shader renders red. extra_commands="", is_coverage_gap=False, ) if __name__ == "__main__": main()
StarcoderdataPython
4843289
<filename>google_or_tools/toNum_sat.py # Copyright 2021 <NAME> <EMAIL> # # 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. """ toNum in OR-tools CP-SAT Solver. Convert a number <-> array of int in a specific base. This is a port of my old CP model toNum.py This model was created by <NAME> (<EMAIL>) Also see my other OR-tools models: http://www.hakank.org/or_tools/ """ from __future__ import print_function from ortools.sat.python import cp_model as cp import math, sys from cp_sat_utils import toNum, SimpleSolutionPrinter, ListPrinter # # # # converts a number (s) <-> an array of integers (t) in the specific base. # # # def toNum(solver, t, s, base): # tlen = len(t) # solver.Add( # s == solver.Sum([(base**(tlen - i - 1)) * t[i] for i in range(tlen)])) def main(): model = cp.CpModel() # data n = 4 base = 10 # declare variables x = [model.NewIntVar(0, n - 1, "x%i" % i) for i in range(n)] y = model.NewIntVar(0, 10**n - 1, "y") # # constraints # # solver.Add(solver.AllDifferent([x[i] for i in range(n)])) model.AddAllDifferent(x) # solver.Add(x[0] > 0) # just for fun toNum(model, x, y, base) # # solution and search # solver = cp.CpSolver() all = x all.append(y) # solution_printer = SimpleSolutionPrinter(all) solution_printer = ListPrinter(all) status = solver.SearchForAllSolutions(model, solution_printer) if status != cp.OPTIMAL: print("No solution!") print() print("NumSolutions", solution_printer.SolutionCount()) print("NumConflicts:", solver.NumConflicts()) print("NumBranches:", solver.NumBranches()) print("WallTime:", solver.WallTime()) if __name__ == "__main__": main()
StarcoderdataPython
121605
<filename>calico/felix/test/test_endpoint.py # -*- coding: utf-8 -*- # Copyright 2014, 2015 Metaswitch Networks # # 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. """ felix.test.test_endpoint ~~~~~~~~~~~~~~~~~~~~~~~~ Tests of endpoint module. """ import gevent import logging import itertools from contextlib import nested from calico.felix.endpoint import EndpointManager from calico.felix.fiptables import IptablesUpdater from calico.felix.dispatch import DispatchChains from calico.felix.profilerules import RulesManager from gevent.event import AsyncResult import mock from mock import Mock, MagicMock, patch from calico.felix.actor import actor_message, ResultOrExc, SplitBatchAndRetry from calico.felix.test.base import BaseTestCase from calico.felix.test import stub_utils from calico.felix import config from calico.felix import devices from calico.felix import endpoint from calico.felix import futils from calico.datamodel_v1 import EndpointId _log = logging.getLogger(__name__) class TestLocalEndpoint(BaseTestCase): def setUp(self): super(TestLocalEndpoint, self).setUp() self.m_config = Mock(spec=config.Config) self.m_config.IFACE_PREFIX = "tap" self.m_iptables_updater = Mock(spec=IptablesUpdater) self.m_dispatch_chains = Mock(spec=DispatchChains) self.m_rules_mgr = Mock(spec=RulesManager) def get_local_endpoint(self, combined_id, ip_type): local_endpoint = endpoint.LocalEndpoint(self.m_config, combined_id, ip_type, self.m_iptables_updater, self.m_dispatch_chains, self.m_rules_mgr) # For purposes of our testing, we force things to happen in line. local_endpoint.greenlet = gevent.getcurrent() return local_endpoint def test_on_endpoint_update_v4(self): combined_id = EndpointId("host_id", "orchestrator_id", "workload_id", "endpoint_id") ip_type = futils.IPV4 retcode = futils.CommandOutput("", "") local_ep = self.get_local_endpoint(combined_id, ip_type) # Call with no data; should be ignored (no configuration to remove). local_ep.on_endpoint_update(None, async=False) ips = ["172.16.31.10"] iface = "tapabcdef" data = { 'endpoint': "endpoint_id", 'mac': stub_utils.get_mac(), 'name': iface, 'ipv4_nets': ips, 'profile_ids': []} # Report an initial update (endpoint creation) and check configured with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv4'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv4.assert_called_once_with(iface) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=True) # Send through an update with no changes - should redo without # resetting ARP. with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv4'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv4.assert_called_once_with(iface) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=False) # Change the MAC address and try again, leading to reset of ARP. data['mac'] = stub_utils.get_mac() with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv4'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv4.assert_called_once_with(iface) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=True) # Send empty data, which deletes the endpoint. with mock.patch('calico.felix.devices.set_routes'): local_ep.on_endpoint_update(None, async=False) devices.set_routes.assert_called_once_with(ip_type, set(), data["name"], None) def test_on_endpoint_update_v6(self): combined_id = EndpointId("host_id", "orchestrator_id", "workload_id", "endpoint_id") ip_type = futils.IPV6 retcode = futils.CommandOutput("", "") local_ep = self.get_local_endpoint(combined_id, ip_type) # Call with no data; should be ignored (no configuration to remove). local_ep.on_endpoint_update(None, async=False) ips = ["2001::abcd"] gway = "fdf8:f53e:61e4::18" iface = "tapabcdef" data = { 'endpoint': "endpoint_id", 'mac': stub_utils.get_mac(), 'name': iface, 'ipv6_nets': ips, 'ipv6_gateway': gway, 'profile_ids': []} # Report an initial update (endpoint creation) and check configured with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv6'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv6.assert_called_once_with(iface, gway) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=False) # Send through an update with no changes - should redo without # resetting ARP. with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv6'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv6.assert_called_once_with(iface, gway) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=False) # Send through an update with no changes - would reset ARP, but this is # IPv6 so it won't. data['mac'] = stub_utils.get_mac() with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv6'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv6.assert_called_once_with(iface, gway) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=False) # Send empty data, which deletes the endpoint. with mock.patch('calico.felix.devices.set_routes'): local_ep.on_endpoint_update(None, async=False) devices.set_routes.assert_called_once_with(ip_type, set(), data["name"], None) def test_on_interface_update_v4(self): combined_id = EndpointId("host_id", "orchestrator_id", "workload_id", "endpoint_id") ip_type = futils.IPV4 retcode = futils.CommandOutput("", "") local_ep = self.get_local_endpoint(combined_id, ip_type) ips = ["1.2.3.4"] iface = "tapabcdef" data = { 'endpoint': "endpoint_id", 'mac': stub_utils.get_mac(), 'name': iface, 'ipv4_nets': ips, 'profile_ids': []} # We can only get on_interface_update calls after the first # on_endpoint_update, so trigger that. with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv4'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv4.assert_called_once_with(iface) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=True) # Now pretend to get an interface update - does all the same work. with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv4'): local_ep.on_interface_update() devices.configure_interface_ipv4.assert_called_once_with(iface) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=True) def test_on_interface_update_v6(self): combined_id = EndpointId("host_id", "orchestrator_id", "workload_id", "endpoint_id") ip_type = futils.IPV6 retcode = futils.CommandOutput("", "") local_ep = self.get_local_endpoint(combined_id, ip_type) ips = ["fdf8:f53e:61e4::18"] iface = "tapabcdef" data = { 'endpoint': "endpoint_id", 'mac': stub_utils.get_mac(), 'name': iface, 'ipv6_nets': ips, 'profile_ids': []} # We can only get on_interface_update calls after the first # on_endpoint_update, so trigger that. with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv6'): local_ep.on_endpoint_update(data, async=False) self.assertEqual(local_ep._mac, data['mac']) devices.configure_interface_ipv6.assert_called_once_with(iface, None) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=False) # Now pretend to get an interface update - does all the same work. with mock.patch('calico.felix.devices.set_routes'): with mock.patch('calico.felix.devices.configure_interface_ipv6'): local_ep.on_interface_update() devices.configure_interface_ipv6.assert_called_once_with(iface, None) devices.set_routes.assert_called_once_with(ip_type, set(ips), iface, data['mac'], reset_arp=False)
StarcoderdataPython
1650267
<filename>src/main/python/lib/default/gtkgui/version_control/custom_widgets.py import gtk # Semi-ugly hack to get hold of the button in a treeview header (treeviewcolumn) # See e.g. http://www.tenslashsix.com/?p=109 or http://piman.livejournal.com/361173.html # or google on e.g. 'gtk treeview header popup menu' for more info. class ButtonedTreeViewColumn(gtk.TreeViewColumn): def __init__(self, title="", *args, **kwargs): super(ButtonedTreeViewColumn, self).__init__(None, *args, **kwargs) label = gtk.Label(title) self.set_widget(label) label.show() def get_button(self): return self.get_widget().get_ancestor(gtk.Button) def get_title(self): return self.get_widget().get_text()
StarcoderdataPython
112468
<gh_stars>0 import pickle from os.path import join import os import numpy as np def pickle_save(data_var, pkl_path, mode='wb'): with open(pkl_path, mode) as pkl_file: pickle.dump(data_var, pkl_file) def pickle_load(pkl_path, mode='rb'): with open(pkl_path, mode) as pkl_file: data = pickle.load(pkl_file) return data def join_path(root_path, path_list): if isinstance(path_list, str): path_list = [path_list] joined_path = root_path for path in path_list: joined_path = join(joined_path, path) return joined_path def check_mkdir(path): if not os.path.exists(path): os.makedirs(path) def count_word(count_dict, word): try: count_dict[word] = count_dict[word] + 1 except KeyError: count_dict[word] = 1 return count_dict def setup_folder(data_folder): search_chunks = join_path(data_folder, 'search_chunks') models = join_path(data_folder, 'models') extracted_txt = join_path(data_folder, 'extracted_txt') tensor = join_path(data_folder, 'tensor') vocab = join_path(data_folder, 'vocab') definition = join_path(data_folder, 'definition') check_mkdir(search_chunks) check_mkdir(models) check_mkdir(extracted_txt) check_mkdir(tensor) check_mkdir(vocab) check_mkdir(definition) def softmax(x): """ Normalize a numeric array with softmax function :param x: Numeric data array :type x: np.array :return: Softmax normalized data :rtype: np.array """ e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
StarcoderdataPython
114303
from http.server import BaseHTTPRequestHandler import os import subprocess import time from typing import ClassVar, Dict, List, Optional, Tuple from onceml.components.base import BaseComponent, BaseExecutor from onceml.orchestration.Workflow.types import PodContainer from onceml.types.artifact import Artifact from onceml.types.channel import Channels from onceml.types.state import State import onceml.types.channel as channel import threading import shutil from onceml.templates import ModelServing import json from onceml.utils.logger import logger from onceml.thirdParty.PyTorchServing import run_ts_serving, outputMar from onceml.thirdParty.PyTorchServing import TS_PROPERTIES_PATH, TS_INFERENCE_PORT, TS_MANAGEMENT_PORT from .Utils import generate_onceml_config_json, queryModelIsExist, registerModelJob, get_handler_path, get_handler_module import pathlib from onceml.utils.json_utils import objectDumps import onceml.global_config as global_config import onceml.utils.pipeline_utils as pipeline_utils from deprecated.sphinx import deprecated from onceml.types.component_msg import Component_Data_URL class _executor(BaseExecutor): def __init__(self): super().__init__() self.ensemble_models = [] ''' model serving template class ''' self.model_serving_cls = None self.lock = threading.Lock() # 当前正在serving的实例 self.model_serving_instance: ModelServing = None self._ts_process = None self.model_timer_thread = None @property def ts_process(self) -> subprocess.Popen: """获得当前的ts serving的Popen实例 """ return self._ts_process @ts_process.setter def ts_process(self, process: subprocess.Popen): """设置ts serving的Popen """ self._ts_process = process def Cycle(self, state: State, params: dict, data_dir, input_channels: Optional[Dict[str, Channels]] = None, input_artifacts: Optional[Dict[str, Artifact]] = None) -> Channels: training_channels = list(input_channels.values())[0] latest_checkpoint = state["model_checkpoint"] if training_channels["checkpoint"] <= latest_checkpoint: # 尝试提交最新的model if not queryModelIsExist(self.component_msg["model_name"]): mar_file = os.path.join( data_dir, "{}-{}.mar".format(self.component_msg["model_name"], str(state["model_checkpoint"]))) if os.path.exists(mar_file): if not registerModelJob( url=os.path.abspath(mar_file), handler=get_handler_module() ): logger.error("register failed") return None to_use_model_dir = os.path.join(list(input_artifacts.values())[ 0].url, "checkpoints", str(training_channels["checkpoint"])) os.makedirs(data_dir, exist_ok=True) # 打包.mar文件 if not outputMar( model_name=self.component_msg["model_name"], handler=get_handler_path(), extra_file="{},{}".format(to_use_model_dir, os.path.join( data_dir, "onceml_config.json")), export_path=data_dir, version=str(training_channels["checkpoint"])): logger.error("outputMar failed") return None # 将.mar文件重命名 os.rename(os.path.join(data_dir, "{}.mar".format( self.component_msg["model_name"])), os.path.join(data_dir, "{}-{}.mar".format( self.component_msg["model_name"], str(training_channels["checkpoint"])))) #提交 .mar if not registerModelJob( url=os.path.abspath( os.path.join(data_dir, "{}-{}.mar".format(self.component_msg["model_name"], str(training_channels["checkpoint"])))), handler=get_handler_module()): logger.error("register failed") return None state["model_checkpoint"] = training_channels["checkpoint"] return None @deprecated(reason="not use", version="0.0.1") def register_model_timer(self, state, data_dir): '''注册模型的定时器 现在的torch serving有一些问题:进程莫名退出,这时候pod的相应容器会自动重启,然后需要main容器里的框架定时进行注册 ''' def put_model(): #尝试提交 .mar while True: # 先查询 if not queryModelIsExist(self.component_msg["model_name"]): mar_file = os.path.join( data_dir, "{}-{}.mar".format(self.component_msg["model_name"], str(state["model_checkpoint"]))) if os.path.exists(mar_file): if not registerModelJob( url=os.path.abspath(mar_file), handler=get_handler_module() ): logger.error("register failed") time.sleep(2) # 创建线程 self.model_timer_thread = threading.Thread(target=put_model) def pre_execute(self, state: State, params: dict, data_dir: str): self.ensemble_models = params["ensemble_models"] self.model_serving_cls: type = params["model_serving_cls"] # 启动ts serving进程 # self.ts_process = run_ts_serving( # TS_PROPERTIES_PATH, model_store=os.path.abspath(data_dir)) initial_mar_file = os.path.join( data_dir, "{}-{}.mar".format(self.component_msg["model_name"], str(state["model_checkpoint"]))) if os.path.exists(initial_mar_file): # 提交一个.mar文件到ts serving if not registerModelJob(url=initial_mar_file, handler=get_handler_module(), maxtry=10): logger.error("register failed") # 生成handler的runtime 的配置onceml_config.json with open(os.path.join(data_dir, "onceml_config.json"), "w") as f: f.write(objectDumps(generate_onceml_config_json( working_dir=global_config.PROJECTDIR, module=self.model_serving_cls.__module__, cls_name=self.model_serving_cls.__name__, task=self.component_msg["task_name"], model=self.component_msg["model_name"], project_name=self.component_msg["project"]))) pipeline_utils.update_pipeline_model_serving_component_id( self.component_msg["project"], self.component_msg["task_name"], self.component_msg["model_name"], self.component_msg['component_id']) @deprecated(reason="not use", version="0.0.1") def exit_execute(self): """结束时,也停止响应的ts serving进程 """ if self.ts_process is not None: self.ts_process.terminate() self.ts_process.wait() self.ts_process.kill() @deprecated(reason="not use", version="0.0.1") def _POST_predict(self, req_handler: BaseHTTPRequestHandler): content_length = int(req_handler.headers['Content-Length']) post_data = req_handler.rfile.read(content_length).decode( 'utf-8') # <--- Gets the data itself '''todo:add ensemble ''' logger.info("收到predict请求") self.lock.acquire() use_instance = self.model_serving_instance self.lock.release() logger.info("获得use_instance") if use_instance is None: req_handler.send_response(200) req_handler.send_header('Content-type', 'application/json') req_handler.end_headers() req_handler.wfile.write("no available model".encode('utf-8')) else: res = self.model_serving_instance.serving(post_data, None) req_handler.send_response(200) req_handler.send_header('Content-type', 'application/json') req_handler.end_headers() req_handler.wfile.write(json.dumps(res).encode('utf-8')) class CycleModelServing(BaseComponent): def __init__(self, model_generator_component: BaseComponent, model_serving_cls, ensemble_models: list = [], **args): """部署模型 接收modelGenerator的更新的模型的消息,从而对部署的模型进行更新 """ super().__init__(executor=_executor, inputs=[model_generator_component], model_serving_cls=model_serving_cls, ensemble_models=ensemble_models, **args) self.state = { "model_checkpoint": -1, # 当前使用的模型的版本号(用模型的时间戳来辨别) } def extra_svc_port_internal(self) -> List[Tuple[str, str, int]]: return [("ts", "TCP", TS_INFERENCE_PORT)] def extra_pod_containers_internal(self) -> List[PodContainer]: ''' 注册torch serving ''' frameworks = super().extra_pod_containers_internal() ts = PodContainer("ts") ts.command = ['python'] ts.args = ["-m", "onceml.thirdParty.PyTorchServing.initProcess", "--model_store", "{}".format(os.path.join( global_config.OUTPUTSDIR, self.artifact.url, Component_Data_URL.ARTIFACTS.value))] ts.SetReadinessProbe([str(TS_INFERENCE_PORT), "/ping"]) ts.SetLivenessProbe([str(TS_INFERENCE_PORT), "/ping"]) return frameworks+[ts]
StarcoderdataPython
3375849
from PIL import Image def plus(str): # 返回指定长度的字符串,原字符串右对齐,前面填充0。 return str.zfill(8) def getCode(img): str = "" # 获取到水印的宽和高进行遍历 for i in range(img.size[0]): for j in range(img.size[1]): # 获取水印的每个像素值 rgb = img.getpixel((i, j)) # 将像素值转为二进制后保存 str = str + plus(bin(rgb[0]).replace('0b', '')) str = str + plus(bin(rgb[1]).replace('0b', '')) str = str + plus(bin(rgb[2]).replace('0b', '')) # print(plus(bin(rgb[0]).replace('0b', ''))+"\n") # print(plus(bin(rgb[1]).replace('0b', '')) + "\n") # print(plus(bin(rgb[2]).replace('0b', '')) + "\n") print(str) return str def encry(img, code): # 计数器 count = 0 # 二进制像素值的长度,可以认为要写入图像的文本长度,提取(解密)时也需要此变量 codeLen = len(code) print(codeLen) # 获取到图像的宽、高进行遍历 for i in range(img.size[0]): for j in range(img.size[1]): # 获取到图片的每个像素值 data = img.getpixel((i, j)) # 如果计数器等于长度,代表水印写入完成 if count == codeLen: break # 将获取到的RGB数值分别保存 r = data[0] g = data[1] b = data[2] """ 下面的是像素值替换,通过取模2得到最后一位像素值(0或1), 然后减去最后一位像素值,在将code的值添加过来 """ r = (r - r % 2) + int(code[count]) count += 1 if count == codeLen: img.putpixel((i, j), (r, g, b)) break g = (g - g % 2) + int(code[count]) count += 1 if count == codeLen: img.putpixel((i, j), (r, g, b)) break b = (b - b % 2) + int(code[count]) count += 1 if count == codeLen: img.putpixel((i, j), (r, g, b)) break # 每3次循环表示一组RGB值被替换完毕,可以进行写入 if count % 3 == 0: img.putpixel((i, j), (r, g, b)) img.save('output/encryption.bmp') # 获取图像对象 # 这里是原图 img1 = Image.open('pic/original.bmp') # 这里包含版权信息的96*96的二维码图片 img2 = Image.open('pic/QR.bmp') # 将图像转换为RGB通道,才能分别获取R,G,B的值 rgb_im1 = img1.convert('RGB') rgb_im2 = img2.convert('RGB') # 将水印的像素值转为文本 code = getCode(rgb_im2) # 将水印写入图像 encry(rgb_im1, code)
StarcoderdataPython
168815
<filename>secdef_parser.py #!/usr/bin/env python3 """secdef_parser.py: Tool to parse secdef and find most active instruments""" import os import sys import urllib.request as request import gzip from argparse import ArgumentParser from contextlib import closing from io import BytesIO import pandas as pd VERSION = '0.1.0' SECDEF_URL = "ftp://ftp.cmegroup.com/SBEFix/Production/secdef.dat.gz" SECDEF_MAP = {'207': 'SecurityExchange', '1151': 'SecurityGroup', '55': 'Symbol', '167': 'SecurityType', '462': 'UnderlyingProduct', '5792': 'OpenInterestQty'} ASSET_CLASS_MAP = {'2': 'Commodity/Agriculture', '4': 'Currency', '5': 'Equity', '12': 'Other', '14': 'Interest Rate', '15': 'FX Cash', '16': 'Energy', '17': 'Metals'} DEFAULT_INPUT = 'secdef.dat.gz' DEFAULT_OUTPUT = 'list.csv' secdef_keys = SECDEF_MAP.keys() def download_secdef(): """ Downloads secdef file from CME FTP server into in-memory object """ print("Downloading secdef file...") try: with closing(request.urlopen(SECDEF_URL)) as response: content_raw = response.read() except Exception as e: print(e.message) print("Unable to access secdef from CME FTP server") sys.exit(1) print("Download complete, decompressing...") content = gzip.GzipFile(fileobj=BytesIO(content_raw)).read() return content.decode('utf8') def process_row(row): """ Extracts only the fields we are interested in and converts them to key-value representation """ return dict((k, v) for k, v in zip(row[::2], row[1::2]) if k in secdef_keys) def parse_secdef(secdef_raw): """ Parses raw, uncompressed secdef data and generates cleaned dataframe with aggregate open interest quantity """ print("Parsing secdef data... this could take a minute...") # Split by row and remove empty rows secdef_raw = [l for l in secdef_raw.split('\n') if l] # Parse FIX format and prepare key-value representation for dataframe secdef_csv = ['='.join(x.rstrip('\x01').split('\x01')).split('=') for x in secdef_raw] data = map(process_row, secdef_csv) # Generate dataframe df = pd.DataFrame(data) # Convert fields to friendly names df.rename(columns=SECDEF_MAP, inplace=True) # Rearrange columns df = df[['SecurityExchange', 'SecurityGroup', 'Symbol', 'SecurityType', 'UnderlyingProduct', 'OpenInterestQty']] # Remove nulls df.dropna(inplace=True) # Convert str quantities to integer type df['OpenInterestQty'] = df['OpenInterestQty'].astype(int) # Remove non-futures instruments df = df[df['SecurityType'] == 'FUT'] # Aggregate open interest by security group agg = df.groupby(['SecurityExchange', 'SecurityGroup', 'UnderlyingProduct'], as_index=False).sum() return agg def main(): # Current path this_file_dir = os.path.dirname(os.path.realpath(__file__)) # Parse arguments parser = ArgumentParser(description="Tool to parse secdef and find most \ active instruments") group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-i', type=str, default=DEFAULT_INPUT, metavar='SECDEF_FILE', help="Input secdef.dat or secdef.dat.gz file \ (default=secdef.dat.gz)", dest='input') group.add_argument('-d', '--download', action='store_true', default=False, help="Download data from CME FTP server (default=off)", dest='download') parser.add_argument('-o', type=str, default=os.path.join(this_file_dir, DEFAULT_OUTPUT), help="Output CSV file listing most active instruments \ (default=list.csv)", dest='output') parser.add_argument('--version', action='store_true', default=False, help="Prints version number", dest='version') args = parser.parse_args() if args.version: print(VERSION) sys.exit(0) if args.download: secdef_raw = download_secdef() else: # Error-checking: -i if not os.path.isfile(args.input): print("Unable to find specified input secdef file") sys.exit(1) bname, ext = os.path.splitext(os.path.basename(args.input)) if ext == '.gz': # Expect compressed secdef file with gzip.open(args.input, 'rb') as f: secdef_raw = f.read().decode('utf8') else: # Expect uncompressed secdef file with open(args.input, 'r') as f: secdef_raw = f.read() try: agg = parse_secdef(secdef_raw) except Exception as e: print(e.message) print("Failed to parse secdef file, check if your file is corrupted") sys.exit(1) # Make output pretty agg['UnderlyingProduct'] = agg['UnderlyingProduct']\ .apply(lambda k: ASSET_CLASS_MAP.get(k)) agg.sort_values(by='OpenInterestQty', ascending=False, inplace=True) try: agg.to_csv(args.output, index=False) except Exception as e: print(e.message) print("Failed to write output file, check if directory exists") sys.exit(1) if __name__ == '__main__': main()
StarcoderdataPython
1633324
<gh_stars>1-10 from django.urls import path from rest_framework.routers import DefaultRouter from .views import ArtistViewSet artist_list = ArtistViewSet.as_view({ 'get': 'list', 'post': 'create' }) artist_detail = ArtistViewSet.as_view({ 'get': 'retrieve', }) router = DefaultRouter() router.register(r'artists', ArtistViewSet, basename='artist') urlpatterns = router.urls
StarcoderdataPython
3366885
"""Django models for Bookmarks app""" from uuid import uuid4 from django.db import models # Create your models here. class Bookmark(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=200) notes = models.TextField('Notes', blank=True) url = models.URLField('URL', unique=True) created_at = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) # Todo add tags and isfavorite #tags = models.ManyToManyField(Tag) class Tag(models.Model): '''Creates Tags for Bookmarks''' id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=30)
StarcoderdataPython
1751304
#!/usr/bin/python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Python imports import unittest # local imports from common import dewey_decimal class DeweyDecimalTest(unittest.TestCase): """Tests the Dewey Decimal Classification (DDC) definitions.""" def testDdcDivisionCount(self): self.assertEquals(100, len(dewey_decimal.GetDdcDivisions())) def testDdcDivisionByNumber(self): self.assertEquals(('900', 'Geography & history'), dewey_decimal.GetDdcDivisionByNumber(900)) self.assertEquals(('900', 'Geography & history'), dewey_decimal.GetDdcDivisionByNumber('900')) self.assertEquals(('010', 'Bibliographies'), dewey_decimal.GetDdcDivisionByNumber(10)) self.assertEquals(('010', 'Bibliographies'), dewey_decimal.GetDdcDivisionByNumber('010')) def testBadDdcDivisionByNumber(self): self.assertEquals(None, dewey_decimal.GetDdcDivisionByNumber(901)) self.assertEquals(None, dewey_decimal.GetDdcDivisionByNumber( 'Bibliographies')) def testDdcDivisionByDescription(self): self.assertEquals( ('900', 'Geography & history'), dewey_decimal.GetDdcDivisionByDescription('Geography & history')) self.assertEquals( ('010', 'Bibliographies'), dewey_decimal.GetDdcDivisionByDescription('Bibliographies')) def testBadDdcDivisionByDescription(self): self.assertEquals( None, dewey_decimal.GetDdcDivisionByDescription('No such topic'))
StarcoderdataPython
4838146
""" This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation class NestedInteger(object): def isInteger(self): # @return {boolean} True if this NestedInteger holds a single integer, # rather than a nested list. def getInteger(self): # @return {int} the single integer that this NestedInteger holds, # if it holds a single integer # Return None if this NestedInteger holds a nested list def getList(self): # @return {NestedInteger[]} the nested list that this NestedInteger holds, # if it holds a nested list # Return None if this NestedInteger holds a single integer """ from collections import deque class NestedIterator(object): def __init__(self, nestedList): # Initialize your data structure here. # :type nestedList: List[NestedInteger] self.next_elem = None self.stack = [] for elem in reversed(nestedList): self.stack.append(elem) # @return {int} the next element in the iteration def next(self): # Write your code here if self.next_elem is None: self.hasNext() temp, self.next_elem = self.next_elem, None return temp # @return {boolean} true if the iteration has more element or false def hasNext(self): # Write your code here if self.next_elem: return True while self.stack: top = self.stack.pop() if top.isInteger(): self.next_elem = top.getInteger() return True for elem in reversed(top.getList()): self.stack.append(elem) return False # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
StarcoderdataPython