code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/******************************************************************************* * This file is part of Educatio. * * Educatio is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Educatio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Educatio. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Filipe Marinho de Brito - filipe.marinho.brito@gmail.com * Rodrigo de Souza Ataides - rodrigoataides@gmail.com *******************************************************************************/ package br.com.core.conversor; import java.util.ArrayList; import java.util.List; import br.com.core.conversor.utils.ConversorUtils; import br.com.core.jdbc.dao.evento.FichaDeInscricaoTable; import br.com.core.modelo.curso.Turma; import br.com.core.modelo.evento.Evento; import br.com.core.modelo.evento.FichaDeInscricao; import br.com.core.modelo.evento.enumerator.StatusFichaInscricao; import br.com.core.modelo.pessoa.Pessoa; import br.com.core.modelo.publico.Aeroporto; import br.com.core.modelo.publico.Arquivo; import flexjson.JSONDeserializer; import flexjson.JSONSerializer; public class FichaDeInscricaoConversor { public static FichaDeInscricaoTable converterModeloParaTabela(FichaDeInscricao modelo){ FichaDeInscricaoTable fichaDeInscricaoTable = new FichaDeInscricaoTable(); fichaDeInscricaoTable.setId(modelo.getId()); Evento evento = modelo.getEvento(); if(evento!=null && evento.getId()!=null){ fichaDeInscricaoTable.setEvento(evento.getId()); } Turma turma = modelo.getTurma(); if(turma!=null && turma.getId()!=null){ fichaDeInscricaoTable.setTurma(turma.getId()); } Pessoa pessoa = modelo.getPessoa(); if(pessoa!=null && pessoa.getId()!=null){ fichaDeInscricaoTable.setPessoa(pessoa.getId()); } Aeroporto aeroportoEmbarque = modelo.getAeroportoEmbarque(); if(aeroportoEmbarque!=null && aeroportoEmbarque.getId()!=null){ fichaDeInscricaoTable.setAeroportoEmbarque(aeroportoEmbarque.getId()); } Aeroporto aeroportoEvento = modelo.getAeroportoEvento(); if(aeroportoEvento!=null && aeroportoEvento.getId()!=null){ fichaDeInscricaoTable.setAeroportoEvento(aeroportoEvento.getId()); } Aeroporto aeroportoRetorno = modelo.getAeroportoRetorno(); if(aeroportoRetorno!=null && aeroportoRetorno.getId()!=null){ fichaDeInscricaoTable.setAeroportoRetorno(aeroportoRetorno.getId()); } Arquivo oficioResposta = modelo.getOficioResposta(); if(oficioResposta!=null && oficioResposta.getId()!=null){ fichaDeInscricaoTable.setOficioResposta(oficioResposta.getId()); } fichaDeInscricaoTable.setObservacao(modelo.getObservacao()); fichaDeInscricaoTable.setTematica(modelo.getTematica()); fichaDeInscricaoTable.setLocal(modelo.getLocal()); fichaDeInscricaoTable.setPeriodo(modelo.getPeriodo()); fichaDeInscricaoTable.setNome(modelo.getNome()); fichaDeInscricaoTable.setIdentidade(modelo.getIdentidade()); fichaDeInscricaoTable.setCpf(modelo.getCpf()); fichaDeInscricaoTable.setMatricula(modelo.getMatricula()); fichaDeInscricaoTable.setSiape(modelo.getSiape()); fichaDeInscricaoTable.setMae(modelo.getMae()); fichaDeInscricaoTable.setDataNascimento(modelo.getDataNascimento()); fichaDeInscricaoTable.setNaturalidade(modelo.getNaturalidade()); fichaDeInscricaoTable.setOrgaoDeLotacao(modelo.getOrgaoDeLotacao()); fichaDeInscricaoTable.setPosto(modelo.getPosto()); fichaDeInscricaoTable.setEmail(modelo.getEmail()); fichaDeInscricaoTable.setEndereco(modelo.getEndereco()); fichaDeInscricaoTable.setBairro(modelo.getBairro()); fichaDeInscricaoTable.setCidadeUf(modelo.getCidadeUf()); fichaDeInscricaoTable.setCep(modelo.getCep()); fichaDeInscricaoTable.setTelefoneContato(modelo.getTelefoneContato()); fichaDeInscricaoTable.setTelefoneFax(modelo.getTelefoneFax()); fichaDeInscricaoTable.setTelefoneCelular(modelo.getTelefoneCelular()); fichaDeInscricaoTable.setValorAlimentacao(modelo.getValorAlimentacao()); fichaDeInscricaoTable.setValorTransporte(modelo.getValorTransporte()); fichaDeInscricaoTable.setBancoNumeroNome(modelo.getBancoNumeroNome()); fichaDeInscricaoTable.setAgencia(modelo.getAgencia()); fichaDeInscricaoTable.setContaCorrente(modelo.getContaCorrente()); fichaDeInscricaoTable.setAeroportoDeEmbarque(modelo.getAeroportoDeEmbarque()); fichaDeInscricaoTable.setAeroportoDeRetorno(modelo.getAeroportoDeRetorno()); fichaDeInscricaoTable.setAeroportoDoEvento(modelo.getAeroportoDoEvento()); fichaDeInscricaoTable.setOutroAeroportoEmbarque(modelo.getOutroAeroportoEmbarque()); fichaDeInscricaoTable.setOutroAeroportoRetorno(modelo.getOutroAeroportoRetorno()); fichaDeInscricaoTable.setNisPisPasep(modelo.getNisPisPasep()); StatusFichaInscricao status = modelo.getStatus(); if(status!=null ){ fichaDeInscricaoTable.setStatus(status.name()); } fichaDeInscricaoTable.setVersion(modelo.getVersion()); return fichaDeInscricaoTable; } public static FichaDeInscricao converterTabelaParaModelo(FichaDeInscricaoTable tabela){ FichaDeInscricao fichaDeInscricao = new FichaDeInscricao(); Evento evento = new Evento(); evento.setId(tabela.getEvento()); fichaDeInscricao.setEvento(evento); Turma turma = new Turma(); turma.setId(tabela.getTurma()); fichaDeInscricao.setTurma(turma); Pessoa pessoa = new Pessoa(); pessoa.setId(tabela.getPessoa()); fichaDeInscricao.setPessoa(pessoa); Aeroporto aeroportoEmbarque = new Aeroporto(); aeroportoEmbarque.setId(tabela.getAeroportoEmbarque()); fichaDeInscricao.setAeroportoEmbarque(aeroportoEmbarque); Aeroporto aeroportoEvento = new Aeroporto(); aeroportoEvento.setId(tabela.getAeroportoEvento()); fichaDeInscricao.setAeroportoEvento(aeroportoEvento); Aeroporto aeroportoRetorno = new Aeroporto(); aeroportoRetorno.setId(tabela.getAeroportoRetorno()); fichaDeInscricao.setAeroportoRetorno(aeroportoRetorno); Arquivo oficioResposta = new Arquivo(); oficioResposta.setId(tabela.getOficioResposta()); fichaDeInscricao.setOficioResposta(oficioResposta); fichaDeInscricao.setId(tabela.getId()); fichaDeInscricao.setVersion(tabela.getVersion()); fichaDeInscricao.setTematica(tabela.getTematica()); fichaDeInscricao.setLocal(tabela.getLocal()); fichaDeInscricao.setPeriodo(tabela.getPeriodo()); fichaDeInscricao.setNome(tabela.getNome()); fichaDeInscricao.setIdentidade(tabela.getIdentidade()); fichaDeInscricao.setCpf(tabela.getCpf()); fichaDeInscricao.setMatricula(tabela.getMatricula()); fichaDeInscricao.setSiape(tabela.getSiape()); fichaDeInscricao.setMae(tabela.getMae()); fichaDeInscricao.setDataNascimento(tabela.getDataNascimento()); fichaDeInscricao.setNaturalidade(tabela.getNaturalidade()); fichaDeInscricao.setOrgaoDeLotacao(tabela.getOrgaoDeLotacao()); fichaDeInscricao.setPosto(tabela.getPosto()); fichaDeInscricao.setEmail(tabela.getEmail()); fichaDeInscricao.setEndereco(tabela.getEndereco()); fichaDeInscricao.setBairro(tabela.getBairro()); fichaDeInscricao.setCidadeUf(tabela.getCidadeUf()); fichaDeInscricao.setCep(tabela.getCep()); fichaDeInscricao.setTelefoneContato(tabela.getTelefoneContato()); fichaDeInscricao.setTelefoneFax(tabela.getTelefoneFax()); fichaDeInscricao.setTelefoneCelular(tabela.getTelefoneCelular()); fichaDeInscricao.setValorAlimentacao(tabela.getValorAlimentacao()); fichaDeInscricao.setValorTransporte(tabela.getValorTransporte()); fichaDeInscricao.setBancoNumeroNome(tabela.getBancoNumeroNome()); fichaDeInscricao.setAgencia(tabela.getAgencia()); fichaDeInscricao.setContaCorrente(tabela.getContaCorrente()); fichaDeInscricao.setAeroportoDeEmbarque(tabela.getAeroportoDeEmbarque()); fichaDeInscricao.setAeroportoDeRetorno(tabela.getAeroportoDeRetorno()); fichaDeInscricao.setAeroportoDoEvento(tabela.getAeroportoDoEvento()); fichaDeInscricao.setOutroAeroportoEmbarque(tabela.getOutroAeroportoEmbarque()); fichaDeInscricao.setOutroAeroportoRetorno(tabela.getOutroAeroportoRetorno()); fichaDeInscricao.setNisPisPasep(tabela.getNisPisPasep()); fichaDeInscricao.setObservacao(tabela.getObservacao()); if(tabela.getStatus() !=null && !tabela.getStatus().isEmpty() ){ StatusFichaInscricao status = StatusFichaInscricao.valueOf(tabela.getStatus()); fichaDeInscricao.setStatus(status); } return fichaDeInscricao; } public static String converterModeloParaJson(FichaDeInscricao fichaDeInscricao){ JSONSerializer serializer = ConversorUtils.getJsonSerializer(); String json = serializer.serialize(fichaDeInscricao); return json; } @SuppressWarnings("rawtypes") public static FichaDeInscricao converterJsonParaModelo(String json){ JSONDeserializer deserializer = ConversorUtils.getJsonDeserializer(); Object objeto = deserializer.use(null, FichaDeInscricao.class).deserialize(json); FichaDeInscricao fichaDeInscricao = (FichaDeInscricao) objeto; return fichaDeInscricao; } public static List<FichaDeInscricao> converterJsonParaList(String json){ List<FichaDeInscricao> lista = new JSONDeserializer<List<FichaDeInscricao>>().use(null, ArrayList.class).use("values", FichaDeInscricao.class).deserialize(json); return lista; } }
filipemb/siesp
app/br/com/core/conversor/FichaDeInscricaoConversor.java
Java
gpl-3.0
9,669
package com.oocl.mnlbc.svc.impl; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.oocl.mnlbc.dao.inf.UserDAO; import com.oocl.mnlbc.model.User; import com.oocl.mnlbc.svc.inf.UserSVC; /** * * @author Lance Jasper Lopez * @desc DAO Implementation for USER TABLE * @date 07-15-2016 */ public class UserSVCImpl implements UserSVC { private UserDAO userDAO; public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } @Override @Transactional public boolean validateUser(String email, String password) { return this.userDAO.validateUser(email, password); } @Override @Transactional public User getUser(String email, String password) { return this.userDAO.getUser(email, password); } @Override @Transactional public List<User> getUserByEmail(String email) { return this.userDAO.getUserByEmail(email); } @Override @Transactional public int createUser(User user) { return this.userDAO.createUser(user); } @Override @Transactional public List<User> getBlackList() { return this.userDAO.getUserBlackList(); } @Override @Transactional public int deleteUser(long id) { return this.userDAO.deleteUser(id); } @Override public int updateUser(User user) { return this.userDAO.updateUser(user); } @Override public List<User> getAllUsers() { return this.userDAO.getAllUser(); } @Override @Transactional public int updateToPremium(String email) { return this.userDAO.updateToPremium(email); } }
MNLBC/Group2Projects
7. Group Project/W6D5_Project/W6D5_Project/Spring Hibernate/src/com/oocl/mnlbc/svc/impl/UserSVCImpl.java
Java
gpl-3.0
1,512
/* * Copyright (C) 2015 Mikhail Sapozhnikov * * This file is part of scriba-android. * * scriba-android is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * scriba-android is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with scriba-android. If not, see <http://www.gnu.org/licenses/>. * */ package org.scribacrm.scriba; import org.scribacrm.libscriba.*; import android.app.Activity; import android.util.Log; import android.app.Fragment; import android.widget.TextView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.view.View; import android.os.Bundle; import android.widget.EditText; import android.widget.ArrayAdapter; import android.content.Loader; import android.app.LoaderManager; import android.widget.AdapterView; import android.widget.Spinner; import java.util.Date; import java.text.DateFormat; import java.util.UUID; import java.util.Set; import java.util.HashSet; import android.widget.LinearLayout; public class EditEntryFragment extends Fragment implements CompanySpinnerHandler.OnSelectedListener, DateTimeHandler.OnDateChangedListener, ReminderDialog.ReminderSetListener { private class ReminderListClickListener implements View.OnClickListener { private EventAlarm _alarm = null; public ReminderListClickListener(EventAlarm alarm) { _alarm = alarm; } @Override public void onClick(View v) { // remove alarm from adapter and its view from reminder list _eventAlarmAdapter.remove(_alarm); LinearLayout reminderList = (LinearLayout)getActivity(). findViewById(R.id.event_reminder_list); reminderList.removeView(v); } } // entry data for each entry type private Company _company = null; private Event _event = null; private Project _project = null; private POC _poc = null; // company spinner handler instance private CompanySpinnerHandler _companySpinnerHandler = null; // project state spinner handler instance private ProjectStateSpinnerHandler _projectStateSpinnerHandler = null; // POC spinner handler instance private POCSpinnerHandler _pocSpinnerHandler = null; // project spinner handler instance private ProjectSpinnerHandler _projectSpinnerHandler = null; // currency spinner handler instance private CurrencySpinnerHandler _currencySpinnerHandler = null; // event type spinner handler instance private EventTypeSpinnerHandler _eventTypeSpinnerHandler = null; // event state spinner handler instance private EventStateSpinnerHandler _eventStateSpinnerHandler = null; // event date private Date _eventDate = null; // date/time handler instance private DateTimeHandler _dateTimeHandler = null; // event reminder adapter private ArrayAdapter<EventAlarm> _eventAlarmAdapter = null; public EditEntryFragment(Company company) { _company = company; } public EditEntryFragment(Event event) { _event = event; } public EditEntryFragment(Project project) { _project = project; } public EditEntryFragment(POC poc) { _poc = poc; } // save changes made by user public void save() { if (_company != null) { saveCompanyData(); } else if (_event != null) { saveEventData(); } else if (_project != null) { saveProjectData(); } else if (_poc != null) { savePOCData(); } else { Log.e("[Scriba]", "EditEntryFragment.save() called, but there's no entry data"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = null; if (_company != null) { view = inflater.inflate(R.layout.add_company, container, false); } else if (_event != null) { view = inflater.inflate(R.layout.add_event, container, false); } else if (_project != null) { view = inflater.inflate(R.layout.add_project, container, false); } else if (_poc != null) { view = inflater.inflate(R.layout.add_poc, container, false); } else { Log.e("[Scriba]", "Cannot create EditEntryFragment view, no data passed to fragment"); } return view; } @Override public void onStart() { if (_company != null) { populateCompanyView(); } else if (_event != null) { populateEventView(); } else if (_project != null) { populateProjectView(); } else if (_poc != null) { populatePOCView(); } getActivity().invalidateOptionsMenu(); super.onStart(); } // CompanySpinnerHandler.OnSelectedListener implementation @Override public void onCompanySelected(UUID companyId) { // only for event editor if (_event != null) { // populate poc spinner with people for currently selected company Spinner pocSpinner = (Spinner)getActivity().findViewById(R.id.event_poc_spinner); _pocSpinnerHandler.load(pocSpinner, companyId, _event.poc_id); // populate project spinner with projects for currently selected company Spinner projectSpinner = (Spinner)getActivity().findViewById(R.id.event_project_spinner); _projectSpinnerHandler.load(projectSpinner, companyId, _event.project_id); } } // DateTimeHandler.OnDateChangedListener implementation @Override public void onDateChanged(Date newDate) { _eventDate = newDate; TextView dateText = (TextView)getActivity().findViewById(R.id.event_date_text); TextView timeText = (TextView)getActivity().findViewById(R.id.event_time_text); DateFormat dateFormat = DateFormat.getDateInstance(); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); dateText.setText(dateFormat.format(_eventDate)); timeText.setText(timeFormat.format(_eventDate)); } // ReminderDialog.ReminderSetListener implementation @Override public void onReminderSet(byte type, long value) { if (_eventAlarmAdapter == null) { // this is the first one, create adapter _eventAlarmAdapter = new ArrayAdapter<EventAlarm>(getActivity(), R.layout.reminder_item, R.id.event_reminder_text); } EventAlarm alarm = new EventAlarm(getActivity(), value, type, _eventDate.getTime()); _eventAlarmAdapter.add(alarm); // get view and add it to the reminder list int pos = _eventAlarmAdapter.getPosition(alarm); LinearLayout reminderList = (LinearLayout)getActivity(). findViewById(R.id.event_reminder_list); View alarmView = _eventAlarmAdapter.getView(pos, null, (ViewGroup)reminderList); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); reminderList.addView(alarmView, params); alarmView.setOnClickListener(new ReminderListClickListener(alarm)); } // populate view with company data private void populateCompanyView() { EditText txt = (EditText)getActivity().findViewById(R.id.company_name_text); txt.setText(_company.name); txt = (EditText)getActivity().findViewById(R.id.company_jur_name_text); txt.setText(_company.jur_name); txt = (EditText)getActivity().findViewById(R.id.company_address_text); txt.setText(_company.address); txt = (EditText)getActivity().findViewById(R.id.company_inn_text); txt.setText(_company.inn); txt = (EditText)getActivity().findViewById(R.id.company_phonenum_text); txt.setText(_company.phonenum); txt = (EditText)getActivity().findViewById(R.id.company_email_text); txt.setText(_company.email); } // populate view with event data private void populateEventView() { EditText txt = (EditText)getActivity().findViewById(R.id.event_descr_text); txt.setText(_event.descr); // setup company spinner _companySpinnerHandler = new CompanySpinnerHandler(getActivity(), getLoaderManager(), this); Spinner companySpinner = (Spinner)getActivity().findViewById(R.id.event_company_spinner); _companySpinnerHandler.load(companySpinner, _event.company_id); // setup poc spinner _pocSpinnerHandler = new POCSpinnerHandler(getActivity(), getLoaderManager()); // load() for poc spinner is called when company spinner reports selection // setup project spinner _projectSpinnerHandler = new ProjectSpinnerHandler(getActivity(), getLoaderManager()); // load() for project spinner is called when company spinner reports selection // setup event type spinner _eventTypeSpinnerHandler = new EventTypeSpinnerHandler(getActivity()); Spinner eventTypeSpinner = (Spinner)getActivity().findViewById(R.id.event_type_spinner); _eventTypeSpinnerHandler.populateSpinner(eventTypeSpinner, _event.type); // setup event state spinner _eventStateSpinnerHandler = new EventStateSpinnerHandler(getActivity()); Spinner eventStateSpinner = (Spinner)getActivity().findViewById(R.id.event_state_spinner); _eventStateSpinnerHandler.populateSpinner(eventStateSpinner, _event.state); // event outcome txt = (EditText)getActivity().findViewById(R.id.event_outcome_text); txt.setText(_event.outcome); // setup event date and time _eventDate = new Date(_event.timestamp * 1000); _dateTimeHandler = new DateTimeHandler(_eventDate, getActivity(), getActivity().getFragmentManager(), this); View dateView = getActivity().findViewById(R.id.event_date); View timeView = getActivity().findViewById(R.id.event_time); dateView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _dateTimeHandler.showDatePicker(); } }); timeView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _dateTimeHandler.showTimePicker(); } }); // populate date and time text fields - onDateChanged() will do the job onDateChanged(_eventDate); // setup "add reminder" button View reminderView = getActivity().findViewById(R.id.event_add_reminder); reminderView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ReminderDialog dialog = new ReminderDialog(EditEntryFragment.this, getActivity()); dialog.show(getActivity().getFragmentManager(), "ReminderDialog"); } }); // create views for already existing reminders EventAlarmMgr eventAlarmMgr = new EventAlarmMgr(getActivity()); Set<Long> existingAlarms = eventAlarmMgr.getAlarms(_event.id); if (existingAlarms != null) { for (Long ts : existingAlarms) { EventAlarm eventAlarm = new EventAlarm(getActivity(), ts.longValue(), _event.timestamp); // onReminderSet will create the view for each reminder onReminderSet(eventAlarm.getIntervalType(), eventAlarm.getInterval()); } } } // populate view with project data private void populateProjectView() { EditText txt = (EditText)getActivity().findViewById(R.id.project_title_text); txt.setText(_project.title); txt = (EditText)getActivity().findViewById(R.id.project_descr_text); txt.setText(_project.descr); // setup company spinner _companySpinnerHandler = new CompanySpinnerHandler(getActivity(), getLoaderManager(), this); Spinner companySpinner = (Spinner)getActivity().findViewById(R.id.project_company_spinner); _companySpinnerHandler.load(companySpinner, _project.company_id); // setup project state spinner Spinner projStateSpinner = (Spinner)getActivity().findViewById(R.id.project_state_spinner); _projectStateSpinnerHandler = new ProjectStateSpinnerHandler(getActivity()); _projectStateSpinnerHandler.populateSpinner(projStateSpinner, _project.state); // setup currency spinner Spinner currencySpinner = (Spinner)getActivity().findViewById(R.id.project_currency_spinner); _currencySpinnerHandler = new CurrencySpinnerHandler(getActivity()); _currencySpinnerHandler.populateSpinner(currencySpinner, _project.currency); txt = (EditText)getActivity().findViewById(R.id.project_cost_text); txt.setText((new Long(_project.cost)).toString()); } // populate view with poc data private void populatePOCView() { EditText txt = (EditText)getActivity().findViewById(R.id.poc_firstname_text); txt.setText(_poc.firstname); txt = (EditText)getActivity().findViewById(R.id.poc_secondname_text); txt.setText(_poc.secondname); txt = (EditText)getActivity().findViewById(R.id.poc_lastname_text); txt.setText(_poc.lastname); txt = (EditText)getActivity().findViewById(R.id.poc_mobilenum_text); txt.setText(_poc.mobilenum); txt = (EditText)getActivity().findViewById(R.id.poc_phonenum_text); txt.setText(_poc.phonenum); txt = (EditText)getActivity().findViewById(R.id.poc_email_text); txt.setText(_poc.email); txt = (EditText)getActivity().findViewById(R.id.poc_position_text); txt.setText(_poc.position); // setup company spinner _companySpinnerHandler = new CompanySpinnerHandler(getActivity(), getLoaderManager(), this); Spinner companySpinner = (Spinner)getActivity().findViewById(R.id.poc_company_spinner); _companySpinnerHandler.load(companySpinner, _poc.company_id); } // save company modifications private void saveCompanyData() { EditText txt = (EditText)getActivity().findViewById(R.id.company_name_text); String companyName = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.company_jur_name_text); String companyJurName = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.company_address_text); String companyAddress = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.company_inn_text); String companyInn = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.company_phonenum_text); String companyPhonenum = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.company_email_text); String companyEmail = txt.getText().toString(); Company company = new Company(_company.id, companyName, companyJurName, companyAddress, companyInn, companyPhonenum, companyEmail); // update company data ScribaDBManager.useDB(getActivity()); ScribaDB.updateCompany(company); ScribaDBManager.releaseDB(); } // save event modifications private void saveEventData() { EditText txt = (EditText)getActivity().findViewById(R.id.event_descr_text); String descr = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.event_outcome_text); String outcome = txt.getText().toString(); UUID companyId = _companySpinnerHandler.getSelectedCompanyId(); UUID pocId = _pocSpinnerHandler.getSelectedPOCId(); UUID projectId = _projectSpinnerHandler.getSelectedProjectId(); byte type = _eventTypeSpinnerHandler.getSelectedType(); byte state = _eventStateSpinnerHandler.getSelectedState(); // libscriba expects timestamp in seconds long timestamp = _eventDate.getTime() / 1000; Event event = new Event(_event.id, descr, companyId, pocId, projectId, type, outcome, timestamp, state); ScribaDBManager.useDB(getActivity()); ScribaDB.updateEvent(event); ScribaDBManager.releaseDB(); saveEventReminders(event); } // save event reminder modifications private void saveEventReminders(Event event) { EventAlarmMgr evtAlarmMgr = new EventAlarmMgr(getActivity()); if (_eventAlarmAdapter != null) { // remove all alarms and add only those that are present // in the alarm adapter evtAlarmMgr.removeAlarms(event.id); for (int i = 0; i < _eventAlarmAdapter.getCount(); i++) { EventAlarm alarm = _eventAlarmAdapter.getItem(i); // event timestamp may have changed since EventAlarm object // creation, so make new object with updated event time EventAlarm updAlarm = new EventAlarm(getActivity(), alarm.getInterval(), alarm.getIntervalType(), event.timestamp); evtAlarmMgr.addAlarm(event.id, updAlarm.getAlarmTimestamp()); } } // if the alarm adapter is not instantiated at this moment, it // means there were no reminders set for this event, so do nothing } // save project modifications private void saveProjectData() { EditText txt = (EditText)getActivity().findViewById(R.id.project_title_text); String title = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.project_descr_text); String descr = txt.getText().toString(); UUID selectedCompanyId = _companySpinnerHandler.getSelectedCompanyId(); byte selectedState = _projectStateSpinnerHandler.getSelectedState(); byte selectedCurrency = _currencySpinnerHandler.getSelectedCurrency(); txt = (EditText)getActivity().findViewById(R.id.project_cost_text); long cost = Long.parseLong(txt.getText().toString(), 10); long mod_time = _project.mod_time; // if project state has changed, update mod_time if (_projectStateSpinnerHandler.hasChanged()) { mod_time = (new Date()).getTime() / 1000; // convert to seconds } Project project = new Project(_project.id, title, descr, selectedCompanyId, selectedState, selectedCurrency, cost, _project.start_time, mod_time); ScribaDBManager.useDB(getActivity()); ScribaDB.updateProject(project); ScribaDBManager.releaseDB(); } // save poc modifications private void savePOCData() { EditText txt = (EditText)getActivity().findViewById(R.id.poc_firstname_text); String firstname = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.poc_secondname_text); String secondname = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.poc_lastname_text); String lastname = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.poc_mobilenum_text); String mobilenum = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.poc_phonenum_text); String phonenum = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.poc_email_text); String email = txt.getText().toString(); txt = (EditText)getActivity().findViewById(R.id.poc_position_text); String position = txt.getText().toString(); UUID selectedCompanyId = _companySpinnerHandler.getSelectedCompanyId(); POC poc = new POC(_poc.id, firstname, secondname, lastname, mobilenum, phonenum, email, position, selectedCompanyId); ScribaDBManager.useDB(getActivity()); ScribaDB.updatePOC(poc); ScribaDBManager.releaseDB(); } }
MooseTheBrown/scriba-android
src/org/scribacrm/scriba/EditEntryFragment.java
Java
gpl-3.0
21,596
/// @addtogroup homology /// @{ ///////////////////////////////////////////////////////////////////////////// /// /// @file bin2pset.cpp /// /// @author Pawel Pilarczyk /// ///////////////////////////////////////////////////////////////////////////// // Copyright (C) 1997-2013 by Pawel Pilarczyk. // // This file is part of the Homology Library. This library is free software; // you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this software; see the file "license.txt". If not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA. // Started on November 18, 2005. Last revision: November 18, 2005. #include "chomp/system/config.h" #include "chomp/system/textfile.h" #include "chomp/system/timeused.h" #include "chomp/system/arg.h" #include <exception> #include <new> #include <iostream> #include <fstream> #include <cstdio> #include <cstdlib> #include <ctime> using namespace std; using namespace chomp::homology; // -------------------------------------------------- // -------------------- OVERTURE -------------------- // -------------------------------------------------- const char *title = "\ BinCube->PointSet, ver. 0.01. Copyright (C) 1997-2013 by Pawel Pilarczyk.\n\ This is free software. No warranty. Consult 'license.txt' for details."; const char *helpinfo = "\ Call with: file.bin file.cub -d dim -s size\n\ This program reads a set of points encoded in a binary format, and writes\n\ the coordinates of the points corresponding to nonzero bits.\n\ Additional arguments:\n\ -d N - set the space dimension (must be specified),\n\ -s N - set the size of the binary cube (repeat for other directions),\n\ -x N, -y N, -z N - set the size in the specific direction,\n\ -i N - skip the initial N bytes in the input file.\n\ -h - display this brief help information only and exit.\n\ For more information ask the author at http://www.PawelPilarczyk.com/."; const int maxdimension = 32; // -------------------------------------------------- // -------------------- BIN2PSET -------------------- // -------------------------------------------------- void inc_counter (int *counter, const int *sizes, int length) { while (length --) { ++ *counter; if (*counter < *sizes) return; *counter = 0; ++ counter; ++ sizes; } return; } /* inc_counter */ int writecubes (const char *buf, int size, int *coord, int dim, ostream &outfile) { int ncubes = 0; int buflength = (size + 7) >> 3; for (int pos = 0; pos < buflength; ++ pos) { if (!buf [pos]) continue; int maxbit = 8; if ((pos << 3) + maxbit > size) maxbit = size - (pos << 3); int byte = buf [pos]; for (int bit = 0; bit < maxbit; ++ bit) { if (!(byte & (1 << bit))) continue; outfile << "(" << ((pos << 3) + bit); for (int i = 1; i < dim; ++ i) outfile << "," << coord [i]; outfile << ")\n"; ++ ncubes; } } return ncubes; } /* writecubes */ int bincube2pointset (char *inname, char *outname, int dim, const int* sizes, int initialskip) // Returns: 0 = Ok, -1 = error (shows msg). { // open the input file ifstream infile; infile. open (inname, ios::binary | ios::in); if (initialskip) infile. seekg (initialskip); if (!infile) fileerror (inname); // prepare data to scan for cubes in the file int coord [maxdimension]; for (int i = 0; i < maxdimension; ++ i) coord [i] = 0; int linelength = (sizes [0] + 7) >> 3; char *buf = new char [linelength]; // open the output file ofstream outfile (outname); if (!outfile) fileerror (outname, "create"); // process all the rows from the file sout << "Processing lines of bits... "; int counter = 0; int ncubes = 0; while (1) { // read a line from the input file and break if none infile. read (buf, linelength); if (infile. eof ()) break; // write the cubes listed within this line to a file ncubes += writecubes (buf, sizes [0], coord, dim, outfile); // increase the other coordinates for the next line inc_counter (coord + 1, sizes + 1, dim - 1); // update the counter and show it if necessary ++ counter; if (!(counter % 1847)) scon << std::setw (10) << counter << "\b\b\b\b\b\b\b\b\b\b"; } sout << ncubes << " cubes extracted.\n"; // finalize delete [] buf; return 0; } /* binary cube to pointset */ // -------------------------------------------------- // ---------------------- MAIN ---------------------- // -------------------------------------------------- int main (int argc, char *argv []) // Return: 0 = Ok, -1 = Error, 1 = Help displayed, 2 = Wrong arguments. { // prepare user-configurable data char *inname = 0, *outname = 0; int dim = 0; int sizes [maxdimension]; for (int i = 0; i < maxdimension; ++ i) sizes [i] = 0; int nsizes = 0; int initialskip = 0; // analyze the command line arguments a; arg (a, 0, inname); arg (a, 0, outname); arg (a, "d", dim); arg (a, "s", sizes, nsizes, maxdimension); arg (a, "i", initialskip); arg (a, "x", sizes [0]); arg (a, "y", sizes [1]); arg (a, "z", sizes [2]); arghelp (a); argstreamprepare (a); int argresult = a. analyze (argc, argv); argstreamset (); // show the program's main title if (argresult >= 0) sout << title << '\n'; // check whether the entered arguments are correct and adjust sizes if (!outname) argresult = 1; for (int i = 0; i < 3; ++ i) if (sizes [i] && (nsizes <= i)) nsizes = i + 1; if (!dim && (nsizes > 1)) dim = nsizes; if (nsizes) { for (int i = nsizes; i < maxdimension; ++ i) sizes [i] = sizes [nsizes - 1]; } for (int i = 0; i < nsizes; ++ i) { if (sizes [i] > 0) continue; sout << "ERROR: The sizes must be positive.\n"; argresult = 1; break; } if (!argresult && !nsizes) { sout << "ERROR: The size of the binary cube " "must be defined.\n"; argresult = 1; } if (!argresult && !dim) { sout << "ERROR: Please, define the dimension of the " "binary cube.\n"; argresult = 1; } // if something was incorrect, show an additional message and exit if (argresult < 0) { sout << "Call with '--help' for help.\n"; return 2; } // if help requested or no output name defined, show help information if (argresult > 0) { sout << helpinfo << '\n'; return 1; } // try running the main function and catch an error message if thrown try { bincube2pointset (inname, outname, dim, sizes, initialskip); program_time = 1; return 0; } catch (const char *msg) { sout << "ERROR: " << msg << '\n'; return -1; } catch (const std::exception &e) { sout << "ERROR: " << e. what () << '\n'; return -1; } catch (...) { sout << "ABORT: An unknown error occurred.\n"; return -1; } } /* main */ /// @}
felixboes/hosd
chomp/programs/cubtools/bin2pset.cpp
C++
gpl-3.0
7,205
// Decompiled with JetBrains decompiler // Type: UIGameMenu_IOS // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 19851F1B-4780-4223-BA01-2C20F2CD781E // Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Assembly-CSharp.dll using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Wb.Lpw.Platform.Protocol; using Wb.Lpw.Shared.Network; public class UIGameMenu_IOS : UIGameMenu_Common { public UIButton DropBoxButton; public UIButton OptionsButton; public PackedSprite InventoryCounterBg; public WBSpriteText InventoryCounterText; public GameObject[] ObjectsToDisable; private int _dropBoxCounter; private int _inventoryCounter; protected override string path_InventoryButton { get { return "MC_SocialBar/MC_AbilityBar/MC_Btns/MC_Btns/BTN_Inventory/BTN_Menu_Inventory/BTN_Menu_Inventory"; } } public int DropBoxCounter { get { return this._dropBoxCounter; } } public int InventoryCounter { get { return this._inventoryCounter; } set { this._inventoryCounter = value; } } public override void OpenMenu(object parameter, Action done) { base.OpenMenu(parameter, done); this._inventoryCounter = 0; this._dropBoxCounter = 0; this.InventoryCounterText.Hide(true); this.InventoryCounterBg.Hide(true); foreach (GameObject go in this.ObjectsToDisable) WBUtility.ActivateRecursively(go, false); this.ApplyGameState(GameStateMgr.Instance.CurrentState); if (done == null) return; done(); } public override string GetGameMenuType() { return "UIGameMenu_IOS"; } public override void Select(string name) { if (FordPanelManager.Instance.IsPanelOpened(UIContextualChatCommon.PanelName)) FordPanelManager.Instance.Dismiss(UIContextualChatCommon.PanelName); UIRightPanel_IOS.Instance.CloseTab(); WBAudioManager.Instance.Play(this.MouseClickButtonSound, (Object) this, AudioResourceUsage.Keep, (Transform) null, 0.0f, (AudioCompletionCallback) null); string key = name; if (key != null) { // ISSUE: reference to a compiler-generated field if (UIGameMenu_IOS.\u003C\u003Ef__switch\u0024map7 == null) { // ISSUE: reference to a compiler-generated field UIGameMenu_IOS.\u003C\u003Ef__switch\u0024map7 = new Dictionary<string, int>(2) { { "Options", 0 }, { "Inventory", 1 } }; } int num; // ISSUE: reference to a compiler-generated field if (UIGameMenu_IOS.\u003C\u003Ef__switch\u0024map7.TryGetValue(key, out num)) { if (num != 0) { if (num == 1) { this._inventoryCounter = 0; NetworkMgr.Instance.InventoriesView.ClearNumNewInventoryItems(); this.InventoryCounterText.Hide(true); this.InventoryCounterBg.Hide(true); base.Select(name); return; } } else { FordPanelManager.Instance.SwitchLayout(FordPanelBase.FordHUDGroup.Options, (Action<string, UIPanelBase>) null, (object) null, (Action<string>) null, (string[]) null); return; } } } base.Select(name); } protected override void SetButtonsActive(bool playerIsInDomain) { if (playerIsInDomain || this.IsInCombat()) this.DomainButton.controlIsEnabled = false; else this.DomainButton.controlIsEnabled = true; } private void OnDropBoxClick() { FordPanelManager.Instance.CheckItemDropBox(Enumerable.ToList<ItemInstance>(InventoryExtensions.GetDropboxItems(NetworkMgr.Instance.InventoriesView)), (Action) null); } public override void UpdateDropBox(List<ItemInstance> items = null) { if (items == null) items = Enumerable.ToList<ItemInstance>(InventoryExtensions.GetDropboxItems(NetworkMgr.Instance.InventoriesView)); this._dropBoxCounter = items.Count; if (this._dropBoxCounter > 0 && FordGameRoom.Instance.IsDomain() && ((DomainRoom) FordGameRoom.Instance).RoomOwnerId == NetworkMgr.Instance.PlayerId) { this.DropBoxButton.controlIsEnabled = true; WBUtility.ActivateRecursively(this.DropBoxAnimRoot, true); this.DropBoxText.Hide(false); this.DropBoxText.Text = this._dropBoxCounter <= 99 ? items.Count.ToString() : "*"; } else { this.DropBoxButton.controlIsEnabled = false; WBUtility.ActivateRecursively(this.DropBoxAnimRoot, true); this.DropBoxText.Hide(false); this.DropBoxText.Text = this._dropBoxCounter <= 99 ? items.Count.ToString() : "*"; } } protected void Update() { if (this._inventoryCounter.ToString() != this.InventoryCounterText.Text) { this.InventoryCounterText.Hide(this._inventoryCounter == 0); this.InventoryCounterBg.Hide(this._inventoryCounter == 0); this.InventoryCounterText.Text = this._inventoryCounter.ToString(); } this.OptionsButton.controlIsEnabled = !UIHUDGoals.AreThereAnyOngoingGoalUIActivities(); } public override void DisplayBetterEquipmentHint() { UITooltip.Open((AutoSpriteBase) this.InventoryButton, UITooltip.ArrowPosition.BottomRight, FordLocalizationMgr.Menu.GetStringFromId("BETTER_GEAR_UPDATE", string.Empty, string.Empty)); UITooltip.WaitAndCloseTooltip(); } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/Assembly-CSharp/UIGameMenu_IOS.cs
C#
gpl-3.0
5,558
/** @ignore */ Kekule.LOCAL_RES = true; Kekule.Localization.setCurrModule("widget"); Kekule.Localization.addResource("zh", "WidgetTexts", { "CAPTION_OK": "确定", "CAPTION_CANCEL": "取消", "CAPTION_YES": "是", "CAPTION_NO": "否", "CAPTION_BROWSE_COLOR": "浏览颜色", "HINT_BROWSE_COLOR": "浏览更多颜色", "S_COLOR_UNSET": "(未设置)", "S_COLOR_DEFAULT": "(缺省值)", "S_COLOR_MIXED": "(多个值)", "S_COLOR_TRANSPARENT": "(透明)", "S_OBJECT_UNSET": "(无)", "S_ITEMS": "条目", "S_OBJECT": "对象", "S_VALUE_UNSET": "(未设置)", "CAPTION_MENU": "Menu", "HINT_MENU": "Open menu", "S_INSPECT_NONE": "(无)", "S_INSPECT_OBJECTS": "({0}个对象)", "S_INSPECT_ID_OBJECT": "{0}: {1}", "S_INSPECT_ANONYMOUS_OBJECT": "({0})", "CAPTION_TOGGLE_TEXTWRAP": "切换文本换行", "CAPTION_INC_TEXT_SIZE": "增大字号", "CAPTION_DEC_TEXT_SIZE": "减小字号", "HINT_TOGGLE_TEXTWRAP": "切换文本是否自动换行", "HINT_INC_TEXT_SIZE": "增大字号", "HINT_DEC_TEXT_SIZE": "减小字号", "HINT_CHOOSE_FONT_FAMILY": "选择字体", "CAPTION_FIRST_PAGE": "首页", "CAPTION_LAST_PAGE": "末页", "CAPTION_PREV_PAGE": "前一页", "CAPTION_NEXT_PAGE": "后一页", "HINT_FIRST_PAGE": "首页", "HINT_LAST_PAGE": "末页", "HINT_PREV_PAGE": "前一页", "HINT_NEXT_PAGE": "后一页", "HINT_CURR_PAGE": "当前页", "MSG_RETRIEVING_DATA": "载入数据…", "CAPTION_DATATABLE_EDIT": "编辑", "CAPTION_DATATABLE_DELETE": "删除", "CAPTION_DATATABLE_INSERT": "插入", "HINT_DATATABLE_EDIT": "编辑数据", "HINT_DATATABLE_DELETE": "删除数据", "HINT_DATATABLE_INSERT": "插入数据", "CAPTION_ADD_CELL": "+", "HINT_ADD_CELL": "添加新单元格", "CAPTION_REMOVE_CELL": "移除", "HINT_REMOVE_CELL": "移除单元格", "CAPTION_CONFIG": "设置…", "HINT_CONFIG": "修改设置" }); Kekule.Localization.addResource("zh", "ChemWidgetTexts", { "CAPTION_CLEAROBJS": "清除", "CAPTION_LOADFILE": "载入…", "CAPTION_LOADDATA": "载入…", "CAPTION_SAVEFILE": "保存…", "CAPTION_ZOOMIN": "放大", "CAPTION_ZOOMOUT": "缩小", "CAPTION_RESETZOOM": "重置缩放", "CAPTION_RESETVIEW": "重置", "CAPTION_ROTATE": "旋转", "CAPTION_ROTATELEFT": "向左旋转", "CAPTION_ROTATERIGHT": "向右旋转", "CAPTION_ROTATEX": "沿X轴旋转", "CAPTION_ROTATEY": "沿Y轴旋转", "CAPTION_ROTATEZ": "沿Z轴旋转", "CAPTION_MOL_DISPLAY_TYPE": "分子显示样式", "CAPTION_SKELETAL": "键线式", "CAPTION_CONDENSED": "缩写式", "CAPTION_WIRE": "单线模型", "CAPTION_STICKS": "棍式模型", "CAPTION_BALLSTICK": "球棍模型", "CAPTION_SPACEFILL": "比例模型", "CAPTION_HIDEHYDROGENS": "显示/隐藏氢原子", "CAPTION_OPENEDITOR": "编辑…", "CAPTION_EDIT_OBJ": "编辑", "HINT_CLEAROBJS": "清除对象", "HINT_LOADFILE": "自文件载入", "HINT_LOADDATA": "载入数据", "HINT_SAVEFILE": "存储到文件", "HINT_ZOOMIN": "放大", "HINT_ZOOMOUT": "缩小", "HINT_RESETZOOM": "重置缩放", "HINT_RESETVIEW": "重置缩放与旋转", "HINT_ROTATE": "旋转", "HINT_ROTATELEFT": "逆时针旋转", "HINT_ROTATERIGHT": "顺时针旋转", "HINT_ROTATEX": "沿X轴旋转", "HINT_ROTATEY": "沿Y轴旋转", "HINT_ROTATEZ": "沿Z轴旋转", "HINT_MOL_DISPLAY_TYPE": "改变分子显示样式", "HINT_SKELETAL": "以键线式显示", "HINT_CONDENSED": "以缩写式显示", "HINT_WIRE": "以单线模型显示", "HINT_STICKS": "以棍式模型显示", "HINT_BALLSTICK": "以球棍模型显示", "HINT_SPACEFILL": "以比例模型显示", "HINT_HIDEHYDROGENS": "模型中显示/隐藏氢原子", "HINT_OPENEDITOR": "编辑当前对象", "CAPTION_NEWDOC": "新建", "CAPTION_UNDO": "撤销", "CAPTION_REDO": "重做", "CAPTION_COPY": "复制", "CAPTION_CUT": "剪切", "CAPTION_PASTE": "粘贴", "CAPTION_CLONE_SELECTION": "克隆选区", "CAPTION_TOGGLE_INSPECTOR": "对象检视器", "CAPTION_MANIPULATE": "选取", "CAPTION_ERASE": "删除", "CAPTION_MOL_BOND": "键", "CAPTION_MOL_BOND_SINGLE": "单键", "CAPTION_MOL_BOND_DOUBLE": "双键", "CAPTION_MOL_BOND_TRIPLE": "三键", "CAPTION_MOL_BOND_WEDGEUP": "实楔线键", "CAPTION_MOL_BOND_WEDGEDOWN": "虚楔线键", "CAPTION_MOL_BOND_CLOSER": "突出(加粗)键", "CAPTION_MOL_BOND_WAVY": "波浪键", "CAPTION_MOL_BOND_DOUBLE_EITHER": "顺或反式双键", "CAPTION_MOL_ATOM": "原子", "CAPTION_MOL_FORMULA": "分子式", "CAPTION_MOL_CHARGE": "电荷", "CAPTION_MOL_CHARGE_CLEAR": "清除电荷", "CAPTION_MOL_CHARGE_POSITIVE": "正电荷", "CAPTION_MOL_CHARGE_NEGATIVE": "负电荷", "CAPTION_MOL_CHARGE_SINGLET": "单线态", "CAPTION_MOL_CHARGE_DOUBLET": "双线态自由基", "CAPTION_MOL_CHARGE_TRIPLET": "三线态", "CAPTION_TEXT_BLOCK": "文本", "CAPTION_REPOSITORY_RING": "环", "CAPTION_REPOSITORY_RING_3": "环丙烷", "CAPTION_REPOSITORY_RING_4": "环丁烷", "CAPTION_REPOSITORY_RING_5": "环戊烷", "CAPTION_REPOSITORY_RING_6": "环己烷", "CAPTION_REPOSITORY_RING_7": "环庚烷", "CAPTION_REPOSITORY_RING_8": "环辛烷", "CAPTION_REPOSITORY_RING_AR_6": "苯", "CAPTION_REPOSITORY_RING_AR_5": "环戊二烯", "CAPTION_REPOSITORY_ARROWLINE": "线段与箭头", "CAPTION_REPOSITORY_GLYPH": "图符", "CAPTION_REPOSITORY_GLYPH_LINE": "直线", "CAPTION_REPOSITORY_GLYPH_OPEN_ARROW_LINE": "开放箭头线", "CAPTION_REPOSITORY_GLYPH_TRIANGLE_ARROW_LINE": "三角箭头线", "CAPTION_REPOSITORY_GLYPH_DI_OPEN_ARROW_LINE": "双向开放箭头线", "CAPTION_REPOSITORY_GLYPH_DI_TRIANGLE_ARROW_LINE": "双向三角箭头线", "CAPTION_REPOSITORY_GLYPH_REV_ARROW_LINE": "可逆箭头线", "CAPTION_REPOSITORY_GLYPH_OPEN_ARROW_DILINE": "开放箭头双线", "CAPTION_REPOSITORY_HEAT_SYMBOL": "加热符号", "CAPTION_REPOSITORY_ADD_SYMBOL": "加号", "CAPTION_PICK_COLOR": "颜色", "CAPTION_TEXT_DIRECTION": "文字方向", "CAPTION_TEXT_DIRECTION_DEFAULT": "缺省", "CAPTION_TEXT_DIRECTION_LTR": "由左至右", "CAPTION_TEXT_DIRECTION_RTL": "由右至左", "CAPTION_TEXT_DIRECTION_TTB": "由上至下", "CAPTION_TEXT_DIRECTION_BTT": "由下至上", "CAPTION_TEXT_HORIZONTAL_ALIGN": "文字水平对齐", "CAPTION_TEXT_VERTICAL_ALIGN": "文字垂直对齐", "CAPTION_TEXT_ALIGN_DEFAULT": "缺省", "CAPTION_TEXT_ALIGN_LEADING": "首对齐", "CAPTION_TEXT_ALIGN_TRAILING": "尾对齐", "CAPTION_TEXT_ALIGN_CENTER": "居中对齐", "CAPTION_TEXT_ALIGN_LEFT": "左对齐", "CAPTION_TEXT_ALIGN_RIGHT": "右对齐", "CAPTION_TEXT_ALIGN_TOP": "上对齐", "CAPTION_TEXT_ALIGN_BOTTOM": "下对齐", "HINT_NEWDOC": "创建新文档", "HINT_UNDO": "撤销", "HINT_REDO": "重做", "HINT_COPY": "将选定对象复制至内部剪贴板", "HINT_CUT": "将选定对象剪切至内部剪贴板", "HINT_PASTE": "自内部剪贴板复制", "HINT_CLONE_SELECTION": "克隆当前选区", "HINT_TOGGLE_INSPECTOR": "显示或隐藏对象检视器", "HINT_MANIPULATE": "选择工具", "HINT_ERASE": "删除工具", "HINT_MOL_BOND": "化学键工具", "HINT_MOL_BOND_SINGLE": "单键", "HINT_MOL_BOND_DOUBLE": "双键", "HINT_MOL_BOND_TRIPLE": "叁键", "HINT_MOL_BOND_WEDGEUP": "实楔线键", "HINT_MOL_BOND_WEDGEDOWN": "虚楔线键", "HINT_MOL_BOND_CLOSER": "突出(加粗)键", "HINT_MOL_BOND_WAVY": "波浪键", "HINT_MOL_BOND_DOUBLE_EITHER": "顺或反式双键", "HINT_MOL_ATOM": "原子工具", "HINT_MOL_FORMULA": "分子式工具", "HINT_MOL_CHARGE": "电荷工具", "HINT_MOL_CHARGE_CLEAR": "清除电荷或自由基", "HINT_MOL_CHARGE_POSITIVE": "正电荷", "HINT_MOL_CHARGE_NEGATIVE": "负电荷", "HINT_MOL_CHARGE_SINGLET": "单线态自由基", "HINT_MOL_CHARGE_DOUBLET": "双线态自由基", "HINT_MOL_CHARGE_TRIPLET": "三线态自由基", "HINT_TEXT_BLOCK": "文字工具", "HINT_REPOSITORY_RING": "环工具", "HINT_REPOSITORY_RING_3": "环丙烷", "HINT_REPOSITORY_RING_4": "环丁烷", "HINT_REPOSITORY_RING_5": "环戊烷", "HINT_REPOSITORY_RING_6": "环己烷", "HINT_REPOSITORY_RING_7": "环庚烷", "HINT_REPOSITORY_RING_8": "环辛烷", "HINT_REPOSITORY_RING_AR_6": "苯", "HINT_REPOSITORY_RING_AR_5": "环戊二烯", "HINT_REPOSITORY_ARROWLINE": "线段与箭头", "HINT_REPOSITORY_GLYPH": "图符", "HINT_REPOSITORY_GLYPH_LINE": "直线", "HINT_REPOSITORY_GLYPH_OPEN_ARROW_LINE": "开放箭头线", "HINT_REPOSITORY_GLYPH_TRIANGLE_ARROW_LINE": "三角箭头线", "HINT_REPOSITORY_GLYPH_DI_OPEN_ARROW_LINE": "双向开放箭头线", "HINT_REPOSITORY_GLYPH_DI_TRIANGLE_ARROW_LINE": "双向三角箭头线", "HINT_REPOSITORY_GLYPH_REV_ARROW_LINE": "可逆箭头线", "HINT_REPOSITORY_GLYPH_OPEN_ARROW_DILINE": "开放箭头双线", "HINT_REPOSITORY_HEAT_SYMBOL": "加热符号", "HINT_REPOSITORY_ADD_SYMBOL": "加号", "HINT_FONTNAME": "设置字体", "HINT_FONTSIZE": "设置字号", "HINT_PICK_COLOR": "选择颜色", "HINT_TEXT_DIRECTION": "设置文字方向", "HINT_TEXT_HORIZONTAL_ALIGN": "设置文字水平对齐方式", "HINT_TEXT_VERTICAL_ALIGN": "设置文字水平垂直方式", "CAPTION_LOADDATA_DIALOG": "载入数据", "CAPTION_DATA_FORMAT": "数据格式:", "CAPTION_DATA_SRC": "在下方输入或粘贴数据:", "CAPTION_LOADDATA_FROM_FILE": "载入文件", "CAPTION_CHOOSEFILEFORMAT": "选择文件格式", "CAPTION_SELECT_FORMAT": "选择格式:", "CAPTION_PREVIEW_FILE_CONTENT": "预览文件内容…", "S_DEF_SAVE_FILENAME": "Unnamed", "CAPTION_ATOMLIST_PERIODIC_TABLE": "更多…", "CAPTION_RGROUP": "取代基", "CAPTION_VARIABLE_ATOM": "(包含)原子列表", "CAPTION_VARIABLE_NOT_ATOM": "(不包含)原子列表", "CAPTION_PSEUDOATOM": "赝原子(Pseudoatom)", "CAPTION_DUMMY_ATOM": "虚原子(Dummy atom)", "CAPTION_HETERO_ATOM": "杂原子", "CAPTION_ANY_ATOM": "任意原子", "CAPTION_PERIODIC_TABLE_DIALOG": "元素周期表", "CAPTION_PERIODIC_TABLE_DIALOG_SEL_ELEM": "选择元素", "CAPTION_PERIODIC_TABLE_DIALOG_SEL_ELEMS": "选择多个元素", "CAPTION_TEXTBLOCK_INIT": "在此输入文字", "LEGEND_CAPTION": "图例", "LEGEND_ELEM_SYMBOL": "元素符号", "LEGEND_ELEM_NAME": "名称", "LEGEND_ATOMIC_NUM": "原子序数", "LEGEND_ATOMIC_WEIGHT": "原子量", "CAPTION_2D": "2D", "CAPTION_3D": "3D", "CAPTION_AUTOSIZE": "自动尺寸", "CAPTION_AUTOFIT": "自动缩放", "CAPTION_SHOWSIZEINFO": "显示尺寸信息", "CAPTION_LABEL_SIZE": "尺寸:", "CAPTION_BACKGROUND_COLOR": "背景颜色:", "CAPTION_WIDTH_HEIGHT": "宽:{0}、高:{1}", "PLACEHOLDER_WIDTH": "宽", "PLACEHOLDER_HEIGHT": "高", "HINT_AUTOSIZE": "图形尺寸是否由对象大小自动调整", "HINT_AUTOFIT": "对象是否填满图形区域", "S_VALUE_DEFAULT": "(缺省)" }); Kekule.Localization.addResource("zh", "ErrorMsg", { "WIDGET_CLASS_NOT_FOUND": "控件类不存在", "WIDGET_CAN_NOT_BIND_TO_ELEM": "控件{0}无法绑定到HTML元素<{1}>", "LOAD_CHEMDATA_FAILED": "载入数据失败", "FILE_API_NOT_SUPPORTED": "您当前的浏览器不支持HTML文件操作,请升级浏览器。", "DRAW_BRIDGE_NOT_SUPPORTED": "您当前的浏览器不支持该绘图功能,请升级浏览器。", "COMMAND_NOT_REVERSIBLE": "命令无法撤销", "PAGE_INDEX_OUTOF_RANGE": "页面超出范围", "FETCH_DATA_TIMEOUT": "加载数据超时", "RENDER_TYPE_CHANGE_NOT_ALLOWED": "渲染类型无法改变", "CAN_NOT_CREATE_EDITOR": "创建编辑器失败", "CAN_NOT_SET_COORD_OF_CLASS": "无法设置对象{0}实例的坐标", "CAN_NOT_SET_DIMENSION_OF_CLASS": "无法设置对象{0}实例的尺寸", "CAN_NOT_MERGE_CONNECTORS": "化学键或连接符无法合并", "NOT_A_VALID_ATOM": "无效的原子", "INVALID_ATOM_SYMBOL": "原子符号无效" });
deepchem/deepchem-gui
gui/static/kekulejs/src/localization/zh/kekule.localize.widget.zh.js
JavaScript
gpl-3.0
12,211
""" Copyright 2016 Puffin Software. All rights reserved. """ from com.puffinware.pistat.models import User, Location, Category, Thermostat, Sensor, Reading from com.puffinware.pistat import DB from logging import getLogger log = getLogger(__name__) def setup_db(app): DB.create_tables([User, Location, Category, Thermostat, Sensor, Reading], safe=True) # This hook ensures that a connection is opened to handle any queries # generated by the request. @app.before_request def _db_connect(): log.debug('DB Connect') DB.connect() # This hook ensures that the connection is closed when we've finished # processing the request. @app.teardown_request def _db_close(exc): if not DB.is_closed(): log.debug('DB Close') DB.close()
PuffinWare/pistat
com/puffinware/pistat/db.py
Python
gpl-3.0
767
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 指纹解注册 * * @author auto create * @since 1.0, 2017-01-12 17:27:09 */ public class AlipaySecurityProdFingerprintDeleteModel extends AlipayObject { private static final long serialVersionUID = 8631337432346717531L; /** * IFAA协议的版本,目前为2.0 */ @ApiField("ifaa_version") private String ifaaVersion; /** * IFAA标准中用于关联IFAA Server和业务方Server开通状态的token,此token为注册时保存的token,传入此token,用于生成服务端去注册信息。 */ @ApiField("token") private String token; public String getIfaaVersion() { return this.ifaaVersion; } public void setIfaaVersion(String ifaaVersion) { this.ifaaVersion = ifaaVersion; } public String getToken() { return this.token; } public void setToken(String token) { this.token = token; } }
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/AlipaySecurityProdFingerprintDeleteModel.java
Java
gpl-3.0
958
namespace TanjiCore.Flazzy.ABC { public interface IClassTrait { ASClass Class { get; } int ClassIndex { get; set; } } }
scottstamp/TanjiCore
TanjiCore/TanjiCore.Flazzy/ABC/Traits/IClassTrait.cs
C#
gpl-3.0
150
var repl = repl || {}; repl.prompt = "> "; repl.cont = "+\t"; repl.command = {}; load(":/resources/core.js"); soft_version = "SOFT v" + version() + " "; soft_license = "GNU LESSER GENERAL PUBLIC LICENSE (v 2.1, February 1999)"; function showHelp() { var message = soft_version + "(" + soft_license + ")\n\n" + "Welcome to Soft Shell\n" + "Shell commands:\n" + ":h This message\n"+ ":ld <file> Load and evaluate file <file>\n" + ":chk <file> Checks the syntax of the program <file>\n" + ":q Quit the shell\n\n"; print (message); } function quit() { repl.exit = true; print ("Bye"); } repl.command['q'] = quit; repl.command['quit'] = quit; repl.command['ld'] = load; repl.command['chk'] = checkSyntax; repl.command['h'] = showHelp; repl.command['help'] = showHelp; function parseCommand(cmd) { if( cmd != undefined ) { var command = cmd[1]; if( command !== undefined && repl.command[command] !== undefined) { repl.command[command](cmd[2]); return true; } else { print("Unknown command " + command); } } return undefined; } function mainrepl() { var s = ""; while(repl.exit === undefined) { try { if( s.length == 0 ) writeline(repl.prompt); s += readline(); cmd = s.match(/^[\:]([a-zA-Z]*)\s?(\S*)/); if( cmd != undefined ) { s = ""; parseCommand(cmd); } else { if( s.trim().length == 0 ) continue; if( isIncompleteSyntax(s) || s[s.length-1] == '\\' ) { if(s[s.length-1] == '\\') { s = s.substring(0,s.length-1); } writeline(repl.cont); } else { ret = eval(s); s = ""; if(!isQObject(ret) && isObject(ret)) { print(JSON.stringify(ret, null, 2)); } else if( ret != undefined) print(ret); else print('undefined'); } } } catch (err) { if (isIncompleteSyntax(s)) continue; print (err); s = ""; } } } function __main__() { var message = soft_version + "(" + soft_license + ")\n\n" + "For help, type :help\n"; print(message); mainrepl(); return 0; }
NanoSim/Porto
tools/src/softshell/resources/repl.js
JavaScript
gpl-3.0
2,146
/* * #%L * Sholl Analysis plugin for ImageJ. * %% * Copyright (C) 2005 - 2020 Tiago Ferreira. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package sholl; import java.util.Iterator; import java.util.List; import java.util.Set; import ij.measure.Calibration; /** * 'Universal Point' Class to access Cartesian coordinates of 2D and 3D points. * Designed to accommodate points from several sources such SWC nodes, pixels, * voxels, and ROIs. * * @author Tiago Ferreira */ public class UPoint { /** The x-coordinate */ public double x; /** The y-coordinate */ public double y; /** The z-coordinate */ public double z; public int flag = NONE; public final static int NONE = -1; public final static int VISITED = -2; public final static int DELETE = -4; public final static int KEEP = -8; public UPoint() { } public UPoint(final double x, final double y, final double z) { this.x = x; this.y = y; this.z = z; } public UPoint(final double x, final double y) { this.x = x; this.y = y; this.z = 0; } public UPoint(final int x, final int y, final int z, final Calibration cal) { this.x = cal.getX(x); this.y = cal.getY(y); this.z = cal.getZ(z); } public UPoint(final int x, final int y, final Calibration cal) { this.x = cal.getX(x); this.y = cal.getY(y); this.z = cal.getZ(0); } public UPoint(final int x, final int y, final int z, final int flag) { this.x = x; this.y = y; this.z = z; this.flag = flag; } public void scale(final double xScale, final double yScale, final double zScale) { this.x *= xScale; this.y *= yScale; this.z *= zScale; } public void applyOffset(final double xOffset, final double yOffset, final double zOffset) { this.x += xOffset; this.y += yOffset; this.z += zOffset; } public UPoint minus(final UPoint point) { return new UPoint(x - point.x, y - point.y, z - point.z); } public UPoint plus(final UPoint point) { return new UPoint(x + point.x, y + point.y, z + point.z); } public double scalar(final UPoint point) { return x * point.x + y * point.y + z * point.z; } public UPoint times(final double factor) { return new UPoint(x * factor, y * factor, z * factor); } public double length() { return Math.sqrt(scalar(this)); } public double distanceSquared(final UPoint point) { final double x1 = x - point.x; final double y1 = y - point.y; final double z1 = z - point.z; return x1 * x1 + y1 * y1 + z1 * z1; } public double euclideanDxTo(final UPoint point) { return Math.sqrt(distanceSquared(point)); } public double chebyshevXYdxTo(final UPoint point) { return Math.max(Math.abs(x - point.x), Math.abs(y - point.y)); } public double chebyshevZdxTo(final UPoint point) { return Math.abs(z - point.z); } public double chebyshevDxTo(final UPoint point) { return Math.max(chebyshevXYdxTo(point), chebyshevZdxTo(point)); } public static UPoint average(final List<UPoint> points) { UPoint result = points.get(0); for(int i = 1; i < points.size(); i++) result = result.plus(points.get(i)); return result.times(1.0 / points.size()); } public static void scale(final Set<UPoint> set, final Calibration cal) { for (final Iterator<UPoint> it = set.iterator(); it.hasNext();) { final UPoint point = it.next(); point.x = cal.getX(point.x); point.y = cal.getY(point.y); point.z = cal.getZ(point.z); } } protected static UPoint fromString(final String string) { if (string == null || string.isEmpty()) return null; final String[] ccs = string.trim().split(","); if (ccs.length == 3) { return new UPoint(Double.valueOf(ccs[0]), Double.valueOf(ccs[1]), Double.valueOf(ccs[2])); } return null; } public double rawX(final Calibration cal) { return cal.getRawX(x); } public double rawY(final Calibration cal) { return cal.getRawY(y); } public double rawZ(final Calibration cal) { return z / cal.pixelDepth + cal.zOrigin; } public void setFlag(final int flag) { this.flag = flag; } public int intX() { return (int) x; } public int intY() { return (int) y; } public int intZ() { return (int) z; } @Override public String toString() { return ShollUtils.d2s(x) + ", " + ShollUtils.d2s(y) + ", " + ShollUtils.d2s(z); } @Override public boolean equals(final Object object) { if (this == object) return true; if (!(object instanceof UPoint)) return false; final UPoint point = (UPoint) object; return (this.x == point.x && this.y == point.y && this.z == point.z); } @Override public int hashCode() { return super.hashCode(); } }
tferr/ASA
src/main/java/sholl/UPoint.java
Java
gpl-3.0
5,219
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #ifndef DRV_QUERYDEVICEINTERFACE #define DRV_RESERVED 0x0800 #define DRV_QUERYDEVICEINTERFACE (DRV_RESERVED + 12) #define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13) #endif namespace juce { class MidiInput::Pimpl { public: virtual ~Pimpl() noexcept = default; virtual String getDeviceIdentifier() = 0; virtual String getDeviceName() = 0; virtual void start() = 0; virtual void stop() = 0; }; class MidiOutput::Pimpl { public: virtual ~Pimpl() noexcept = default; virtual String getDeviceIdentifier() = 0; virtual String getDeviceName() = 0; virtual void sendMessageNow (const MidiMessage&) = 0; }; struct MidiServiceType { MidiServiceType() = default; virtual ~MidiServiceType() noexcept = default; virtual Array<MidiDeviceInfo> getAvailableDevices (bool) = 0; virtual MidiDeviceInfo getDefaultDevice (bool) = 0; virtual MidiInput::Pimpl* createInputWrapper (MidiInput&, const String&, MidiInputCallback&) = 0; virtual MidiOutput::Pimpl* createOutputWrapper (const String&) = 0; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiServiceType) }; //============================================================================== struct Win32MidiService : public MidiServiceType, private Timer { Win32MidiService() {} Array<MidiDeviceInfo> getAvailableDevices (bool isInput) override { return isInput ? Win32InputWrapper::getAvailableDevices() : Win32OutputWrapper::getAvailableDevices(); } MidiDeviceInfo getDefaultDevice (bool isInput) override { return isInput ? Win32InputWrapper::getDefaultDevice() : Win32OutputWrapper::getDefaultDevice(); } MidiInput::Pimpl* createInputWrapper (MidiInput& input, const String& deviceIdentifier, MidiInputCallback& callback) override { return new Win32InputWrapper (*this, input, deviceIdentifier, callback); } MidiOutput::Pimpl* createOutputWrapper (const String& deviceIdentifier) override { return new Win32OutputWrapper (*this, deviceIdentifier); } private: struct Win32InputWrapper; //============================================================================== struct MidiInCollector : public ReferenceCountedObject { MidiInCollector (Win32MidiService& s, MidiDeviceInfo d) : deviceInfo (d), midiService (s) { } ~MidiInCollector() { stop(); if (deviceHandle != 0) { for (int count = 5; --count >= 0;) { if (midiInClose (deviceHandle) == MMSYSERR_NOERROR) break; Sleep (20); } } } using Ptr = ReferenceCountedObjectPtr<MidiInCollector>; void addClient (Win32InputWrapper* c) { const ScopedLock sl (clientLock); jassert (! clients.contains (c)); clients.add (c); } void removeClient (Win32InputWrapper* c) { const ScopedLock sl (clientLock); clients.removeFirstMatchingValue (c); startOrStop(); midiService.asyncCheckForUnusedCollectors(); } void handleMessage (const uint8* bytes, uint32 timeStamp) { if (bytes[0] >= 0x80 && isStarted.load()) { { auto len = MidiMessage::getMessageLengthFromFirstByte (bytes[0]); auto time = convertTimeStamp (timeStamp); const ScopedLock sl (clientLock); for (auto* c : clients) c->pushMidiData (bytes, len, time); } writeFinishedBlocks(); } } void handleSysEx (MIDIHDR* hdr, uint32 timeStamp) { if (isStarted.load() && hdr->dwBytesRecorded > 0) { { auto time = convertTimeStamp (timeStamp); const ScopedLock sl (clientLock); for (auto* c : clients) c->pushMidiData (hdr->lpData, (int) hdr->dwBytesRecorded, time); } writeFinishedBlocks(); } } void startOrStop() { const ScopedLock sl (clientLock); if (countRunningClients() == 0) stop(); else start(); } void start() { if (deviceHandle != 0 && ! isStarted.load()) { activeMidiCollectors.addIfNotAlreadyThere (this); for (int i = 0; i < (int) numHeaders; ++i) { headers[i].prepare (deviceHandle); headers[i].write (deviceHandle); } startTime = Time::getMillisecondCounterHiRes(); auto res = midiInStart (deviceHandle); if (res == MMSYSERR_NOERROR) isStarted = true; else unprepareAllHeaders(); } } void stop() { if (isStarted.load()) { isStarted = false; midiInReset (deviceHandle); midiInStop (deviceHandle); activeMidiCollectors.removeFirstMatchingValue (this); unprepareAllHeaders(); } } static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp) { auto* collector = reinterpret_cast<MidiInCollector*> (dwInstance); // This is primarily a check for the collector being a dangling // pointer, as the callback can sometimes be delayed if (activeMidiCollectors.contains (collector)) { if (uMsg == MIM_DATA) collector->handleMessage ((const uint8*) &midiMessage, (uint32) timeStamp); else if (uMsg == MIM_LONGDATA) collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp); } } MidiDeviceInfo deviceInfo; HMIDIIN deviceHandle = 0; private: Win32MidiService& midiService; CriticalSection clientLock; Array<Win32InputWrapper*> clients; std::atomic<bool> isStarted { false }; double startTime = 0; // This static array is used to prevent occasional callbacks to objects that are // in the process of being deleted static Array<MidiInCollector*, CriticalSection> activeMidiCollectors; int countRunningClients() const { int num = 0; for (auto* c : clients) if (c->started) ++num; return num; } struct MidiHeader { MidiHeader() {} void prepare (HMIDIIN device) { zerostruct (hdr); hdr.lpData = data; hdr.dwBufferLength = (DWORD) numElementsInArray (data); midiInPrepareHeader (device, &hdr, sizeof (hdr)); } void unprepare (HMIDIIN device) { if ((hdr.dwFlags & WHDR_DONE) != 0) { int c = 10; while (--c >= 0 && midiInUnprepareHeader (device, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING) Thread::sleep (20); jassert (c >= 0); } } void write (HMIDIIN device) { hdr.dwBytesRecorded = 0; midiInAddBuffer (device, &hdr, sizeof (hdr)); } void writeIfFinished (HMIDIIN device) { if ((hdr.dwFlags & WHDR_DONE) != 0) write (device); } MIDIHDR hdr; char data[256]; JUCE_DECLARE_NON_COPYABLE (MidiHeader) }; enum { numHeaders = 32 }; MidiHeader headers[numHeaders]; void writeFinishedBlocks() { for (int i = 0; i < (int) numHeaders; ++i) headers[i].writeIfFinished (deviceHandle); } void unprepareAllHeaders() { for (int i = 0; i < (int) numHeaders; ++i) headers[i].unprepare (deviceHandle); } double convertTimeStamp (uint32 timeStamp) { auto t = startTime + timeStamp; auto now = Time::getMillisecondCounterHiRes(); if (t > now) { if (t > now + 2.0) startTime -= 1.0; t = now; } return t * 0.001; } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector) }; //============================================================================== template<class WrapperType> struct Win32MidiDeviceQuery { static Array<MidiDeviceInfo> getAvailableDevices() { StringArray deviceNames, deviceIDs; auto deviceCaps = WrapperType::getDeviceCaps(); for (int i = 0; i < deviceCaps.size(); ++i) { deviceNames.add (deviceCaps[i].szPname); auto identifier = getInterfaceIDForDevice ((UINT) i); if (identifier.isNotEmpty()) deviceIDs.add (identifier); else deviceIDs.add (deviceNames[i]); } deviceNames.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 ("")); deviceIDs .appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 ("")); Array<MidiDeviceInfo> devices; for (int i = 0; i < deviceNames.size(); ++i) devices.add ({ deviceNames[i], deviceIDs[i] }); return devices; } private: static String getInterfaceIDForDevice (UINT id) { ULONG size = 0; if (WrapperType::sendMidiMessage ((UINT_PTR) id, DRV_QUERYDEVICEINTERFACESIZE, (DWORD_PTR) &size, 0) == MMSYSERR_NOERROR) { WCHAR interfaceName[512] = {}; if (isPositiveAndBelow (size, sizeof (interfaceName)) && WrapperType::sendMidiMessage ((UINT_PTR) id, DRV_QUERYDEVICEINTERFACE, (DWORD_PTR) interfaceName, sizeof (interfaceName)) == MMSYSERR_NOERROR) { return interfaceName; } } return {}; } }; struct Win32InputWrapper : public MidiInput::Pimpl, public Win32MidiDeviceQuery<Win32InputWrapper> { Win32InputWrapper (Win32MidiService& parentService, MidiInput& midiInput, const String& deviceIdentifier, MidiInputCallback& c) : input (midiInput), callback (c) { collector = getOrCreateCollector (parentService, deviceIdentifier); collector->addClient (this); } ~Win32InputWrapper() { collector->removeClient (this); } static MidiInCollector::Ptr getOrCreateCollector (Win32MidiService& parentService, const String& deviceIdentifier) { UINT deviceID = MIDI_MAPPER; String deviceName; auto devices = getAvailableDevices(); for (int i = 0; i < devices.size(); ++i) { auto d = devices.getUnchecked (i); if (d.identifier == deviceIdentifier) { deviceID = i; deviceName = d.name; break; } } const ScopedLock sl (parentService.activeCollectorLock); for (auto& c : parentService.activeCollectors) if (c->deviceInfo.identifier == deviceIdentifier) return c; MidiInCollector::Ptr c (new MidiInCollector (parentService, { deviceName, deviceIdentifier })); HMIDIIN h; auto err = midiInOpen (&h, deviceID, (DWORD_PTR) &MidiInCollector::midiInCallback, (DWORD_PTR) (MidiInCollector*) c.get(), CALLBACK_FUNCTION); if (err != MMSYSERR_NOERROR) throw std::runtime_error ("Failed to create Windows input device wrapper"); c->deviceHandle = h; parentService.activeCollectors.add (c); return c; } static DWORD sendMidiMessage (UINT_PTR deviceID, UINT msg, DWORD_PTR arg1, DWORD_PTR arg2) { return midiInMessage ((HMIDIIN) deviceID, msg, arg1, arg2); } static Array<MIDIINCAPS> getDeviceCaps() { Array<MIDIINCAPS> devices; for (UINT i = 0; i < midiInGetNumDevs(); ++i) { MIDIINCAPS mc = {}; if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR) devices.add (mc); } return devices; } static MidiDeviceInfo getDefaultDevice() { return getAvailableDevices().getFirst(); } void start() override { started = true; concatenator.reset(); collector->startOrStop(); } void stop() override { started = false; collector->startOrStop(); concatenator.reset(); } String getDeviceIdentifier() override { return collector->deviceInfo.identifier; } String getDeviceName() override { return collector->deviceInfo.name; } void pushMidiData (const void* inputData, int numBytes, double time) { concatenator.pushMidiData (inputData, numBytes, time, &input, callback); } MidiInput& input; MidiInputCallback& callback; MidiDataConcatenator concatenator { 4096 }; MidiInCollector::Ptr collector; bool started = false; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32InputWrapper) }; //============================================================================== struct MidiOutHandle : public ReferenceCountedObject { using Ptr = ReferenceCountedObjectPtr<MidiOutHandle>; MidiOutHandle (Win32MidiService& parent, MidiDeviceInfo d, HMIDIOUT h) : owner (parent), deviceInfo (d), handle (h) { owner.activeOutputHandles.add (this); } ~MidiOutHandle() { if (handle != nullptr) midiOutClose (handle); owner.activeOutputHandles.removeFirstMatchingValue (this); } Win32MidiService& owner; MidiDeviceInfo deviceInfo; HMIDIOUT handle; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutHandle) }; //============================================================================== struct Win32OutputWrapper : public MidiOutput::Pimpl, public Win32MidiDeviceQuery<Win32OutputWrapper> { Win32OutputWrapper (Win32MidiService& p, const String& deviceIdentifier) : parent (p) { auto devices = getAvailableDevices(); UINT deviceID = MIDI_MAPPER; String deviceName; for (int i = 0; i < devices.size(); ++i) { auto d = devices.getUnchecked (i); if (d.identifier == deviceIdentifier) { deviceID = i; deviceName = d.name; break; } } if (deviceID == MIDI_MAPPER) { // use the microsoft sw synth as a default - best not to allow deviceID // to be MIDI_MAPPER, or else device sharing breaks for (int i = 0; i < devices.size(); ++i) if (devices[i].name.containsIgnoreCase ("microsoft")) deviceID = (UINT) i; } for (int i = parent.activeOutputHandles.size(); --i >= 0;) { auto* activeHandle = parent.activeOutputHandles.getUnchecked (i); if (activeHandle->deviceInfo.identifier == deviceIdentifier) { han = activeHandle; return; } } for (int i = 4; --i >= 0;) { HMIDIOUT h = 0; auto res = midiOutOpen (&h, deviceID, 0, 0, CALLBACK_NULL); if (res == MMSYSERR_NOERROR) { han = new MidiOutHandle (parent, { deviceName, deviceIdentifier }, h); return; } if (res == MMSYSERR_ALLOCATED) Sleep (100); else break; } throw std::runtime_error ("Failed to create Windows output device wrapper"); } void sendMessageNow (const MidiMessage& message) override { if (message.getRawDataSize() > 3 || message.isSysEx()) { MIDIHDR h = {}; h.lpData = (char*) message.getRawData(); h.dwBytesRecorded = h.dwBufferLength = (DWORD) message.getRawDataSize(); if (midiOutPrepareHeader (han->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR) { auto res = midiOutLongMsg (han->handle, &h, sizeof (MIDIHDR)); if (res == MMSYSERR_NOERROR) { while ((h.dwFlags & MHDR_DONE) == 0) Sleep (1); int count = 500; // 1 sec timeout while (--count >= 0) { res = midiOutUnprepareHeader (han->handle, &h, sizeof (MIDIHDR)); if (res == MIDIERR_STILLPLAYING) Sleep (2); else break; } } } } else { for (int i = 0; i < 50; ++i) { if (midiOutShortMsg (han->handle, *(unsigned int*) message.getRawData()) != MIDIERR_NOTREADY) break; Sleep (1); } } } static DWORD sendMidiMessage (UINT_PTR deviceID, UINT msg, DWORD_PTR arg1, DWORD_PTR arg2) { return midiOutMessage ((HMIDIOUT) deviceID, msg, arg1, arg2); } static Array<MIDIOUTCAPS> getDeviceCaps() { Array<MIDIOUTCAPS> devices; for (UINT i = 0; i < midiOutGetNumDevs(); ++i) { MIDIOUTCAPS mc = {}; if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR) devices.add (mc); } return devices; } static MidiDeviceInfo getDefaultDevice() { auto defaultIndex = []() { auto deviceCaps = getDeviceCaps(); for (int i = 0; i < deviceCaps.size(); ++i) if ((deviceCaps[i].wTechnology & MOD_MAPPER) != 0) return i; return 0; }(); return getAvailableDevices()[defaultIndex]; } String getDeviceIdentifier() override { return han->deviceInfo.identifier; } String getDeviceName() override { return han->deviceInfo.name; } Win32MidiService& parent; MidiOutHandle::Ptr han; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32OutputWrapper) }; //============================================================================== void asyncCheckForUnusedCollectors() { startTimer (10); } void timerCallback() override { stopTimer(); const ScopedLock sl (activeCollectorLock); for (int i = activeCollectors.size(); --i >= 0;) if (activeCollectors.getObjectPointer(i)->getReferenceCount() == 1) activeCollectors.remove (i); } CriticalSection activeCollectorLock; ReferenceCountedArray<MidiInCollector> activeCollectors; Array<MidiOutHandle*> activeOutputHandles; }; Array<Win32MidiService::MidiInCollector*, CriticalSection> Win32MidiService::MidiInCollector::activeMidiCollectors; //============================================================================== //============================================================================== #if JUCE_USE_WINRT_MIDI #ifndef JUCE_FORCE_WINRT_MIDI #define JUCE_FORCE_WINRT_MIDI 0 #endif #ifndef JUCE_WINRT_MIDI_LOGGING #define JUCE_WINRT_MIDI_LOGGING 0 #endif #if JUCE_WINRT_MIDI_LOGGING #define JUCE_WINRT_MIDI_LOG(x) DBG(x) #else #define JUCE_WINRT_MIDI_LOG(x) #endif using namespace Microsoft::WRL; using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Foundation::Collections; using namespace ABI::Windows::Devices::Midi; using namespace ABI::Windows::Devices::Enumeration; using namespace ABI::Windows::Storage::Streams; //============================================================================== struct WinRTMidiService : public MidiServiceType { public: //============================================================================== WinRTMidiService() { auto* wrtWrapper = WinRTWrapper::getInstance(); if (! wrtWrapper->isInitialised()) throw std::runtime_error ("Failed to initialise the WinRT wrapper"); midiInFactory = wrtWrapper->getWRLFactory<IMidiInPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiInPort[0]); if (midiInFactory == nullptr) throw std::runtime_error ("Failed to create midi in factory"); midiOutFactory = wrtWrapper->getWRLFactory<IMidiOutPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiOutPort[0]); if (midiOutFactory == nullptr) throw std::runtime_error ("Failed to create midi out factory"); // The WinRT BLE MIDI API doesn't provide callbacks when devices become disconnected, // but it does require a disconnection via the API before a device will reconnect again. // We can monitor the BLE connection state of paired devices to get callbacks when // connections are broken. bleDeviceWatcher.reset (new BLEDeviceWatcher()); if (! bleDeviceWatcher->start()) throw std::runtime_error ("Failed to start the BLE device watcher"); inputDeviceWatcher.reset (new MidiIODeviceWatcher<IMidiInPortStatics> (midiInFactory)); if (! inputDeviceWatcher->start()) throw std::runtime_error ("Failed to start the midi input device watcher"); outputDeviceWatcher.reset (new MidiIODeviceWatcher<IMidiOutPortStatics> (midiOutFactory)); if (! outputDeviceWatcher->start()) throw std::runtime_error ("Failed to start the midi output device watcher"); } Array<MidiDeviceInfo> getAvailableDevices (bool isInput) override { return isInput ? inputDeviceWatcher ->getAvailableDevices() : outputDeviceWatcher->getAvailableDevices(); } MidiDeviceInfo getDefaultDevice (bool isInput) override { return isInput ? inputDeviceWatcher ->getDefaultDevice() : outputDeviceWatcher->getDefaultDevice(); } MidiInput::Pimpl* createInputWrapper (MidiInput& input, const String& deviceIdentifier, MidiInputCallback& callback) override { return new WinRTInputWrapper (*this, input, deviceIdentifier, callback); } MidiOutput::Pimpl* createOutputWrapper (const String& deviceIdentifier) override { return new WinRTOutputWrapper (*this, deviceIdentifier); } private: //============================================================================== class DeviceCallbackHandler { public: virtual ~DeviceCallbackHandler() {}; virtual HRESULT addDevice (IDeviceInformation*) = 0; virtual HRESULT removeDevice (IDeviceInformationUpdate*) = 0; virtual HRESULT updateDevice (IDeviceInformationUpdate*) = 0; bool attach (HSTRING deviceSelector, DeviceInformationKind infoKind) { auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) { JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!"); return false; } auto deviceInfoFactory = wrtWrapper->getWRLFactory<IDeviceInformationStatics2> (&RuntimeClass_Windows_Devices_Enumeration_DeviceInformation[0]); if (deviceInfoFactory == nullptr) return false; // A quick way of getting an IVector<HSTRING>... auto requestedProperties = [wrtWrapper] { auto devicePicker = wrtWrapper->activateInstance<IDevicePicker> (&RuntimeClass_Windows_Devices_Enumeration_DevicePicker[0], __uuidof (IDevicePicker)); jassert (devicePicker != nullptr); IVector<HSTRING>* result; auto hr = devicePicker->get_RequestedProperties (&result); jassert (SUCCEEDED (hr)); hr = result->Clear(); jassert (SUCCEEDED (hr)); return result; }(); StringArray propertyKeys ("System.Devices.ContainerId", "System.Devices.Aep.ContainerId", "System.Devices.Aep.IsConnected"); for (auto& key : propertyKeys) { WinRTWrapper::ScopedHString hstr (key); auto hr = requestedProperties->Append (hstr.get()); if (FAILED (hr)) { jassertfalse; return false; } } WinRTWrapper::ComPtr<IIterable<HSTRING>> iter; auto hr = requestedProperties->QueryInterface (__uuidof (IIterable<HSTRING>), (void**) iter.resetAndGetPointerAddress()); if (FAILED (hr)) { jassertfalse; return false; } hr = deviceInfoFactory->CreateWatcherWithKindAqsFilterAndAdditionalProperties (deviceSelector, iter, infoKind, watcher.resetAndGetPointerAddress()); if (FAILED (hr)) { jassertfalse; return false; } enumerationThread.startThread(); return true; }; void detach() { enumerationThread.stopThread (2000); if (watcher == nullptr) return; auto hr = watcher->Stop(); jassert (SUCCEEDED (hr)); if (deviceAddedToken.value != 0) { hr = watcher->remove_Added (deviceAddedToken); jassert (SUCCEEDED (hr)); deviceAddedToken.value = 0; } if (deviceUpdatedToken.value != 0) { hr = watcher->remove_Updated (deviceUpdatedToken); jassert (SUCCEEDED (hr)); deviceUpdatedToken.value = 0; } if (deviceRemovedToken.value != 0) { hr = watcher->remove_Removed (deviceRemovedToken); jassert (SUCCEEDED (hr)); deviceRemovedToken.value = 0; } watcher = nullptr; } template<typename InfoType> IInspectable* getValueFromDeviceInfo (String key, InfoType* info) { __FIMapView_2_HSTRING_IInspectable* properties; info->get_Properties (&properties); boolean found = false; WinRTWrapper::ScopedHString keyHstr (key); auto hr = properties->HasKey (keyHstr.get(), &found); if (FAILED (hr)) { jassertfalse; return nullptr; } if (! found) return nullptr; IInspectable* inspectable; hr = properties->Lookup (keyHstr.get(), &inspectable); if (FAILED (hr)) { jassertfalse; return nullptr; } return inspectable; } String getGUIDFromInspectable (IInspectable& inspectable) { WinRTWrapper::ComPtr<IReference<GUID>> guidRef; auto hr = inspectable.QueryInterface (__uuidof (IReference<GUID>), (void**) guidRef.resetAndGetPointerAddress()); if (FAILED (hr)) { jassertfalse; return {}; } GUID result; hr = guidRef->get_Value (&result); if (FAILED (hr)) { jassertfalse; return {}; } OLECHAR* resultString; StringFromCLSID (result, &resultString); return resultString; } bool getBoolFromInspectable (IInspectable& inspectable) { WinRTWrapper::ComPtr<IReference<bool>> boolRef; auto hr = inspectable.QueryInterface (__uuidof (IReference<bool>), (void**) boolRef.resetAndGetPointerAddress()); if (FAILED (hr)) { jassertfalse; return false; } boolean result; hr = boolRef->get_Value (&result); if (FAILED (hr)) { jassertfalse; return false; } return result; } private: //============================================================================== struct DeviceEnumerationThread : public Thread { DeviceEnumerationThread (DeviceCallbackHandler& h, WinRTWrapper::ComPtr<IDeviceWatcher>& w, EventRegistrationToken& added, EventRegistrationToken& removed, EventRegistrationToken& updated) : Thread ("WinRT Device Enumeration Thread"), handler (h), watcher (w), deviceAddedToken (added), deviceRemovedToken (removed), deviceUpdatedToken (updated) {} void run() override { auto handlerPtr = std::addressof (handler); watcher->add_Added ( Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformation*>> ( [handlerPtr] (IDeviceWatcher*, IDeviceInformation* info) { return handlerPtr->addDevice (info); } ).Get(), &deviceAddedToken); watcher->add_Removed ( Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>> ( [handlerPtr] (IDeviceWatcher*, IDeviceInformationUpdate* infoUpdate) { return handlerPtr->removeDevice (infoUpdate); } ).Get(), &deviceRemovedToken); watcher->add_Updated ( Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>> ( [handlerPtr] (IDeviceWatcher*, IDeviceInformationUpdate* infoUpdate) { return handlerPtr->updateDevice (infoUpdate); } ).Get(), &deviceUpdatedToken); watcher->Start(); } DeviceCallbackHandler& handler; WinRTWrapper::ComPtr<IDeviceWatcher>& watcher; EventRegistrationToken& deviceAddedToken, deviceRemovedToken, deviceUpdatedToken; }; //============================================================================== WinRTWrapper::ComPtr<IDeviceWatcher> watcher; EventRegistrationToken deviceAddedToken { 0 }, deviceRemovedToken { 0 }, deviceUpdatedToken { 0 }; DeviceEnumerationThread enumerationThread { *this, watcher, deviceAddedToken, deviceRemovedToken, deviceUpdatedToken }; }; //============================================================================== struct BLEDeviceWatcher final : private DeviceCallbackHandler { struct DeviceInfo { String containerID; bool isConnected = false; }; BLEDeviceWatcher() = default; ~BLEDeviceWatcher() { detach(); } //============================================================================== HRESULT addDevice (IDeviceInformation* addedDeviceInfo) override { HSTRING deviceIDHst; auto hr = addedDeviceInfo->get_Id (&deviceIDHst); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query added BLE device ID!"); return S_OK; } auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) { JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!"); return false; } auto deviceID = wrtWrapper->hStringToString (deviceIDHst); JUCE_WINRT_MIDI_LOG ("Detected paired BLE device: " << deviceID); if (auto* containerIDValue = getValueFromDeviceInfo ("System.Devices.Aep.ContainerId", addedDeviceInfo)) { auto containerID = getGUIDFromInspectable (*containerIDValue); if (containerID.isNotEmpty()) { DeviceInfo info = { containerID }; if (auto* connectedValue = getValueFromDeviceInfo ("System.Devices.Aep.IsConnected", addedDeviceInfo)) info.isConnected = getBoolFromInspectable (*connectedValue); JUCE_WINRT_MIDI_LOG ("Adding BLE device: " << deviceID << " " << info.containerID << " " << (info.isConnected ? "connected" : "disconnected")); devices.set (deviceID, info); return S_OK; } } JUCE_WINRT_MIDI_LOG ("Failed to get a container ID for BLE device: " << deviceID); return S_OK; } HRESULT removeDevice (IDeviceInformationUpdate* removedDeviceInfo) override { HSTRING removedDeviceIdHstr; auto hr = removedDeviceInfo->get_Id (&removedDeviceIdHstr); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query removed BLE device ID!"); return S_OK; } auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) { JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!"); return false; } auto removedDeviceId = wrtWrapper->hStringToString (removedDeviceIdHstr); JUCE_WINRT_MIDI_LOG ("Removing BLE device: " << removedDeviceId); { const ScopedLock lock (deviceChanges); if (devices.contains (removedDeviceId)) { auto& info = devices.getReference (removedDeviceId); listeners.call ([&info] (Listener& l) { l.bleDeviceDisconnected (info.containerID); }); devices.remove (removedDeviceId); JUCE_WINRT_MIDI_LOG ("Removed BLE device: " << removedDeviceId); } } return S_OK; } HRESULT updateDevice (IDeviceInformationUpdate* updatedDeviceInfo) override { HSTRING updatedDeviceIdHstr; auto hr = updatedDeviceInfo->get_Id (&updatedDeviceIdHstr); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query updated BLE device ID!"); return S_OK; } auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) { JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!"); return false; } auto updatedDeviceId = wrtWrapper->hStringToString (updatedDeviceIdHstr); JUCE_WINRT_MIDI_LOG ("Updating BLE device: " << updatedDeviceId); if (auto* connectedValue = getValueFromDeviceInfo ("System.Devices.Aep.IsConnected", updatedDeviceInfo)) { auto isConnected = getBoolFromInspectable (*connectedValue); { const ScopedLock lock (deviceChanges); if (! devices.contains (updatedDeviceId)) return S_OK; auto& info = devices.getReference (updatedDeviceId); if (info.isConnected && ! isConnected) { JUCE_WINRT_MIDI_LOG ("BLE device connection status change: " << updatedDeviceId << " " << info.containerID << " " << (isConnected ? "connected" : "disconnected")); listeners.call ([&info] (Listener& l) { l.bleDeviceDisconnected (info.containerID); }); } info.isConnected = isConnected; } } return S_OK; } //============================================================================== bool start() { WinRTWrapper::ScopedHString deviceSelector ("System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\"" " AND System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True"); return attach (deviceSelector.get(), DeviceInformationKind::DeviceInformationKind_AssociationEndpoint); } //============================================================================== struct Listener { virtual ~Listener() {}; virtual void bleDeviceAdded (const String& containerID) = 0; virtual void bleDeviceDisconnected (const String& containerID) = 0; }; void addListener (Listener* l) { listeners.add (l); } void removeListener (Listener* l) { listeners.remove (l); } //============================================================================== ListenerList<Listener> listeners; HashMap<String, DeviceInfo> devices; CriticalSection deviceChanges; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BLEDeviceWatcher); }; //============================================================================== struct WinRTMIDIDeviceInfo { String deviceID, containerID, name; bool isDefault = false; }; //============================================================================== template <typename COMFactoryType> struct MidiIODeviceWatcher final : private DeviceCallbackHandler { MidiIODeviceWatcher (WinRTWrapper::ComPtr<COMFactoryType>& comFactory) : factory (comFactory) { } ~MidiIODeviceWatcher() { detach(); } HRESULT addDevice (IDeviceInformation* addedDeviceInfo) override { WinRTMIDIDeviceInfo info; HSTRING deviceID; auto hr = addedDeviceInfo->get_Id (&deviceID); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query added MIDI device ID!"); return S_OK; } auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) { JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!"); return false; } info.deviceID = wrtWrapper->hStringToString (deviceID); JUCE_WINRT_MIDI_LOG ("Detected MIDI device: " << info.deviceID); boolean isEnabled = false; hr = addedDeviceInfo->get_IsEnabled (&isEnabled); if (FAILED (hr) || ! isEnabled) { JUCE_WINRT_MIDI_LOG ("MIDI device not enabled: " << info.deviceID); return S_OK; } // We use the container ID to match a MIDI device with a generic BLE device, if possible if (auto* containerIDValue = getValueFromDeviceInfo ("System.Devices.ContainerId", addedDeviceInfo)) info.containerID = getGUIDFromInspectable (*containerIDValue); HSTRING name; hr = addedDeviceInfo->get_Name (&name); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query detected MIDI device name for " << info.deviceID); return S_OK; } info.name = wrtWrapper->hStringToString (name); boolean isDefault = false; hr = addedDeviceInfo->get_IsDefault (&isDefault); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query detected MIDI device defaultness for " << info.deviceID << " " << info.name); return S_OK; } info.isDefault = isDefault; JUCE_WINRT_MIDI_LOG ("Adding MIDI device: " << info.deviceID << " " << info.containerID << " " << info.name); { const ScopedLock lock (deviceChanges); connectedDevices.add (info); } return S_OK; } HRESULT removeDevice (IDeviceInformationUpdate* removedDeviceInfo) override { HSTRING removedDeviceIdHstr; auto hr = removedDeviceInfo->get_Id (&removedDeviceIdHstr); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to query removed MIDI device ID!"); return S_OK; } auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) { JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!"); return false; } auto removedDeviceId = wrtWrapper->hStringToString (removedDeviceIdHstr); JUCE_WINRT_MIDI_LOG ("Removing MIDI device: " << removedDeviceId); { const ScopedLock lock (deviceChanges); for (int i = 0; i < connectedDevices.size(); ++i) { if (connectedDevices[i].deviceID == removedDeviceId) { connectedDevices.remove (i); JUCE_WINRT_MIDI_LOG ("Removed MIDI device: " << removedDeviceId); break; } } } return S_OK; } // This is never called HRESULT updateDevice (IDeviceInformationUpdate*) override { return S_OK; } bool start() { HSTRING deviceSelector; auto hr = factory->GetDeviceSelector (&deviceSelector); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to get MIDI device selector!"); return false; } return attach (deviceSelector, DeviceInformationKind::DeviceInformationKind_DeviceInterface); } Array<MidiDeviceInfo> getAvailableDevices() { { const ScopedLock lock (deviceChanges); lastQueriedConnectedDevices = connectedDevices; } StringArray deviceNames, deviceIDs; for (auto info : lastQueriedConnectedDevices.get()) { deviceNames.add (info.name); deviceIDs .add (info.containerID); } deviceNames.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 ("")); deviceIDs .appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 ("")); Array<MidiDeviceInfo> devices; for (int i = 0; i < deviceNames.size(); ++i) devices.add ({ deviceNames[i], deviceIDs[i] }); return devices; } MidiDeviceInfo getDefaultDevice() { auto& lastDevices = lastQueriedConnectedDevices.get(); for (auto& d : lastDevices) if (d.isDefault) return { d.name, d.containerID }; return {}; } WinRTMIDIDeviceInfo getWinRTDeviceInfoForDevice (const String& deviceIdentifier) { auto devices = getAvailableDevices(); for (int i = 0; i < devices.size(); ++i) if (devices.getUnchecked (i).identifier == deviceIdentifier) return lastQueriedConnectedDevices.get()[i]; return {}; } WinRTWrapper::ComPtr<COMFactoryType>& factory; Array<WinRTMIDIDeviceInfo> connectedDevices; CriticalSection deviceChanges; ThreadLocalValue<Array<WinRTMIDIDeviceInfo>> lastQueriedConnectedDevices; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiIODeviceWatcher); }; //============================================================================== template <typename COMFactoryType, typename COMInterfaceType, typename COMType> struct OpenMidiPortThread : public Thread { OpenMidiPortThread (String threadName, String midiDeviceID, WinRTWrapper::ComPtr<COMFactoryType>& comFactory, WinRTWrapper::ComPtr<COMInterfaceType>& comPort) : Thread (threadName), deviceID (midiDeviceID), factory (comFactory), port (comPort) { } ~OpenMidiPortThread() { stopThread (2000); } void run() override { WinRTWrapper::ScopedHString hDeviceId (deviceID); WinRTWrapper::ComPtr<IAsyncOperation<COMType*>> asyncOp; auto hr = factory->FromIdAsync (hDeviceId.get(), asyncOp.resetAndGetPointerAddress()); if (FAILED (hr)) return; hr = asyncOp->put_Completed (Callback<IAsyncOperationCompletedHandler<COMType*>> ( [this] (IAsyncOperation<COMType*>* asyncOpPtr, AsyncStatus) { if (asyncOpPtr == nullptr) return E_ABORT; auto hr = asyncOpPtr->GetResults (port.resetAndGetPointerAddress()); if (FAILED (hr)) return hr; portOpened.signal(); return S_OK; } ).Get()); // We need to use a timeout here, rather than waiting indefinitely, as the // WinRT API can occasionally hang! portOpened.wait (2000); } const String deviceID; WinRTWrapper::ComPtr<COMFactoryType>& factory; WinRTWrapper::ComPtr<COMInterfaceType>& port; WaitableEvent portOpened { true }; }; //============================================================================== template <typename MIDIIOStaticsType, typename MIDIPort> class WinRTIOWrapper : private BLEDeviceWatcher::Listener { public: WinRTIOWrapper (BLEDeviceWatcher& bleWatcher, MidiIODeviceWatcher<MIDIIOStaticsType>& midiDeviceWatcher, const String& deviceIdentifier) : bleDeviceWatcher (bleWatcher) { { const ScopedLock lock (midiDeviceWatcher.deviceChanges); deviceInfo = midiDeviceWatcher.getWinRTDeviceInfoForDevice (deviceIdentifier); } if (deviceInfo.deviceID.isEmpty()) throw std::runtime_error ("Invalid device index"); JUCE_WINRT_MIDI_LOG ("Creating JUCE MIDI IO: " << deviceInfo.deviceID); if (deviceInfo.containerID.isNotEmpty()) { bleDeviceWatcher.addListener (this); const ScopedLock lock (bleDeviceWatcher.deviceChanges); HashMap<String, BLEDeviceWatcher::DeviceInfo>::Iterator iter (bleDeviceWatcher.devices); while (iter.next()) { if (iter.getValue().containerID == deviceInfo.containerID) { isBLEDevice = true; break; } } } } virtual ~WinRTIOWrapper() { bleDeviceWatcher.removeListener (this); disconnect(); } //============================================================================== virtual void disconnect() { if (midiPort != nullptr) { if (isBLEDevice) midiPort->Release(); } midiPort = nullptr; } private: //============================================================================== void bleDeviceAdded (const String& containerID) override { if (containerID == deviceInfo.containerID) isBLEDevice = true; } void bleDeviceDisconnected (const String& containerID) override { if (containerID == deviceInfo.containerID) { JUCE_WINRT_MIDI_LOG ("Disconnecting MIDI port from BLE disconnection: " << deviceInfo.deviceID << " " << deviceInfo.containerID << " " << deviceInfo.name); disconnect(); } } protected: //============================================================================== BLEDeviceWatcher& bleDeviceWatcher; WinRTMIDIDeviceInfo deviceInfo; bool isBLEDevice = false; WinRTWrapper::ComPtr<MIDIPort> midiPort; }; //============================================================================== struct WinRTInputWrapper final : public MidiInput::Pimpl, private WinRTIOWrapper<IMidiInPortStatics, IMidiInPort> { WinRTInputWrapper (WinRTMidiService& service, MidiInput& input, const String& deviceIdentifier, MidiInputCallback& cb) : WinRTIOWrapper <IMidiInPortStatics, IMidiInPort> (*service.bleDeviceWatcher, *service.inputDeviceWatcher, deviceIdentifier), inputDevice (input), callback (cb) { OpenMidiPortThread<IMidiInPortStatics, IMidiInPort, MidiInPort> portThread ("Open WinRT MIDI input port", deviceInfo.deviceID, service.midiInFactory, midiPort); portThread.startThread(); portThread.waitForThreadToExit (-1); if (midiPort == nullptr) { JUCE_WINRT_MIDI_LOG ("Timed out waiting for midi input port creation"); return; } startTime = Time::getMillisecondCounterHiRes(); auto hr = midiPort->add_MessageReceived ( Callback<ITypedEventHandler<MidiInPort*, MidiMessageReceivedEventArgs*>> ( [this] (IMidiInPort*, IMidiMessageReceivedEventArgs* args) { return midiInMessageReceived (args); } ).Get(), &midiInMessageToken); if (FAILED (hr)) { JUCE_WINRT_MIDI_LOG ("Failed to set MIDI input callback"); jassertfalse; } } ~WinRTInputWrapper() { disconnect(); } //============================================================================== void start() override { if (! isStarted) { concatenator.reset(); isStarted = true; } } void stop() override { if (isStarted) { isStarted = false; concatenator.reset(); } } String getDeviceIdentifier() override { return deviceInfo.containerID; } String getDeviceName() override { return deviceInfo.name; } //============================================================================== void disconnect() override { stop(); if (midiPort != nullptr && midiInMessageToken.value != 0) midiPort->remove_MessageReceived (midiInMessageToken); WinRTIOWrapper<IMidiInPortStatics, IMidiInPort>::disconnect(); } //============================================================================== HRESULT midiInMessageReceived (IMidiMessageReceivedEventArgs* args) { if (! isStarted) return S_OK; WinRTWrapper::ComPtr<IMidiMessage> message; auto hr = args->get_Message (message.resetAndGetPointerAddress()); if (FAILED (hr)) return hr; WinRTWrapper::ComPtr<IBuffer> buffer; hr = message->get_RawData (buffer.resetAndGetPointerAddress()); if (FAILED (hr)) return hr; WinRTWrapper::ComPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess; hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress()); if (FAILED (hr)) return hr; uint8_t* bufferData = nullptr; hr = bufferByteAccess->Buffer (&bufferData); if (FAILED (hr)) return hr; uint32_t numBytes = 0; hr = buffer->get_Length (&numBytes); if (FAILED (hr)) return hr; ABI::Windows::Foundation::TimeSpan timespan; hr = message->get_Timestamp (&timespan); if (FAILED (hr)) return hr; concatenator.pushMidiData (bufferData, numBytes, convertTimeStamp (timespan.Duration), &inputDevice, callback); return S_OK; } double convertTimeStamp (int64 timestamp) { auto millisecondsSinceStart = static_cast<double> (timestamp) / 10000.0; auto t = startTime + millisecondsSinceStart; auto now = Time::getMillisecondCounterHiRes(); if (t > now) { if (t > now + 2.0) startTime -= 1.0; t = now; } return t * 0.001; } //============================================================================== MidiInput& inputDevice; MidiInputCallback& callback; MidiDataConcatenator concatenator { 4096 }; EventRegistrationToken midiInMessageToken { 0 }; double startTime = 0; bool isStarted = false; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTInputWrapper); }; //============================================================================== struct WinRTOutputWrapper final : public MidiOutput::Pimpl, private WinRTIOWrapper <IMidiOutPortStatics, IMidiOutPort> { WinRTOutputWrapper (WinRTMidiService& service, const String& deviceIdentifier) : WinRTIOWrapper <IMidiOutPortStatics, IMidiOutPort> (*service.bleDeviceWatcher, *service.outputDeviceWatcher, deviceIdentifier) { OpenMidiPortThread<IMidiOutPortStatics, IMidiOutPort, IMidiOutPort> portThread ("Open WinRT MIDI output port", deviceInfo.deviceID, service.midiOutFactory, midiPort); portThread.startThread(); portThread.waitForThreadToExit (-1); if (midiPort == nullptr) throw std::runtime_error ("Timed out waiting for midi output port creation"); auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating(); if (wrtWrapper == nullptr) throw std::runtime_error ("Failed to get the WinRTWrapper singleton!"); auto bufferFactory = wrtWrapper->getWRLFactory<IBufferFactory> (&RuntimeClass_Windows_Storage_Streams_Buffer[0]); if (bufferFactory == nullptr) throw std::runtime_error ("Failed to create output buffer factory"); auto hr = bufferFactory->Create (static_cast<UINT32> (65536), buffer.resetAndGetPointerAddress()); if (FAILED (hr)) throw std::runtime_error ("Failed to create output buffer"); hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress()); if (FAILED (hr)) throw std::runtime_error ("Failed to get buffer byte access"); hr = bufferByteAccess->Buffer (&bufferData); if (FAILED (hr)) throw std::runtime_error ("Failed to get buffer data pointer"); } //============================================================================== void sendMessageNow (const MidiMessage& message) override { if (midiPort == nullptr) return; auto numBytes = message.getRawDataSize(); auto hr = buffer->put_Length (numBytes); if (FAILED (hr)) { jassertfalse; return; } memcpy_s (bufferData, numBytes, message.getRawData(), numBytes); midiPort->SendBuffer (buffer); } String getDeviceIdentifier() override { return deviceInfo.containerID; } String getDeviceName() override { return deviceInfo.name; } //============================================================================== WinRTWrapper::ComPtr<IBuffer> buffer; WinRTWrapper::ComPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess; uint8_t* bufferData = nullptr; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTOutputWrapper); }; WinRTWrapper::ComPtr<IMidiInPortStatics> midiInFactory; WinRTWrapper::ComPtr<IMidiOutPortStatics> midiOutFactory; std::unique_ptr<MidiIODeviceWatcher<IMidiInPortStatics>> inputDeviceWatcher; std::unique_ptr<MidiIODeviceWatcher<IMidiOutPortStatics>> outputDeviceWatcher; std::unique_ptr<BLEDeviceWatcher> bleDeviceWatcher; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTMidiService) }; #endif // JUCE_USE_WINRT_MIDI //============================================================================== //============================================================================== #if ! JUCE_MINGW extern RTL_OSVERSIONINFOW getWindowsVersionInfo(); #endif struct MidiService : public DeletedAtShutdown { MidiService() { #if JUCE_USE_WINRT_MIDI && ! JUCE_MINGW #if ! JUCE_FORCE_WINRT_MIDI auto windowsVersionInfo = getWindowsVersionInfo(); if (windowsVersionInfo.dwMajorVersion >= 10 && windowsVersionInfo.dwBuildNumber >= 17763) #endif { try { internal.reset (new WinRTMidiService()); return; } catch (std::runtime_error&) {} } #endif internal.reset (new Win32MidiService()); } ~MidiService() { clearSingletonInstance(); } static MidiServiceType& getService() { jassert (getInstance()->internal != nullptr); return *getInstance()->internal.get(); } JUCE_DECLARE_SINGLETON (MidiService, false) private: std::unique_ptr<MidiServiceType> internal; }; JUCE_IMPLEMENT_SINGLETON (MidiService) //============================================================================== static int findDefaultDeviceIndex (const Array<MidiDeviceInfo>& available, const MidiDeviceInfo& defaultDevice) { for (int i = 0; i < available.size(); ++i) if (available.getUnchecked (i) == defaultDevice) return i; return 0; } Array<MidiDeviceInfo> MidiInput::getAvailableDevices() { return MidiService::getService().getAvailableDevices (true); } MidiDeviceInfo MidiInput::getDefaultDevice() { return MidiService::getService().getDefaultDevice (true); } std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback) { if (deviceIdentifier.isEmpty() || callback == nullptr) return {}; std::unique_ptr<MidiInput> in (new MidiInput ({}, deviceIdentifier)); std::unique_ptr<Pimpl> wrapper; try { wrapper.reset (MidiService::getService().createInputWrapper (*in, deviceIdentifier, *callback)); } catch (std::runtime_error&) { return {}; } in->setName (wrapper->getDeviceName()); in->internal = std::move (wrapper); return in; } StringArray MidiInput::getDevices() { StringArray deviceNames; for (auto& d : getAvailableDevices()) deviceNames.add (d.name); return deviceNames; } int MidiInput::getDefaultDeviceIndex() { return findDefaultDeviceIndex (getAvailableDevices(), getDefaultDevice()); } std::unique_ptr<MidiInput> MidiInput::openDevice (int index, MidiInputCallback* callback) { return openDevice (getAvailableDevices()[index].identifier, callback); } MidiInput::MidiInput (const String& deviceName, const String& deviceIdentifier) : deviceInfo (deviceName, deviceIdentifier) { } MidiInput::~MidiInput() = default; void MidiInput::start() { internal->start(); } void MidiInput::stop() { internal->stop(); } //============================================================================== Array<MidiDeviceInfo> MidiOutput::getAvailableDevices() { return MidiService::getService().getAvailableDevices (false); } MidiDeviceInfo MidiOutput::getDefaultDevice() { return MidiService::getService().getDefaultDevice (false); } std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String& deviceIdentifier) { if (deviceIdentifier.isEmpty()) return {}; std::unique_ptr<Pimpl> wrapper; try { wrapper.reset (MidiService::getService().createOutputWrapper (deviceIdentifier)); } catch (std::runtime_error&) { return {}; } std::unique_ptr<MidiOutput> out; out.reset (new MidiOutput (wrapper->getDeviceName(), deviceIdentifier)); out->internal = std::move (wrapper); return out; } StringArray MidiOutput::getDevices() { StringArray deviceNames; for (auto& d : getAvailableDevices()) deviceNames.add (d.name); return deviceNames; } int MidiOutput::getDefaultDeviceIndex() { return findDefaultDeviceIndex (getAvailableDevices(), getDefaultDevice()); } std::unique_ptr<MidiOutput> MidiOutput::openDevice (int index) { return openDevice (getAvailableDevices()[index].identifier); } MidiOutput::~MidiOutput() { stopBackgroundThread(); } void MidiOutput::sendMessageNow (const MidiMessage& message) { internal->sendMessageNow (message); } } // namespace juce
paynebc/tunefish
src/tunefish4/JuceLibraryCode/modules/juce_audio_devices/native/juce_win32_Midi.cpp
C++
gpl-3.0
66,071
Bitrix 16.5 Business Demo = 1e67873c11e83e6bcc02d85d9da11bcc
gohdan/DFC
known_files/hashes/bitrix/modules/mobileapp/templates_app/simple/menu.php
PHP
gpl-3.0
61
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Etrias\MagentoConnector\Exceptions; class EmptyQuoteException extends MagentoSoapException { }
etrias-nl/magento-connector
src/Exceptions/EmptyQuoteException.php
PHP
gpl-3.0
402
/* * #%L * GC4S components * %% * Copyright (C) 2014 - 2019 Hugo López-Fernández, Daniel Glez-Peña, Miguel Reboiro-Jato, * Florentino Fdez-Riverola, Rosalía Laza-Fidalgo, Reyes Pavón-Rial * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package org.sing_group.gc4s.input.tree; import static javax.swing.BorderFactory.createEmptyBorder; import static org.sing_group.gc4s.utilities.builder.JButtonBuilder.newJButtonBuilder; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import org.sing_group.gc4s.utilities.JTreeUtils; /** * A component to select an element from a {@code JTree}. The tree is displayed in a popup menu when user clicks the * button and the selected element in the tree is displayed in the component. * * @author hlfernandez * */ public class JTreeSelectionPanel extends JPanel { private static final long serialVersionUID = 1L; private static final String DEFAULT_CHOOSE_BUTTON_LABEL = "Choose"; private static final boolean DEFAULT_CLOSE_POPUP_TREE_SELECTION = false; private static final boolean DEFAULT_BUTTON_CLOSE_VISIBLE = true; private static final boolean DEFAULT_BUTTON_EXPAND_ALL_VISIBLE = true; private static final boolean DEFAULT_BUTTON_COLLAPSE_ALL_VISIBLE = true; private JTree tree; private JLabel selectionLabel; private JTreePopupMenu popupMenu; private String chooseButtonLabel; private JButton chooseButton; private boolean closePopupOnTreeSelection; private boolean closeButtonVisible; private boolean expandAllButtonVisible; private boolean collapseAllButtonVisible; /** * Constructs a new {@code JTreeSelectionPanel} with the specified tree and default values for the rest of the * parameters. * * @param tree the {@code JTree} for the user selection */ public JTreeSelectionPanel( JTree tree ) { this( tree, DEFAULT_CHOOSE_BUTTON_LABEL, DEFAULT_CLOSE_POPUP_TREE_SELECTION, DEFAULT_BUTTON_CLOSE_VISIBLE, DEFAULT_BUTTON_EXPAND_ALL_VISIBLE, DEFAULT_BUTTON_COLLAPSE_ALL_VISIBLE ); } /** * Constructs a new {@code JTreeSelectionPanel} with the specified tree. This constructor also allows to specify: * * <ul> * <li>The label for the choose button.</li> * <li>Whether the popup must be closed when an item is selected.</li> * <li>The visibility of the close, expand all and collapse all buttons.</li> * </ul> * * @param tree the {@code JTree} for the user selection * @param chooseButtonLabel the label for the choose button * @param closePopupOnTreeSelection whether the popup must be closed when an item is selected */ public JTreeSelectionPanel( JTree tree, String chooseButtonLabel, boolean closePopupOnTreeSelection, boolean closeButtonVisible, boolean expandAllButtonVisible, boolean collapseAllButtonVisible ) { this.tree = tree; this.chooseButtonLabel = chooseButtonLabel; this.closePopupOnTreeSelection = closePopupOnTreeSelection; this.closeButtonVisible = closeButtonVisible; this.expandAllButtonVisible = expandAllButtonVisible; this.collapseAllButtonVisible = collapseAllButtonVisible; this.init(); this.tree.getSelectionModel().addTreeSelectionListener(this::treeValueChanged); } private void init() { this.popupMenu = new JTreePopupMenu(this.tree, this.closeButtonVisible, this.expandAllButtonVisible, this.collapseAllButtonVisible); this.setLayout(new BorderLayout()); this.add(getChooseButton(), BorderLayout.WEST); this.add(getSelectionLabel(), BorderLayout.CENTER); } private Component getChooseButton() { if (this.chooseButton == null) { this.chooseButton = newJButtonBuilder().withText(this.chooseButtonLabel).thatDoes(getChooseButtonAction()).build(); } return this.chooseButton; } private Action getChooseButtonAction() { return new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { chooseButtonAction(); } }; } private void chooseButtonAction() { popupMenu.show( this.chooseButton, this.chooseButton.getX(), this.chooseButton.getY() ); popupMenu.pack(); } /** * Returns the selection label component. * * @return the {@code JLabel} used to display the current selection */ public JLabel getSelectionLabel() { if (this.selectionLabel == null) { this.selectionLabel = new JLabel(getCurrentSelection()); this.selectionLabel.setMinimumSize(getSelectionLabelMinimumSize()); this.selectionLabel.setPreferredSize(getSelectionLabelMinimumSize()); this.selectionLabel.setBorder(createEmptyBorder(0, 10, 0, 5)); this.selectionLabel.setFont(getSelectionLabelFont()); } return this.selectionLabel; } /** * Returns the font of the selected item text label. * * @return the {@code Font} of the selected item text label */ protected Font getSelectionLabelFont() { return new JLabel().getFont(); } /** * Returns the minimum size of the selected item text label. * * @return the minimum size of the selected item text label */ protected Dimension getSelectionLabelMinimumSize() { return new Dimension(150, 30); } private String getCurrentSelection() { if (this.tree.getSelectionModel().isSelectionEmpty()) { return ""; } else { return this.tree.getSelectionModel().getSelectionPath() .getLastPathComponent().toString(); } } private void treeValueChanged(TreeSelectionEvent e) { this.selectionLabel.setText(getCurrentSelection()); if (this.closePopupOnTreeSelection) { this.popupMenu.setVisible(false); } } /** * * An extension of {@code JPopupMenu} that show a {@code JTree} when it becomes visible. It has also some buttons to * control the tree (expand/collapse nodes) and to close the menu. * * @author hlfernandez * */ public static class JTreePopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; private JTree tree; private JScrollPane scrollPane; private JPanel buttonsPanel; private boolean closeButtonVisible; private boolean expandAllButtonVisible; private boolean collapseAllButtonVisible; /** * Constructs a new {@code JTreePopupMenu} with the specified tree. * * @param tree the {@code JTree} to be displayed */ public JTreePopupMenu(JTree tree) { this(tree, true, true, true); } public JTreePopupMenu( JTree tree, boolean closeButtonVisible, boolean expandAllButtonVisible, boolean collapseAllButtonVisible ) { this.tree = tree; this.closeButtonVisible = closeButtonVisible; this.expandAllButtonVisible = expandAllButtonVisible; this.collapseAllButtonVisible = collapseAllButtonVisible; this.setLayout(new BorderLayout()); this.add(getTreeViewScrollPane(), BorderLayout.CENTER); this.add(getButtonsPanel(), BorderLayout.SOUTH); } private Component getTreeViewScrollPane() { if (scrollPane == null) { JPanel treePanel = new JPanel(); treePanel.setLayout(new BorderLayout()); treePanel.add(this.tree, BorderLayout.NORTH); treePanel.setBackground(tree.getBackground()); scrollPane = new JScrollPane(treePanel); scrollPane.setPreferredSize(new Dimension(400, 400)); scrollPane.getVerticalScrollBar().setUnitIncrement(15); } return scrollPane; } private Component getButtonsPanel() { if (this.buttonsPanel == null) { buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton closeButton = new JButton("Close"); closeButton.setVisible(closeButtonVisible); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == closeButton) { setVisible(false); } } }); JButton collapseAllButton = new JButton("Collapse all"); collapseAllButton.setVisible(collapseAllButtonVisible); collapseAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == collapseAllButton) { JTreeUtils.collapseAll(tree); } } }); JButton expandAllButton = new JButton("Expand all"); expandAllButton.setVisible(expandAllButtonVisible); expandAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == expandAllButton) { JTreeUtils.expandAll(tree); } } }); buttonsPanel.add(closeButton); buttonsPanel.add(collapseAllButton); buttonsPanel.add(expandAllButton); } return this.buttonsPanel; } } }
hlfernandez/GC4S
gc4s/src/main/java/org/sing_group/gc4s/input/tree/JTreeSelectionPanel.java
Java
gpl-3.0
10,120
<?php class T4PSC_TwoThird { public static $args; /** * Initiate the shortcode */ public function __construct() { add_filter( 't4p_attr_two-third-shortcode', array( $this, 'attr' ) ); add_shortcode( 'two_third', array( $this, 'render' ) ); } /** * Render the shortcode * * @param array $args Shortcode paramters * @param string $content Content between shortcode * @return string HTML output */ function render( $args, $content = '') { $defaults = shortcode_atts( array( 'class' => '', 'id' => '', 'last' => 'no' ), $args ); extract( $defaults ); self::$args = $defaults; $clearfix = ''; if( self::$args['last'] == 'yes' ) { $clearfix = sprintf( '<div %s></div>', T4PCore_Plugin::attributes( 't4p-clearfix' ) ); } $html = sprintf( '<div %s>%s</div>%s', T4PCore_Plugin::attributes( 'two-third-shortcode' ), do_shortcode( $content ), $clearfix ); return $html; } function attr() { $attr['class'] = 't4p-two-third two_third t4p-column'; if( self::$args['last'] == 'yes' ) { $attr['class'] .= ' last'; } if( self::$args['class'] ) { $attr['class'] .= ' ' . self::$args['class']; } if( self::$args['id'] ) { $attr['id'] = self::$args['id']; } return $attr; } } new T4PSC_TwoThird();
bolsadoinfinito/site
wp-content/plugins/t4p-core-composer/shortcodes/class-two-third.php
PHP
gpl-3.0
1,384
/* * This file is part of the VCF.Filter project (https://biomedical-sequencing.at/VCFFilter/). * VCF.Filter permits graphical filtering of VCF files on cutom annotations and standard VCF fields, pedigree analysis, and cohort searches. * %% * Copyright © 2016, 2017 Heiko Müller (hmueller@cemm.oeaw.ac.at) * %% * * VCF.Filter is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VCF.Filter. If not, see <http://www.gnu.org/licenses/>. * * VCF.Filter Copyright © 2016, 2017 Heiko Müller (hmueller@cemm.oeaw.ac.at) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it * under certain conditions; * For details interrogate the About section in the File menu. */ package at.ac.oeaw.cemm.bsf.vcffilter.filter; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFCompoundHeaderLine; /** * Filters for default QUAL field (Phred scaled quality). * QualFilter.java 04 OCT 2016 * * @author Heiko Müller * @version 1.0 * @since 1.0 */ public class QualFilter extends DoubleNumberFilter{ /** * The version number of this class. */ static final long serialVersionUID = 1L; /** * Creates new QualFilter. * * @param header VCF header line object * @author Heiko Müller * @since 1.0 */ public QualFilter(VCFCompoundHeaderLine header){ super(header); criterion1.setToolTipText(">1000"); criterion2.setToolTipText("=1000"); criterion3.setToolTipText(""); } public boolean passesFilter(VariantContext vc) { Object o = vc.getPhredScaledQual(); if (o == null) { //System.out.println(ID + " not found"); return false; } String attstring = o.toString(); //System.out.println("attribute string: " + attstring); Double attribute = parseNumber(attstring); if(testPredicate(attribute, operator1, predicate1) || testPredicate(attribute, operator2, predicate2) || testPredicate(attribute, operator3, predicate3)){ return true; }else{ return false; } } private boolean testPredicate(Double attribute, String operator, Double predicate){ if(operator.equals("<")){ if(attribute.doubleValue() < predicate.doubleValue()){ return true; }else{ return false; } } if(operator.equals("=")){ if(attribute.doubleValue() == predicate.doubleValue()){ return true; }else{ return false; } } if(operator.equals(">")){ if(attribute.doubleValue() > predicate.doubleValue()){ return true; }else{ return false; } } return false; } }
hmueller80/VCF.Filter
VCFFilter/src/at/ac/oeaw/cemm/bsf/vcffilter/filter/QualFilter.java
Java
gpl-3.0
3,595
x = int(input()) y = int(input()) print('In this test case x =', x, 'and y =', y) if x >= y: print('(The maximum is x)') theMax = x else: print('(The maximum is y)') theMax = y print('The maximum is', theMax)
cemc/cscircles-wp-content
lesson_files/lesson9/if.py
Python
gpl-3.0
225
<?php if ( !class_exists( "contactbuddy_admin" ) ) { class contactbuddy_admin { function contactbuddy_admin(&$parent) { $this->_parent = &$parent; $this->_var = &$parent->_var; $this->_name = &$parent->_name; $this->_options = &$parent->_options; $this->_pluginPath = &$parent->_pluginPath; $this->_pluginURL = &$parent->_pluginURL; $this->_selfLink = &$parent->_selfLink; add_action('admin_menu', array(&$this, 'admin_menu')); // Add menu in admin. // SHORTCODE BUTTON add_action( 'media_buttons_context', array( &$this, 'add_post_button' ) ); } function alert( $arg1, $arg2 = false ) { $this->_parent->alert( $arg1, $arg2 ); } function nonce() { wp_nonce_field( $this->_parent->_var . '-nonce' ); } function savesettings() { check_admin_referer( $this->_parent->_var . '-nonce' ); if(empty($_POST[$this->_var . '-recipemail'])) { $this->_parent->_errors[] = 'recipemail'; $this->_parent->_showErrorMessage( 'Recipient email address is empty' ); } if(empty($_POST[$this->_var . '-subject'])) { $this->_parent->_errors[] = 'subject'; $this->_parent->_showErrorMessage( 'Subject is empty' ); } if($_POST[$this->_var . '-recaptcha'] == '1') { if(empty($_POST[$this->_var . '-recaptcha-pubkey'])) { $this->_parent->_errors[] = 'recaptcha-pubkey'; $this->_parent->_showErrorMessage( 'If you are using recaptcha you must input a reCAPTCHA public key' ); } if(empty($_POST[$this->_var . '-recaptcha-privkey'])) { $this->_parent->_errors[] = 'recaptcha-privkey'; $this->_parent->_showErrorMessage( 'If you are using recaptcha you must input a reCAPTCHA private key' ); } } if ( isset( $this->_parent->_errors ) ) { $this->_parent->_showErrorMessage( 'Please correct the ' . ngettext( 'error', 'errors', count( $this->_parent->_errors ) ) . ' in order to save changes.' ); } else { $this->_options['recipemail'] = $_POST[$this->_var . '-recipemail']; $this->_options['subject'] = $_POST[$this->_var . '-subject']; $this->_options['recaptcha'] = $_POST[$this->_var . '-recaptcha']; $this->_options['recaptcha-pubkey'] = $_POST[$this->_var . '-recaptcha-pubkey']; $this->_options['recaptcha-privkey'] = $_POST[$this->_var . '-recaptcha-privkey']; $this->_options['defaultcss'] = $_POST[$this->_var . '-defaultcss']; $this->_parent->save(); $this->alert( 'Settings saved...' ); } } function admin_scripts() { //wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'pluginbuddy-tooltip-js', $this->_parent->_pluginURL . '/js/tooltip.js' ); wp_print_scripts( 'pluginbuddy-tooltip-js' ); wp_enqueue_script( 'pluginbuddy-swiftpopup-js', $this->_parent->_pluginURL . '/js/swiftpopup.js' ); wp_print_scripts( 'pluginbuddy-swiftpopup-js' ); wp_enqueue_script( 'pluginbuddy-'.$this->_var.'-admin-js', $this->_parent->_pluginURL . '/js/admin.js' ); wp_print_scripts( 'pluginbuddy-'.$this->_var.'-admin-js' ); echo '<link rel="stylesheet" href="'.$this->_pluginURL . '/css/admin.css" type="text/css" media="all" />'; } /** * get_feed() * * Gets an RSS or other feed and inserts it as a list of links... * * $feed string URL to the feed. * $limit integer Number of items to retrieve. * $append string HTML to include in the list. Should usually be <li> items including the <li> code. * $replace string String to replace in every title returned. ie twitter includes your own username at the beginning of each line. */ function get_feed( $feed, $limit, $append = '', $replace = '' ) { require_once(ABSPATH.WPINC.'/feed.php'); $rss = fetch_feed( $feed ); if (!is_wp_error( $rss ) ) { $maxitems = $rss->get_item_quantity( $limit ); // Limit $rss_items = $rss->get_items(0, $maxitems); echo '<ul class="pluginbuddy-nodecor">'; $feed_html = get_transient( md5( $feed ) ); if ( $feed_html == '' ) { foreach ( (array) $rss_items as $item ) { $feed_html .= '<li>- <a href="' . $item->get_permalink() . '">'; $title = $item->get_title(); //, ENT_NOQUOTES, 'UTF-8'); if ( $replace != '' ) { $title = str_replace( $replace, '', $title ); } if ( strlen( $title ) < 30 ) { $feed_html .= $title; } else { $feed_html .= substr( $title, 0, 32 ) . ' ...'; } $feed_html .= '</a></li>'; } set_transient( md5( $feed ), $feed_html, 300 ); // expires in 300secs aka 5min } echo $feed_html; echo $append; echo '</ul>'; } else { echo 'Temporarily unable to load feed...'; } } function add_post_button( $content ){ return $content . ' <a onclick="cb_add_post();" title="Add simple contact form"><img src="' . $this->_pluginURL . '/images/atsymbol.png" alt="Add simple contact form" /></a> <script> function cb_add_post() { var win = window.dialogArguments || opener || parent || top; win.send_to_editor( \'[contactbuddy]\' ); } </script>'; } function view_gettingstarted() { // Needed for fancy boxes... wp_enqueue_style('dashboard'); wp_print_styles('dashboard'); wp_enqueue_script('dashboard'); wp_print_scripts('dashboard'); // Load scripts and CSS used on this page. $this->admin_scripts(); // If they clicked the button to reset plugin defaults... if (!empty($_POST['reset_defaults'])) { $this->_options = $this->_parent->_defaults; $this->_parent->save(); $this->_parent->_showStatusMessage( 'Plugin settings have been reset to defaults.' ); } ?> <div class="wrap"> <div class="postbox-container" style="width:70%;"> <h2>Getting Started with <?php echo $this->_parent->_name; ?> v<?php echo $this->_parent->_version; ?></h2> <p> ContactBuddy allows you to easily add a contact form to your site by placing it in a widget or using shortcode button in the posts and page editors. </p> <ol> <li>Go to the <a href="<?php echo $this->_selfLink; ?>-settings">ContactBuddy Settings</a> link.</li> <li>Set the "Recipient email address" to the address you would like the entries to be sent to.</li> <li>Set the "Subject" to the subject you would like to appear on the emails from the ContactBuddy form.</li> <li>Choose to enable or disable reCAPTCHA validation for your ContactBuddy form.</li> <li> Add into your widgets on your site or add into posts and pages by clicking the shortcode button <img src="<?php echo $this->_pluginURL . '/images/atsymbol.png'; ?>" alt="shortcodebutton" /> in the post and page editors. </li> </ol> <h3>Version History</h3> <textarea rows="7" cols="65"><?php readfile( $this->_parent->_pluginPath . '/history.txt' ); ?></textarea> <br /><br /> <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#pluginbuddy_debugtoggle").click(function() { jQuery("#pluginbuddy_debugtoggle_div").slideToggle(); }); }); </script> <a id="pluginbuddy_debugtoggle" class="button secondary-button">Debugging Information</a> <div id="pluginbuddy_debugtoggle_div" style="display: none;"> <h3>Debugging Information</h3> <?php echo '<textarea rows="7" cols="65">'; echo 'Plugin Version = '.$this->_name.' '.$this->_parent->_version.' ('.$this->_parent->_var.')'."\n"; echo 'WordPress Version = '.get_bloginfo("version")."\n"; echo 'PHP Version = '.phpversion()."\n"; global $wpdb; echo 'DB Version = '.$wpdb->db_version()."\n"; echo "\n".serialize($this->_options); echo '</textarea>'; ?> <p> <form method="post" action="<?php echo $this->_selfLink; ?>"> <input type="hidden" name="reset_defaults" value="true" /> <input type="submit" name="submit" value="Reset Plugin Settings & Defaults" id="reset_defaults" class="button secondary-button" onclick="if ( !confirm('WARNING: This will reset all settings associated with this plugin to their defaults. Are you sure you want to do this?') ) { return false; }" /> </form> </p> </div> <br /><br /><br /> <a href="http://pluginbuddy.com" style="text-decoration: none;"><img src="<?php echo $this->_pluginURL; ?>/images/pluginbuddy.png" style="vertical-align: -3px;" /> PluginBuddy.com</a><br /><br /> </div> <div class="postbox-container" style="width:20%; margin-top: 35px; margin-left: 15px;"> <div class="metabox-holder"> <div class="meta-box-sortables"> <div id="breadcrumbslike" class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span>Want more form options?</span></h3> <div class="inside"> <ul> <li>Try <a href="https://www.e-junkie.com/ecom/gb.php?cl=54585&c=ib&aff=14589" target="_blank">Gravity forms</a></li> </ul> </div> </div> <div id="breadcrumbslike" class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span>Things to do...</span></h3> <div class="inside"> <ul class="pluginbuddy-nodecor"> <li>- <a href="http://twitter.com/home?status=<?php echo urlencode('Check out this awesome plugin, ' . $this->_parent->_name . '! ' . $this->_parent->_url . ' @pluginbuddy'); ?>" title="Share on Twitter" onClick="window.open(jQuery(this).attr('href'),'ithemes_popup','toolbar=0,status=0,width=820,height=500,scrollbars=1'); return false;">Tweet about this plugin.</a></li> <li>- <a href="http://pluginbuddy.com/purchase/">Check out PluginBuddy plugins.</a></li> <li>- <a href="http://pluginbuddy.com/purchase/">Check out iThemes themes.</a></li> <li>- <a href="http://secure.hostgator.com/cgi-bin/affiliates/clickthru.cgi?id=ithemes">Get HostGator web hosting.</a></li> </ul> </div> </div> <div id="breadcrumsnews" class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span>Latest news from PluginBuddy</span></h3> <div class="inside"> <p style="font-weight: bold;">PluginBuddy.com</p> <?php $this->get_feed( 'http://pluginbuddy.com/feed/', 5 ); ?> <p style="font-weight: bold;">Twitter @pluginbuddy</p> <?php $twit_append = '<li>&nbsp;</li>'; $twit_append .= '<li><img src="'.$this->_pluginURL.'/images/twitter.png" style="vertical-align: -3px;" /> <a href="http://twitter.com/pluginbuddy/">Follow @pluginbuddy on Twitter.</a></li>'; $twit_append .= '<li><img src="'.$this->_pluginURL.'/images/feed.png" style="vertical-align: -3px;" /> <a href="http://pluginbuddy.com/feed/">Subscribe to RSS news feed.</a></li>'; $twit_append .= '<li><img src="'.$this->_pluginURL.'/images/email.png" style="vertical-align: -3px;" /> <a href="http://pluginbuddy.com/subscribe/">Subscribe to Email Newsletter.</a></li>'; $this->get_feed( 'http://twitter.com/statuses/user_timeline/108700480.rss', 5, $twit_append, 'pluginbuddy: ' ); ?> </div> </div> <div id="breadcrumbssupport" class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span>Need support?</span></h3> <div class="inside"> <p>See our <a href="http://pluginbuddy.com/tutorials/">tutorials & videos</a> or visit our <a href="http://pluginbuddy.com/support/">support forum</a> for additional information and help.</p> </div> </div> </div> </div> </div> </div> <?php } function view_settings() { $this->_parent->load(); $this->admin_scripts(); /* echo '<pre>'; print_r($this->_options); echo '</pre>'; */ if ( !empty( $_POST['save_recip'] ) ) { $this->savesettings(); } ?> <div class="wrap"> <h2><?php echo $this->_name; ?> Settings</h2> <form method="post" action="<?php echo $this->_selfLink; ?>-settings"> <?php // Ex. for saving in a group you might do something like: $this->_options['groups'][$_GET['group_id']['settings'] which would be: ['groups'][$_GET['group_id']['settings'] ?> <input type="hidden" name="savepoint" value="" /> <table class="form-table"> <tr> <td><label for="first_name">Recipient email address <a class="pluginbuddy_tip" title=" - Enter the email for the form submissions to go to.">(?)</a>:</label></td> <td><input type="text" name="<?php echo $this->_var; ?>-recipemail" size="45" maxlength="45" value="<?php echo $this->_options['recipemail']; ?>" /></td> </tr> <tr> <td><label for="last_name">Subject <a class="pluginbuddy_tip" title=" - Enter the email subject.">(?)</a>:</label></td> <td><input type="text" name="<?php echo $this->_var; ?>-subject" size="45" maxlength="45" value="<?php echo $this->_options['subject']; ?>" /></td> </tr> <tr> <td> <label for="recaptcha"> Enable reCAPTCHA <a class="pluginbuddy_tip" title=" - [Default: disabled] - When enabled, a recaptcha input will be added to your contact form to insure entries weren't made by a robot">(?)</a>: </label> </td> <input type="hidden" name="<?php echo $this->_var; ?>-recaptcha" value="0" /> <?php if (($this->_options['recaptcha'] == '1') || (isset($_POST[$this->_var . '-recaptcha']) && ($_POST[$this->_var . '-recaptcha'] == '1'))) { $checked = 'checked'; } else { $checked = ''; } ?> <td><input class="option_toggle" type="checkbox" name="<?php echo $this->_var; ?>-recaptcha" id="recaptcha" value="1" <?php echo $checked; ?> /></td> </tr> <?php // Check if recaptcha is checked if (($this->_options['recaptcha'] != '1') || (isset($_POST[$this->_var . '-recaptcha']) && ($_POST[$this->_var . '-recaptcha'] != '1'))) { $keyshow = 'style="display: none;"'; } else { $keyshow = ''; } ?> <tr class="recaptcha_toggle" <?php echo $keyshow; ?>> <td colspan="2"><h3>With reCAPTCHA enabled you can only have one <?php echo $this->_name; ?> form on each page.</h3></td> </tr> <tr class="recaptcha_toggle" <?php echo $keyshow; ?>> <td colspan="2"><h3><a href="https://www.google.com/recaptcha" target="_blank">Click here to get a <span style="color: #C52C03";>reCAPTCHA</span> keys</a></h3></td> </tr> <tr class="recaptcha_toggle" <?php echo $keyshow; ?>> <td><label for="recaptcha-pubkey">reCAPTCHA public key <a class="pluginbuddy_tip" title=" - Enter your reCAPTCHA public key from https://www.google.com/recaptcha">(?)</a>:</label></td> <td><input type="text" name="<?php echo $this->_var; ?>-recaptcha-pubkey" id="recaptcha-pubkey" size="45" maxlength="45" value="<?php if ( isset( $this->_options['recaptcha-pubkey'] ) ) { echo $this->_options['recaptcha-pubkey']; } ?>" /></td> </tr> <tr class="recaptcha_toggle" <?php echo $keyshow; ?>> <td><label for="recaptcha-privkey">reCAPTCHA private key <a class="pluginbuddy_tip" title=" - Enter your reCAPTCHA private key from https://www.google.com/recaptcha">(?)</a>:</label></td> <td><input type="text" name="<?php echo $this->_var; ?>-recaptcha-privkey" id="recaptcha-privkey" size="45" maxlength="45" value="<?php if ( isset( $this->_options['recaptcha-privkey'] ) ) { echo $this->_options['recaptcha-privkey']; } ?>" /></td> </tr> <tr><td colspan="2"><h3>CSS Options</h3></td></tr> <tr> <td> <label for="cb-defaultcss">Style Options <a class="pluginbuddy_tip" title=" - - Choose a from multiple styles for your contact form.">(?)</a>:</label> </td> <td> <?php $cbstylelist = array( 'on' => 'default', 'light' => 'light', 'dark' => 'dark', 'skinny' => 'skinny', 'fat' => 'fat', 'full-width' => 'full width', 'compressed' => 'compressed', 'off' => 'no styles' ); ?> <select name="<?php echo $this->_var; ?>-defaultcss" id="cb-defaultcss"> <?php foreach( $cbstylelist as $stylekey => $styleval ) { $select = ''; if ( isset( $this->_options['defaultcss'] ) ) { if ( $this->_options['defaultcss'] == $stylekey) { $select = " selected "; } } echo '<option value="' . $stylekey . '"' . $select . '>' . $styleval . '</option>'; } ?> </select> </td> </tr> </table> <p class="submit"><input type="submit" name="save_recip" value="Save Settings" class="button-primary" id="save" /></p> <?php $this->nonce(); ?> </form> <p>CSS tip: the class used to style the ContactBuddy form is "contactbuddy-form".</p> </div> <?php } function Gravity_Forms() { ?> <h3>Need more flexibility with your forms? <a href="https://www.e-junkie.com/ecom/gb.php?cl=54585&c=ib&aff=14589">Try Gravity Forms</a>.</h3> <p>Gravity Forms is a beautiful and simple form creation and management plugin that makes it quick and easy to add simple or advanced forms.</p> <p>Here are some of the great ways to use Gravity Forms:</p> <ul> <li>- Allow people to submit guest posts to your WordPress blog</li> <li>- Create multiple forms and have them emailed to you</li> <li>- Get customer input with surveys forms</li> <li>- Import/Export forms</li> <li>- and much more!</li> </ul> <h4>Learn more about Gravity Forms <a href="https://www.e-junkie.com/ecom/gb.php?cl=54585&c=ib&aff=14589">here</a></h4> <?php } /** admin_menu() * * Initialize menu for admin section. * */ function admin_menu() { // Add main menu (default when clicking top of menu) add_menu_page($this->_parent->_name.' Getting Started', $this->_parent->_name, 'administrator', $this->_parent->_var, array(&$this, 'view_gettingstarted'), $this->_parent->_pluginURL.'/images/pluginbuddy.png'); // Add sub-menu items (first should match default page above) add_submenu_page( $this->_parent->_var, $this->_parent->_name.' Getting Started', 'Getting Started', 'administrator', $this->_parent->_var, array(&$this, 'view_gettingstarted')); //add_submenu_page( $this->_parent->_var, $this->_parent->_name.' Themes & Devices', 'Themes & Devices', 'administrator', $this->_parent->_var.'-themes', array(&$this, 'view_themes')); add_submenu_page( $this->_parent->_var, $this->_parent->_name.' Settings', 'Settings', 'administrator', $this->_parent->_var.'-settings', array(&$this, 'view_settings')); add_submenu_page( $this->_parent->_var, $this->_parent->_name.' Gravity Forms', 'Try Gravity Forms', 'administrator', $this->_parent->_var.'-GravityForms', array(&$this, 'Gravity_Forms')); } } // End class $contactbuddy_admin = new contactbuddy_admin($this); // Create instance }
wcorrigan/portals
plugins/contactbuddy-by-pluginbuddycom/classes/admin.php
PHP
gpl-3.0
19,206
package com.sun.corba.se.PortableActivationIDL; /** * com/sun/corba/se/PortableActivationIDL/Locator.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from /HUDSON/workspace/8-2-build-linux-amd64/jdk8u77/6540/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl * Sunday, March 20, 2016 10:01:25 PM PDT */ public interface Locator extends LocatorOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { } // interface Locator
TLQPQPQ/tlq_git_study
src/com/sun/corba/se/PortableActivationIDL/Locator.java
Java
gpl-3.0
492
<?php /* @var $this TvShowController */ /* @var $details TVShow */ $this->pageTitle = $details->getDisplayName(); ?> <div class="row"> <div class="span3"> <?php echo CHtml::image(new ThumbnailVideo($details->getArtwork(), Thumbnail::SIZE_LARGE), '', array( 'class'=>'item-thumbnail hidden-phone', )); ?> <div class="item-links"> <?php echo TbHtml::linkButton(Yii::t('TVShows', 'Watch the whole show'), array( 'color'=>TbHtml::BUTTON_COLOR_SUCCESS, 'size'=>TbHtml::BUTTON_SIZE_LARGE, 'url'=>$this->createUrl('tvShow/getTVShowPlaylist', array('tvshowId'=>$details->getId())), 'class'=>'fa fa-play', )); ?> <p style="margin-top: 20px;"> <?php echo Yii::t('TVShows', 'or choose individual episodes from the list below'); ?> </p> </div> </div> <div class="span9 item-description"> <div class="item-top"> <div class="item-title"> <h2> <a href="<?php echo $details->getTVDBUrl(); ?>" target="_blank"> <?php echo $details->label; ?> </a> </h2> <?php if(!empty($details->year)) echo '<p>('.$details->year.')</p>'; ?> </div> </div> <div class="item-info clearfix"> <?php if ($details->hasRating()) $this->renderPartial('/videoLibrary/_rating', array('item'=>$details)); ?> <div class="pull-left"> <div class="item-metadata clearfix"> <p><?php echo $details->getGenreString(); ?></p> <?php $this->widget('MPAARating', array( 'rating'=>$details->mpaa)); ?> </div> </div> </div> <h3><?php echo Yii::t('Media', 'Plot'); ?></h3> <div class="item-plot"> <p><?php echo $details->getPlot(); ?></p> </div> <div class="cast"> <h3><?php echo Yii::t('Media', 'Cast'); ?></h3> <?php echo FormHelper::helpBlock(Yii::t('TVShows', "Click the name to go to the person's IMDb page")); ?> <div class="row-fluid"> <?php $this->widget('zii.widgets.CListView', array( 'dataProvider'=>$actorDataProvider, 'itemView'=>'/videoLibrary/_actorGridItem', 'itemsTagName'=>'ul', 'itemsCssClass'=>'thumbnails actor-grid', 'enablePagination'=>false, 'template'=>'{items}' )); ?> </div> </div> </div> </div> <?php $this->widget('Seasons', array( 'tvshow'=>$details, 'seasons'=>$seasons, ));
enen92/xbmc-video-server
src/protected/views/tvShow/details.php
PHP
gpl-3.0
2,297
package com.alipay.api.domain; import java.util.Date; import java.util.List; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; /** * 流程实例 * * @author auto create * @since 1.0, 2017-03-03 11:29:15 */ public class BPOpenApiInstance extends AlipayObject { private static final long serialVersionUID = 5581722165768253843L; /** * 业务上下文,JSON格式 */ @ApiField("biz_context") private String bizContext; /** * 业务ID */ @ApiField("biz_id") private String bizId; /** * 创建人域账号 */ @ApiField("create_user") private String createUser; /** * 流程实例描述 */ @ApiField("description") private String description; /** * 创建到完成的毫秒数,未完结为0 */ @ApiField("duration") private Long duration; /** * 创建时间 */ @ApiField("gmt_create") private Date gmtCreate; /** * 完结时间,未完结时为空 */ @ApiField("gmt_end") private Date gmtEnd; /** * 最后更新时间 */ @ApiField("gmt_modified") private Date gmtModified; /** * 2088账号 */ @ApiField("ip_role_id") private String ipRoleId; /** * 最后更新人域账号 */ @ApiField("modify_user") private String modifyUser; /** * 流程配置名称 */ @ApiField("name") private String name; /** * 父流程实例ID。用于描述父子流程 */ @ApiField("parent_id") private String parentId; /** * 父流程实例所处的节点 */ @ApiField("parent_node") private String parentNode; /** * 优先级 */ @ApiField("priority") private Long priority; /** * 全局唯一ID */ @ApiField("puid") private String puid; /** * 前置流程ID。用于描述流程串联 */ @ApiField("source_id") private String sourceId; /** * 前置流程从哪个节点发起的本流程 */ @ApiField("source_node_name") private String sourceNodeName; /** * 流程实例状态:CREATED,PROCESSING,COMPLETED,CANCELED */ @ApiField("state") private String state; /** * 包含的任务列表 */ @ApiListField("tasks") @ApiField("b_p_open_api_task") private List<BPOpenApiTask> tasks; public String getBizContext() { return this.bizContext; } public void setBizContext(String bizContext) { this.bizContext = bizContext; } public String getBizId() { return this.bizId; } public void setBizId(String bizId) { this.bizId = bizId; } public String getCreateUser() { return this.createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public Long getDuration() { return this.duration; } public void setDuration(Long duration) { this.duration = duration; } public Date getGmtCreate() { return this.gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtEnd() { return this.gmtEnd; } public void setGmtEnd(Date gmtEnd) { this.gmtEnd = gmtEnd; } public Date getGmtModified() { return this.gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getIpRoleId() { return this.ipRoleId; } public void setIpRoleId(String ipRoleId) { this.ipRoleId = ipRoleId; } public String getModifyUser() { return this.modifyUser; } public void setModifyUser(String modifyUser) { this.modifyUser = modifyUser; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getParentId() { return this.parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getParentNode() { return this.parentNode; } public void setParentNode(String parentNode) { this.parentNode = parentNode; } public Long getPriority() { return this.priority; } public void setPriority(Long priority) { this.priority = priority; } public String getPuid() { return this.puid; } public void setPuid(String puid) { this.puid = puid; } public String getSourceId() { return this.sourceId; } public void setSourceId(String sourceId) { this.sourceId = sourceId; } public String getSourceNodeName() { return this.sourceNodeName; } public void setSourceNodeName(String sourceNodeName) { this.sourceNodeName = sourceNodeName; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public List<BPOpenApiTask> getTasks() { return this.tasks; } public void setTasks(List<BPOpenApiTask> tasks) { this.tasks = tasks; } }
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/BPOpenApiInstance.java
Java
gpl-3.0
4,773
#include "Server.h" Server::Server() { } Server::~Server() { }
samcosmo/KingdomFlux
KingdomFlux/KingdomFlux/Server.cpp
C++
gpl-3.0
68
/* TimerEvent.cc -*- c++ -*- * Copyright (c) 2009 Ross Biro * * An event that posts itself after a predetermined about of time. * Similiar to Timer, but Timer doesn't use events since the * EventQueue timeouts are built on it. */ /* * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 3 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ #include "textus/event/TimerEvent.h" namespace textus { namespace event { void TimerEvent::timeOut() { if (!first_time_out) { Event::timeOut(); return; } first_time_out = false; post(); } }} // namespace
TextusData/Mover
textus/event/TimerEvent.cc
C++
gpl-3.0
1,096
package sportsallaround.utils.generales; import com.sna_deportivo.utils.gr.FactoryObjectSNSDeportivo; import com.sna_deportivo.utils.gr.ObjectSNSDeportivo; import com.sna_deportivo.utils.json.JsonUtils; import com.sna_deportivo.utils.json.excepciones.ExcepcionJsonDeserializacion; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import sportsallaround.utils.gui.KeyValueItem; /** * Created by nicolas on 30/08/15. */ public final class ConstructorArrObjSNS { private ConstructorArrObjSNS(){} public static ArrayList<ObjectSNSDeportivo> producirArrayObjetoSNS(FactoryObjectSNSDeportivo fabrica, JSONArray arrayJson){ if(fabrica != null && arrayJson != null) { ArrayList<ObjectSNSDeportivo> retorno = new ArrayList<ObjectSNSDeportivo>(); try { for(int i = 0;i < arrayJson.length(); i++){ retorno.add(i,fabrica.getObjetoSNS()); retorno.get(i).deserializarJson(JsonUtils.JsonStringToObject(arrayJson.getString(i))); } } catch (ExcepcionJsonDeserializacion excepcionJsonDeserializacion) { excepcionJsonDeserializacion.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return retorno; } return null; } public static ArrayList<KeyValueItem> producirArrayAdapterObjSNS(ArrayList<ObjectSNSDeportivo> objetos, String[] atributoAMostrarAdapter){ ArrayList<KeyValueItem> adapter = new ArrayList<KeyValueItem>(); Integer i = 0; for(ObjectSNSDeportivo obj:objetos){ obj.retornoToString(atributoAMostrarAdapter); adapter.add(new KeyValueItem(i++,obj)); } return adapter; } public static ArrayList<KeyValueItem> producirArrayAdapterObjSNS(ArrayList<ObjectSNSDeportivo> objetos, String[] atributoAMostrarAdapter, String[] separadoresAtributos) throws Exception{ ArrayList<KeyValueItem> adapter = new ArrayList<KeyValueItem>(); Integer i = 0; for(ObjectSNSDeportivo obj:objetos){ obj.retornoToStringSeparadores(atributoAMostrarAdapter,separadoresAtributos); adapter.add(new KeyValueItem(i++,obj)); } return adapter; } }
Nick2324/tesis_red_social
Prototipo/Construccion/SNADeportivo/app/src/main/java/sportsallaround/utils/generales/ConstructorArrObjSNS.java
Java
gpl-3.0
2,607
package net.syncarus.gui; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.filechooser.FileSystemView; import net.syncarus.core.FileOperation; import net.syncarus.rcp.ResourceRegistry; import net.syncarus.rcp.SyncarusPlugin; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TypedListener; /** * Useful component allowing the user to choose a directory form a treeViewer. */ public class DirSelectComposite extends Composite { private TableViewer viewer; public DirSelectComposite(Composite parent, int style) { super(parent, style); setBackground(new Color(this.getDisplay(), 255, 0, 0)); setLayout(new FillLayout()); buildListViewer(); } /** * build a new listViewer where the initial root is the second element of * java.io.File.listRoots() if there is only one root, use this one. */ private void buildListViewer() { viewer = new TableViewer(this); viewer.setLabelProvider(new FileLabelProvider()); viewer.setContentProvider(new FileContentProvider()); viewer.setSorter(new ViewerSorter() { @Override public int compare(Viewer viewer, Object e1, Object e2) { EncapsulatedFile ef1 = (EncapsulatedFile) e1; EncapsulatedFile ef2 = (EncapsulatedFile) e2; return ef1.compareTo(ef2); } }); viewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); setCurrentDirectory(((EncapsulatedFile) selection.getFirstElement()).getFile()); } }); setCurrentDirectory(FileOperation.getDefaultDirectory()); } /** * @param directory * set this directory as new root of the treeViewer */ public void setCurrentDirectory(File directory) { viewer.setInput(directory); viewer.getTable().setSelection(viewer.getTable().getItem(0)); notifyListeners(SWT.Selection, null); } public void addSelectionListener(SelectionListener listener) { checkWidget(); if (listener == null) return; TypedListener typedListener = new TypedListener(listener); addListener(SWT.Selection, typedListener); addListener(SWT.DefaultSelection, typedListener); } /** * @return the currently selected directory */ public File getCurrentDirectory() { return (File) viewer.getInput(); } } /** * Helper class which encapsulates a file and the information whether this file * is a root (example: C:\, A:\, ..) or if it's a parent (first element in * treeViewer - UPDIR) */ class EncapsulatedFile implements Comparable<EncapsulatedFile> { private File file = null; private boolean isParent = false; private boolean isRoot; /** * Constructor for the root of root Files (parent of '/', 'C:\', ...) */ public EncapsulatedFile() { this.file = new File(""); this.isParent = true; this.isRoot = false; } /** * Constructor for root Files ('/', 'C:\', ...) * * @param file */ public EncapsulatedFile(File file) { this.file = file; this.isParent = false; this.isRoot = true; } /** * Constructor for regular, existing files and directories * * @param file * @param isParent */ public EncapsulatedFile(File file, boolean isParent) { this.file = file; this.isParent = isParent; this.isRoot = false; } public File getFile() { return file; } /** * compares two encapsulated files where the order is as follows: * <ul> * <li>isParent()</li> * <li>compare case-insensitive directory names</li> * </ul> * * @param other * @return result of comparison */ @Override public int compareTo(EncapsulatedFile other) { if (isParent()) return -1; if (other.isParent()) return 1; return file.getName().compareToIgnoreCase(other.getFile().getName()); } public boolean isParent() { return isParent; } public boolean isRoot() { return isRoot; } } class FileContentProvider extends ArrayContentProvider implements IStructuredContentProvider { @Override public Object[] getElements(Object inputElement) { File file = (File) inputElement; List<EncapsulatedFile> fileList = new ArrayList<EncapsulatedFile>(); if (!file.exists()) // top - level, list drives { for (File rootFile : File.listRoots()) fileList.add(new EncapsulatedFile(rootFile)); } else { if (file.getParentFile() == null) // go to drive selection fileList.add(new EncapsulatedFile()); else // go one dir up fileList.add(new EncapsulatedFile(file.getParentFile(), true)); if (file.listFiles() != null) for (File subFile : file.listFiles()) if (subFile.isDirectory()) fileList.add(new EncapsulatedFile(subFile, false)); } return fileList.toArray(); } } class FileLabelProvider extends LabelProvider { @Override public String getText(Object element) { EncapsulatedFile encapsFile = (EncapsulatedFile) element; if (encapsFile.isParent()) return ""; if (encapsFile.isRoot()) { String rootName = FileSystemView.getFileSystemView().getSystemDisplayName(encapsFile.getFile()); if (rootName == null || rootName.equals("")) rootName = encapsFile.getFile().getAbsolutePath(); return rootName; } String name = encapsFile.getFile().getName(); if (name == null || name.equals("")) name = encapsFile.getFile().getAbsolutePath(); return name; } @Override public Image getImage(Object element) { EncapsulatedFile file = (EncapsulatedFile) element; String imageKey = null; if (file.isParent()) imageKey = ResourceRegistry.IMAGE_DIR_UP; else if (file.isRoot()) { if (FileSystemView.getFileSystemView().isFloppyDrive(file.getFile())) imageKey = ResourceRegistry.IMAGE_DIR_FLOPPY; else imageKey = ResourceRegistry.IMAGE_DIR_HDD; } else imageKey = ResourceRegistry.IMAGE_DIR_NORMAL; return SyncarusPlugin.getInstance().getResourceRegistry().getImage(imageKey); } }
schiermike/syncarus
src/net/syncarus/gui/DirSelectComposite.java
Java
gpl-3.0
6,577
module Utils { export class Generator { public static newGuid() { var guid = ""; for (var i = 1; i <= 32; i++) { var n = Math.floor(Math.random() * 16.0).toString(16); guid += n; if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) guid += "-"; } return guid; } } export class Common { public static isInt(val: string): boolean { var regInt = /^-?[0-9]+(\.0*)?$/; return regInt.test(val); } public static resolveAlertMsg(val: string, isError: boolean): string { var result; var msgFormat; if (isError) { msgFormat = '{0}[[[失败]]]'; } else { msgFormat = '{0}[[[成功]]]'; } switch (val) { case 'Submit': case 'ReSubmit': result = '[[[提交]]]'; break; case 'Save': result = '[[[保存]]]'; break; case 'Return': result = '[[[退回]]]'; break; case 'Approve': result = '[[[审批]]]'; break; case 'Decline': result = '[[[拒绝]]]'; break; case 'Recall': result = '[[[撤回]]]'; break; default: result = '[[[操作]]]'; } return Common.format.call(this, msgFormat, result); } public static isUserAction(from: string): boolean { var isUserAction = false; if (from && from == 'useraction') { isUserAction = true; } return isUserAction; } public static getParameterByName(name: string): string { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.hash ? location.hash : location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } public static filterDefaultDate(val: Date): Date { var result = null; var valMoment = moment(val); if (valMoment.isValid() && valMoment.year() != 1900) { result = val; } return result; } public static format(): string { if (arguments.length == 0) return null; var str = arguments[0]; for (var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; } public static GetQueryString(key: string): string { var result = ""; if (document.URL.indexOf("?") > 0) { var query = document.URL.substr(document.URL.indexOf("?") + 1).split("&"); for (var i = 0, len = query.length; i < len; i++) { var keyVal = query[i].split("="); if (keyVal[0].toLowerCase() == key.toLowerCase()) { result = keyVal[1]; break; } } } return result; } } ///Javascript中的浮点数精确计算 ///Author: Stephen.Wang ///Date: 2014-07-09 export class caculator { //加法 public static plus(a: number, b: number): number { if (!a) { a = 0; }; if (!b) { b = 0; } var s1 = a.toString(), s2 = b.toString(), m1 = s1.indexOf(".") > 0 ? s1.length - s1.indexOf(".") - 1 : 0, m2 = s2.indexOf(".") > 0 ? s2.length - s2.indexOf(".") - 1 : 0, m = Math.pow(10, Math.max(m1, m2)); return (caculator.multiply(a, m) + caculator.multiply(b, m)) / m; } //乘法 public static multiply(a, b): number { if (!a) { a = 0; }; if (!b) { b = 0; } var s1 = a.toString(), s2 = b.toString(), m1 = s1.indexOf(".") > 0 ? s1.length - s1.indexOf(".") - 1 : 0, m2 = s2.indexOf(".") > 0 ? s2.length - s2.indexOf(".") - 1 : 0; return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m1 + m2); } ///减法 public static subtract(a, b): number { return caculator.plus(a, -b); } ///除法 public static division(a, b): number { //return caculator.multiply(a, 1 / b); return a * 1 / b; } } export class ServiceURI { //webApi地址 public static Address() { return "http://172.24.130.43:10083/"; //本机 return "http://localhost:10083/"; } //web服务器地址 public static WebAddress() { return "http://172.24.130.43:10082/"; //本机 return "http://localhost:10082/"; } //基础框架Api地址 public static FrameAddress() { return "http://172.24.130.43:10080/"; } //基础框架Web地址 public static FrameWebAddress() { return "http://172.24.130.43:10081/"; } //附件服务器地址 public static AttachmentAddress() { return "http://1.1.2.5:9000/PMT/upload?action=download&&fileName="; } public static AppUri = window["AppUri"]; public static ApiDelegate = ServiceURI.AppUri + "ApiDelegate.ashx"; } export class Constants { public static ApiDelegate = Utils.ServiceURI.ApiDelegate; public static BaseUri = Utils.ServiceURI.FrameWebAddress(); public static ServiceUri = Utils.ServiceURI.FrameAddress(); } } declare function escape(str: any);
XiaoYaTech/Demo
Business/Mcdonalds.AM.Web/Scripts/Utils/Utils.ts
TypeScript
gpl-3.0
6,343
from django.conf.urls import url from django.contrib.auth.views import login, \ logout, \ logout_then_login, \ password_change, \ password_change_done, \ password_reset, \ password_reset_done, \ password_reset_confirm, \ password_reset_complete from . import views urlpatterns = [ url(r'^$', views.dashboard, name='dashboard'), # login / logout urls url(r'^login/$', view=login, name='login'), url(r'^logout/$', view=logout, name='logout'), url(r'^logout-then-login/$', view=logout_then_login, name='logout_then_login'), # change password urls url(r'^password-change/$', view=password_change, name='password_change'), url(r'^password-change/done/$', view=password_change_done, name='password_change_done'), # restore password urls url(r'^password-reset/$', view=password_reset, name='password_reset'), url(r'^password-reset/done/$', view=password_reset_done, name='password_reset_done'), url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$', view=password_reset_confirm, name='password_reset_confirm'), url(r'^password-reset/complete/$', view=password_reset_complete, name='password_reset_complete'), ]
t104801/webapp
security/urls.py
Python
gpl-3.0
1,479
import pygame from Explosion import Explosion class Bullet(object): PLAYER, ENEMY = 1, 0 def __init__(self, manager, parent, init_pos, direction, speed=3): self.manager = manager self.parent = parent self.image = pygame.image.load("res/tanks/bullet.png") self.explosion = pygame.image.load("res/explosions/bullet_explosion.png") self.rect = self.calculate_init_point(direction, init_pos) self.speed = self.calculate_speed(direction, speed) def calculate_speed(self, direction, speed): if direction == 0: # Up return (0, -speed) if direction == 1: # Down self.image = pygame.transform.rotate(self.image, 180) return (0, speed) if direction == 2: # Left self.image = pygame.transform.rotate(self.image, 90) return (-speed, 0) if direction == 3: # Right self.image = pygame.transform.rotate(self.image, -90) return (speed, 0) def calculate_init_point(self, direction, init_pos): rect = self.image.get_rect() posX = init_pos[0] posY = init_pos[1] if direction == 0: rect.x = posX + 12 rect.y = posY - 14 if direction == 1: rect.x = posX + 12 rect.y = posY + 32 if direction == 2: rect.x = posX - 14 rect.y = posY + 12 if direction == 3: rect.x = posX + 32 rect.y = posY + 12 return rect def update(self, blocks): posX = self.speed[0] posY = self.speed[1] self.rect.x += posX self.rect.y += posY # Si nos vamos a salir del mundo, explotamos if self.rect.x < 0: self.rect.x = 0 self.explode() if self.rect.x > 632: self.rect.x = 632 self.explode() if self.rect.y < 0: self.rect.y = 0 self.explode() if self.rect.y > 568: self.rect.y = 568 self.explode() crashed = False # Check if we crashed with another block for block in blocks: # We can't crash with ourselves... can we? if block == self: pass # If we do crash, we tell the manager to destroy said block elif self.rect.colliderect(block): # Right after we check if we can destroy said block block_name = type(block).__name__ if block_name in ["Block", "Heart", "Bullet"]: self.impact_side(block) if self.manager.destroy_element(block): # Block tells us if it destroyed crashed = True else: # Else, we explode self.explode() elif block_name == "Enemy" and self.parent: # Player bullet against enemy self.impact_side(block) # If enemy tells us it destroyed, it's a kill if self.manager.destroy_element(block): self.manager.increment_kills() crashed = True else: # Else, we explode self.explode() elif block_name == "Enemy" and not self.parent: # Enemy bullet hitting enemy crashed = True elif block_name == "Jugador" and not self.parent: # Enemy bullet hitting the player self.impact_side(block) # If the player destroys, we destroy if self.manager.destroy_element(block): crashed = True else: # Else, we explode self.explode() else: pass if crashed: # If we crashed, we destroy ourselves self.destroy() def destroy(self): if self.parent == self.PLAYER: self.manager.remove_player_bullet() self.manager.remove_bullet(self) return True def explode(self): if self.parent == self.PLAYER: self.manager.remove_player_bullet() # Create the explosion Explosion(self.manager, self.rect) self.manager.remove_bullet(self) return True def impact_side(self, block): posX = self.speed[0] posY = self.speed[1] if posX > 0: # Left side self.rect.right = block.rect.left if posX < 0: # Right side self.rect.left = block.rect.right if posY > 0: # Upper side self.rect.bottom = block.rect.top if posY < 0: # Lower side self.rect.top = block.rect.bottom
Vicyorus/BattleTank
src/Bullet.py
Python
gpl-3.0
5,190
namespace EmployeeReview.Forms { partial class SummaryForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lbl_Summary = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lbl_Summary // this.lbl_Summary.AutoSize = true; this.lbl_Summary.Dock = System.Windows.Forms.DockStyle.Fill; this.lbl_Summary.Location = new System.Drawing.Point(0, 0); this.lbl_Summary.Name = "lbl_Summary"; this.lbl_Summary.Size = new System.Drawing.Size(35, 13); this.lbl_Summary.TabIndex = 0; this.lbl_Summary.Text = "label1"; this.lbl_Summary.Click += new System.EventHandler(this.lbl_Summary_Click); // // SummaryForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(737, 395); this.Controls.Add(this.lbl_Summary); this.Name = "SummaryForm"; this.Text = "SummaryForm"; this.Load += new System.EventHandler(this.SummaryForm_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lbl_Summary; } }
aamod0611/Playground
WinForms/employeeform/EmployeeReview/Forms/SummaryForm.Designer.cs
C#
gpl-3.0
2,220
/* Copyright (c) 2012, Jardalu LLC. (http://jardalu.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For complete licensing, see license.txt or visit http://ratnazone.com/v0.2/license.txt */ namespace Jardalu.Ratna.Core { #region using using System; #endregion public class Tag { #region public properties public string Name { get; set; } public int Weight { get; set; } #endregion #region public methods public override bool Equals(object obj) { Tag t = obj as Tag; if (t == null) return false; return (t.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } public override int GetHashCode() { return base.GetHashCode(); } #endregion } }
ratnazone/ratna
ratna/om/Core/Tags/Tag.cs
C#
gpl-3.0
1,604
# -*- coding: utf-8 -*- # from rest_framework.viewsets import ModelViewSet from rest_framework.generics import RetrieveAPIView, ListAPIView from django.shortcuts import get_object_or_404 from django.db.models import Q from common.utils import get_logger, get_object_or_none from common.mixins.api import SuggestionMixin from users.models import User, UserGroup from users.serializers import UserSerializer, UserGroupSerializer from users.filters import UserFilter from perms.models import AssetPermission from perms.serializers import AssetPermissionSerializer from perms.filters import AssetPermissionFilter from orgs.mixins.api import OrgBulkModelViewSet from orgs.mixins import generics from assets.api import FilterAssetByNodeMixin from ..models import Asset, Node, Platform from .. import serializers from ..tasks import ( update_assets_hardware_info_manual, test_assets_connectivity_manual, test_system_users_connectivity_a_asset, push_system_users_a_asset ) from ..filters import FilterAssetByNodeFilterBackend, LabelFilterBackend, IpInFilterBackend logger = get_logger(__file__) __all__ = [ 'AssetViewSet', 'AssetPlatformRetrieveApi', 'AssetGatewayListApi', 'AssetPlatformViewSet', 'AssetTaskCreateApi', 'AssetsTaskCreateApi', 'AssetPermUserListApi', 'AssetPermUserPermissionsListApi', 'AssetPermUserGroupListApi', 'AssetPermUserGroupPermissionsListApi', ] class AssetViewSet(SuggestionMixin, FilterAssetByNodeMixin, OrgBulkModelViewSet): """ API endpoint that allows Asset to be viewed or edited. """ model = Asset filterset_fields = { 'hostname': ['exact'], 'ip': ['exact'], 'system_users__id': ['exact'], 'platform__base': ['exact'], 'is_active': ['exact'], 'protocols': ['exact', 'icontains'] } search_fields = ("hostname", "ip") ordering_fields = ("hostname", "ip", "port", "cpu_cores") ordering = ('hostname', ) serializer_classes = { 'default': serializers.AssetSerializer, 'suggestion': serializers.MiniAssetSerializer } rbac_perms = { 'match': 'assets.match_asset' } extra_filter_backends = [FilterAssetByNodeFilterBackend, LabelFilterBackend, IpInFilterBackend] def set_assets_node(self, assets): if not isinstance(assets, list): assets = [assets] node_id = self.request.query_params.get('node_id') if not node_id: return node = get_object_or_none(Node, pk=node_id) if not node: return node.assets.add(*assets) def perform_create(self, serializer): assets = serializer.save() self.set_assets_node(assets) class AssetPlatformRetrieveApi(RetrieveAPIView): queryset = Platform.objects.all() serializer_class = serializers.PlatformSerializer rbac_perms = { 'retrieve': 'assets.view_gateway' } def get_object(self): asset_pk = self.kwargs.get('pk') asset = get_object_or_404(Asset, pk=asset_pk) return asset.platform class AssetPlatformViewSet(ModelViewSet): queryset = Platform.objects.all() serializer_class = serializers.PlatformSerializer filterset_fields = ['name', 'base'] search_fields = ['name'] def check_object_permissions(self, request, obj): if request.method.lower() in ['delete', 'put', 'patch'] and obj.internal: self.permission_denied( request, message={"detail": "Internal platform"} ) return super().check_object_permissions(request, obj) class AssetsTaskMixin: def perform_assets_task(self, serializer): data = serializer.validated_data action = data['action'] assets = data.get('assets', []) if action == "refresh": task = update_assets_hardware_info_manual.delay(assets) else: # action == 'test': task = test_assets_connectivity_manual.delay(assets) return task def perform_create(self, serializer): task = self.perform_assets_task(serializer) self.set_task_to_serializer_data(serializer, task) def set_task_to_serializer_data(self, serializer, task): data = getattr(serializer, '_data', {}) data["task"] = task.id setattr(serializer, '_data', data) class AssetTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView): model = Asset serializer_class = serializers.AssetTaskSerializer def create(self, request, *args, **kwargs): pk = self.kwargs.get('pk') request.data['asset'] = pk request.data['assets'] = [pk] return super().create(request, *args, **kwargs) def check_permissions(self, request): action = request.data.get('action') action_perm_require = { 'refresh': 'assets.refresh_assethardwareinfo', 'push_system_user': 'assets.push_assetsystemuser', 'test': 'assets.test_assetconnectivity', 'test_system_user': 'assets.test_assetconnectivity' } perm_required = action_perm_require.get(action) has = self.request.user.has_perm(perm_required) if not has: self.permission_denied(request) def perform_asset_task(self, serializer): data = serializer.validated_data action = data['action'] if action not in ['push_system_user', 'test_system_user']: return asset = data['asset'] system_users = data.get('system_users') if not system_users: system_users = asset.get_all_system_users() if action == 'push_system_user': task = push_system_users_a_asset.delay(system_users, asset=asset) elif action == 'test_system_user': task = test_system_users_connectivity_a_asset.delay(system_users, asset=asset) else: task = None return task def perform_create(self, serializer): task = self.perform_asset_task(serializer) if not task: task = self.perform_assets_task(serializer) self.set_task_to_serializer_data(serializer, task) class AssetsTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView): model = Asset serializer_class = serializers.AssetsTaskSerializer class AssetGatewayListApi(generics.ListAPIView): serializer_class = serializers.GatewayWithAuthSerializer rbac_perms = { 'list': 'assets.view_gateway' } def get_queryset(self): asset_id = self.kwargs.get('pk') asset = get_object_or_404(Asset, pk=asset_id) if not asset.domain: return [] queryset = asset.domain.gateways.filter(protocol='ssh') return queryset class BaseAssetPermUserOrUserGroupListApi(ListAPIView): def get_object(self): asset_id = self.kwargs.get('pk') asset = get_object_or_404(Asset, pk=asset_id) return asset def get_asset_related_perms(self): asset = self.get_object() nodes = asset.get_all_nodes(flat=True) perms = AssetPermission.objects.filter(Q(assets=asset) | Q(nodes__in=nodes)) return perms class AssetPermUserListApi(BaseAssetPermUserOrUserGroupListApi): filterset_class = UserFilter search_fields = ('username', 'email', 'name', 'id', 'source', 'role') serializer_class = UserSerializer def get_queryset(self): perms = self.get_asset_related_perms() users = User.objects.filter( Q(assetpermissions__in=perms) | Q(groups__assetpermissions__in=perms) ).distinct() return users class AssetPermUserGroupListApi(BaseAssetPermUserOrUserGroupListApi): serializer_class = UserGroupSerializer def get_queryset(self): perms = self.get_asset_related_perms() user_groups = UserGroup.objects.filter(assetpermissions__in=perms).distinct() return user_groups class BaseAssetPermUserOrUserGroupPermissionsListApiMixin(generics.ListAPIView): model = AssetPermission serializer_class = AssetPermissionSerializer filterset_class = AssetPermissionFilter search_fields = ('name',) rbac_perms = { 'list': 'perms.view_assetpermission' } def get_object(self): asset_id = self.kwargs.get('pk') asset = get_object_or_404(Asset, pk=asset_id) return asset def filter_asset_related(self, queryset): asset = self.get_object() nodes = asset.get_all_nodes(flat=True) perms = queryset.filter(Q(assets=asset) | Q(nodes__in=nodes)) return perms def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) queryset = self.filter_asset_related(queryset) return queryset class AssetPermUserPermissionsListApi(BaseAssetPermUserOrUserGroupPermissionsListApiMixin): def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) queryset = self.filter_user_related(queryset) queryset = queryset.distinct() return queryset def filter_user_related(self, queryset): user = self.get_perm_user() user_groups = user.groups.all() perms = queryset.filter(Q(users=user) | Q(user_groups__in=user_groups)) return perms def get_perm_user(self): user_id = self.kwargs.get('perm_user_id') user = get_object_or_404(User, pk=user_id) return user class AssetPermUserGroupPermissionsListApi(BaseAssetPermUserOrUserGroupPermissionsListApiMixin): def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) queryset = self.filter_user_group_related(queryset) queryset = queryset.distinct() return queryset def filter_user_group_related(self, queryset): user_group = self.get_perm_user_group() perms = queryset.filter(user_groups=user_group) return perms def get_perm_user_group(self): user_group_id = self.kwargs.get('perm_user_group_id') user_group = get_object_or_404(UserGroup, pk=user_group_id) return user_group
jumpserver/jumpserver
apps/assets/api/asset.py
Python
gpl-3.0
10,108
/** * @file * $Revision: 1.6 $ * $Date: 2008/09/03 16:21:02 $ * * Unless noted otherwise, the portions of Isis written by the USGS are * public domain. See individual third-party library and package descriptions * for intellectual property information, user agreements, and related * information. * * Although Isis has been used by the USGS, no warranty, expressed or * implied, is made by the USGS as to the accuracy and functioning of such * software and related material nor shall the fact of distribution * constitute any such warranty, and no responsibility is assumed by the * USGS in connection therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html * in a browser or see the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include "CubeBsqHandler.h" #include <iostream> #include <QFile> #include "IException.h" #include "Pvl.h" #include "PvlKeyword.h" #include "PvlObject.h" #include "RawCubeChunk.h" using namespace std; namespace Isis { /** * Construct a BSQ IO handler. This will determine a good chunk size to use * that does not result in the cube being enlarged or misordered. * * @param dataFile The file with cube DN data in it * @param virtualBandList The mapping from virtual band to physical band, see * CubeIoHandler's description. * @param labels The Pvl labels for the cube * @param alreadyOnDisk True if the cube is allocated on the disk, false * otherwise */ CubeBsqHandler::CubeBsqHandler(QFile * dataFile, const QList<int> *virtualBandList, const Pvl &labels, bool alreadyOnDisk) : CubeIoHandler(dataFile, virtualBandList, labels, alreadyOnDisk) { int numSamplesInChunk = sampleCount(); int numLinesInChunk = 1; // The chunk size must evenly divide into the cube size... if(lineCount() < 1024) numLinesInChunk = lineCount(); else { int attemptedSize = 1024; while(numLinesInChunk == 1 && attemptedSize > 1) { if(lineCount() % attemptedSize == 0) numLinesInChunk = attemptedSize; else attemptedSize /= 2; } } setChunkSizes(numSamplesInChunk, numLinesInChunk, 1); } /** * The destructor writes all cached data to disk. */ CubeBsqHandler::~CubeBsqHandler() { clearCache(); } void CubeBsqHandler::updateLabels(Pvl &label) { PvlObject &core = label.findObject("IsisCube").findObject("Core"); core.addKeyword(PvlKeyword("Format", "BandSequential"), PvlContainer::Replace); } void CubeBsqHandler::readRaw(RawCubeChunk &chunkToFill) { BigInt startByte = getChunkStartByte(chunkToFill); bool success = false; QFile * dataFile = getDataFile(); if(dataFile->seek(startByte)) { QByteArray binaryData = dataFile->read(chunkToFill.getByteCount()); if(binaryData.size() == chunkToFill.getByteCount()) { chunkToFill.setRawData(binaryData); success = true; } } if(!success) { IString msg = "Reading from the file [" + dataFile->fileName() + "] " "failed with reading [" + QString::number(chunkToFill.getByteCount()) + "] bytes at position [" + QString::number(startByte) + "]"; throw IException(IException::Io, msg, _FILEINFO_); } } void CubeBsqHandler::writeRaw(const RawCubeChunk &chunkToWrite) { BigInt startByte = getChunkStartByte(chunkToWrite); bool success = false; QFile * dataFile = getDataFile(); if(dataFile->seek(startByte)) { BigInt dataWritten = dataFile->write(chunkToWrite.getRawData()); if(dataWritten == chunkToWrite.getByteCount()) { success = true; } } if(!success) { IString msg = "Writing to the file [" + dataFile->fileName() + "] " "failed with writing [" + QString::number(chunkToWrite.getByteCount()) + "] bytes at position [" + QString::number(startByte) + "]"; throw IException(IException::Io, msg, _FILEINFO_); } } /** * This is a helper method that goes from chunk to file position. * * @param chunk The chunk to locate in the file. * @return The file position to start reading or writing at */ BigInt CubeBsqHandler::getChunkStartByte(const RawCubeChunk &chunk) const { return getDataStartByte() + getChunkIndex(chunk) * getBytesPerChunk(); } }
corburn/ISIS
isis/src/base/objs/Cube/CubeBsqHandler.cpp
C++
gpl-3.0
4,563
using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Collections.Generic; public class Ruche : MonoBehaviour { public int _population; public bool EstAuSol; Image _image; Etat _state; Text _text; Button _button; Secours[] _secours; bool devoileMenu; Transform _initialePosition; Sprite rucheNormal; Sprite rucheInonde; Sprite rucheInondeSafe; Sprite rucheOuraganSafe; NuiageDePluie nuage; bool IsDead { get { return _population <= 0; } } public void DevoileMenu() { if(devoileMenu) { foreach (var secour in _secours) { secour.gameObject.SetActive(true); } devoileMenu = false; } else { foreach (var secour in _secours) { secour.gameObject.SetActive(false); } devoileMenu = true; } } void Awake() { _initialePosition = this.transform; _button = GetComponent<Button>(); devoileMenu = true; _button.onClick.AddListener( () => { DevoileMenu(); }); _state = Etat.None; _population = 1000; _image = GetComponent<Image>(); _secours = GetComponentsInChildren<Secours>(); _text = GetComponentInChildren<Text>(); rucheInonde = Resources.Load<Sprite>("IMG/RucheInonde"); rucheInondeSafe = Resources.Load<Sprite>("IMG/RucheInondeSafe"); rucheNormal = Resources.Load<Sprite>("IMG/RucheNormal"); rucheOuraganSafe = Resources.Load<Sprite>("IMG/RucheOuraganSafe"); } void Start() { nuage = GetComponentInChildren<NuiageDePluie>(); nuage.gameObject.SetActive(false); foreach (var secour in _secours) { secour.gameObject.SetActive(false); } } public void SetState(Etat etat) { _state = etat; switch(_state) { case Etat.None: _image.sprite = rucheNormal; break; case Etat.Inondation: _image.sprite = rucheInonde; break; case Etat.Canicule: AnimRed(); break; case Etat.Pesticide: AnimGreen(); break; } } void AnimRed() { _image.CrossFadeColor(new Color(1, 0, 0), 1f, false, false); } void AnimGreen() { _image.CrossFadeColor(new Color(0, 1, 0), 1f, false, false); } public void ReturnToNormalColor() { _image.CrossFadeColor(new Color(1, 1, 1), 0.5f, false, false); } public void SetSprite(Sprite sprite) { _image.sprite = sprite; } public enum Etat { None, Pesticide, Inondation, Ouragan, Canicule } void Update() { if (IsDead) return; switch(_state) { case Etat.None: return; break; case Etat.Inondation: PopLower(); break; case Etat.Ouragan: Tremble(); PopLower(); break; case Etat.Canicule: PopLower(); break; case Etat.Pesticide: PopLower(); break; } } void Tremble() { var signe = Random.value; Vector3 direction = new Vector3(Random.value, Random.value); if (signe > 0.5) direction *= -1; this.transform.Translate(direction); } void PopLower() { _population--; _text.text = _population.ToString(); if (IsDead) { _image.sprite = rucheNormal; _image.color = new Color(0.5f, 0.5f, 0.5f); _text.text = ""; _button.onClick.RemoveAllListeners(); } } public void SoignePesticide() { if (_state == Etat.Pesticide) { ReturnToNormalColor(); SetState(Etat.None); } } public void SoigneInondation() { if(_state == Etat.Inondation) { SetState(Etat.None); _image.sprite = rucheInondeSafe; } } public void SoigneOuragan() { if(_state == Etat.Ouragan) { RemetPosition(); SetState(Etat.None); _image.sprite = rucheOuraganSafe; } } public void SoigneCanicule() { if(_state == Etat.Canicule) { ReturnToNormalColor(); SetState(Etat.None); NuageOTD(); } } void NuageOTD() { nuage.gameObject.SetActive(true); Invoke("FermeTaGueuleNuage", 1f); } void FermeTaGueuleNuage() { nuage.gameObject.SetActive(false); } public void RemetPosition() { this.transform.position = _initialePosition.position; } }
TeamAieNDI/UnityProjects
Nuit de l'info 2015/Assets/Ruche.cs
C#
gpl-3.0
5,185
# encoding: UTF-8 =begin Copyright Alexander E. Fischer <aef@raxys.net>, 2011 This file is part of Lilith. Lilith is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lilith is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Lilith. If not, see <http://www.gnu.org/licenses/>. =end # Possibly recurring event in a course class Event < ActiveRecord::Base include Lilith::UUIDHelper belongs_to :course belongs_to :schedule_state has_many :lecturer_associations, :class_name => 'EventLecturerAssociation', :dependent => :destroy has_many :lecturers, :through => :lecturer_associations has_many :group_associations, :class_name => 'EventGroupAssociation', :dependent => :destroy has_many :groups, :through => :group_associations has_many :category_associations, :class_name => 'CategoryEventAssociation', :dependent => :destroy has_many :categories, :through => :category_associations has_many :week_associations, :class_name => 'EventWeekAssociation', :dependent => :destroy has_many :weeks, :through => :week_associations # Returns all occurrences of this event as Aef::Weekling::WeekDay objects def occurrences occurrence_weeks = weeks.map(&:to_week) first_week_day = Aef::Weekling::WeekDay.new(first_start) holidays = Lilith::HolidayList.for(weeks.first.year) holidays += Lilith::HolidayList.for(weeks.last.year) occurrence_week_days = occurrence_weeks.map!{|week| week.day(first_week_day.index) } occurrence_week_days.reject{|week_day| holidays.any?{|holiday| holiday == week_day } } end # Returns all exceptions of this event as Aef::Weekling::WeekDay objects def exceptions first_week_day = Aef::Weekling::WeekDay.new(first_start) course.study_unit.semester.weeks.map{|week| week.day(first_week_day.index) } - occurrences end # Generates an iCalendar event def to_ical ical_event = RiCal::Component::Event.new ical_event.dtstart = first_start ical_event.dtend = first_end ical_event.summary = "#{course.name} (#{categories.map{|category| category.name || category.eva_id}.join(', ')})" ical_event.location = "Hochschule Bonn-Rhein-Sieg, #{I18n.t('schedules.room')}: #{room}" ical_event.categories = categories.map{|category| category.name || category.eva_id} description = "" description += "#{I18n.t('schedules.lecturers')}: #{lecturers.map(&:name).join(', ')}\n" unless lecturers.empty? description += "#{I18n.t('schedules.groups')}: #{groups.map(&:name).join(', ')}\n" unless groups.empty? ical_event.description = description # If recurrence is needed, make event recurring each week and define exceptions # # This is needed because Evolution 2.30.3 still has problems interpreting rdate recurrence # # Although iCalendar chapter 4.3.10 "Recurrence Rule" states "The UNTIL rule part defines a date-time value which # bounds the recurrence rule in an inclusive manner.", some programs interpret this in an exclusive manner (Sunbird, # Terminplaner.Net). Therefore the day after the real until date is chosen, which should not cause problems in a # weekly recurrence. if weeks.length > 1 ical_event.exdates = exceptions.map(&:to_date) ical_event.rrules = [{:freq => 'weekly', :until => self.until + 1}] end ical_event end end
fslab/lilith
app/models/event.rb
Ruby
gpl-3.0
3,841
/** * * Copyright (c) 2014, Openflexo * * This file is part of Xmlconnector, a component of the software infrastructure * developed at Openflexo. * * * Openflexo is dual-licensed under the European Union Public License (EUPL, either * version 1.1 of the License, or any later version ), which is available at * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * and the GNU General Public License (GPL, either version 3 of the License, or any * later version), which is available at http://www.gnu.org/licenses/gpl.html . * * You can redistribute it and/or modify under the terms of either of these licenses * * If you choose to redistribute it and/or modify under the terms of the GNU GPL, you * must include the following additional permission. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with software containing parts covered by the terms * of EPL 1.0, the licensors of this Program grant you additional permission * to convey the resulting work. * * * This software is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.openflexo.org/license.html for details. * * * Please contact Openflexo (openflexo-contacts@openflexo.org) * or visit www.openflexo.org if you need additional information. * */ package org.openflexo.technologyadapter.xml.model; import java.lang.reflect.Type; import java.util.List; import org.openflexo.foundation.resource.FlexoResource; import org.openflexo.foundation.technologyadapter.FlexoModel; import org.openflexo.pamela.annotations.Adder; import org.openflexo.pamela.annotations.CloningStrategy; import org.openflexo.pamela.annotations.Embedded; import org.openflexo.pamela.annotations.Finder; import org.openflexo.pamela.annotations.Getter; import org.openflexo.pamela.annotations.ImplementationClass; import org.openflexo.pamela.annotations.Initializer; import org.openflexo.pamela.annotations.ModelEntity; import org.openflexo.pamela.annotations.Parameter; import org.openflexo.pamela.annotations.PastingPoint; import org.openflexo.pamela.annotations.Remover; import org.openflexo.pamela.annotations.Setter; import org.openflexo.pamela.annotations.CloningStrategy.StrategyType; import org.openflexo.pamela.annotations.Getter.Cardinality; import org.openflexo.technologyadapter.xml.metamodel.XMLMetaModel; import org.openflexo.technologyadapter.xml.metamodel.XMLObject; import org.openflexo.technologyadapter.xml.metamodel.XMLType; /** * @author xtof * * This interface defines a PAMELA model to represent an XML Document that is conformant to an {@link XMLMetaModel} that might be: - * given by an XSD - dynamically built (on purpose) * */ @ModelEntity @ImplementationClass(XMLModelImpl.class) public interface XMLModel extends XMLObject, FlexoModel<XMLModel, XMLMetaModel> { /** * Reference to the {@link XMLMetaModel} that this document is conformant to */ public static final String MM = "metaModel"; /** * Link to the {@XMLResource} that manages the concrete serialization of this model * */ public static final String RSC = "resource"; /** * Collection of {@link XMLIndividuals} */ public static final String IND = "individuals"; /** * Root individual of the XML Objects graph */ public static final String ROOT = "root"; /** * Properties that host uri and Namespace prefix for this Model */ public static final int NSPREFIX_INDEX = 0; public static final int NSURI_INDEX = 1; @Initializer public XMLModel init(); @Initializer public XMLModel init(@Parameter(MM) XMLMetaModel mm); @Override @Getter(MM) XMLMetaModel getMetaModel(); @Setter(MM) void setMetaModel(XMLMetaModel mm); @Override @Getter(RSC) public FlexoResource<XMLModel> getResource(); @Override @Setter(RSC) public void setResource(FlexoResource<XMLModel> resource); @Getter(ROOT) public XMLIndividual getRoot(); @Setter(ROOT) public void setRoot(XMLIndividual indiv); @Getter(value = IND, cardinality = Cardinality.LIST) @CloningStrategy(StrategyType.CLONE) @Embedded public List<? extends XMLIndividual> getIndividuals(); // TODO ask Syl pourkoi on ne peut pas avoir +eurs adders... public XMLIndividual addNewIndividual(Type aType); @Adder(IND) @PastingPoint public void addIndividual(XMLIndividual ind); @Remover(IND) public void removeFromIndividuals(XMLIndividual ind); @Finder(attribute = XMLIndividual.TYPE, collection = IND, isMultiValued = true) public List<? extends XMLIndividual> getIndividualsOfType(XMLType aType); /* * Non-PAMELA-managed properties */ public List<String> getNamespace(); public void setNamespace(String ns, String prefix); }
openflexo-team/openflexo-technology-adapters
xmlconnector/src/main/java/org/openflexo/technologyadapter/xml/model/XMLModel.java
Java
gpl-3.0
4,930
<?php /* * 第一部分,全局设置 **/ /* * 1.1 优化设置 **/ //1.1.1 去除wordpress功能 remove_action( 'wp_head', 'wp_generator' ); remove_action( 'wp_head', 'wlwmanifest_link' ); remove_action( 'wp_head', 'rsd_link' ); define( 'WP_POST_REVISIONS', 2);//只保存最近两次的版本修订 define( 'AUTOSAVE_INTERVAL', 300);//没5分钟自动保存一次 //1.1.2关闭rss remove_action('wp_head', 'feed_links_extra', 3); remove_action('wp_head', 'feed_links', 2); function wordpress_disable_feed() { wp_die('本站不提供rss订阅功能。'); } add_action('do_feed', 'wordpress_disable_feed', 1); add_action('do_feed_rdf', 'wordpress_disable_feed', 1); add_action('do_feed_rss', 'wordpress_disable_feed', 1); add_action('do_feed_rss2', 'wordpress_disable_feed', 1); add_action('do_feed_atom', 'wordpress_disable_feed', 1); //1.1.3关闭wordpress自带搜索 function fb_filter_query( $query, $error = true ) { if ( is_search() ) { $query->is_search = false; $query->query_vars[s] = false; $query->query[s] = false; if ( $error == true ) $query->is_404 = true; } } add_action( 'parse_query', 'fb_filter_query' ); add_filter( 'get_search_form', create_function( '$a', 'return null;' ) ); //1.1.4关闭链接猜测功能 add_filter('redirect_canonical', 'stop_guessing'); function stop_guessing($url) { if (is_404()) { return false; } return $url; } //1.1.5去掉emoji加载 remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); //1.1.6移除admin-bar function southbase_remove_admin_bar(){ return false; } add_filter( 'show_admin_bar' , 'southbase_remove_admin_bar'); //1.1.7移除仪表盘某些组件 remove_action('welcome_panel', 'wp_welcome_panel');//欢迎面板 function remove_screen_options() {//显示选项选项卡 return false; } add_filter('screen_options_show_screen', 'remove_screen_options'); function wpse50723_remove_help($old_help, $screen_id, $screen){//帮助选项卡 $screen->remove_help_tabs(); return $old_help; } add_filter( 'contextual_help', 'wpse50723_remove_help', 999, 3 ); function gamux_remove_dashboard_widgets() { global $wp_meta_boxes; //删除 "快速发布" 模块 unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']); // 以下这一行代码将删除 "WordPress 开发日志" 模块 unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']); // 以下这一行代码将删除 "其它 WordPress 新闻" 模块 unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']); } add_action('wp_dashboard_setup', 'gamux_remove_dashboard_widgets' ); /* * 1.2 修改wordpress功能 **/ //1.2.1修改自带jq调用规则 if ( !is_admin() ) { // 后台不禁止 function my_init_method() { wp_deregister_script( 'jquery' ); // 取消原有的 jquery 定义 } add_action('init', 'my_init_method'); } wp_deregister_script( 'l10n' ); //1.2.2 获取当前页面url function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") { $pageURL .= "s"; } $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; } return $pageURL; } /* * 1.3 增加wordpress功能 **/ //1.3.1 增加github登陆 get_template_part( 'function/github_login' ); //1.3.2 增加编辑文章扩展功能 get_template_part( 'function/edit_extra_box' ); //1.3.3 上传文件重命名 /*function rename_upload_file($file) { $time=date("Y-m-d H:i:s"); $file['name'] = $time."".mt_rand(100,999).".".pathinfo($file['name'] , PATHINFO_EXTENSION); return $file; } add_filter('wp_handle_upload_prefilter', 'rename_upload_file');*/ //1.3.4 修改上传目录 function slider_upload_dir($uploads) { $siteurl = get_option( 'siteurl' ); $uploads['path'] = WP_CONTENT_DIR . '/uploads'; $uploads['url'] = $siteurl . '/wp-content/uploads'; $uploads['subdir'] = ''; $uploads['basedir'] = $uploads['path']; $uploads['baseurl'] = $uploads['url']; $uploads['error'] = false; return $uploads; } add_filter('upload_dir', 'slider_upload_dir'); //1.3.5 增加和注销可上传类型 add_filter('upload_mimes', 'custom_upload_mimes'); function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes['xz'] = 'application/x-xz'; return $existing_mimes; } //1.3.6 获取特色图片的地址 function get_thumbnail_url($id) { $thumbid = get_post_thumbnail_id($id); $func = wp_get_attachment_image_src(get_post_thumbnail_id($id)); if($func) return $func[0]; else return "https://avatars3.githubusercontent.com/u/4121607"; } //1.3.7 自定义url //自定义页面模板 function loadCustomTemplate($template) { global $wp_query; if(!file_exists($template))return; $wp_query->is_page = true; $wp_query->is_single = false; $wp_query->is_home = false; $wp_query->comments = false; // if we have a 404 status if ($wp_query->is_404) { // set status of 404 to false unset($wp_query->query["error"]); $wp_query->query_vars["error"]=""; $wp_query->is_404=false; } // change the header to 200 OK header("HTTP/1.1 200 OK"); //load our template include($template); exit; } function templateRedirect() { $basename = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']); loadCustomTemplate(TEMPLATEPATH.'/gamux/'."/$basename.php"); } add_action('template_redirect', 'templateRedirect'); //1.3.7 统计已发布文章数 /* * 1.4 Rest API 修改 */ //1.4.1 增加posts API里的缩略图字段 add_action( 'rest_api_init', 'slug_register_starship' ); function slug_register_starship() { register_rest_field( 'post', 'gmeta', array( 'get_callback' => 'rest_post_gmeta', 'update_callback' => null, 'schema' => null ) ); } function list_the_tags() { global $post; //输出tag列表 $a = wp_get_post_tags($post->ID); $b = count($a); $c = []; if ($b == 0) { return '未设置标签'; } else { for( $d=0; $d<$b; $d++ ) { $c[$d] = $a[$d]->name; } return $c; } } function rest_post_gmeta() { global $post; $a[0] = get_thumbnail_url($post->ID); $a[1] = downlist_array(); $a[2] = get_the_category()[0]->cat_name; $a[3] = get_the_category()[0]->count; $a[4] = list_the_tags(); $a[5] = get_the_author(); return $a; } /* * 第二部分,前台 */ //1.1 获取文章内图片 function get_all_img($content){ $pattern = '/<img[^>]*src=\"([^\"]+)\"[^>]*\/?>/si'; $matches = array(); $out = ''; if (preg_match_all($pattern, $content, $matches)) { if (count($matches[1]) == 1) { return '<div class="carousel-item active"><img class="d-block w-100" src="' . $matches[1][0] . '" alt="1"></div>'; } else { $out1 = '<div class="carousel-item active"><img class="d-block w-100" src="' . $matches[1][0] . '" alt="1"></div>'; for ($i = 1; $i < count($matches[1]); $i++) { $out .= '<div class="carousel-item"><img class="d-block w-100" src="' . $matches[1][$i] . '" alt="'.($i+1).'"></div>'; } return $out1.$out; } } else { return ""; } } add_action( 'after_setup_theme', 'default_attachment_display_settings' ); function default_attachment_display_settings() { update_option( 'image_default_align', 'center' ); update_option( 'image_default_link_type', 'none' ); update_option( 'image_default_size', 'full' ); }
Gamuxorg/bbs
website-source/functions.php
PHP
gpl-3.0
7,746
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sarfDic.Midleware.Noun.trilateral; /** * * @author Gowzancha */ import sarf.noun.*; import sarf.verb.trilateral.unaugmented.*; import java.util.*; import sarf.*; import sarf.noun.trilateral.unaugmented.timeandplace.*; /** * <p>Title: Sarf Program</p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: ALEXO</p> * * @author Haytham Mohtasseb Billah * @version 1.0 */ public class TimeAndPlaceConjugator implements IUnaugmentedTrilateralNounConjugator{ private Map formulaClassNamesMap = new HashMap(); //map <symbol,formulaName> private Map formulaSymbolsNamesMap = new HashMap(); private TimeAndPlaceConjugator() { for (int i=1; i<=3;i++) { String formulaClassName = /*getClass().getPackage().getName()*/"sarf.noun.trilateral.unaugmented.timeandplace"+".nonstandard.NounFormula"+i; try { Class formulaClass = Class.forName(formulaClassName); NonStandardTimeAndPlaceNounFormula nounFormula = (NonStandardTimeAndPlaceNounFormula) formulaClass.newInstance(); formulaClassNamesMap.put(nounFormula.getFormulaName(), formulaClass); formulaSymbolsNamesMap.put(nounFormula.getSymbol(), nounFormula.getFormulaName()); } catch (Exception ex) { ex.printStackTrace(); } } } private static TimeAndPlaceConjugator instance = new TimeAndPlaceConjugator(); public static TimeAndPlaceConjugator getInstance() { return instance; } public NounFormula createNoun(UnaugmentedTrilateralRoot root, int suffixNo, String formulaName) { Object [] parameters = {root, suffixNo+""}; try { Class formulaClass = (Class) formulaClassNamesMap.get(formulaName); NounFormula noun = (NounFormula) formulaClass.getConstructors()[0].newInstance(parameters); return noun; } catch (Exception ex) { ex.printStackTrace(); } return null; } public List createNounList(UnaugmentedTrilateralRoot root, String formulaName) { List result = new LinkedList(); for (int i = 0; i < 18; i++) { NounFormula noun = createNoun(root, i, formulaName); result.add(noun); } return result; } /** * إعادة الصيغ الممكنة للجذر * @param root UnaugmentedTrilateralRoot * @return List */ public List getAppliedFormulaList(UnaugmentedTrilateralRoot root) { XmlTimeAndPlaceNounFormulaTree formulaTree = sarfDic.Midleware.DatabaseManager.getInstance().getTimeAndPlaceNounFormulaTree(root.getC1()); if (formulaTree == null) return null; List result = new LinkedList(); Iterator iter = formulaTree.getFormulaList().iterator(); while (iter.hasNext()) { XmlTimeAndPlaceNounFormula formula = (XmlTimeAndPlaceNounFormula) iter.next(); if (formula.getNoc().equals(root.getConjugation()) && formula.getC2() == root.getC2() && formula.getC3() == root.getC3()) { if (formula.getForm1() != null && formula.getForm1() != "") //add the formula pattern insteaed of the symbol (form1) result.add(formulaSymbolsNamesMap.get(formula.getForm1())); //may the verb has two forms of instumentals if (formula.getForm2() != null && formula.getForm2() != "") //add the formula pattern insteaed of the symbol (form2) result.add(formulaSymbolsNamesMap.get(formula.getForm2())); } } return result; } }
oghalawinji/InteractiveArabicDictionary
IAD/src/java/sarfDic/Midleware/Noun/trilateral/TimeAndPlaceConjugator.java
Java
gpl-3.0
3,831
/* photo_prev: Application to assist in sorting through photographs. Copyright (C) 2008 Jeremiah LaRocco This file is part of photo_prev. photo_prev is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. photo_prev is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with photo_prev. If not, see <http://www.gnu.org/licenses/>. */ #include <QtGui> #include "photopreviewdlg.h" PhotoPreviewDlg::PhotoPreviewDlg(QWidget *parent) : QDialog(parent) { ftw = false; buildImageList(QDir::currentPath()); setWindowTitle(tr("Photo Previewer")); // Setup GUI here... QVBoxLayout *theLayout = new QVBoxLayout; QHBoxLayout *input_layout = new QHBoxLayout; QHBoxLayout *accept_layout = new QHBoxLayout; QHBoxLayout *reject_layout = new QHBoxLayout; QHBoxLayout *fname_layout = new QHBoxLayout; QHBoxLayout *ar_buttons_layout = new QHBoxLayout; QHBoxLayout *zoom_layout = new QHBoxLayout; QHBoxLayout *extensions_layout = new QHBoxLayout; QCompleter *input_completer = new QCompleter(this); input_completer->setCompletionMode(QCompleter::InlineCompletion); QDirModel *indm = new QDirModel(input_completer); indm->index(QDir::currentPath()); indm->setFilter(QDir::AllDirs | QDir::Dirs | QDir::NoDotAndDotDot | QDir::CaseSensitive); input_completer->setModel(indm); input_completer->setCompletionPrefix(QDir::currentPath()); input_dir_lbl = new QLabel(tr("Accept directory")); input_dir_tb = new QLineEdit(QDir::currentPath()); input_dir_tb->setCompleter(input_completer); input_dir_choose = new QPushButton(QIcon(":/icons/fileopen.png"),""); input_layout->addWidget(input_dir_lbl); input_layout->addWidget(input_dir_tb); input_layout->addWidget(input_dir_choose); QCompleter *accept_completer = new QCompleter(this); accept_completer->setCompletionMode(QCompleter::InlineCompletion); QDirModel *accdm = new QDirModel(accept_completer); accdm->index(QDir::currentPath()); accdm->setFilter(QDir::AllDirs | QDir::Dirs | QDir::NoDotAndDotDot | QDir::CaseSensitive); accept_completer->setModel(accdm); accept_completer->setCompletionPrefix(QDir::currentPath()+tr("/accept")); QCompleter *reject_completer = new QCompleter(this); reject_completer->setCompletionMode(QCompleter::InlineCompletion); QDirModel *outdm = new QDirModel(accept_completer); outdm->index(QDir::currentPath()); outdm->setFilter(QDir::AllDirs | QDir::Dirs | QDir::NoDotAndDotDot | QDir::CaseSensitive); reject_completer->setModel(outdm); reject_completer->setCompletionPrefix(QDir::currentPath()+tr("/reject")); accept_dir_lbl = new QLabel(tr("Accept directory")); accept_dir_tb = new QLineEdit(QDir::currentPath() + tr("/accept")); accept_dir_tb->setCompleter(accept_completer); accept_dir_choose = new QPushButton(QIcon(":/icons/fileopen.png"),""); accept_layout->addWidget(accept_dir_lbl); accept_layout->addWidget(accept_dir_tb); accept_layout->addWidget(accept_dir_choose); reject_dir_lbl = new QLabel(tr("Reject directory")); reject_dir_tb = new QLineEdit(QDir::currentPath() + tr("/reject")); reject_dir_tb->setCompleter(reject_completer); reject_dir_choose = new QPushButton(QIcon(":/icons/fileopen.png"),""); reject_layout->addWidget(reject_dir_lbl); reject_layout->addWidget(reject_dir_tb); reject_layout->addWidget(reject_dir_choose); fname_lbl_lbl = new QLabel(tr("File name: ")); fname_lbl = new QLabel(tr("")); fname_layout->addWidget(fname_lbl_lbl); fname_layout->addWidget(fname_lbl); accept_image = new QPushButton(tr("Accept")); reject_image = new QPushButton(tr("Reject")); skip_image = new QPushButton(tr("Skip")); ar_buttons_layout->addWidget(accept_image); ar_buttons_layout->addWidget(reject_image); ar_buttons_layout->addWidget(skip_image); fit_to_window = new QPushButton(tr("Fit To Window")); normal_size = new QPushButton(tr("Actual Size")); zoom_lbl = new QLabel(tr("Zoom: 100%")); zoom_layout->addWidget(fit_to_window); zoom_layout->addWidget(normal_size); zoom_layout->addWidget(zoom_lbl); extensions_lbl = new QLabel(tr("Extensions to move")); extensions_tb = new QLineEdit(tr(".jpg,.JPG,.cr2,.CR2")); extensions_layout->addWidget(extensions_lbl); extensions_layout->addWidget(extensions_tb); img_lbl = new QLabel; if (files.size()>0) { updatePreview(); } img_scroller = new QScrollArea; img_scroller->setBackgroundRole(QPalette::Dark); img_scroller->setWidget(img_lbl); theLayout->addLayout(input_layout); theLayout->addLayout(accept_layout); theLayout->addLayout(reject_layout); theLayout->addLayout(fname_layout); theLayout->addWidget(img_scroller); theLayout->addLayout(ar_buttons_layout); theLayout->addLayout(zoom_layout); theLayout->addLayout(extensions_layout); setLayout(theLayout); setupConnections(); update_extension_list(); } void PhotoPreviewDlg::setupConnections() { connect(input_dir_choose, SIGNAL(clicked()), this, SLOT(chooseInputDir())); connect(accept_dir_choose, SIGNAL(clicked()), this, SLOT(chooseAcceptDir())); connect(reject_dir_choose, SIGNAL(clicked()), this, SLOT(chooseRejectDir())); connect(accept_image, SIGNAL(clicked()), this, SLOT(accept_button())); connect(reject_image, SIGNAL(clicked()), this, SLOT(reject_button())); connect(skip_image, SIGNAL(clicked()), this, SLOT(skip_button())); connect(fit_to_window, SIGNAL(clicked()), this, SLOT(ftw_button())); connect(normal_size, SIGNAL(clicked()), this, SLOT(actual_size_button())); connect(extensions_tb, SIGNAL(textChanged(const QString &)), this, SLOT(update_extension_list())); connect(input_dir_tb, SIGNAL(editingFinished()), this, SLOT(inputDirChange())); } void PhotoPreviewDlg::criticalErr(QString errMsg) { QMessageBox::critical(this, tr("Error"), errMsg, QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void PhotoPreviewDlg::chooseInputDir() { QString fileName = QFileDialog::getExistingDirectory(this, tr("Choose an input directory"), input_dir_tb->text()); if (fileName == tr("")) { return; } input_dir_tb->setText(fileName); buildImageList(fileName); curIdx = 0; updatePreview(); } void PhotoPreviewDlg::inputDirChange() { if (input_dir_tb->text() == tr("")) { return; } if (QDir(input_dir_tb->text()).exists()) { buildImageList(input_dir_tb->text()); curIdx = 0; updatePreview(); } } void PhotoPreviewDlg::chooseAcceptDir() { QString fileName = QFileDialog::getExistingDirectory(this, tr("Choose a directory"), accept_dir_tb->text()); if (fileName == tr("")) { return; } accept_dir_tb->setText(fileName); } void PhotoPreviewDlg::chooseRejectDir() { QString fileName = QFileDialog::getExistingDirectory(this, tr("Choose a directory"), reject_dir_tb->text()); if (fileName == tr("")) { return; } reject_dir_tb->setText(fileName); } void PhotoPreviewDlg::buildImageList(QString where) { QDir imgDir(where); QStringList filters; filters += "*.jpg"; files = imgDir.entryList(filters, QDir::Files, QDir::IgnoreCase | QDir::Name); curIdx = 0; } void PhotoPreviewDlg::accept_button() { if (curIdx >= files.size()) { return; } QDir id(input_dir_tb->text()); QDir od(accept_dir_tb->text()); foreach (QString ext, extensions) { QString fn = files[curIdx]; int extIdx = fn.lastIndexOf(tr(".jpg"), -1, Qt::CaseInsensitive); fn.replace(extIdx, 4, ext); QFile tf(id.filePath(fn)); if (tf.exists()) { tf.rename(od.filePath(fn)); } } files.erase(files.begin()); updatePreview(); } void PhotoPreviewDlg::reject_button() { if (curIdx >= files.size()) { return; } QDir id(input_dir_tb->text()); QDir od(reject_dir_tb->text()); foreach (QString ext, extensions) { QString fn = files[curIdx]; int extIdx = fn.lastIndexOf(tr(".jpg"), -1, Qt::CaseInsensitive); fn.replace(extIdx, 4, ext); QFile tf(id.filePath(fn)); if (tf.exists()) { tf.rename(od.filePath(fn)); } } files.erase(files.begin()); updatePreview(); } void PhotoPreviewDlg::skip_button() { if (curIdx < files.size()-1) { ++curIdx; updatePreview(); return; } curIdx = 0; updatePreview(); } void PhotoPreviewDlg::ftw_button() { ftw = true; updatePreview(); } void PhotoPreviewDlg::actual_size_button() { ftw = false; updatePreview(); } void PhotoPreviewDlg::update_extension_list() { QStringList exts = extensions_tb->text().split(","); if (exts.size()>0) { extensions.clear(); QStringList::const_iterator iter; for (iter = exts.constBegin(); iter != exts.end(); ++iter) { extensions += *iter; } } } void PhotoPreviewDlg::updatePreview() { if (curIdx >= files.size()) { img_lbl->setPixmap(QPixmap()); img_lbl->setText(tr("None")); fname_lbl->setText(tr("No files!")); return; } QDir id(input_dir_tb->text()); QString infn = id.filePath(files[curIdx]); if (!curImage.load(infn)) { fname_lbl->setText(tr("Error!!")); img_lbl->setText(tr("Error!!")); criticalErr(tr("Error creating preview image for: ") + infn); return; } img_lbl->setText(tr("")); fname_lbl->setText(infn); if (ftw) { curImage = curImage.scaled( img_scroller->width()-4, img_scroller->height()-4, Qt::KeepAspectRatio, Qt::SmoothTransformation); } img_lbl->setPixmap(QPixmap::fromImage(curImage)); img_lbl->resize(curImage.size()); }
jl2/PhotoPreviewer
photopreviewdlg.cpp
C++
gpl-3.0
10,042
/* * @lc app=leetcode id=33 lang=csharp * * [33] Search in Rotated Sorted Array */ public class Solution { public int Search(int[] nums, int target) { int left = 0, right = nums.Length - 1; while (left <= right - 2) { int mid = (left + right) / 2; if (target >= nums[mid]) { if (nums[left] > nums[mid] && nums[left] <= target) { right = mid; } else { left = mid; } } else { if (nums[right] < nums[mid] && nums[right] >= target) { left = mid; } else { right = mid; } } } while (left <= right) { if (nums[left] == target) { return left; } ++left; } return -1; } }
yamstudio/leetcode
csharp/33.search-in-rotated-sorted-array.cs
C#
gpl-3.0
899
/****************************************************************************** * Copyright (c) 2015 by * * Andreas Stockmayer <stockmay@f0o.bar> and * * Mark Schmidt <schmidtm@f0o.bar> * * * * This file (MapRegister.java) is part of jlisp. * * * * jlisp is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * jlisp is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with $project.name.If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ package bar.f0o.jlisp.lib.ControlPlane; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * Map Register * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |Type=3 |P| Reserved |M| Record Count | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Nonce . . . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . . . Nonce | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Key ID | Authentication Data Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ~ Authentication Data ~ * +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | Record TTL | * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * R | Loc Count | EID mask-len | ACT |A| Reserved | * e +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * c | Rsvd | Map-Version Number | EID-Prefix-AFI | * o +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * r | EID-Prefix | * d +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | /| Priority | Weight | M Priority | M Weight | * | L +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | o | Unused Flags |L|p|R| Loc-AFI | * | c +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | \| Loc | * +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ /** * Map Register as defined in RFC6830 * */ public class MapRegister extends ControlMessage { /** * HMAC for the key used in the Map Register message * */ public enum HmacType { NONE(0), HMAC_SHA_1_96(1), HMAC_SHA_256_128(2); private final int val; private HmacType(int x) { this.val = x; } public int getVal() { return val; } /** * Hmac create from int * @param x type of HMAC, 0 = NONE, 1 = SHA1_96, 2 = SHA_256_128 * @return */ public static HmacType fromInt(int x) { switch (x) { case 0: return NONE; case 1: return HMAC_SHA_1_96; case 2: return HMAC_SHA_256_128; } return null; } /** * * @return length of the HMAC */ public short getLength() { switch(val){ case 1: return (short)20; case 2: return (short)24;//??? } return 0; } } /** * P: Proxy Map Reply bit: if 1 etr sends map register requesting the map server to proxy a map reply. * M: Want map notify bit: if 1 ETR wants a map notify as response to this * Record Count: Number of records in this message * Nonce 64 bit (not currently used) * Key ID: Type of key (0 none, 1 HMAC-SHA-1-96, 2 HMAC-SHA-256-128) * AuthenticationDataLength length in octets of the Authentication Data * AuthenticationData: the key */ private boolean pFlag, mFlag; private byte recordCount; private long nonce; private HmacType keyId; private short authenticationDataLength; private byte[] authenticationData; private ArrayList<Record> records = new ArrayList<>(); /** * * @param stream Byte stream containing the Map Register message * @throws IOException */ public MapRegister(DataInputStream stream) throws IOException { this(stream,stream.readByte()); } /** * * @param stream Byte Stream to create the Map Register Message, missing the first byte * @param version the missing first byte * @throws IOException */ public MapRegister(DataInputStream stream, byte version) throws IOException { this.type = 3; byte flag = version; this.pFlag = (flag & 8) != 0; short reserved = stream.readShort(); this.mFlag = (reserved & 1) != 0; this.recordCount = stream.readByte(); this.nonce = stream.readLong(); short key = stream.readShort(); this.keyId = HmacType.fromInt(key); this.authenticationDataLength = stream.readShort(); this.authenticationData = new byte[authenticationDataLength]; stream.read(authenticationData); for (int i = 0; i < recordCount; i++) this.records.add(new Record(stream)); } /** * * @param pFlag Proxy Map Reply flag * @param mFlag Map Notify Bit * @param nonce 64bit Nonce * @param keyId Type of Hmac as defined in MapRegister.HMAC * @param authenticationData Key encoded with corresponding HMAC * @param records Records to register */ public MapRegister(boolean pFlag, boolean mFlag, long nonce, HmacType keyId, byte[] authenticationData, ArrayList<Record> records) { this.pFlag = pFlag; this.mFlag = mFlag; this.recordCount = (byte) records.size(); this.nonce = nonce; this.keyId = keyId; this.records = records; if(keyId != HmacType.NONE){ this.authenticationDataLength = keyId.getLength(); this.authenticationData = new byte[authenticationDataLength]; byte[] toAuthenticate = toByteArray(); String hmac; if(keyId == HmacType.HMAC_SHA_1_96) hmac="HmacSha1"; else hmac="HmacSha256"; SecretKeySpec key = new SecretKeySpec(authenticationData, hmac); try { Mac mac = Mac.getInstance(hmac); mac.init(key); this.authenticationData = mac.doFinal(toAuthenticate); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } } else{ this.authenticationData = authenticationData; this.authenticationDataLength = (short) authenticationData.length; } } public byte[] toByteArray() { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream stream = new DataOutputStream(byteStream); try { byte typeFlagTmp = 48; if (this.pFlag) typeFlagTmp |= 8; stream.writeByte(typeFlagTmp); short reserved = (short) (this.mFlag ? 1 : 0); stream.writeShort(reserved); stream.writeByte(this.recordCount); stream.writeLong(this.nonce); stream.writeShort(this.keyId.getVal()); stream.writeShort(this.authenticationDataLength); stream.write(this.authenticationData); for (Record r : this.records) stream.write(r.toByteArray()); } catch (IOException e) { e.printStackTrace(); } return byteStream.toByteArray(); } /** * * @return Proxy Map Reply bit */ public boolean ispFlag() { return pFlag; } /** * * @return Wants Map notify flag */ public boolean ismFlag() { return mFlag; } /** * * @return Number of records in the Map register */ public byte getRecordCount() { return recordCount; } /** * * @return 64bit Nonce */ public long getNonce() { return nonce; } /** * * @return Type of the HMAC as defined in MapRegister.HMAC */ public HmacType getKeyId() { return keyId; } /** * * @return Length of the authenticationData in octets */ public short getAuthenticationDataLength() { return authenticationDataLength; } /** * * @return Raw authentification data */ public byte[] getAuthenticationData() { return authenticationData; } /** * * @return Records included in the Map Register */ public ArrayList<Record> getRecords() { return records; } }
jLisp/jlisp
src/bar/f0o/jlisp/lib/ControlPlane/MapRegister.java
Java
gpl-3.0
10,354
package band.full.test.video.encoder; import static band.full.core.Resolution.STD_1080p; import static band.full.core.Resolution.STD_2160p; import static band.full.core.Resolution.STD_720p; import static band.full.video.buffer.Framerate.FPS_23_976; import static band.full.video.itu.BT2020.BT2020_10bit; import static band.full.video.itu.BT709.BT709_8bit; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.empty; import static java.util.Optional.ofNullable; import band.full.core.Resolution; import band.full.video.buffer.Framerate; import band.full.video.itu.BT2100; import band.full.video.itu.ColorMatrix; import java.util.List; import java.util.Optional; public class EncoderParameters { public static final String MASTER_DISPLAY_PRIMARIES = "G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)"; public static final String MASTER_DISPLAY = MASTER_DISPLAY_PRIMARIES + "L(10000000,5)"; public static final EncoderParameters HD_MAIN = new EncoderParameters( STD_720p, BT709_8bit, FPS_23_976); public static final EncoderParameters FULLHD_MAIN8 = new EncoderParameters( STD_1080p, BT709_8bit, FPS_23_976); public static final EncoderParameters UHD4K_MAIN8 = new EncoderParameters( STD_2160p, BT709_8bit, FPS_23_976); public static final EncoderParameters UHD4K_MAIN10 = new EncoderParameters( STD_2160p, BT2020_10bit, FPS_23_976); public static final EncoderParameters HLG10 = new EncoderParameters( STD_2160p, BT2100.HLG10, FPS_23_976); public static final EncoderParameters HLG10ITP = new EncoderParameters( STD_2160p, BT2100.HLG10ITP, FPS_23_976); public static final EncoderParameters HDR10 = new EncoderParameters( STD_2160p, BT2100.PQ10, FPS_23_976) .withMasterDisplay(MASTER_DISPLAY); public static final EncoderParameters HDR10FR = new EncoderParameters( STD_2160p, BT2100.PQ10FR, FPS_23_976) .withMasterDisplay(MASTER_DISPLAY); public static final EncoderParameters HDR10ITP = new EncoderParameters( STD_2160p, BT2100.PQ10ITP, FPS_23_976) .withMasterDisplay(MASTER_DISPLAY); public final Resolution resolution; public final ColorMatrix matrix; public final Framerate framerate; public final Optional<String> masterDisplay; // HEVC HDR only public final List<String> encoderOptions; public EncoderParameters(Resolution resolution, ColorMatrix matrix, Framerate framerate) { this(resolution, matrix, framerate, empty(), emptyList()); } private EncoderParameters(Resolution resolution, ColorMatrix matrix, Framerate framerate, Optional<String> masterDisplay, List<String> encoderOptions) { this.resolution = resolution; this.matrix = matrix; this.framerate = framerate; this.masterDisplay = masterDisplay; this.encoderOptions = encoderOptions; } public EncoderParameters withFramerate(Framerate framerate) { return new EncoderParameters(resolution, matrix, framerate, masterDisplay, encoderOptions); } public EncoderParameters withMasterDisplay(String masterDisplay) { return new EncoderParameters(resolution, matrix, framerate, ofNullable(masterDisplay), encoderOptions); } public EncoderParameters withEncoderOptions(String... options) { return withEncoderOptions(asList(options)); } public EncoderParameters withEncoderOptions(List<String> options) { return new EncoderParameters(resolution, matrix, framerate, masterDisplay, options); } }
testing-av/testing-video
generators/src/main/java/band/full/test/video/encoder/EncoderParameters.java
Java
gpl-3.0
3,811
import { Meteor } from 'meteor/meteor'; import '../images.js'; import { Devs } from '../../devs/devs.js'; import { Teams } from '../../teams/teams.js'; import { Visitors } from '../../visitors/visitors.js'; import { Sponsors } from '../../sponsors/sponsors.js'; Meteor.publish('profile.image', function(id){ let d = Devs.findOne({"user":id}); //console.log(Images.findOne({"_id":d.picture})); return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('profile.image.user', function(username){ let u = Meteor.users.findOne({"username":username}); let d = Devs.findOne({"user":u._id}); return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('profile.image.team', function(id){ let t = Teams.findOne({'_id':id}); if ( t !== undefined ) { let list = []; let c = Devs.findOne({"user":t.captain}); list.push(c.picture); t.members.forEach(function(m){ let d = Devs.findOne({"user":m}); if ( d.picture != undefined ) list.push(d.picture); }); return Images.find({'_id':{ $in : list }}).cursor; } }); Meteor.publish('visitor.image', function(){ let d = Visitors.findOne({"user":this.userId}); if ( d !== undefined ) return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('sponsors.members.image', function(name){ let s = Sponsors.findOne({'short':name}); if ( s !== undefined ) { let list = []; s.members.forEach(function(m){ let v = Visitors.findOne({"user":m}); if ( v.picture !== undefined ) list.push(v.picture); }); return Images.find({'_id':{ $in : list }}).cursor; } }); Meteor.publish('sponsors.single.image', function(name){ let s = Sponsors.findOne({"short":name}); if ( s !== undefined ) return Images.find({"_id":s.picture}).cursor; }); Meteor.publish('sponsor.image', function(){ let v = Visitors.findOne({"user":this.userId}); if ( v !== undefined ) { let s = Sponsors.findOne({"short":v.company}); if ( s !== undefined ) return Images.find({"_id":s.picture}).cursor; } }); Meteor.publish('alldevs.image', function(){ let d = Devs.find({"picture":{"$exists":true}}); if ( d !== undefined ) { //console.log(d); let list = []; d.forEach(function(m){ list.push(m.picture); }); return Images.find({'_id':{ $in : list }}).cursor; //return Images.find({}).cursor; } }); //Admin Use Meteor.publish('files.images.all', function () { return Images.find().cursor; });
NEETIIST/BreakingDev17
imports/api/images/server/publications.js
JavaScript
gpl-3.0
2,393
<?php // Some settings $msg = ""; $username = "demo"; $password = "asdf"; // Change the password to something suitable if (!$password) $msg = 'You must set a password in the file "login_session_auth.php" inorder to login using this page or reconfigure it the authenticator config options to fit your needs. Consult the <a href="http://wiki.moxiecode.com/index.php/Main_Page" target="_blank">Wiki</a> for more details.'; if (isset($_POST['submit_button'])) { // If password match, then set login if ($_POST['login'] == $username && $_POST['password'] == $password && $password) { // Set session session_start(); $_SESSION['isLoggedIn'] = true; $_SESSION['user'] = $_POST['login']; // Override any config option //$_SESSION['imagemanager.filesystem.rootpath'] = 'some path'; //$_SESSION['filemanager.filesystem.rootpath'] = 'some path'; // Redirect header("location: " . $_POST['return_url']); die; } else $msg = "Wrong username/password."; } ?> <html> <head> <title>Sample login page</title> <style> body { font-family: Arial, Verdana; font-size: 11px; } fieldset { display: block; width: 170px; } legend { font-weight: bold; } label { display: block; } div { margin-bottom: 10px; } div.last { margin: 0; } div.container { position: absolute; top: 50%; left: 50%; margin: -100px 0 0 -85px; } h1 { font-size: 14px; } .button { border: 1px solid gray; font-family: Arial, Verdana; font-size: 11px; } .error { color: red; margin: 0; margin-top: 10px; } </style> </head> <body> <div class="container"> <form action="login_session_auth.php" method="post"> <input type="hidden" name="return_url" value="<?php echo isset($_REQUEST['return_url']) ? htmlentities($_REQUEST['return_url']) : ""; ?>" /> <fieldset> <legend>Example login</legend> <div> <label>Username:</label> <input type="text" name="login" class="text" value="<?php echo isset($_POST['login']) ? htmlentities($_POST['login']) : ""; ?>" /> </div> <div> <label>Password:</label> <input type="password" name="password" class="text" value="<?php echo isset($_POST['password']) ? htmlentities($_POST['password']) : ""; ?>" /> </div> <div class="last"> <input type="submit" name="submit_button" value="Login" class="button" /> </div> <?php if ($msg) { ?> <div class="error"> <?php echo $msg; ?> </div> <?php } ?> </fieldset> </form> </div> </body> </html>
sean9999/Gourd-Application-Framework
domains/core/web/lib/imagemanager/login_session_auth.php
PHP
gpl-3.0
2,504
#!/usr/bin/env ../jazzshell """ Perform song identification by loading up a corpus of harmonic analyses and comparing parse results to all of them, according to some distance metric. """ """ ============================== License ======================================== Copyright (C) 2008, 2010-12 University of Edinburgh, Mark Granroth-Wilding This file is part of The Jazz Parser. The Jazz Parser is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Jazz Parser is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with The Jazz Parser. If not, see <http://www.gnu.org/licenses/>. ============================ End license ====================================== """ __author__ = "Mark Granroth-Wilding <mark.granroth-wilding@ed.ac.uk>" import sys from optparse import OptionParser from jazzparser.data.parsing import ParseResults from jazzparser.parsers.cky.parser import DirectedCkyParser from jazzparser.utils.options import options_help_text, ModuleOption from jazzparser.data.tonalspace import TonalSpaceAnalysisSet from jazzparser.formalisms.music_halfspan import Formalism from jazzparser.utils.tableprint import pprint_table def main(): usage = "%prog [options] <song-set> <results-file0> [<results-file1> ...]" parser = OptionParser(usage=usage) parser.add_option("--popt", "--parser-options", dest="popts", action="append", help="specify options for the parser that interprets the gold standard annotations. Type '--popt help' to get a list of options (we use a DirectedCkyParser)") parser.add_option("-m", "--metric", dest="metric", action="store", help="semantics distance metric to use. Use '-m help' for a list of available metrics") parser.add_option("--mopt", "--metric-options", dest="mopts", action="append", help="options to pass to the semantics metric. Use with '--mopt help' with -m to see available options") parser.add_option("-r", "--print-results", dest="print_results", action="store", default=5, type="int", help="number of top search results to print for each query (parse result). Default: 5. Use -1 to print distances from all songs in the corpus") parser.add_option("-g", "--gold-only", dest="gold_only", action="store_true", help="skip results that have no gold standard sequence associated with them (we can't tell which is the right answer for these)") parser.add_option("--mc", "--metric-computation", dest="metric_computation", action="store_true", help="output the computation information for the metric between the parse result and each top search result") options, arguments = parser.parse_args() # For now, we always use the music_halfspan formalism with this script # If we wanted to make it generic, we'd just load the formalism according # to a command-line option formalism = Formalism # Process parser options if options.popts is not None: poptstr = options.popts if "help" in [s.strip().lower() for s in poptstr]: # Output this parser's option help print options_help_text(DirectedCkyParser.PARSER_OPTIONS, intro="Available options for gold standard interpreter") sys.exit(0) poptstr = ":".join(poptstr) else: poptstr = "" popts = ModuleOption.process_option_string(poptstr) # Check that the options are valid try: DirectedCkyParser.check_options(popts) except ModuleOptionError, err: logger.error("Problem with parser options (--popt): %s" % err) sys.exit(1) # Get a distance metric # Just check this, as it'll cause problems if len(formalism.semantics_distance_metrics) == 0: print "ERROR: the formalism defines no distance metrics, so this "\ "script won't work" sys.exit(1) # First get the metric if options.metric == "help": # Print out a list of metrics available print "Available distance metrics:" print ", ".join([metric.name for metric in \ formalism.semantics_distance_metrics]) sys.exit(0) if options.metric is None: # Use the first in the list as default metric_cls = formalism.semantics_distance_metrics[0] else: for m in formalism.semantics_distance_metrics: if m.name == options.metric: metric_cls = m break else: # No metric found matching this name print "No metric '%s'" % options.metric sys.exit(1) print >>sys.stderr, "Using distance metric: %s" % metric_cls.name # Now process the metric options if options.mopts is not None: moptstr = options.mopts if "help" in [s.strip().lower() for s in moptstr]: # Output this parser's option help print options_help_text(metric_cls.OPTIONS, intro="Available options for metric '%s'" % metric_cls.name) sys.exit(0) moptstr = ":".join(moptstr) else: moptstr = "" mopts = ModuleOption.process_option_string(moptstr) # Instantiate the metric with these options metric = metric_cls(options=mopts) if len(arguments) < 2: print >>sys.stderr, "Specify a song corpus name and one or more files to read results from" sys.exit(1) # First argument is an TonalSpaceAnalysisSet corpus_name = arguments[0] # Load the corpus file corpus = TonalSpaceAnalysisSet.load(corpus_name) # The rest of the args are result files to analyze res_files = arguments[1:] # Work out how many results to print out if options.print_results == -1: print_up_to = None else: print_up_to = options.print_results ranks = [] num_ranked = 0 for filename in res_files: # Load the parse results pres = ParseResults.from_file(filename) if options.gold_only and pres.gold_sequence is None: # Skip this sequence altogether if requested continue print "######################" print "Read %s" % filename # Try to get a correct answer from the PR file if pres.gold_sequence is None: print "No correct answer specified in input file" correct_song = None else: # Process the name of the sequence in the same way that # TonalSpaceAnalysisSet does # Ideally, they should make a common function call, but let's be # bad for once correct_song = pres.gold_sequence.string_name.lower() print "Correct answer: %s" % correct_song # Could have an empty result list: skip if it does if len(pres.semantics) == 0: print "No results" # Failed to get any result: if this is one of the sequences that # is in the corpus, count it as a 0 result. Otherwise, skip: # we wouldn't have counted it anyway num_ranked += 1 ranks.append(None) continue result = pres.semantics[0][1] # Compare to each of the songs distances = [] for name,songsem in corpus: # Get the distance from this song dist = metric.distance(result, songsem) distances.append((name,dist,songsem)) # Sort them to get the closest first distances.sort(key=lambda x:x[1]) print # Print out the top results, as many as requested top_results = distances[:print_up_to] table = [["","Song","Distance"]] + [ ["*" if res[0] == correct_song else "", "%s" % res[0], "%.2f" % res[1]] for res in top_results] pprint_table(sys.stdout, table, default_just=True) print if correct_song is not None: # Look for the correct answer in the results for rank,(name,distance,__) in enumerate(distances): # Match up the song name to the correct one if name == correct_song: correct_rank = rank break else: # The song name was not found in the corpus at all correct_rank = None if correct_rank is None: print "Song was not found in corpus" else: print "Correct answer got rank %d" % correct_rank # Record the ranks so we can compute the MRR ranks.append(correct_rank+1) num_ranked += 1 print if options.metric_computation: print "Explanation of top result:" print metric.print_computation(result, distances[0][2]) print if num_ranked: print "\nGot ranks for %d sequences" % num_ranked # Compute the mean reciprocal rank, the reciprocal of the harmonic mean # of the ranks of the correct answers mrr = sum([0.0 if rank is None else 1.0/rank for rank in ranks], 0.0) \ / len(ranks) print "Mean reciprocal rank: %f" % mrr if mrr > 0.0: hmr = 1.0/mrr print "Harmonic mean rank: %f" % hmr succ_ranks = [rank for rank in ranks if rank is not None] print "\nIncluding only successful parses (%d):" % len(succ_ranks) mrr_succ = sum([1.0/rank for rank in succ_ranks], 0.0) / len(succ_ranks) print "Mean reciprocal rank: %f" % mrr_succ if mrr_succ > 0.0: hmr_succ = 1.0/mrr_succ print "Harmonic mean rank: %f" % hmr_succ else: print "\nNo results to analyze" if __name__ == "__main__": main()
markgw/jazzparser
bin/analysis/findsong.py
Python
gpl-3.0
10,264
package magic.ui.widget; import java.awt.Dimension; import java.util.List; import javax.swing.JButton; import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; @SuppressWarnings("serial") public class ActionButtonTitleBar extends TitleBar { private final JPanel actionsPanel = new JPanel(); public ActionButtonTitleBar(String caption, List<JButton> actionButtons) { super(caption); setPreferredSize(new Dimension(getPreferredSize().width, 26)); setPreferredSize(getPreferredSize()); actionsPanel.setOpaque(false); actionsPanel.setLayout(new MigLayout("insets 0, gap 12", "", "grow, fill")); for (JButton btn : actionButtons) { actionsPanel.add(btn, "w 16!, h 16!"); } add(actionsPanel, "alignx right, hidemode 3"); } public void setActionsVisible(boolean b) { actionsPanel.setVisible(b); } }
magarena/magarena
src/magic/ui/widget/ActionButtonTitleBar.java
Java
gpl-3.0
919
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace HashGenerator.core.hashing { internal sealed class hgMD5 : hgHashAlgorithm { public String ComputeHash(String filename) { using (MD5 md5 = MD5.Create()) { using (FileStream stream = File.OpenRead(filename)) { return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); } } } } }
maldevel/HashGenerator
src/HashGenerator/core/hashing/hgMD5.cs
C#
gpl-3.0
624
#include "buttonpress.h" #include <iostream> void button::shutdown() { std::cout << "Shutdown" << std::endl; } void button::pause48h() { std::cout << "Pause" << std::endl; } void button::masterButton() { std::cout << "Master" << std::endl; } void button::button1Pressed() { std::cout << "Button 1" << std::endl; } void button::button2Pressed() { std::cout << "Button 2" << std::endl; }
stadtmueller/pihoco
src/buttonpress.cpp
C++
gpl-3.0
411
#include "animation_manager.hpp" using namespace engine; AnimationManager AnimationManager::instance; void AnimationManager::add_animation_quad(AnimationQuad* newQuad){ animationQuads.push_back(newQuad); } void AnimationManager::add_collider(SDL_Rect* newQuad){ colliderRects.push_back(newQuad); } void AnimationManager::clearAnimationQuads(){ animationQuads.clear(); } void AnimationManager::draw_quads(){ //ORDER QUADS BY Y; std::sort(animationQuads.begin(), animationQuads.end(),[](const AnimationQuad* lhs, const AnimationQuad* rhs){ return lhs->y < rhs->y; }); for(AnimationQuad * quad : animationQuads) { SDL_RenderCopy(WindowManager::getGameCanvas(), quad->getTexture(), quad->getClipRect(), quad->getRenderQuad()); } draw_colliders(); clearAnimationQuads(); } void AnimationManager::draw_colliders(){ SDL_SetRenderDrawColor(WindowManager::getGameCanvas(), 0, 0, 0, 255); for(SDL_Rect * quad : colliderRects) { SDL_RenderDrawRect(WindowManager::getGameCanvas(), quad); } colliderRects.clear(); }
pablodiegoss/paperboy
engine/src/animation_manager.cpp
C++
gpl-3.0
1,081
package org.uncertweb.ps.data; import java.net.URL; public class DataReference { private URL url; private String mimeType; private boolean compressed; public DataReference(URL url, String mimeType, boolean compressed) { this.url = url; this.mimeType = mimeType; this.compressed = compressed; } public DataReference(URL url, boolean compressed) { this(url, null, compressed); } public DataReference(URL url, String mimeType) { this(url, mimeType, false); } public DataReference(URL url) { this(url, null, false); } public URL getURL() { return url; } public String getMimeType() { return mimeType; } public boolean isCompressed() { return compressed; } }
itszootime/ps-framework
src/main/java/org/uncertweb/ps/data/DataReference.java
Java
gpl-3.0
701
/** * File ./src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java * Lemo-Data-Management-Server for learning analytics. * Copyright (C) 2015 * Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ /** * File ./src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java * Date 2015-01-05 * Project Lemo Learning Analytics */ package de.lemo.dms.connectors.lemo_0_8.mapping; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Represanting an object of the level of an hierarchy * @author Sebastian Schwarzrock * */ @Entity @Table(name = "level_course") public class LevelCourseLMS{ private long id; private long course; private long level; private Long platform; /** * standard getter for the attribute id * * @return the identifier for the association between department and resource */ @Id public long getId() { return this.id; } /** * standard setter for the attribute id * * @param id * the identifier for the association between department and resource */ public void setId(final long id) { this.id = id; } /** * standard getter for the attribute * * @return a department in which the resource is used */ @Column(name="course_id") public long getCourse() { return this.course; } public void setCourse(final long course) { this.course = course; } @Column(name="level_id") public long getLevel() { return this.level; } public void setLevel(final long degree) { this.level = degree; } @Column(name="platform") public Long getPlatform() { return this.platform; } public void setPlatform(final Long platform) { this.platform = platform; } }
LemoProject/Lemo-Data-Management-Server
src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java
Java
gpl-3.0
2,522
import React from 'react'; import { shallow, mount } from 'enzyme'; import Tabs from '../components/layout/Tabs'; describe('Tabs render with different props', () => { const tabs = [ { label: 'Přihlášení', render: () => {} }, { label: 'Registrace', render: () => {} } ]; it('renders without crashing', () => { expect( shallow(<Tabs tabs={tabs} />).length ).toEqual(1); }); it('contains exactly two tabs', () => { const wrapper = mount(<Tabs tabs={tabs} />); expect(wrapper.render().find('li').length).toEqual(2); }); it('contains correct labels in tabs', () => { const wrapper = mount(<Tabs tabs={tabs} />); expect(wrapper.find('li').at(0).text()).toEqual(tabs[0].label); expect(wrapper.find('li').at(1).text()).toEqual(tabs[1].label); }); });
jirkae/hobby_hub
src/Base/__tests__/Tabs.test.js
JavaScript
gpl-3.0
869
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207, * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com. ********************************************************************************/ class MarketingListEditView extends SecuredEditView { public static function getDefaultMetadata() { $metadata = array( 'global' => array( 'toolbar' => array( 'elements' => array( array('type' => 'MarketingListsCancelLink'), array('type' => 'SaveButton'), ), ), 'panels' => array( array( 'rows' => array( array('cells' => array( array( 'elements' => array( array('attributeName' => 'name', 'type' => 'Text'), ), ), ), ), array('cells' => array( array( 'elements' => array( array('attributeName' => 'description', 'type' => 'TextArea'), ), ), ) ), array('cells' => array( array( 'elements' => array( array('attributeName' => 'fromName', 'type' => 'Text'), ), ), ), ), array('cells' => array( array( 'elements' => array( array('attributeName' => 'fromAddress', 'type' => 'Text'), ), ), ), ), ), ), ), ), ); return $metadata; } } ?>
deep9/zurmo
app/protected/modules/marketingLists/views/MarketingListEditView.php
PHP
gpl-3.0
4,103
#ifndef METASHELL_PRAGMA_HELP_HPP #define METASHELL_PRAGMA_HELP_HPP // Metashell - Interactive C++ template metaprogramming shell // Copyright (C) 2014, Abel Sinkovics (abel@sinkovics.hu) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <metashell/iface/pragma_handler.hpp> namespace metashell { namespace pragma { class help : public iface::pragma_handler { public: std::string arguments() const override; std::string description() const override; void run(const data::command::iterator& name_begin_, const data::command::iterator& name_end_, const data::command::iterator& args_begin_, const data::command::iterator& args_end_, iface::main_shell& shell_, iface::displayer& displayer_) const override; data::code_completion code_complete(data::command::const_iterator, data::command::const_iterator, iface::main_shell&) const override; }; } } #endif
r0mai/metashell
lib/pragma/include/metashell/pragma/help.hpp
C++
gpl-3.0
1,671
/*------------------------------------------------------------------------- * Copyright (c) 2012,2013, Alex Athanasopoulos. All Rights Reserved. * alex@melato.org *------------------------------------------------------------------------- * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *------------------------------------------------------------------------- */ package org.melato.geometry.util; public class Sequencer { private int[] array; private boolean[] visited; public Sequencer(int[] array) { super(); this.array = array; visited = new boolean[array.length]; } public void findSequence(int start, int end, Sequence sequence) { int a = array[start]; sequence.start = start; sequence.last = start; sequence.length = 1; int j = start + 1; for( ; j < end ;j++ ) { int b = array[j]; if ( b != -1 && ! visited[j]) { if ( b == a + 1 ) { a = b; sequence.length++; } else if ( b != a ) { continue; } sequence.last = j; visited[j] = true; } } System.out.println( "findSequence start=" + start + " end=" + end + " sequence=" + sequence); } private void filter() { System.out.println( "approaches sorted: " + toString(array, 0, array.length)); removeOutOfOrder(0, array.length ); //System.out.println( "approaches in-order: " + toString(approaches, 0, approaches.length)); removeDuplicates(); System.out.println( "approaches unique: " + toString(array, 0, array.length)); } /** remove array so that the remaining array are in non-decreasing order. * array are removed by setting them to -1. * */ private void removeOutOfOrder(int start, int end) { if ( end <= start ) return; for( int i = start; i < end; i++ ) { visited[i] = false; } Sequence bestSequence = null; Sequence sequence = new Sequence(); // find the longest sub-sequence of sequential or equal array for( int i = start; i < end; i++ ) { int a = array[i]; if ( a != -1 ) { //System.out.println( "i=" + i + " visited=" + a.visited); if ( visited[i] ) continue; findSequence(i, end, sequence); if ( bestSequence == null || sequence.length > bestSequence.length ) { bestSequence = sequence; sequence = new Sequence(); } } } if ( bestSequence == null ) { // there is nothing return; } System.out.println( "best sequence: " + bestSequence); bestSequence.clearInside(array); bestSequence.clearLeft(array, start); bestSequence.clearRight(array, end); //System.out.println( "a: " + toString( approaches, 0, approaches.length )); // do the same on each side removeOutOfOrder( start, bestSequence.start); removeOutOfOrder( bestSequence.last + 1, end ); //System.out.println( "b: " + toString( approaches, 0, approaches.length )); } private void removeDuplicates() { // keep the last position that has the lowest element int item = -1; int lastIndex = -1; int i = 0; for( ; i < array.length; i++ ) { int a = array[i]; if ( a != -1 ) { if ( item == -1 ) { item = a; lastIndex = i; } else if ( item == a ) { array[lastIndex] = -1; lastIndex = i; } else { item = a; i++; break; } } } // for subsequent array, keep the first one among equal elements for( ; i < array.length; i++ ) { int a = array[i]; if ( a != -1 ) { if ( item == a ) { array[i] = -1; } else { item = a; } } } } public static String toString( int[] array, int start, int end ) { StringBuilder buf = new StringBuilder(); buf.append( "["); int count = 0; for( int i = start; i < end; i++ ) { int a = array[i]; if ( a != -1 ) { if ( count > 0 ) { buf.append( " " ); } count++; buf.append( String.valueOf(a) ); } } buf.append("]"); return buf.toString(); } /** Find a subsequence of increasing items by setting the remaining items to -1. */ public static void filter(int[] items) { Sequencer sequencer = new Sequencer(items); sequencer.filter(); } }
melato/next-bus
src/org/melato/geometry/util/Sequencer.java
Java
gpl-3.0
5,006
package num.complexwiring.world.decor; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.oredict.OreDictionary; import num.complexwiring.lib.Reference; import num.complexwiring.lib.Strings; import num.complexwiring.world.ModuleWorld; public enum EnumDecor { LIMESTONE_ROUGH(Strings.DECOR_LIMESTONE_ROUGH_NAME, Type.ROUGH), DOLOMITE_ROUGH(Strings.DECOR_DOLOMITE_ROUGH_NAME, Type.ROUGH), ARENITE_ROUGH(Strings.DECOR_ARENITE_ROUGH_NAME, Type.ROUGH), LIMESTONE(Strings.DECOR_LIMESTONE_SMOOTH_NAME, Type.SMOOTH), DOLOMITE(Strings.DECOR_DOLOMITE_SMOOTH_NAME, Type.SMOOTH), ARENITE(Strings.DECOR_ARENITE_SMOOTH_NAME, Type.SMOOTH), DARKDOLOMITE(Strings.DECOR_DARKDOLOMITE_NAME, Type.SMOOTH), LIMESTONE_BRICK(Strings.DECOR_LIMESTONE_BRICK_NAME, Type.BRICK), DOLOMITE_BRICK(Strings.DECOR_DOLOMITE_BRICK_NAME, Type.BRICK), ARENITE_BRICK(Strings.DECOR_ARENITE_BRICK_NAME, Type.BRICK), DARKDOLOMITE_BRICK(Strings.DECOR_DARKDOLOMITE_BRICK_NAME, Type.BRICK), LIMESTONE_SMALLBRICK(Strings.DECOR_LIMESTONE_SMALLBRICK_NAME, Type.SMALLBRICK), DOLOMITE_SMALLBRICK(Strings.DECOR_DOLOMITE_SMALLBRICK_NAME, Type.SMALLBRICK), ARENITE_SMALLBRICK(Strings.DECOR_ARENITE_SMALLBRICK_NAME, Type.SMALLBRICK), DARKDOLOMITE_SMALLBRICK(Strings.DECOR_DARKDOLOMITE_SMALLBRICK_NAME, Type.SMALLBRICK), DOLOMITE_DARKDOLOMITE_MIX(Strings.DECOR_DOLOMITE_DARKDOLOMITE_MIX_NAME, Type.MIX); public static final EnumDecor[] VALID = values(); public final String name; public final Type type; public final int meta = this.ordinal(); public IIcon icon; private EnumDecor(String name, Type type) { this.name = name; this.type = type; } public String getUnlocalizedName() { // removes the "decor" from the name and makes it lowercase (ex. decorLimestone -> limestone) return name.substring(5, 6).toLowerCase() + name.substring(5 + 1); } public void registerIcon(IIconRegister ir) { icon = ir.registerIcon(Reference.TEXTURE_PATH + "world/ore/decor/" + name); } public ItemStack getIS(int amount) { return new ItemStack(ModuleWorld.decor, amount, meta); } public void registerOre() { if (this.type.equals(Type.SMOOTH)) { OreDictionary.registerOre(getUnlocalizedName(), this.getIS(1)); // limestone OreDictionary.registerOre("block" + getUnlocalizedName().substring(0, 1).toUpperCase() + getUnlocalizedName().substring(1), this.getIS(1)); // blockLimestone } } public enum Type { ROUGH, SMOOTH, BRICK, SMALLBRICK, MIX } }
Numerios/ComplexWiring
common/num/complexwiring/world/decor/EnumDecor.java
Java
gpl-3.0
2,725
#include "log.h" #include <iostream> using WhatsAcppi::Util::Log; using std::cout; using std::endl; Log::LogMsgType Log::logLevel = CriticalMsg; Log::Log(Log::LogMsgType type) : level(type) { } Log::~Log(){ cout << this->ss.str() << endl; } void Log::setLogLevel(Log::LogMsgType level){ Log::logLevel = level; }
NickCis/whats-acppi
src/util/log.cpp
C++
gpl-3.0
321
package com.java2us.jpa2us.jpa; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * This class is responsible for providing the entire infrastructure for * connecting to the database. The system needs a {@link JPASessionManager} to * get the EntityManager to connect to the database. This instance is provided * by this class. * * @author Otavio Ferreira * * @version 1.0.0 * @since 1.0.0 */ public class JPAFactory { private final EntityManagerFactory factory; private JPASessionManager sessionManager; /** * Constructor of class {@link JPAFactory}. In the call of this builder, the * factory is also built. * * @param persistenceUnitName * PersistenceUnit name that contains the access settings to the * bank within persistence.xml. * * @author Otavio Ferreira * * @version 1.0.0 * @since 1.0.0 */ public JPAFactory(String persistenceUnitName) { this.factory = createEntityFactory(persistenceUnitName); } /** * It effectively creates the EntityManagers factory. * * @param persistenceUnitName * PersistenceUnit name that contains the access settings to the * bank within persistence.xml. * @return The EntityManagerFactory built. * * @author Otavio Ferreira * * @version 1.0.0 * @since 1.0.0 */ private EntityManagerFactory createEntityFactory(String persistenceUnitName) { try { return Persistence.createEntityManagerFactory(persistenceUnitName); } catch (Exception ex) { System.out.println(ex.getMessage()); } return null; } /** * Creates the {@link JPASessionManager}, which is responsible for managing * and requesting the creation of sessions with the Database. * * @return A new {@link JPASessionManager}. * * @author Otavio Ferreira * * @version 1.0.0 * @since 1.0.0 */ public JPASessionManager getSessionManager() { this.sessionManager = new JPASessionManager(factory); return sessionManager; } /** * Close the EntityManagerFactory. * * @author Otavio Ferreira * * @version 1.0.0 * @since 1.0.0 */ public void closeEntityFactory() { factory.close(); } }
Java2Us/jpa2us
src/com/java2us/jpa2us/jpa/JPAFactory.java
Java
gpl-3.0
2,196
<?php namespace Pest; require_once 'Pest.php'; /** * Small Pest addition by Egbert Teeselink (http://www.github.com/eteeselink) * * Pest is a REST client for PHP. * PestJSON adds JSON-specific functionality to Pest, automatically converting * JSON data resturned from REST services into PHP arrays and vice versa. * * In other words, while Pest's get/post/put/delete calls return raw strings, * PestJSON return (associative) arrays. * * In case of >= 400 status codes, an exception is thrown with $e->getMessage() * containing the error message that the server produced. User code will have to * json_decode() that manually, if applicable, because the PHP Exception base * class does not accept arrays for the exception message and some JSON/REST servers * do not produce nice JSON * * See http://github.com/educoder/pest for details. * * This code is licensed for use, modification, and distribution * under the terms of the MIT License (see http://en.wikipedia.org/wiki/MIT_License) */ class PestJSON extends Pest { public function post($url, $data, $headers=array()) { return parent::post($url, json_encode($data), $headers); } public function put($url, $data, $headers=array()) { return parent::put($url, json_encode($data), $headers); } protected function prepRequest($opts, $url) { $opts[CURLOPT_HTTPHEADER][] = 'Accept: application/json'; $opts[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json'; return parent::prepRequest($opts, $url); } public function processBody($body) { return json_decode($body, true); } }
MeinHAUS/HAUS-Server-PHP
lib/Pest/PestJSON.php
PHP
gpl-3.0
1,598
#!/usr/bin/env python # -*- coding, utf-8 -*- # FIDATA. Open-source system for analysis of financial and economic data # Copyright © 2013 Basil Peace # This file is part of FIDATA. # # FIDATA is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIDATA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FIDATA. If not, see <http://www.gnu.org/licenses/>. from FIDATA import * initArgParser('Importer of predefined data', defLogFilename = 'import.log') initFIDATA() from csv import DictReader from os import path from PIL import Image classes = [] logging.info('Import of predefined data started') # logging.info('Importing langs') # reader = DictReader(open('langs.csv', 'r', encoding = 'UTF8'), delimiter = ';') # for row in reader: # Lang(FIDATA, row = row, write = True, tryGetFromDB = False) # del reader # commit() # classes += [Lang] logging.info('Importing scripts') reader = DictReader(open('scripts.csv', 'r', encoding = 'UTF8'), delimiter = ';') for row in reader: Script(FIDATA, row = row, write = True, tryGetFromDB = False) del reader commit() classes += [Script] logging.info('Importing countries') reader = DictReader(open('countries.csv', 'r', encoding = 'UTF8'), delimiter = ';') for row in reader: # parent_country # associated_with if row['alpha2_code'] == '': row['alpha2_code'] = None else: flagFilename = 'flags\{:s}.png'.format(row['alpha2_code'].lower()) if path.exists(flagFilename): row['flag'] = Image.open(flagFilename) if row['gov_website'] == '': row['gov_website'] = None if row['stats_website'] == '': row['stats_website'] = None FIDATA.country(row = row, write = True, tryGetFromDB = False) del reader commit() classes += [Country] # logging.info('Importing issuers') # reader = DictReader(open('issuers.csv', 'r', encoding = 'UTF8'), delimiter = ';') # for row in reader: # FIDATA.issuer(row = row, write = True, tryGetFromDB = False) # del reader # commit() # classes += [Issuer] # logging.info('Importing currencies') # reader = DictReader(open('currencies.csv', 'r', encoding = 'UTF8'), delimiter = ';') # for row in reader: # row['instr_type'] = InstrumentType.Currency # FIDATA.instrument(row = row, write = True, tryGetFromDB = False) # del reader # commit() # logging.info('Importing instruments') # reader = DictReader(open('instruments.csv', 'r', encoding = 'UTF8'), delimiter = ';') # for row in reader: # FIDATA.instrument(row = row, write = True, tryGetFromDB = False) # del reader # commit() # classes += [Instrument] logging.info('Importing markets') reader = DictReader(open('markets.csv', 'r', encoding = 'UTF8'), delimiter = ';') child_markets = list() for row in reader: if row['country_alpha2_code'] == '': row['country'] = None else: row['country'] = FIDATA.country(row = { 'alpha2_code': row['country_alpha2_code'], 'name' : row['country_name'] }) if row['acronym'] == '': row['acronym'] = None if row['website'] == '': row['website'] = None if row['trade_organizer_symbol'] == '': FIDATA.market(row = row, write = True, tryGetFromDB = False) else: child_markets.append((FIDATA.market(row = row, write = False, tryGetFromDB = False), row['trade_organizer_symbol'])) del reader for (market, trade_organizer_symbol) in child_markets: market.tradeOrganizer = FIDATA.market(row = {'symbol': trade_organizer_symbol}) market.write() del child_markets commit() classes += [Market] logging.info('Importing data providers') reader = DictReader(open('data_providers.csv', 'r', encoding = 'UTF8'), delimiter = ';') for row in reader: if row['trade_organizer_symbol'] == '': row['trade_organizer'] = None else: row['trade_organizer'] = FIDATA.market(row = {'symbol': row['trade_organizer_symbol']}) FIDATA.dataProvider(row = row, write = True, tryGetFromDB = False) del reader commit() classes += [DataProvider] logging.info('Import of predefined data finished') FIDATA.analyze(classes)
FIDATA/database-draft
predefined-data/import.py
Python
gpl-3.0
4,368
#include "stateMachine.h" #include <vector> #include "../Ecs/World.h" #include "../AI/AiComponent.h" #include "../AI/BasicAiModule.h" #include "../AI/Action/MoveCloseToTargetAction.h" #include "../AI/Action/NoAction.h" #include "../AI/SubSystems/NavigationSubsystem.h" #include "../AI/SubSystems/TargetingSystem.h" #include "../AI/SubSystems/TargetingComponent.h" #include "../AI/Sensor/SightSensor.h" #include "../AI/AiSystem.h" #include "../AI/NavMesh/NavMeshContainer.h" #include "../Geometry/PositionComponent.h" #include "../Physics/MovementComponent.h" #include "../Physics/MovementSystem.h" #include "../Threading/Thread.h" using AI::BasicStateMachine; using AI::BasicAiModule; using AI::Action::MoveCloseToTargetAction; using std::vector; using Threading::ConcurrentRessource; using Threading::ConcurrentReader; using Threading::ConcurrentWriter; using Threading::getConcurrentReader; using Threading::getConcurrentWriter; namespace StateMachineTest { float toIdleState(Ecs::ComponentGroup& ) { return 0.1f; } float toOnAttack(Ecs::ComponentGroup& components) { try { ConcurrentReader<Geometry::PositionComponent> positionComponent = getConcurrentReader<Ecs::Component, Geometry::PositionComponent>( components.getComponent(Geometry::PositionComponent::Type) ); ConcurrentReader<AI::Subsystem::TargetingComponent> targetingComponent = getConcurrentReader<Ecs::Component, AI::Subsystem::TargetingComponent>( components.getComponent(AI::Subsystem::TargetingComponent::Type) ); float maxDistance = 10.f; if(targetingComponent->hasValidTarget() && (targetingComponent->getTargetPosition() - positionComponent->getPosition()).getLength() < maxDistance) { return 1.0f; } return 0.f; } catch (const Ecs::ComponentGroup::UnexistingComponentException& e) { return 0.f; } } float toCloseToTarget(Ecs::ComponentGroup& components) { try { ConcurrentReader<Geometry::PositionComponent> positionComponent = getConcurrentReader<Ecs::Component, Geometry::PositionComponent>( components.getComponent(Geometry::PositionComponent::Type) ); ConcurrentReader<AI::Subsystem::TargetingComponent> targetingComponent = getConcurrentReader<Ecs::Component, AI::Subsystem::TargetingComponent>( components.getComponent(AI::Subsystem::TargetingComponent::Type) ); float maxDistance = 120.f; if(targetingComponent->hasValidTarget() && (targetingComponent->getTargetPosition() - positionComponent->getPosition()).getLength() < maxDistance) { return 1.0f; } return 0.f; } catch (const Ecs::ComponentGroup::UnexistingComponentException& e) { return 0.f; } } void setupStateMachine(BasicAiModule& aiModule) { aiModule.addState(CloseToTarget); aiModule.addState(OnAttack); //Transition Idle -> CloseToTarget BasicAiModule::Transition idleToCloseToTarget(AI::Action::MoveCloseToTargetAction::Type, &toCloseToTarget); aiModule.addTransition(Idle, CloseToTarget, idleToCloseToTarget); // Transition CloseToTarget- > OnAttack BasicAiModule::Transition closeToTargetToOnAttack(AI::Action::MoveCloseToTargetAction::Type, &toOnAttack); aiModule.addTransition(CloseToTarget, OnAttack, closeToTargetToOnAttack); // Transition OnAttack- > Idle BasicAiModule::Transition onAttackToIdle(AI::Action::NoAction::Type, &toIdleState); aiModule.addTransition(OnAttack, Idle, onAttackToIdle); // Transition CloseToTarget- > Idle BasicAiModule::Transition closeToTargetToIdle(AI::Action::NoAction::Type, &toIdleState); aiModule.addTransition(CloseToTarget, Idle, closeToTargetToIdle); } void testStateMachine() { /* Ecs::World w = Ecs::World(); NavMesh::NavMeshContainer navMeshes; Ecs::Entity e1 = w.createEntity(); // Create component for e1 Geometry::PositionComponent* positionComponentE1 = new Geometry::PositionComponent(Geometry::Vec3Df(0.f,0.f,0.0f)); Physics::MovementComponent* movementComponentE1= new Physics::MovementComponent(Geometry::Vec3Df(0.f,0.f,0.0f)); w.addComponent(e1, positionComponentE1); w.addComponent(e1, movementComponentE1); AI::AiComponent* aiComponent = new AI::AiComponent(e1, navMeshes); BasicAiModule* aiModule = new BasicAiModule(Idle); setupStateMachine(*aiModule); aiComponent->setAiModule(aiModule); w.addComponent(e1, aiComponent); // Add navigation and targeting subsytems AI::Subsystem::SubSystemsManager& subsystemsManager = aiComponent->getSubsystemsManager(); subsystemsManager.addSubsystem(AI::Subsystem::TargetingSubsystem::Type, w); subsystemsManager.addSubsystem(AI::Subsystem::NavigationSubSystem::Type, w); // Create an other entity Ecs::Entity e2 = w.createEntity(); Geometry::PositionComponent* positionComponent = new Geometry::PositionComponent(Geometry::Vec3Df(0.f,80.f,0.0f)); w.addComponent(e2, positionComponent); w.addComponent(e2, new Physics::MovementComponent(Geometry::Vec3Df(0.f,0.f,0.0f))); // Create the systems for ai and movement AI::AiSystem aiSystem(w); Physics::MovementSystem movementSystem(w); vector<Threading::ThreadableInterface*> aiSystemVector; vector<Threading::ThreadableInterface*> movementSystemVector; aiSystemVector.push_back(&aiSystem); movementSystemVector.push_back(&movementSystem); Threading::Thread aiThread(aiSystemVector, 5); Threading::Thread movementThread(movementSystemVector, 5); aiThread.start(); movementThread.start(); bool b = true; while(b) { if((positionComponentE1->getPosition()-positionComponent->getPosition()).getLength() < 10.f) b = false; } aiThread.stop(); movementThread.stop(); //aiModule->computeNewPlan(); */ } }
stevenremot/tlsd-prototype
src/tests/stateMachine.cpp
C++
gpl-3.0
6,547
#ifndef SELECT_ALIEN_HPP #define SELECT_ALIEN_HPP #include "animation.hpp" #include "game_object.hpp" #include "text.hpp" using namespace engine; class Header: public GameObject{ public: Header(double positionX, double positionY, int maxPapers, int stageNumber); ~Header(); void update(double timeElapsed); void draw(); void init(); void setAlienSelect(int select); Animation * getAnimation(); void updatePaperQuantity(int newValue); private: Animation* animator; Animation* paper_icon; Text* paper_text; Text* stage_text; int total_papers; //declareting variables total papers int alien_select; // declareting variables alien selection Text* convertToText(int newValue); void verifySelect(); }; #endif
joaosaliba/Conspiracy
game/include/header.hpp
C++
gpl-3.0
771
/** * This file is part of Xena. * * Xena is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. * * Xena is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Xena; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * @author Andrew Keeling * @author Chris Bitmead * @author Justin Waddell */ package au.gov.naa.digipres.xena.plugin.pdf; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.transform.stream.StreamResult; import org.jpedal.examples.simpleviewer.SimpleViewer; import org.xml.sax.ContentHandler; import au.gov.naa.digipres.xena.kernel.XenaException; import au.gov.naa.digipres.xena.kernel.view.XenaView; import au.gov.naa.digipres.xena.util.BinaryDeNormaliser; /** * View for PDF files. * */ public class PdfView extends XenaView { public static final String PDFVIEW_VIEW_NAME = "PDF Viewer"; private static final long serialVersionUID = 1L; private SimpleViewer simpleViewer; private File pdfFile; public PdfView() { } @Override public boolean canShowTag(String tag) throws XenaException { return tag.equals(viewManager.getPluginManager().getTypeManager().lookupXenaFileType(XenaPdfFileType.class).getTag()); } @Override public String getViewName() { return PDFVIEW_VIEW_NAME; } @Override public ContentHandler getContentHandler() throws XenaException { FileOutputStream xenaTempOS = null; try { pdfFile = File.createTempFile("pdffile", ".pdf"); pdfFile.deleteOnExit(); xenaTempOS = new FileOutputStream(pdfFile); } catch (IOException e) { throw new XenaException("Problem creating temporary xena output file", e); } BinaryDeNormaliser base64Handler = new BinaryDeNormaliser() { /* * (non-Javadoc) * @see au.gov.naa.digipres.xena.kernel.normalise.AbstractDeNormaliser#endDocument() */ @Override public void endDocument() { if (pdfFile.exists()) { simpleViewer = new SimpleViewer(); simpleViewer.setRootContainer(PdfView.this); simpleViewer.setupViewer(); simpleViewer.openDefaultFile(pdfFile.getAbsolutePath()); } } }; StreamResult result = new StreamResult(xenaTempOS); base64Handler.setResult(result); return base64Handler; } /* * (non-Javadoc) * @see au.gov.naa.digipres.xena.kernel.view.XenaView#doClose() */ @Override public void doClose() { super.doClose(); } }
srnsw/xena
plugins/pdf/src/au/gov/naa/digipres/xena/plugin/pdf/PdfView.java
Java
gpl-3.0
2,869
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Class file for the block_ajax_marking_nodes_builder_base class * * @package block * @subpackage ajax_marking * @copyright 2011 Matt Gibson * @author Matt Gibson {@link http://moodle.org/user/view.php?id=81450} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /* * Four days, before which, work is considered 'recent', after which things are considered 'medium' */ //We decided we want the cutoff to be THREE DAYS instead of 4 //define('BLOCK_AJAX_MARKING_FOUR_DAYS', 345600);--kaw define('BLOCK_AJAX_MARKING_FOUR_DAYS', 259200); /* * Ten days. Later than this is overdue. */ //We decided we want the cutoff to be SEVEN DAYS instead of 10 //define('BLOCK_AJAX_MARKING_TEN_DAYS', 864000); --kaw define('BLOCK_AJAX_MARKING_TEN_DAYS', 604800); global $CFG; require_once($CFG->dirroot.'/blocks/ajax_marking/classes/query_base.class.php'); require_once($CFG->dirroot.'/blocks/ajax_marking/classes/bulk_context_module.class.php'); require_once($CFG->dirroot.'/blocks/ajax_marking/lib.php'); /** * This is to build a query based on the parameters passed in from the client. Without parameters, * the query should return all unmarked items across all of the site. * * The query has 3 layers: the innermost is a UNION of several queries that go and fetch the * unmarked submissions from each module (1 for each module as they all store unmarked work * differently). The middle layer attaches standard filters via apply_sql_xxxx_settings() functions * e.g. 'only show submissions from currently enrolled students' and 'only show submissions that * I have not configured to be hidden'. It also applies filters so that drilling down through the * nodes tree, the lower levels filter by the upper levels e.g. expanding a course node leads to a * 'WHERE courseid = xxx' clause being added. Finally, a GROUP BY statement is added for the * current node level e.g. for coursemodule nodes, we want to use coursemoduleid for this, then * count the submissions. The outermost layer then joins to the GROUP BY ids and counts (the only * two columns that the middle query provides) to supply the display details e.g. the name * of the coursemodule. This arrangement is needed because Oracle doesn't allow text * fields and GROUP BY to be mixed. */ class block_ajax_marking_nodes_builder_base { /** * This function applies standard joins to the module query so it can filter as much as possible before we * UNION the results. The more we do here, the better, as this stuff can use JOINs and therefore indexes. * Stuff that's done in the outer countwrapper query will be join to the temporary table created by the UNION * and therefore may not perform so well. * * @param array $filters * @param block_ajax_marking_module_base $moduleclass e.g. quiz, assignment to supply the module specific query. * @return block_ajax_marking_query */ private static function get_unmarked_module_query(array $filters, block_ajax_marking_module_base $moduleclass) { // Might be a config nodes query, in which case, we want to leave off the unmarked work // stuff and make sure we add the display select stuff to this query instead of leaving // it for the outer displayquery that the unmarked work needs. $confignodes = isset($filters['config']) ? true : false; if ($confignodes) { $query = new block_ajax_marking_query_base($moduleclass); $query->add_from(array( 'table' => $moduleclass->get_module_name(), 'alias' => 'moduletable', )); } else { $query = $moduleclass->query_factory(); } $query->add_select(array('table' => 'course_modules', 'column' => 'id', 'alias' =>'coursemoduleid')); $query->set_column('coursemoduleid', 'course_modules.id'); // Need the course to join to other filters. $query->add_select(array('table' => 'moduletable', 'column' => 'course')); // Some filters need a coursemodule id to join to, so we need to make it part of every query. $query->add_from(array('table' => 'course_modules', 'on' => 'course_modules.instance = moduletable.id AND course_modules.module = '.$moduleclass->get_module_id())); // Some modules need to add stuff by joining the moduleunion back to the sub table. This // gets round the way we can't add stuff from just one module's sub table into the UNION // bit. $query->add_select(array('table' => 'sub', 'column' => 'id', 'alias' =>'subid')); // Need to pass this through sometimes for the javascript to know what sort of node it is. $query->add_select(array('column' => "'".$moduleclass->get_module_name()."'", 'alias' =>'modulename')); self::apply_sql_enrolled_students($query, $filters); self::apply_sql_visible($query); if (!block_ajax_marking_admin_see_all($filters)) { self::apply_sql_owncourses($query); } return $query; } /** * This is to build whatever query is needed in order to return the requested nodes. It may be * necessary to compose this query from quite a few different pieces. Without filters, this * should return all unmarked work across the whole site for this teacher. * * The main union query structure involves two levels of nesting: First, all modules provide a * query that counts the unmarked work and leaves us with * * In: * - filters as an array. course, coursemodule, student, others (as defined by module base * classes * * Issues: * - maintainability: easy to add and subtract query filters * - readability: this is very complex * * @global moodle_database $DB * @param array $filters list of functions to run on the query. Methods of this or the module * class * @return array */ public static function unmarked_nodes(array $filters = array()) { global $CFG; $modulequeries = self::get_module_queries_array($filters); $nextnodefilter = block_ajax_marking_get_nextnodefilter_from_params($filters); $havecoursemodulefilter = array_key_exists('coursemoduleid', $filters) && $filters['coursemoduleid'] !== 'nextnodefilter'; $moduleclass = false; if ($havecoursemodulefilter) { $moduleclass = self::get_module_object_from_cmid($filters['coursemoduleid']); } if (empty($modulequeries)) { return array(); } $countwrapperquery = self::get_count_wrapper_query($modulequeries, $filters); // This is just for copying and pasting from the paused debugger into a DB GUI. if ($CFG->debug == DEBUG_DEVELOPER) { $debugquery = $countwrapperquery->debuggable_query(); } // Join to the config tables so we have settings available for the nodes context menus and for filtering // hidden ones. self::add_query_filter($countwrapperquery, 'core', 'attach_config_tables_countwrapper'); // Apply all the standard filters. These only make sense when there's unmarked work. self::apply_sql_display_settings($countwrapperquery); // TODO is it more efficient to have this in the moduleunions to limit the rows? // This is just for copying and pasting from the paused debugger into a DB GUI. if ($CFG->debug == DEBUG_DEVELOPER) { $debugquery = $countwrapperquery->debuggable_query(); } $displayquery = self::get_display_query($countwrapperquery, $filters); // This is just for copying and pasting from the paused debugger into a DB GUI. if ($CFG->debug == DEBUG_DEVELOPER) { $debugquery = $displayquery->debuggable_query(); } $nodes = $displayquery->execute(); if ($nextnodefilter == 'courseid') { $nodes = self::attach_groups_to_course_nodes($nodes); } else if ($nextnodefilter == 'coursemoduleid') { $nodes = self::attach_groups_to_coursemodule_nodes($nodes); } if ($havecoursemodulefilter) { // This e.g. allows the forum module to tweak the name depending on forum type. $moduleclass->postprocess_nodes_hook($nodes, $filters); } return $nodes; } /** * Uses the list of filters supplied by AJAX to find functions within this class and the * module classes which will modify the query * * @static * @param array $filters * @param block_ajax_marking_query $query which will have varying levels of nesting * @param bool $config flag to tell us if this is the config tree, which has a differently * structured query * @param block_ajax_marking_module_base|bool $moduleclass if we have a coursemoduleid filter, * this is the corresponding module * object */ private static function apply_filters_to_query(array $filters, block_ajax_marking_query $query, $config = false, $moduleclass = false) { // Now that the query object has been constructed, we want to add all the filters that will // limit the nodes to just the stuff we want (ignore hidden things, ignore things in other // parts of the tree) and groups the unmarked work by whatever it needs to be grouped by. foreach ($filters as $name => $value) { // Classes that hold the filters are named 'block_ajax_marking_filtername', where // filtername may be courseid, groupid, etc. For module overrides, they are // 'block_ajax_marking_quiz_filtername'. // We want a single node count. $classnamesuffix = $name; $filterfunctionname = ($value == 'nextnodefilter') ? 'nextnodetype_filter' : 'where_filter'; $filterfunctionname = $config ? 'config'.$filterfunctionname : $filterfunctionname; $coreclassname = 'block_ajax_marking_'.$classnamesuffix; if ($moduleclass) { // Special case for nextnodefilter. Usually, we will have ancestors. $moduleclassname = self::module_override_available($moduleclass, $classnamesuffix, $filterfunctionname); if ($moduleclassname) { // Modules provide a separate class for each type of node (userid, groupid, etc) // which provide static methods for these operations. $moduleclassname::$filterfunctionname($query, $value); } } else if (class_exists($coreclassname) && method_exists($coreclassname, $filterfunctionname)) { // Config tree needs to have select stuff that doesn't mention sub. Like for the // outer wrappers of the normal query for the unmarked work nodes. $coreclassname::$filterfunctionname($query, $value); } } } /** * Finds out whether there is a method provided by the modules that overrides the core ones. * * @static * @param $moduleclass * @param $classnamesuffix * @param $filterfunctionname * @return bool|string */ private static function module_override_available(block_ajax_marking_module_base $moduleclass, $classnamesuffix, $filterfunctionname) { // If we are filtering by a specific module, look there first. $moduleclassname = 'block_ajax_marking_'.$moduleclass->get_module_name().'_'.$classnamesuffix; $moduleoverrideavailable = class_exists($moduleclassname) && method_exists($moduleclassname, $filterfunctionname); if ($moduleoverrideavailable) { return $moduleclassname; } return false; } /** * We need to check whether the activity can be displayed (the user may have hidden it * using the settings). This sql can be dropped into a query so that it will get the right * students. This will also make sure that if only some groups are being displayed, the * submission is by a user who is in one of the displayed groups. * * @param block_ajax_marking_query_base $query a query object to apply these changes to * @return void */ private static function apply_sql_display_settings($query) { // We allow course settings to override the site default and activity settings to override // the course ones. $sitedefaultactivitydisplay = 1; $query->add_where("COALESCE(cmconfig.display, courseconfig.display, {$sitedefaultactivitydisplay}) = 1"); } /** * All modules have a common need to hide work which has been submitted to items that are now * hidden. Not sure if this is relevant so much, but it's worth doing so that test data and test * courses don't appear. General approach is to use cached context info from user session to * find a small list of contexts that a teacher cannot grade in within the courses where they * normally can, then do a NOT IN thing with it. Also the obvious visible = 1 stuff. * * @param block_ajax_marking_query $query * @param bool $includehidden Do we want to have hidden coursemodules included? Config = yes * @return array The join string, where string and params array. Note, where starts with 'AND' */ private static function apply_sql_visible(block_ajax_marking_query $query, $includehidden = false) { global $DB; $query->add_from(array( 'join' => 'INNER JOIN', 'table' => 'course', 'on' => 'course.id = '.$query->get_column('courseid') )); // If the user can potentially be blocked from accessing some things using permissions overrides, then we // need to take this into account. $mods = block_ajax_marking_get_module_classes(); $modids = array(); foreach ($mods as $mod) { $modids[] = $mod->get_module_id(); // Save these for later. } // Get coursemoduleids for all items of this type in all courses as one query. Won't come // back empty or else we would not have gotten this far. if (!is_siteadmin()) { $courses = block_ajax_marking_get_my_teacher_courses(); // TODO Note that change to login as... in another tab may break this. Needs testing. list($coursesql, $courseparams) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED); list($modsql, $modparams) = $DB->get_in_or_equal(array_keys($modids), SQL_PARAMS_NAMED); $params = array_merge($courseparams, $modparams); // Get all course modules the current user could potentially access. Limit to the enabled // mods. $sql = "SELECT context.* FROM {context} context INNER JOIN {course_modules} course_modules ON context.instanceid = course_modules.id AND context.contextlevel = ".CONTEXT_MODULE." WHERE course_modules.course {$coursesql} AND course_modules.module {$modsql}"; // No point caching - only one request per module per page request... $contexts = $DB->get_records_sql($sql, $params); // Use has_capability to loop through them finding out which are blocked. Unset all that we // have permission to grade, leaving just those we are not allowed (smaller list). Hopefully // this will never exceed 1000 (oracle hard limit on number of IN values). // TODO - very inefficient as we are checking every context even though many will be for a different mod. foreach ($mods as $mod) { foreach ($contexts as $key => $context) { // If we don't find any capabilities for a context, it will remain and be excluded // from the SQL. Hopefully this will be a small list. n.b. the list is of all // course modules. if (has_capability($mod->get_capability(), new bulk_context_module($context))) { unset($contexts[$key]); } } } // Return a get_in_or_equals with NOT IN if there are any, or empty strings if there aren't. if (!empty($contexts)) { list($contextssql, $contextsparams) = $DB->get_in_or_equal(array_keys($contexts), SQL_PARAMS_NAMED, 'context0000', false); $query->add_where("course_modules.id {$contextssql}", $contextsparams); } } // We want the coursmeodules that are hidden to be gone form the main trees. For config, // We may want to show them greyed out so that settings can be sorted before they are shown // to students. if (!$includehidden) { $query->add_where('course_modules.visible = 1'); } $query->add_where('course.visible = 1'); } /** * Makes sure we only get stuff for the courses this user is a teacher in * * @param block_ajax_marking_query $query * @return void */ private static function apply_sql_owncourses(block_ajax_marking_query $query) { global $DB; $coursecolumn = $query->get_column('courseid'); $courses = block_ajax_marking_get_my_teacher_courses(); $courseids = array_keys($courses); if ($courseids) { list($sql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, $query->get_module_name().'courseid0000'); $query->add_where($coursecolumn.' '.$sql, $params); } } /** * Returns an SQL snippet that will tell us whether a student is directly enrolled in this * course. Params need to be made specific to this module as they will be duplicated. This is required * because sometimes, students leave and their work is left over. * * @param block_ajax_marking_query $query * @param array $filters So we can filter by cohort id if we need to * @return array The join and where strings, with params. (Where starts with 'AND') */ private static function apply_sql_enrolled_students(block_ajax_marking_query $query, array $filters) { global $DB, $CFG, $USER; $nextnodefilter = block_ajax_marking_get_nextnodefilter_from_params($filters); // Hide users added by plugins which are now disabled. if (isset($filters['cohortid']) || $nextnodefilter == 'cohortid') { // We need to specify only people enrolled via a cohort. No other enrollment methods matter as // people who are part of a cohort will have been added to the course via a cohort enrolment or // else they wouldn't be there. $enabledsql = " = 'cohort'"; $params = array(); } else if ($CFG->enrol_plugins_enabled) { // Returns list of english names of enrolment plugins. $plugins = explode(',', $CFG->enrol_plugins_enabled); list($enabledsql, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'enrol'.$query->get_module_name().'001'); } else { // No enabled enrolment plugins. $enabledsql = ' = :sqlenrollednever'.$query->get_module_name(); $params = array('sqlenrollednever'.$query->get_module_name() => -1); } $sql = <<<SQL SELECT NULL FROM {enrol} enrol INNER JOIN {user_enrolments} user_enrolments ON user_enrolments.enrolid = enrol.id WHERE enrol.enrol {$enabledsql} AND enrol.courseid = {$query->get_column('courseid')} AND user_enrolments.userid != :enrol{$query->get_module_name()}currentuser AND user_enrolments.userid = {$query->get_column('userid')} SQL; $params['enrol'.$query->get_module_name().'currentuser'] = $USER->id; $query->add_where("EXISTS ({$sql})", $params); } /** * For the config nodes, we want all of the coursemodules. No need to worry about counting etc. * There is also no need for a dynamic rearrangement of the nodes, so we have two simple queries * * @param array $filters * @return array * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public static function get_config_nodes($filters) { global $CFG; $modulename = self::get_module_name_from_filters($filters); // The logic is that we need to filter the course modules because some of them will be // hidden or the user will not have access to them. Then we may or may not group them by // course. $configbasequery = new block_ajax_marking_query_base(); $configbasequery->add_from(array('table' => 'course_modules')); $configbasequery->set_column('coursemoduleid', 'course_modules.id'); $configbasequery->set_column('courseid', 'course_modules.course'); // Now apply the filters. self::apply_sql_owncourses($configbasequery); self::apply_sql_visible($configbasequery, true); // TODO put this into its own function. reset($filters); foreach ($filters as $filtername => $filtervalue) { if ($filtervalue == 'nextnodefilter') { // This will attach an id to the query, to either be retrieved directly from the moduleunion, // or added via a join of some sort. self::add_query_filter($configbasequery, $filtername, 'current_config', null, $modulename); // If this one needs it, we add the decorator that gets the config settings. // TODO this is not a very elegant way of determining this. // Currently, we use the same wrapper for the display query, no matter what the mechanism // for getting the settings into the countwrapper query is, because they will just have standard // aliases. We don't always need it though. } else { self::add_query_filter($configbasequery, $filtername, 'ancestor', $filtervalue, $modulename); } } // This is just for copying and pasting from the paused debugger into a DB GUI. if ($CFG->debug == DEBUG_DEVELOPER) { $debugquery = $configbasequery->debuggable_query(); } $nodes = $configbasequery->execute(); $nextnodefilter = block_ajax_marking_get_nextnodefilter_from_params($filters); if ($nextnodefilter === 'courseid') { $nodes = self::attach_groups_to_course_nodes($nodes); } else if ($nextnodefilter === 'coursemoduleid') { $nodes = self::attach_groups_to_coursemodule_nodes($nodes); } return $nodes; } /** * In order to adjust the groups display settings properly, we need to know what groups are * available. This takes the nodes we have and attaches the groups to them if there are any. * We only need this for the main tree if we intend to have the ability to adjust settings * via right-click menus. * * @param array $nodes * @return array */ private static function attach_groups_to_course_nodes($nodes) { global $DB, $USER; if (!$nodes) { return array(); } // Need to get all groups for each node. Can't do this in the main query as there are // possibly multiple groups settings for each node. // Get the ids of the nodes. $courseids = array(); foreach ($nodes as $node) { if (isset($node->courseid)) { $courseids[] = $node->courseid; } } if ($courseids) { // Retrieve all groups that we may need. This includes those with no settings yet as // otherwise, we won't be able to offer to create settings for them. list($coursesql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED); $params['userid'] = $USER->id; $separategroups = SEPARATEGROUPS; $sql = <<<SQL SELECT groups.id, groups.courseid AS courseid, groups.name, settings.display FROM {groups} groups INNER JOIN {course} course ON course.id = groups.courseid LEFT JOIN (SELECT coursesettings.instanceid AS courseid, groupsettings.groupid, groupsettings.display FROM {block_ajax_marking_groups} AS groupsettings INNER JOIN {block_ajax_marking} coursesettings ON (coursesettings.tablename = 'course' AND coursesettings.id = groupsettings.configid) WHERE coursesettings.userid = :userid ) settings ON (groups.courseid = settings.courseid AND groups.id = settings.groupid) WHERE groups.courseid {$coursesql} AND ( course.groupmode != {$separategroups} OR EXISTS ( SELECT 1 FROM {groups_members} teachermemberships WHERE teachermemberships.groupid = groups.id AND teachermemberships.userid = :teacheruserid ) ) SQL; $params['teacheruserid'] = $USER->id; $groups = $DB->get_records_sql($sql, $params); foreach ($groups as $group) { // Cast to integers so we can do strict type checking in javascript. $group->id = (int)$group->id; $group->courseid = (int)$group->courseid; $group->display = (int)$group->display; if (!isset($nodes[$group->courseid]->groups)) { $nodes[$group->courseid]->groups = array(); } $nodes[$group->courseid]->groups[$group->id] = $group; } } return $nodes; } /** * Adds an array of groups to each node for coursemodules. * * @param array $nodes * @throws coding_exception * @return mixed */ private static function attach_groups_to_coursemodule_nodes($nodes) { global $DB, $USER; $coursemoduleids = array(); foreach ($nodes as $node) { if (isset($node->coursemoduleid)) { if (in_array($node->coursemoduleid, $coursemoduleids)) { throw new coding_exception('Duplicate coursemoduleids: '.$node->coursemoduleid); } $coursemoduleids[] = $node->coursemoduleid; } } if ($coursemoduleids) { // This will include groups that have no settings as we may want to make settings // for them. list($cmsql, $params) = $DB->get_in_or_equal($coursemoduleids, SQL_PARAMS_NAMED); // Can't have repeating groupids in column 1 or it throws an error. $concat = $DB->sql_concat('groups.id', "'-'", 'course_modules.id'); $sql = <<<SQL SELECT {$concat} as uniqueid, groups.id, course_modules.id AS coursemoduleid, groups.name, COALESCE(coursemodulesettingsgroups.display, coursesettingsgroups.display, 1) AS display FROM {groups} groups INNER JOIN {course_modules} course_modules ON course_modules.course = groups.courseid /* Get course default if it's there */ /* There can only be one config setting at course level per group, so this is unique */ LEFT JOIN {block_ajax_marking} coursesettings ON coursesettings.tablename = 'course' AND coursesettings.instanceid = groups.courseid AND coursesettings.userid = :courseuserid LEFT JOIN {block_ajax_marking_groups} coursesettingsgroups ON coursesettingsgroups.groupid = groups.id AND coursesettings.id = coursesettingsgroups.configid /* Get coursemodule setting if it's there */ LEFT JOIN {block_ajax_marking} coursemodulesettings ON coursemodulesettings.tablename = 'course_modules' AND coursemodulesettings.instanceid = course_modules.id AND coursemodulesettings.userid = :coursemoduleuserid LEFT JOIN {block_ajax_marking_groups} coursemodulesettingsgroups ON coursemodulesettingsgroups.groupid = groups.id AND coursemodulesettings.id = coursemodulesettingsgroups.configid WHERE course_modules.id {$cmsql} SQL; $params['coursemoduleuserid'] = $USER->id; $params['courseuserid'] = $USER->id; $groups = $DB->get_records_sql($sql, $params); foreach ($groups as $group) { unset($group->uniqueid); // Cast to integers so we can do strict type checking in javascript. $group->id = (int)$group->id; $group->coursemoduleid = (int)$group->coursemoduleid; $group->display = (int)$group->display; if (!isset($nodes[$group->coursemoduleid]->groups)) { $nodes[$group->coursemoduleid]->groups = array(); } $nodes[$group->coursemoduleid]->groups[$group->id] = $group; } } return $nodes; } /** * Gets an array of queries, one for each module, which when UNION ALLed will provide * all marking from across the site. This will get us the counts for each * module. Implode separate subqueries with UNION ALL. Must use ALL to cope with duplicate * rows with same counts and ids across the UNION. Doing it this way keeps the other items * needing to be placed into the SELECT out of the way of the GROUP BY bit, which makes * Oracle bork up. * * @static * @param $filters * @return array */ private static function get_module_queries_array($filters) { global $DB; // If not a union query, we will want to remember which module we are narrowed down to so we // can apply the postprocessing hook later. $modulequeries = array(); $moduleid = false; $moduleclasses = block_ajax_marking_get_module_classes(); if (!$moduleclasses) { return array(); // No nodes. } $havecoursemodulefilter = array_key_exists('coursemoduleid', $filters) && $filters['coursemoduleid'] !== 'nextnodefilter'; // If one of the filters is coursemodule, then we want to avoid querying all of the module // tables and just stick to the one with that coursemodule. If not, we do a UNION of all // the modules. if ($havecoursemodulefilter) { // Get the right module id. $moduleid = $DB->get_field('course_modules', 'module', array('id' => $filters['coursemoduleid'])); } foreach ($moduleclasses as $modname => $moduleclass) { /* @var $moduleclass block_ajax_marking_module_base */ if ($moduleid && $moduleclass->get_module_id() !== $moduleid) { // We don't want this one as we're filtering by a single coursemodule. continue; } $query = self::get_unmarked_module_query($filters, $moduleclass); // A very small (currently only quiz question id) number of filters need to be applied // at moduleunion level. if ($havecoursemodulefilter) { foreach (array_keys($filters) as $filter) { if (!in_array($filter, array('courseid', 'coursemoduleid'))) { // Save a filesystem lookup. self::add_query_filter($query, $filter, 'attach_moduleunion', null, $modname); } } } $modulequeries[$modname] = $query; if ($moduleid) { break; // No need to carry on once we've got the only one we need. } } return $modulequeries; } /** * Wraps the array of moduleunion queries in an outer one that will group the submissions * into nodes with counts. We want the bare minimum here. The idea is to avoid problems with * GROUP BY ambiguity, so we just get the counts as well as the node ids. * * @static * @param $modulequeries * @param $filters * @return \block_ajax_marking_query_base */ private static function get_count_wrapper_query($modulequeries, $filters) { $havecoursemodulefilter = array_key_exists('coursemoduleid', $filters); $modulename = null; if (!empty($filters['coursemoduleid']) && is_numeric($filters['coursemoduleid'])) { $moduleobject = self::get_module_object_from_cmid($filters['coursemoduleid']); if ($moduleobject) { $modulename = $moduleobject->get_module_name(); } } $nextnodefilter = block_ajax_marking_get_nextnodefilter_from_params($filters); $makingcoursemodulenodes = ($nextnodefilter === 'coursemoduleid'); $countwrapperquery = new block_ajax_marking_query_base(); $countwrapperquery->set_column('courseid', 'moduleunion.course'); $countwrapperquery->set_column('coursemoduleid', 'moduleunion.coursemoduleid'); $countwrapperquery->set_column('userid', 'moduleunion.userid'); // We find out how many submissions we have here. Not DISTINCT as we are grouping by // nextnodefilter in the superquery. if ($havecoursemodulefilter || $makingcoursemodulenodes) { // Needed to access the correct javascript so we can open the correct popup, so // we include the name of the module. $countwrapperquery->add_select(array('table' => 'moduleunion', 'column' => 'modulename')); } // We want all nodes to have an oldest piece of work timestamp for background colours. $countwrapperquery->add_select(array('table' => 'moduleunion', 'column' => 'timestamp', 'function' => 'MAX', 'alias' => 'timestamp')); $countwrapperquery->add_from(array('table' => $modulequeries, 'alias' => 'moduleunion', 'union' => true, 'subquery' => true)); // Add the counts - total, recent, medium and overdue. self::add_query_filter($countwrapperquery, 'core', 'counts_countwrapper'); // Add the groupid so we can check the settings. if (self::filters_need_cohort_id($filters)) { self::add_query_filter($countwrapperquery, 'cohortid', 'attach_highest'); } // Add the groupid stuff. This is expensive, so we don't add this to each module query. It also // uses a lot of tables, so if we duplicated it a lot of times, there's a risk of hitting the table // join limit. self::add_query_filter($countwrapperquery, 'groupid', 'attach_highest'); // Apply the node decorators to the query, depending on what nodes are being asked for. reset($filters); foreach ($filters as $filtername => $filtervalue) { // Current nodes need to be grouped by this filter. if ($filtervalue === 'nextnodefilter') { // This will attach an id to the query, to either be retrieved directly from the moduleunion, // or added via a join of some sort. self::add_query_filter($countwrapperquery, $filtername, 'attach_countwrapper', null, $modulename); self::add_query_filter($countwrapperquery, $filtername, 'select_config_display_countwrapper'); } else { // The rest of the filters are all of the same sort. self::add_query_filter($countwrapperquery, $filtername, 'ancestor', $filtervalue, $modulename); } } return $countwrapperquery; } /** * If we need the cohort id, then it has to ba attached. This will eventually be non-optional because * the user may have configured some cohorts to be hidden, so we will always need to cross reference * with the settings. * * @static * @param array $filters * @return bool */ private static function filters_need_cohort_id(array $filters) { if (array_key_exists('cohortid', $filters)) { return true; } return false; } /** * Finds the file with the right filter (decorator) class in it and wraps the query object in it if possible. * Might be a filter provided by a module, so we need to check in the right place first if so in order * that the modules can always override any core filters. Occasionally, we use the return value to know * whether related filters need to be attached. * * @param block_ajax_marking_query $query * @param string $filterid e.g. courseid, groupid * @param string $type Name of the class within the folder for that id * @param int|string|null $parameter * @param string|null $modulename * @return bool */ private static function add_query_filter(block_ajax_marking_query &$query, $filterid, $type, $parameter = null, $modulename = null) { global $CFG; $placestotry = array(); // Module specific location. Try this first. We can't be sure that a module will // actually provide an override. if (!empty($modulename) && $modulename !== 'nextnodefilter') { $filename = $CFG->dirroot.'/blocks/ajax_marking/modules/'.$modulename.'/filters/'. $filterid.'/'.$type.'.class.php'; $classname = 'block_ajax_marking_'.$modulename.'_filter_'.$filterid.'_'.$type; $placestotry[$filename] = $classname; } // Core filter location. $filename = $CFG->dirroot.'/blocks/ajax_marking/filters/'.$filterid.'/'.$type.'.class.php'; $classname = 'block_ajax_marking_filter_'.$filterid.'_'.$type; $placestotry[$filename] = $classname; foreach ($placestotry as $filename => $classname) { if (file_exists($filename)) { require_once($filename); if (class_exists($classname)) { $query = new $classname($query, $parameter); return true; } } } return false; } /** * Wraps the countwrapper query so that a join can be done to the table(s) that hold the name * and other text fields which provide data for the node labels. We can't put the text * fields into the countwrapper because Oracle won't have any of it. * * @static * @param $countwrapperquery * @param $filters * @return block_ajax_marking_query_base */ private static function get_display_query($countwrapperquery, $filters) { // The outermost query just joins the already counted nodes with their display data e.g. we // already have a count for each courseid, now we want course name and course description // but we don't do this in the counting bit so as to avoid weird issues with group by on // Oracle. $displayquery = new block_ajax_marking_query_base(); $modulename = self::get_module_name_from_filters($filters); $nextnodefilter = block_ajax_marking_get_nextnodefilter_from_params($filters); $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'id', 'alias' => $nextnodefilter)); $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'itemcount')); $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'timestamp')); $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'recentcount')); $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'mediumcount')); $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'overduecount')); $havecoursemodulefilter = array_key_exists('coursemoduleid', $filters); if ($havecoursemodulefilter) { // Need to have this pass through in case we have a mixture. $displayquery->add_select(array( 'table' => 'countwrapperquery', 'column' => 'modulename')); } $displayquery->add_from(array( 'table' => $countwrapperquery, 'alias' => 'countwrapperquery', 'subquery' => true)); reset($filters); foreach ($filters as $filtername => $filtervalue) { if ($filtervalue === 'nextnodefilter') { // This will attach an id to the query, to either be retrieved directly from the moduleunion, // or added via a join of some sort. self::add_query_filter($displayquery, $filtername, 'current', null, $modulename); // If this one needs it, we add the decorator that gets the config settings. // TODO this is not a very elegant way of determining this. // Currently, we use the same wrapper for the display query, no matter what the mechanism // for getting the settings into the countwrapper query is, because they will just have standard // aliases. We don't always need it though. if (in_array($filtername, array('courseid', 'coursemoduleid'))) { self::add_query_filter($displayquery, 'core', 'select_config_display_displayquery'); } } } return $displayquery; } /** * If there is a coursemodule in the filters, get the name of the associated module so we know what class to use. * * @static * @param $filters * @return array|null|string */ private static function get_module_name_from_filters($filters) { $modulename = null; if (!empty($filters['coursemoduleid']) && is_numeric($filters['coursemoduleid'])) { $moduleobject = self::get_module_object_from_cmid($filters['coursemoduleid']); if ($moduleobject) { $modulename = $moduleobject->get_module_name(); } } return $modulename; } /** * If we have a coursemoduleid, we want to be able to get the module object that corresponds * to it * * @static * @param int $coursemoduleid * @return block_ajax_marking_module_base|bool */ private static function get_module_object_from_cmid($coursemoduleid) { global $DB; $moduleclasses = block_ajax_marking_get_module_classes(); $moduleid = $DB->get_field('course_modules', 'module', array('id' => $coursemoduleid)); foreach ($moduleclasses as $moduleclass) { /* @var $moduleclass block_ajax_marking_module_base */ if ($moduleclass->get_module_id() == $moduleid) { // We don't want this one as we're filtering by a single coursemodule. return $moduleclass; } } return false; } /** * Called from ajax_node_count.php and returns the counts for a specific node so we can update * it in the tree when groups display stuff is changed and it is not expanded. * * We don't need a group by, just a where that's specific to the node, and a count. * * @param array $filters * @return array * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public static function get_count_for_single_node($filters) { // New approach... // Re-do the filters so that whatever the current filter is, it gets used to group the nodes again. // e.g. click on a course and nextnodefilter will normally be the next level down, but we are going to ask // for a course grouping whilst also having courseid = 2 so course is used for both current and ancestor // decorators. // TODO this will wipe out the existing value via the same array key being used. Needs a unit test. $filters[$filters['currentfilter']] = 'nextnodefilter'; // Get nodes using unmarked nodes function. $nodes = self::unmarked_nodes($filters); // Pop the only one off the end. $node = array_pop($nodes); // Single node object. return array('recentcount' => $node->recentcount, 'mediumcount' => $node->mediumcount, 'overduecount' => $node->overduecount, 'itemcount' => $node->itemcount); } }
orvsd-skol/moodle25
blocks/ajax_marking/classes/nodes_builder_base.class.php
PHP
gpl-3.0
48,650
/* * types.hpp */ #ifndef _TYPES_HPP #define _TYPES_HPP namespace fbi { namespace network { typedef boost::shared_ptr<string> ChatMessage; typedef deque<ChatMessage> ChatMessageQueue; } } #endif
yeahunterteam/Fbi
src/network/types.hpp
C++
gpl-3.0
207
Bitrix 16.5 Business Demo = f019cf17026f7fafdf5b17ba7334c6fb
gohdan/DFC
known_files/hashes/bitrix/modules/calendar/prolog.php
PHP
gpl-3.0
61
using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Newtonsoft.Json; namespace StackWarden.Core.Serialization { public class PrivateMemberContractResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var members = properties.Cast<MemberInfo>() .Union(fields.Cast<MemberInfo>()) .Where(x => !x.Name.Contains("__BackingField")) .Select(x => { var createdProperty = CreateProperty(x, memberSerialization); createdProperty.Writable = true; createdProperty.Readable = true; return createdProperty; }) .ToList(); return members; } //protected override List<MemberInfo> GetSerializableMembers(Type objectType) //{ // var inheritedMembers = new List<MemberInfo>(base.GetSerializableMembers(objectType)); // var nonPublicFields = objectType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField); // var nonPublicProperties = objectType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetProperty); // var result = inheritedMembers.Concat(nonPublicFields) // .Concat(nonPublicProperties) // .Distinct() // .Select(x => base.CreateProperty(x, Newtonsoft.Json.MemberSerialization)) // .ToList(); // foreach (var currentItem in result) // { // currentItem. // } // return result; //} } }
Neurosion/StackWarden
src/StackWarden.Core/Serialization/PrivateMemberContractResolver.cs
C#
gpl-3.0
2,370
<?php /* HCSF - A multilingual CMS and Shopsystem Copyright (C) 2014 Marcus Haase - mail@marcus.haase.name This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace HaaseIT\HCSF\Controller\Shop; use Zend\ServiceManager\ServiceManager; /** * Class Base * @package HaaseIT\HCSF\Controller\Shop */ class Base extends \HaaseIT\HCSF\Controller\Base { /** * @var \HaaseIT\HCSF\Customer\Helper */ protected $helperCustomer; /** * @var \HaaseIT\HCSF\Shop\Helper */ protected $helperShop; /** * Base constructor. * @param ServiceManager $serviceManager */ public function __construct(ServiceManager $serviceManager) { parent::__construct($serviceManager); $this->requireModuleShop = true; $this->helperCustomer = $serviceManager->get('helpercustomer'); $this->helperShop = $serviceManager->get('helpershop'); } }
HaaseIT/HCSF
src/Controller/Shop/Base.php
PHP
gpl-3.0
1,531
import { connect } from "react-redux" import { RoadmapPage } from "../components/roadmap-page/roadmap-page" const getActiveRoadmap = (roadmaps: any[], activeRoadmapId: number) => { return roadmaps[activeRoadmapId] } const mapStateToProps = (state: any, ownProps: any) => { return { roadmap: getActiveRoadmap(state.roadmaps, ownProps.params.id) } } export const ActiveRoadmapPage = connect( mapStateToProps )(RoadmapPage)
conan007ai/roadmap
client/src/containers/active-roadmap-page.tsx
TypeScript
gpl-3.0
447
package sk.hackcraft.artificialwars.computersim.toolchain; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import sk.epholl.artificialwars.entities.instructionsets.EPH32InstructionSet; import sk.epholl.artificialwars.entities.instructionsets.EPH32InstructionSet.EPH32MemoryAddressing; import sk.hackcraft.artificialwars.computersim.Endianness; public class AssemblerEPH32 extends AbstractAssembler { private final int programSegmentStart, dataSegmentStart; private final int programMemorySize, dataMemorySize; public AssemblerEPH32(int programSegmentStart, int dataSegmentStart, int programMemorySize, int dataMemorySize) { super(EPH32InstructionSet.getInstance(), Endianness.BIG, ".segment", "(.+):"); this.programSegmentStart = programSegmentStart; this.dataSegmentStart = dataSegmentStart; this.programMemorySize = programMemorySize; this.dataMemorySize = dataMemorySize; // TODO vyhodit ak to nebude potrebne addSegmentIdentifier(Segment.PROGRAM, "program"); addSegmentIdentifier(Segment.DATA, "data"); addMemoryAddressingFormat(EPH32MemoryAddressing.IMPLIED, ""); addMemoryAddressingFormat(EPH32MemoryAddressing.IMMEDIATE, "%"); LabelType labelType = new LabelType() { @Override public int getOperandsBitsSize() { return EPH32InstructionSet.WORD_BYTES_SIZE; } @Override public int getOperandValue(int labelAddress, int programCounterAddress) { return labelAddress; } }; enableLabels("jmp", labelType); enableLabels("jmpz", labelType); enableLabels("jmpc", labelType); enableLabels("jmpm", labelType); enableLabels("jmpl", labelType); addValueParser((value) -> { return Integer.decode(value); }); addVariableType("int", Integer.BYTES); } @Override protected AssemblerState started() { AssemblerState state = super.started(); state.setSegmentStartAddress(Segment.PROGRAM, programSegmentStart); state.setSegmentStartAddress(Segment.DATA, dataSegmentStart); return state; } @Override protected void linkTogether(AssemblerState state, OutputStream output) throws CodeProcessor.CodeProcessException, IOException { byte program[] = state.getSegmentBytes(Segment.PROGRAM); byte data[] = state.getSegmentBytes(Segment.DATA); // TODO int programWordLength = program.length / EPH32InstructionSet.WORD_BYTES_SIZE; if (program.length / Integer.BYTES / 2 > programMemorySize) { throw new CodeProcessException(-1, "Program size is bigger than available program memory."); } if (data.length / Integer.BYTES > programMemorySize) { throw new CodeProcessException(-1, "Data size is bigger than available data memory."); } DataOutputStream dataOutput = new DataOutputStream(output); dataOutput.writeInt(program.length); dataOutput.writeInt(data.length); dataOutput.write(program); dataOutput.write(data); } }
Moergil/ArtificialWars
src/sk/hackcraft/artificialwars/computersim/toolchain/AssemblerEPH32.java
Java
gpl-3.0
2,925
/* * Copyright (C) 2014 Christophe Chapuis <chris.chapuis@gmail.com> * Copyright (C) 2013 Simon Busch <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QFile> #include <QDebug> #include <json-c/json.h> #include "applicationdescription.h" namespace luna { ApplicationDescription::ApplicationDescription() : ApplicationDescriptionBase(), mTrustScope(ApplicationDescription::TrustScopeSystem) { } ApplicationDescription::ApplicationDescription(const ApplicationDescription& other) : ApplicationDescriptionBase(other), mApplicationBasePath(other.basePath()), mTrustScope(other.trustScope()), mUseLuneOSStyle(other.useLuneOSStyle()), mUseWebEngine(other.useWebEngine()) { } ApplicationDescription::ApplicationDescription(const QString &data, const QString &applicationBasePath) : ApplicationDescriptionBase(), mApplicationBasePath(applicationBasePath), mTrustScope(ApplicationDescription::TrustScopeSystem), mUseLuneOSStyle(false), mUseWebEngine(false) { initializeFromData(data); } ApplicationDescription::~ApplicationDescription() { } void ApplicationDescription::initializeFromData(const QString &data) { struct json_object* root = json_tokener_parse( data.toUtf8().constData() ); if(!root) { qWarning() << "Failed to parse application description"; return; } fromJsonObject(root); struct json_object* label = json_object_object_get(root,"useLuneOSStyle"); if (label) { mUseLuneOSStyle = json_object_get_boolean(label); } label = json_object_object_get(root,"useWebEngine"); if (label) { mUseWebEngine = json_object_get_boolean(label); } if(root) json_object_put(root); } QUrl ApplicationDescription::locateEntryPoint(const QString &entryPoint) const { QUrl entryPointAsUrl(entryPoint); if (entryPointAsUrl.scheme() == "file" || entryPointAsUrl.scheme() == "http" || entryPointAsUrl.scheme() == "https") return entryPointAsUrl; if (entryPointAsUrl.scheme() != "") { qWarning("Entry point %s for application %s is invalid", entryPoint.toUtf8().constData(), getId().toUtf8().constData()); return QUrl(""); } return QUrl(QString("file://%1/%2").arg(mApplicationBasePath).arg(entryPoint)); } bool ApplicationDescription::hasRemoteEntryPoint() const { return getEntryPoint().scheme() == "http" || getEntryPoint().scheme() == "https"; } QString ApplicationDescription::getId() const { return QString::fromStdString(id()); } QString ApplicationDescription::getTitle() const { return QString::fromStdString(title()); } QUrl ApplicationDescription::getIcon() const { QString iconPath = QString::fromStdString(icon()); // we're only allow locally stored icons so we must prefix them with file:// to // store it in a QUrl object if (!iconPath.startsWith("file://")) iconPath.prepend("file://"); QUrl lIcon(iconPath); if (lIcon.isEmpty() || !lIcon.isLocalFile() || !QFile::exists(lIcon.toLocalFile())) lIcon = QUrl("qrc:///qml/images/default-app-icon.png"); return lIcon; } QUrl ApplicationDescription::getEntryPoint() const { return locateEntryPoint(QString::fromStdString(entryPoint())); } ApplicationDescription::TrustScope ApplicationDescription::trustScope() const { return mTrustScope; } QString ApplicationDescription::basePath() const { return mApplicationBasePath; } QString ApplicationDescription::getPluginName() const { return QString::fromStdString(pluginName()); } QStringList ApplicationDescription::getUrlsAllowed() const { QStringList mQStringList; std::list<std::string>::const_iterator constIterator; for (constIterator = urlsAllowed().begin(); constIterator != urlsAllowed().end(); ++constIterator) { mQStringList << QString::fromStdString(*constIterator); } return mQStringList; } QString ApplicationDescription::getUserAgent() const { return QString::fromStdString(userAgent()); } bool ApplicationDescription::useLuneOSStyle() const { return mUseLuneOSStyle; } bool ApplicationDescription::useWebEngine() const { return mUseWebEngine; } }
webOS-ports/luna-qml-launcher
src/applicationdescription.cpp
C++
gpl-3.0
4,946
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function _videoplayerApp(uiaId) { log.debug("Constructor called."); // Base application functionality is provided in a common location via this call to baseApp.init(). // See framework/js/BaseApp.js for details. baseApp.init(this, uiaId); } // load jQuery Globally (if needed) if (!window.jQuery) { utility.loadScript("addon-common/jquery.min.js"); } /********************************* * App Init is standard function * * called by framework * *********************************/ /* * Called just after the app is instantiated by framework. * All variables local to this app should be declared in this function */ _videoplayerApp.prototype.appInit = function() { log.debug("_videoplayerApp appInit called..."); // These values need to persist through videoplayer instances this.hold = false; this.resumePlay = 0; this.musicIsPaused = false; this.savedVideoList = null; this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null; //this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0; //Context table //@formatter:off this._contextTable = { "Start": { // initial context must be called "Start" "sbName": "Video Player", "template": "VideoPlayerTmplt", "templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates "readyFunction": this._StartContextReady.bind(this), "contextOutFunction": this._StartContextOut.bind(this), "noLongerDisplayedFunction": this._noLongerDisplayed.bind(this) } // end of "VideoPlayer" }; // end of this.contextTable object //@formatter:on //@formatter:off this._messageTable = { // haven't yet been able to receive messages from MMUI }; //@formatter:on framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP"; }; /** * ========================= * CONTEXT CALLBACKS * ========================= */ _videoplayerApp.prototype._StartContextReady = function() { framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png"); }; _videoplayerApp.prototype._StartContextOut = function() { CloseVideoFrame(); framework.common.setSbName(''); }; _videoplayerApp.prototype._noLongerDisplayed = function() { // Stop and close video frame CloseVideoFrame(); // If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) { this.resumePlay = this.resumePlay || CurrentVideoPlayTime; CurrentVideoPlayTime = 0; //localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime)); } // If we press the 'Entertainment' button we will be running this in the 'usbaudio' context if (!this.musicIsPaused) { setTimeout(function() { if (framework.getCurrentApp() === 'usbaudio') { framework.sendEventToMmui('Common', 'Global.Pause'); framework.sendEventToMmui('Common', 'Global.GoBack'); this.musicIsPaused = true; // Only run this once } }, 100); } }; /** * ========================= * Framework register * Tell framework this .js file has finished loading * ========================= */ framework.registerAppLoaded("_videoplayer", null, false);
Trevelopment/MZD-AIO-TI-X
app/files/tweaks/config/videoplayer/jci/gui/apps/_videoplayer/js/_videoplayerApp.js
JavaScript
gpl-3.0
3,832
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ baseClassName, colorClassName, underlineClassName, italicClassName, props.className, ], className = arrayToClassName( classes ), getRouterLink = () => ( <LocationProvider history={ router.appHistory }> <Link to={ props.url } className={ className } > { props.children } </Link> </LocationProvider> ), getExternalLink = () => ( <a href={ props.url } target={ props.target } rel={ props.rel } className={ className } > { props.children } </a> ); return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink(); } InlineLink.propTypes = { className: PropTypes.string, children: PropTypes.string, url: PropTypes.string, target: PropTypes.string, rel: PropTypes.string, text: PropTypes.string, color: PropTypes.oneOf( [ 'primary', 'secondary', 'cta', 'link', 'disabled' ] ), underline: PropTypes.oneOf( [ 'none', 'hover', 'always' ] ), italic: PropTypes.bool, }; InlineLink.defaultProps = { className: '', color: 'link', underline: 'always', target: '_blank', rel: 'noopener noreferrer', };
ramiy/elementor
core/app/assets/js/ui/molecules/inline-link.js
JavaScript
gpl-3.0
1,644
/// <reference path="windowbutton/battlelog.windowbutton.js" /> /// <reference path="playbar/battlelog.bf3.playbar.js" /> /// <reference path="dialog/battlelog.bf3.dialog.js" /> /// <reference path="stats/battlelog.bf3.stats.js" /> var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'; function injectOnce() { if (document.getElementById('_windowbutton') == null) { injectScript('_windowbutton', baseurl+'/windowbutton/battlelog.windowbutton.min.js'); } if (document.getElementById('css_windowbutton') == null) { injectCSS('css_windowbutton', baseurl + '/windowbutton/battlelog.windowbutton.min.css'); } if (document.getElementById('css_misc') == null) { injectCSS('css_misc', baseurl + '/misc/battlelog.misc.min.css'); } if (document.getElementById('_battlelogplaybar') == null) { injectScript('_battlelogplaybar', baseurl + '/playbar/battlelog.mohw.playbar.min.js'); } if (document.getElementById('_battlelogstats') == null) { injectScript('_battlelogstats', baseurl + '/stats/battlelog.mohw.stats.min.js'); } if (document.getElementById('_battlelogsettings') == null) { injectScript('_battlelogsettings', baseurl + '/settings/battlelog.mohw.settings.min.js'); } } function runCustomJS() { try { battlelogplaybar.fixQuickMatchButtons(); windowbutton.addWindowButtons(); windowbutton.updateMaximizeButton(); battlelogplaybar.fixEAPlaybarButtons(); battlelogplaybar.addPlaybarButton(battlelogplaybar.createPlaybarButton('btnServers', 'SERVERS', 'location.href = "http://battlelog.battlefield.com/mohw/servers/"')); $("#base-header-secondary-nav>ul>li>a:contains('Buy Battlefield 4')").remove(); } catch (error) { } if (window.location.href.match(/\/soldier\//) != null) { battlelogstats.overview(); } if (window.location.href == 'http://battlelog.battlefield.com/mohw/profile/edit/') { battlelogsettings.addSettingsSection(); } } function injectScript(id, url) { var script = document.createElement('script'); script.setAttribute('src', url); script.setAttribute('id', id); document.getElementsByTagName('head')[0].appendChild(script); } function injectCSS(id, url) { var script = document.createElement('link'); script.setAttribute('rel', 'stylesheet'); script.setAttribute('type', 'text/css'); script.setAttribute('href', url); script.setAttribute('id', id); document.getElementsByTagName('head')[0].appendChild(script); } injectOnce();
Battlelogium/Battlelogium
Battlelogium.Core/Javascript/battlelog.mohw.inject.js
JavaScript
gpl-3.0
2,616
package com.headbangers.epsilon.v3.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import java.util.Date; @JsonIgnoreProperties({"class"}) public class Wish implements Serializable { @JsonProperty("id") private String id; @JsonProperty("name") private String name; @JsonProperty("description") private String description; @JsonProperty("price") private Double price; @JsonProperty("webShopUrl") private String webShopUrl; @JsonProperty("thumbnailUrl") private String thumbnailUrl; @JsonProperty("bought") private Boolean bought; @JsonProperty("boughtDate") private Date boughtDate; @JsonProperty("previsionBuy") private Date previsionBuy; @JsonProperty("account") private String account; @JsonProperty("category") private String category; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getWebShopUrl() { return webShopUrl; } public void setWebShopUrl(String webShopUrl) { this.webShopUrl = webShopUrl; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public Boolean getBought() { return bought; } public void setBought(Boolean bought) { this.bought = bought; } public Date getBoughtDate() { return boughtDate; } public void setBoughtDate(Date boughtDate) { this.boughtDate = boughtDate; } public Date getPrevisionBuy() { return previsionBuy; } public void setPrevisionBuy(Date previsionBuy) { this.previsionBuy = previsionBuy; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getPrevisionBuyFormated() { if (previsionBuy != null) { return Account.sdf.format(this.previsionBuy); } return "n/a"; } }
cbrouillard/epsilon-mobile
epsilon/src/main/java/com/headbangers/epsilon/v3/model/Wish.java
Java
gpl-3.0
2,798
package model import "time" type User struct { Id int64 `json:"-"` Email string `json:"email,omitempty"` PasswordHash string `json:"-"` Active bool `json:"active,omitempty"` UpdateToken string `json:"update_token,omitempty"` NotificationEnabled bool `json:"notification_enabled"` Timestamp time.Time `json:"timestamp,omitempty"` SubscriptionId *string `json:"subscription_id,omitempty"` }
syncloud/redirect
backend/model/user.go
GO
gpl-3.0
498
# Copyright 2016 Sam Parkinson <sam@sam.today> # # This file is part of Something for Reddit. # # Something for Reddit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Something for Reddit is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Something for Reddit. If not, see <http://www.gnu.org/licenses/>. import re import sys from argparse import ArgumentParser from gi.repository import Gtk from gi.repository import Gdk from gi.repository import Gio from gi.repository import GLib from gi.repository import Soup from redditisgtk.sublist import SubList from redditisgtk.subentry import SubEntry from redditisgtk.api import RedditAPI, APIFactory from redditisgtk.webviews import (FullscreenableWebview, ProgressContainer, WebviewToolbar) from redditisgtk.readcontroller import get_read_controller from redditisgtk.identity import IdentityController from redditisgtk.identitybutton import IdentityButton from redditisgtk.comments import CommentsView from redditisgtk.settings import get_settings, show_settings from redditisgtk import webviews VIEW_WEB = 0 VIEW_COMMENTS = 1 class RedditWindow(Gtk.Window): def __init__( self, ic: IdentityController, api_factory: APIFactory, start_sub: str = None): Gtk.Window.__init__(self, title='Something For Reddit', icon_name='today.sam.reddit-is-gtk') self.add_events(Gdk.EventMask.KEY_PRESS_MASK) self.set_default_size(600, 600) self.set_wmclass("reddit-is-gtk", "Something For Reddit") self._ic = ic self._ic.token_changed.connect(self._token_changed_cb) self._api = None self._api_factory = api_factory settings = Gtk.Settings.get_default() screen = Gdk.Screen.get_default() css_provider = Gtk.CssProvider.get_default() if settings.props.gtk_application_prefer_dark_theme: css_provider.load_from_resource( '/today/sam/reddit-is-gtk/style.dark.css') else: css_provider.load_from_resource( '/today/sam/reddit-is-gtk/style.css') context = Gtk.StyleContext() context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) self._paned = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL) self.add(self._paned) self._paned.show() self._webview = FullscreenableWebview() self._webview_bin = ProgressContainer(self._webview) self._comments = None self._stack = Gtk.Stack() self._stack.connect('notify::visible-child', self.__stack_child_cb) self._paned.add2(self._stack) #self._paned.child_set_property(self._stack, 'shrink', True) self._stack.show() self._sublist_bin = Gtk.Box() self._paned.add1(self._sublist_bin) self._sublist_bin.show() self._sublist = None self._make_header() left = Gtk.SizeGroup(mode=Gtk.SizeGroupMode.HORIZONTAL) left.add_widget(self._left_header) left.add_widget(self._sublist_bin) self._paned.connect('notify::position', self.__notify_position_cb, self._header_paned) self._header_paned.connect('notify::position', self.__notify_position_cb, self._paned) self._token_changed_cb(self._ic) def _token_changed_cb(self, ic): api = self._api_factory.get_for_token(self._ic.active_token) if self._api != api: self.connect_api(api) def connect_api(self, api: RedditAPI): start_sub = None if start_sub is None: start_sub = get_settings()['default-sub'] if self._api is not None: # TODO: swap right panel print('Swapping', self._api, 'for', api) start_sub = self._sublist.get_uri() # FIXME: do we need to disconnect the callbacks? self._sublist.destroy() self._subentry.destroy() self._api = api self._api.request_failed.connect(self.__request_failed_cb) self._sublist = SubList(self._api, start_sub) self._sublist.new_other_pane.connect(self.__new_other_pane_cb) self._sublist_bin.add(self._sublist) #self._paned.child_set_property(self._sublist, 'shrink', True) self._sublist.show() self._subentry = SubEntry(self._api, start_sub) self._subentry.activate.connect(self.__subentry_activate_cb) self._subentry.escape_me.connect(self.__subentry_escape_me_cb) self._left_header.props.custom_title = self._subentry self._subentry.show() def __request_failed_cb(self, api, msg, info): dialog = Gtk.Dialog(use_header_bar=True) label = Gtk.Label(label=info) dialog.get_content_area().add(label) label.show() dialog.add_button('Retry', Gtk.ResponseType.ACCEPT) dialog.add_button(':shrug-shoulders:', Gtk.ResponseType.REJECT) dialog.set_default_response(Gtk.ResponseType.ACCEPT) dialog.props.transient_for = self response = dialog.run() if response == Gtk.ResponseType.ACCEPT: self._api.resend_message(msg) dialog.destroy() def do_event(self, event): if event.type != Gdk.EventType.KEY_PRESS: return if isinstance(self.get_focus(), (Gtk.TextView, Gtk.Entry)): return if event.keyval == Gdk.KEY_F6: self._subentry.focus() return True if event.keyval == Gdk.KEY_1: self._sublist.focus() return True if event.keyval == Gdk.KEY_2: self._stack.set_visible_child(self._comments) self._comments.focus() return True if event.keyval == Gdk.KEY_3: self._stack.set_visible_child(self._webview_bin) self._webview.grab_focus() return True if event.state & Gdk.ModifierType.MOD1_MASK: if event.keyval == Gdk.KEY_Left: self._webview.go_back() return True if event.keyval == Gdk.KEY_Right: self._webview.go_forward() return True def __new_other_pane_cb(self, sublist, link, comments, link_first): if self._comments is not None: self._stack.remove(self._comments) self._stack.remove(self._webview_bin) self._comments = comments if self._comments is not None: self._stack.add_titled(self._comments, 'comments', 'Comments') self._comments.show() self._stack.add_titled(self._webview_bin, 'web', 'Web') self._webview_bin.show() self._webview.show() self._paned.position = 400 # TODO: constant if link_first and link: self._stack.set_visible_child(self._webview_bin) self._webview.load_uri(link) else: self._stack.set_visible_child(self._comments) if link is not None: self._webview.load_when_visible(link) def load_uri_from_label(self, uri): is_relative = not uri.startswith('http') is_reddit = re.match('https?:\/\/(www\.|np\.)?reddit\.com\/', uri) if is_relative or is_reddit: self.goto_reddit_uri(uri) return self._stack.set_visible_child(self._webview_bin) self._webview.load_uri(uri) def __notify_position_cb(self, caller, pspec, other): other.props.position = caller.props.position def _make_header(self): self._header_paned = Gtk.Paned() self.set_titlebar(self._header_paned) self._left_header = Gtk.HeaderBar() layout = Gtk.Settings.get_default().props.gtk_decoration_layout self._left_header.set_decoration_layout(layout.split(':')[0]) self._right_header = Gtk.HeaderBar() self._right_header.set_decoration_layout(':'+layout.split(':')[1]) self._right_header.props.show_close_button = True self._header_paned.add1(self._left_header) self._header_paned.child_set_property( self._left_header, 'shrink', False) self._header_paned.add2(self._right_header) self._header_paned.child_set_property( self._right_header, 'shrink', False) self._header_paned.show_all() self._identity = IdentityButton(self._ic) self._right_header.pack_start(self._identity) self._identity.show() self._stack_switcher = Gtk.StackSwitcher(stack=self._stack) self._right_header.pack_end(self._stack_switcher) self._stack_switcher.show() self._webview_toolbar = WebviewToolbar(self._webview) self._right_header.pack_end(self._webview_toolbar) def __stack_child_cb(self, stack, pspec): self._webview_toolbar.props.visible = \ stack.props.visible_child == self._webview_bin def get_sublist(self): return self._sublist def get_comments_view(self): return self._comments def goto_sublist(self, to): ''' Public api for children: widget.get_toplevel().goto_sublist('/u/samdroid_/overview') ''' self._sublist.goto(to) self._subentry.goto(to) def goto_reddit_uri(self, uri): ''' Go to a reddit.com uri, eg. "https://www.reddit.com/r/rct" ''' for cond in ['https://', 'http://', 'www.', 'np.', 'reddit.com']: if uri.startswith(cond): uri = uri[len(cond):] # Disregard the '' before the leading / parts = uri.split('/')[1:] if len(parts) <= 3: # /u/*/*, /r/*, /r/*/*(sorting) self.goto_sublist(uri) elif parts[2] == 'comments': self.goto_sublist('/r/{}/'.format(parts[1])) cv = CommentsView(self._api, permalink=uri) cv.got_post_data.connect(self.__cv_got_post_data_cb) self.__new_other_pane_cb(None, None, cv, False) def __cv_got_post_data_cb(self, cv, post): if not post.get('is_self') and 'url' in post: self.__new_other_pane_cb(None, post['url'], cv, True) def __subentry_activate_cb(self, entry, sub): self._sublist.goto(sub) self._sublist.focus() def __subentry_escape_me_cb(self, entry): self._sublist.focus() class Application(Gtk.Application): def __init__(self, ic: IdentityController, api_factory: APIFactory): Gtk.Application.__init__(self, application_id='today.sam.reddit-is-gtk') self.connect('startup', self.__do_startup_cb) GLib.set_application_name("Something For Reddit") GLib.set_prgname("reddit-is-gtk") self._w = None self._queue_uri = None self._ic = ic self._api_factory = api_factory def do_activate(self): self._w = RedditWindow(self._ic, self._api_factory) self.add_window(self._w) self._w.show() if self._queue_uri is not None: self._w.goto_reddit_uri(self._queue_uri) self._queue_uri = None def goto_reddit_uri(self, uri): if self._w is None: self._queue_uri = uri else: self._w.goto_reddit_uri(uri) # TODO: Using do_startup causes SIGSEGV for me def __do_startup_cb(self, app): actions = [('about', self.__about_cb), ('quit', self.__quit_cb), ('issues', self.__issues_cb), ('shortcuts', self.__shortcuts_cb), ('settings', self.__settings_cb)] for name, cb in actions: a = Gio.SimpleAction.new(name, None) a.connect('activate', cb) self.add_action(a) builder = Gtk.Builder.new_from_resource( '/today/sam/reddit-is-gtk/app-menu.ui') self._menu = builder.get_object('app-menu') self.props.app_menu = self._menu def __about_cb(self, action, param): about_dialog = Gtk.AboutDialog( program_name='Something for Reddit', comments=('A simple but powerful Reddit client, built for GNOME ' 'powered by Gtk+ 3.0'), license_type=Gtk.License.GPL_3_0, logo_icon_name='today.sam.reddit-is-gtk', authors=['Sam P. <sam@sam.today>'], website='https://github.com/samdroid-apps/something-for-reddit', website_label='Git Repo and Issue Tracker on GitHub', # VERSION: version='0.2.2 - “The Bugfix Release ⓇⒺⒹⓊⓍ”', transient_for=self._w, modal=True) about_dialog.present() def __issues_cb(self, action, param): webviews.open_uri_external( 'https://github.com/samdroid-apps/something-for-reddit/issues') def __quit_cb(self, action, param): self.quit() def __shortcuts_cb(self, action, param): builder = Gtk.Builder.new_from_resource( '/today/sam/reddit-is-gtk/shortcuts-window.ui') builder.get_object('window').show() def __settings_cb(self, action, param): show_settings() def run(): parser = ArgumentParser( description='Something For Reddit - a Gtk+ Reddit Client') parser.add_argument('uri', help='Reddit.com URI to open, or None', default=None, nargs='?') parser.add_argument('--dark', help='Force Gtk+ dark theme', action='store_true') args = parser.parse_args() settings = Gtk.Settings.get_default() theme = get_settings()['theme'] if theme == 'dark': settings.props.gtk_application_prefer_dark_theme = True elif theme == 'light': settings.props.gtk_application_prefer_dark_theme = False if args.dark: settings.props.gtk_application_prefer_dark_theme = True session = Soup.Session() ic = IdentityController(session) api_factory = APIFactory(session) a = Application(ic, api_factory) if args.uri is not None: a.goto_reddit_uri(args.uri) status = a.run() get_read_controller().save() sys.exit(status)
samdroid-apps/something-for-reddit
redditisgtk/main.py
Python
gpl-3.0
14,799
/**************************************************************************** ** ** Copyright (C) 2016 BogDan Vatra <bog_dan_ro@yahoo.com> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "androidqtversionfactory.h" #include "androidqtversion.h" #include "androidconstants.h" #include <qtsupport/qtsupportconstants.h> #include <utils/qtcassert.h> #include <proparser/profileevaluator.h> #include <QFileInfo> namespace Android { namespace Internal { AndroidQtVersionFactory::AndroidQtVersionFactory(QObject *parent) : QtSupport::QtVersionFactory(parent) { } bool AndroidQtVersionFactory::canRestore(const QString &type) { return type == QLatin1String(Constants::ANDROIDQT); } QtSupport::BaseQtVersion *AndroidQtVersionFactory::restore(const QString &type, const QVariantMap &data) { QTC_ASSERT(canRestore(type), return nullptr); auto v = new AndroidQtVersion; v->fromMap(data); return v; } int AndroidQtVersionFactory::priority() const { return 90; } QtSupport::BaseQtVersion *AndroidQtVersionFactory::create(const Utils::FileName &qmakePath, ProFileEvaluator *evaluator, bool isAutoDetected, const QString &autoDetectionSource) { QFileInfo fi = qmakePath.toFileInfo(); if (!fi.exists() || !fi.isExecutable() || !fi.isFile()) return nullptr; if (!evaluator->values(QLatin1String("CONFIG")).contains(QLatin1String("android")) && evaluator->value(QLatin1String("QMAKE_PLATFORM")) != QLatin1String("android")) return nullptr; if (evaluator->values(QLatin1String("CONFIG")).contains(QLatin1String("android-no-sdk"))) return nullptr; return new AndroidQtVersion(qmakePath, isAutoDetected, autoDetectionSource); } } // Internal } // Android
sailfish-sdk/sailfish-qtcreator
src/plugins/android/androidqtversionfactory.cpp
C++
gpl-3.0
2,761
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with foam-extend. If not, see <http://www.gnu.org/licenses/>. \*----------------------------------------------------------------------------*/ #include "meshRefinement.H" #include "combineFaces.H" #include "directTopoChange.H" #include "removePoints.H" // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // // Merge faces that are in-line. Foam::label Foam::meshRefinement::mergePatchFaces ( const scalar minCos, const scalar concaveCos, const labelList& patchIDs ) { // Patch face merging engine combineFaces faceCombiner(mesh_); const polyBoundaryMesh& patches = mesh_.boundaryMesh(); // Pick up all candidate cells on boundary labelHashSet boundaryCells(mesh_.nFaces()-mesh_.nInternalFaces()); forAll(patchIDs, i) { label patchI = patchIDs[i]; const polyPatch& patch = patches[patchI]; if (!patch.coupled()) { forAll(patch, i) { boundaryCells.insert(mesh_.faceOwner()[patch.start()+i]); } } } // Get all sets of faces that can be merged labelListList mergeSets ( faceCombiner.getMergeSets ( minCos, concaveCos, boundaryCells ) ); label nFaceSets = returnReduce(mergeSets.size(), sumOp<label>()); Info<< "mergePatchFaces : Merging " << nFaceSets << " sets of faces." << endl; if (nFaceSets > 0) { // Topology changes container directTopoChange meshMod(mesh_); // Merge all faces of a set into the first face of the set. Remove // unused points. faceCombiner.setRefinement(mergeSets, meshMod); // Change the mesh (no inflation) autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh_, false, true); // Update fields mesh_.updateMesh(map); // Move mesh (since morphing does not do this) if (map().hasMotionPoints()) { mesh_.movePoints(map().preMotionPoints()); } else { // Delete mesh volumes. No other way to do this? mesh_.clearOut(); } if (overwrite()) { mesh_.setInstance(oldInstance()); } faceCombiner.updateMesh(map); // Get the kept faces that need to be recalculated. // Merging two boundary faces might shift the cell centre // (unless the faces are absolutely planar) labelHashSet retestFaces(6*mergeSets.size()); forAll(mergeSets, setI) { label oldMasterI = mergeSets[setI][0]; label faceI = map().reverseFaceMap()[oldMasterI]; // faceI is always uncoupled boundary face const cell& cFaces = mesh_.cells()[mesh_.faceOwner()[faceI]]; forAll(cFaces, i) { retestFaces.insert(cFaces[i]); } } updateMesh(map, retestFaces.toc()); } return nFaceSets; } // Remove points not used by any face or points used by only two faces where // the edges are in line Foam::autoPtr<Foam::mapPolyMesh> Foam::meshRefinement::mergeEdges ( const scalar minCos ) { // Point removal analysis engine removePoints pointRemover(mesh_); // Count usage of points boolList pointCanBeDeleted; label nRemove = pointRemover.countPointUsage(minCos, pointCanBeDeleted); Info<< "Removing " << nRemove << " straight edge points." << endl; autoPtr<mapPolyMesh> map; if (nRemove > 0) { // Save my local faces that will change. These changed faces might // cause a shift in the cell centre which needs to be retested. // Have to do this before changing mesh since point will be removed. labelHashSet retestOldFaces(nRemove / Pstream::nProcs()); { const faceList& faces = mesh_.faces(); forAll(faces, faceI) { const face& f = faces[faceI]; forAll(f, fp) { if (pointCanBeDeleted[f[fp]]) { retestOldFaces.insert(faceI); break; } } } } // Topology changes container directTopoChange meshMod(mesh_); pointRemover.setRefinement(pointCanBeDeleted, meshMod); // Change the mesh (no inflation) map = meshMod.changeMesh(mesh_, false, true); // Update fields mesh_.updateMesh(map); // Move mesh (since morphing does not do this) if (map().hasMotionPoints()) { mesh_.movePoints(map().preMotionPoints()); } else { // Delete mesh volumes. No other way to do this? mesh_.clearOut(); } if (overwrite()) { mesh_.setInstance(oldInstance()); } pointRemover.updateMesh(map); // Get the kept faces that need to be recalculated. labelHashSet retestFaces(6*retestOldFaces.size()); const cellList& cells = mesh_.cells(); forAllConstIter(labelHashSet, retestOldFaces, iter) { label faceI = map().reverseFaceMap()[iter.key()]; const cell& ownFaces = cells[mesh_.faceOwner()[faceI]]; forAll(ownFaces, i) { retestFaces.insert(ownFaces[i]); } if (mesh_.isInternalFace(faceI)) { const cell& neiFaces = cells[mesh_.faceNeighbour()[faceI]]; forAll(neiFaces, i) { retestFaces.insert(neiFaces[i]); } } } updateMesh(map, retestFaces.toc()); } return map; } // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/mesh/autoMesh/autoHexMesh/meshRefinement/meshRefinementMerge.C
C++
gpl-3.0
6,999
#!/usr/bin/env python """XBeeModem.py bypasses the XBee's 802.15.4 capabilities and simply uses it modem for communications You don't have to master 802.15.4 and a large set of XBee commands to make a very simple but potentially useful network. At its core, the XBee radio is a modem and you can use it directly for simple serial communications. Reference Materials: Non-blocking read from stdin in python - http://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/ Non-blocking read on a subprocess.PIPE in python - http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python Originally Created By: Jeff Irland (jeff.irland@gmail.com) in March 2013 """ # imported modules # import os # portable way of using operating system dependent functionality import sys # provides access to some variables used or maintained by the interpreter import time # provides various time-related functions # import fcntl # performs file control and I/O control on file descriptors # import serial # encapsulates the access for the serial port # import urllib from serial import Serial # from pretty import switchColor, printc # provides colored text for xterm & VT100 type terminals using ANSI escape sequences from webiopi.clients import PiHttpClient, Macro from webiopi.utils.logger import exception, setDebug, info, debug, logToFile from webiopi.utils.thread import stop VERSION = '1.0' def displayHelp(): print("Xbee command-line usage") print("xbee [-h] [-c config] [-l log] [-d] [port]") print("") print("Options:") print(" -h, --help Display this help") print(" -c, --config file Load config from file") print(" -l, --log file Log to file") print(" -d, --debug Enable DEBUG") print("") print("Arguments:") print(" port WebIOPi port") exit() def main(argv): port = 8000 configfile = None logfile = None i = 1 while i < len(argv): if argv[i] in ["-c", "-C", "--config-file"]: configfile = argv[i+1] i+=1 elif argv[i] in ["-l", "-L", "--log-file"]: logfile = argv[i+1] i+=1 elif argv[i] in ["-h", "-H", "--help"]: displayHelp() elif argv[i] in ["-d", "--debug"]: setDebug() else: try: port = int(argv[i]) except ValueError: displayHelp() i+=1 if logfile: logToFile(logfile) info("Starting XBee %s" % VERSION) # setup serial serial = Serial() serial.port = '/dev/ttyAMA0' serial.baudrate = 9600 serial.timeout = 1 serial.writeTimeout = 1 serial.open() # disregard any pending data in xbee buffer serial.flushInput() # force to show xbee boot menu time.sleep(.5) serial.writelines("\r") time.sleep(.5) # read menu while serial.inWaiting() > 0: debug("%s" % serial.readline()) # trigger bypass automatically serial.writelines("B") # post startup message to other XBee's and at stdout #serial.writelines("RPi #1 is up and running.\r\n") info("RPi #1 is up and running.") try: while True: waitToSend = True # read a line from XBee and convert it from b'xxx\r\n' to xxx and send to webiopi while serial.inWaiting() > 0: try: line = serial.readline().decode('utf-8').strip('\n\r') if line: waitToSend = False debug("Received: %s" % line) try: client = PiHttpClient("127.0.0.1") macro = Macro(client, "setCarInfo") macro.call(line.replace(",", "%2C")) except: exception("setting car info failed!") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) try: time.sleep(1.) client = PiHttpClient("127.0.0.1") macro = Macro(client, "getPitInfo") data = macro.call() if data: debug("Sending: %s" % data) serial.writelines(data + "\n") except KeyboardInterrupt: raise except Exception as e: exception(e) time.sleep(1.) except KeyboardInterrupt: info("*** Ctrl-C keyboard interrupt ***") if __name__ == "__main__": try: main(sys.argv) except Exception as e: exception(e) stop() info("RPi #1 is going down")
HelloClarice/ClariceNet
Pit/RaspberryPi/daemons/xbee.py
Python
gpl-3.0
4,184
<?php if(isset($_POST["path"]) && isset($_POST["name"]) && isset($_POST["category"]) && isset($_POST["nid"])) { $path = $_POST['path']; $name = $_POST['name']; $category = $_POST["category"]; $nid = $_POST['nid']; session_start(); $us_id = $_SESSION[$_SESSION['views'].'id']; require('../mysql.php'); $mysql = new mysql(); $mysql->connect(); $query ="SELECT f_add_newsfile('$path', '$name', '$nid', '$category', '$us_id')"; $result = $mysql->query($query); $resp = '1'; } else { $resp = '0'; } echo json_encode(array("text"=>$resp)); ?>
yasilvalmeida/gov_portal
backgp/ajax/noticia_anexo/insert.php
PHP
gpl-3.0
703
using System; using System.Collections.Generic; using System.Security; using VideoOS.Platform.DriverFramework; using VideoOS.Platform.DriverFramework.Data.Settings; using VideoOS.Platform.DriverFramework.Definitions; namespace Safecare.BeiaDeviceDriver_Light { /// <summary> /// The main entry point for the device driver. /// </summary> public class BeiaDeviceDriver_LightDriverDefinition : DriverDefinition { /// <summary> /// Create session to device, or throw exceptions if not successful /// </summary> /// <param name="uri">The URI specified by the operator when adding the device</param> /// <param name="userName">The user name specified</param> /// <param name="password">The password specified</param> /// <returns>Container representing a device</returns> protected override Container CreateContainer(Uri uri, string userName, SecureString password, ICollection<HardwareSetting> hardwareSettings) { return new BeiaDeviceDriver_LightContainer(this); } protected override DriverInfo CreateDriverInfo() { // TODO: Replace values below with values describing your driver. return new DriverInfo(Constants.DriverId, "BeiaDeviceDriver_Light", "BeiaDeviceDriver_Light group", "1.0", new[] { Constants.Product1 }); } } }
beia/beialand
projects/SAFECARE/XProtect/BeiaDeviceDriver_Light/DriverFramework/BeiaDeviceDriverDriverDefinition.cs
C#
gpl-3.0
1,389
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_lingua_finder_session'
PabloScolpino/LinguaFinder
config/initializers/session_store.rb
Ruby
gpl-3.0
145
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="pt_BR"> <context> <name>AVForm</name> <message> <source>Audio/Video</source> <translation>Áudio/Vídeo</translation> </message> <message> <source>Default resolution</source> <translation>Resolução padrão</translation> </message> <message> <source>Disabled</source> <translation>Desabilitado</translation> </message> <message> <source>Play a test sound while changing the output volume.</source> <translation>Reproduzir um som ao mudar de volume.</translation> </message> <message> <source>Use slider to set the gain of your input device ranging from %1dB to %2dB.</source> <translation>Use o controle deslizante para definir o ganho do seu dispositivo de entrada entre % 1dB e % 2dB.</translation> </message> <message> <source>Select region</source> <translation>Selecionar região</translation> </message> <message> <source>Screen %1</source> <translation>Tela %1</translation> </message> <message> <source>Audio Settings</source> <translation type="unfinished">Configurações de Áudio</translation> </message> <message> <source>Gain</source> <translation type="unfinished">Ganho</translation> </message> <message> <source>Playback device</source> <translation>Dispositivo de Reprodução</translation> </message> <message> <source>Use slider to set volume of your speakers.</source> <translation>Deslize para ajustar o volume dos auto-falantes.</translation> </message> <message> <source>Capture device</source> <translation>Dispositivo de Captura</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Video Settings</source> <translation>Configurações de Vídeo</translation> </message> <message> <source>Video device</source> <translation>Dispositivo de Vídeo</translation> </message> <message> <source>Set resolution of your camera. The higher values, the better video quality your friends may get. Note though that with better video quality there is needed better internet connection. Sometimes your connection may not be good enough to handle higher video quality, which may lead to problems with video calls.</source> <translation>Define a resolução da sua câmera. Valores mais altos fornecem uma qualidade melhor. Observe no entanto que uma qualidade de vídeo maior exige uma conexão melhor com a internet. Eventualmente sua conexão pode não ser suficiente para uma qualidade de vídeo maior, que pode acarretar em problemas nas chamadas de vídeo.</translation> </message> <message> <source>Resolution</source> <translation>Resolução</translation> </message> <message> <source>Rescan devices</source> <translation>Re-escanear dispositivos</translation> </message> <message> <source>Test Sound</source> <translation>Testar Som</translation> </message> <message> <source>Enables the experimental audio backend with echo cancelling support, needs qTox restart to take effect.</source> <translation>Habilita o backend de áudio experimental com suporte a cancelamento de eco, necessita reiniciar o qTox para ser ativado.</translation> </message> <message> <source>Enable experimental audio backend</source> <translation>Habilita backend de audio experimental</translation> </message> <message> <source>Audio quality</source> <translation>Qualidade de áudio</translation> </message> <message> <source>Transmitted audio quality. Lower this setting if your bandwidth is not high enough or if you want to lower the internet usage.</source> <translation>Qualidade de audio transmitida. Reduza essa configuração se sua largura de banda não é alta o suficiente ou se você deseja reduzir seu uso de internet. </translation> </message> <message> <source>High (64 kbps)</source> <translation>Alto (64 kbps)</translation> </message> <message> <source>Medium (32 kbps)</source> <translation>Médio (32 kbps)</translation> </message> <message> <source>Low (16 kbps)</source> <translation>Baixo (16 kbps)</translation> </message> <message> <source>Very low (8 kbps)</source> <translation>Muito baixo (8 kbps)</translation> </message> </context> <context> <name>AboutForm</name> <message> <source>About</source> <translation>Sobre</translation> </message> <message> <source>Restart qTox to install version %1</source> <translation>Reinicie o qTox para instalar a versão %1</translation> </message> <message> <source>qTox is downloading update %1</source> <comment>%1 is the version of the update</comment> <translation>qTox está baixando a atualização %1</translation> </message> <message> <source>Original author: %1</source> <translation>Autor original: %1</translation> </message> <message> <source>You are using qTox version %1.</source> <translation>Você está usando a versão %1 do qTox.</translation> </message> <message> <source>Commit hash: %1</source> <translation>Hash do commit: %1</translation> </message> <message> <source>toxcore version: %1</source> <translation>versão do toxcore: %1</translation> </message> <message> <source>Qt version: %1</source> <translation>Versão do Qt: %1</translation> </message> <message> <source>A list of all known issues may be found at our %1 at Github. If you discover a bug or security vulnerability within qTox, please report it according to the guidelines in our %2 wiki article.</source> <comment>`%1` is replaced by translation of `bug tracker` `%2` is replaced by translation of `Writing Useful Bug Reports`</comment> <translation>Uma lista de todos os problemas conhecidos pode ser encontrada no nosso % 1 no Github. Se você descobrir um bug ou vulnerabilidade de segurança no qTox, informe-o de acordo com as diretrizes em nosso artigo wiki % 2.</translation> </message> <message> <source>bug-tracker</source> <comment>Replaces `%1` in the `A list of all known…`</comment> <translation type="unfinished">bug-tracker</translation> </message> <message> <source>Writing Useful Bug Reports</source> <comment>Replaces `%2` in the `A list of all known…`</comment> <translation type="unfinished">Escrevendo reportagem de bug útil</translation> </message> <message> <source>Click here to report a bug.</source> <translation>Clique aqui para comunicar um bug.</translation> </message> <message> <source>See a full list of %1 at Github</source> <comment>`%1` is replaced with translation of word `contributors`</comment> <translation type="unfinished">Veja uma lista completa de %1 no Github</translation> </message> <message> <source>contributors</source> <comment>Replaces `%1` in `See a full list of…`</comment> <translation type="unfinished">contribuidores</translation> </message> </context> <context> <name>AboutFriendForm</name> <message> <source>Dialog</source> <translation type="unfinished">Diálogo</translation> </message> <message> <source>username</source> <translation type="unfinished">nome de usuário</translation> </message> <message> <source>status message</source> <translation type="unfinished">mensagem de status</translation> </message> <message> <source>Public key:</source> <translation type="unfinished">Chave pública:</translation> </message> <message> <source>Used aliases:</source> <translation type="unfinished">Alias usados:</translation> </message> <message> <source>HISTORY OF ALIASES</source> <translation type="unfinished">HISTÓRICO DE ALIASES</translation> </message> <message> <source>Automatically accept files from contact if set</source> <translation>Se marcado, aceita automaticamente arquivos do contato</translation> </message> <message> <source>Auto accept files</source> <translation type="unfinished">Aceitar arquivos automaticamente</translation> </message> <message> <source>Default directory to save files:</source> <translation type="unfinished">Diretório de arquivos salvos padrão:</translation> </message> <message> <source>Auto accept for this contact is disabled</source> <translation type="unfinished">Aceitar automaticamente desabilitado para esse contato</translation> </message> <message> <source>Auto accept call:</source> <translation type="unfinished">Aceitar chamada automaticamente:</translation> </message> <message> <source>Manual</source> <translation type="unfinished">Manual</translation> </message> <message> <source>Audio</source> <translation type="unfinished">Áudio</translation> </message> <message> <source>Audio + Video</source> <translation type="unfinished">Áudio + Vídeo</translation> </message> <message> <source>Automatically accept group chat invitations from this contact if set.</source> <translation>Se marcado, aceita automaticamente os convites de chat em grupo desse contato.</translation> </message> <message> <source>Auto accept group invites</source> <translation>Aceitar automaticamente convites de grupos</translation> </message> <message> <source>Remove history (operation can not be undone!)</source> <translation type="unfinished">Apagar histórico (Operação irreversível!)</translation> </message> <message> <source>Notes</source> <translation type="unfinished">Notas</translation> </message> <message> <source>Input field for notes about the contact</source> <translation>Campo de entrada para notas sobre o contato</translation> </message> <message> <source>You can save comment about this contact here.</source> <translation type="unfinished">Você pode salvar comentários sobre esse contato aqui.</translation> </message> <message> <source>Choose an auto accept directory</source> <comment>popup title</comment> <translation type="unfinished">Escolher um diretório para aceitar arquivos automaticamente</translation> </message> <message> <source>History removed</source> <translation type="unfinished">Histórico apagado</translation> </message> <message> <source>Chat history with %1 removed!</source> <translation type="unfinished">O histórico de conversas com %1 foi apagado!</translation> </message> </context> <context> <name>AboutSettings</name> <message> <source>Version</source> <translation>Versão</translation> </message> <message> <source>License</source> <translation>Licença</translation> </message> <message> <source>Authors</source> <translation>Autores</translation> </message> <message> <source>Known Issues</source> <translation>Problemas Conhecidos</translation> </message> <message> <source>Downloading update: %p%</source> <translation>Baixando atualização: %p%</translation> </message> </context> <context> <name>AddFriendForm</name> <message> <source>Add Friends</source> <translation>Adicionar aos Contatos</translation> </message> <message> <source>Send friend request</source> <translation>Enviar pedido de amizade</translation> </message> <message> <source>Couldn&apos;t add friend</source> <translation>Não foi possível adicionar amigo</translation> </message> <message> <source>Invalid Tox ID format</source> <translation>Formato inválido de ID Tox</translation> </message> <message> <source>Add a friend</source> <translation>Adicionar um contato</translation> </message> <message> <source>Friend requests</source> <translation>Solicitações de amizade</translation> </message> <message> <source>Accept</source> <translation>Aceitar</translation> </message> <message> <source>Reject</source> <translation>Rejeitar</translation> </message> <message> <source>Tox ID, either 76 hexadecimal characters or name@example.com</source> <translation>ID Tox, sejam os 76 caracteres hexadecimais ou nome@exemplo.com</translation> </message> <message> <source>Type in Tox ID of your friend</source> <translation>Digite o ID Tox do seu amigo</translation> </message> <message> <source>Friend request message</source> <translation>Mensagem de solicitação de amigo</translation> </message> <message> <source>Type message to send with the friend request or leave empty to send a default message</source> <translation>Digite a mensagem para enviar com a solicitação de amizade ou deixe vazio para enviar uma mensagem padrão</translation> </message> <message> <source>%1 Tox ID is invalid or does not exist</source> <comment>Toxme error</comment> <translation>% 1 Tox ID é inválido ou não existe</translation> </message> <message> <source>You can&apos;t add yourself as a friend!</source> <extracomment>When trying to add your own Tox ID as friend</extracomment> <translation type="unfinished">Você não pode adicionar a si mesmo como contato!</translation> </message> <message> <source>Open contact list</source> <translation>Abrir lista de contatos</translation> </message> <message> <source>Couldn&apos;t open file</source> <translation>Não foi possível abrir o arquivo</translation> </message> <message> <source>Couldn&apos;t open the contact file</source> <extracomment>Error message when trying to open a contact list file to import</extracomment> <translation>Não foi possível abrir o arquivo de contatos</translation> </message> <message> <source>Invalid file</source> <translation>Arquivo inválido</translation> </message> <message> <source>We couldn&apos;t find any contacts to import in this file!</source> <translation>Não foi possível encontrar nenhum contato para importar nesse arquivo!</translation> </message> <message> <source>Tox ID</source> <extracomment>Tox ID of the person you&apos;re sending a friend request to</extracomment> <translation type="unfinished">ID Tox</translation> </message> <message> <source>either 76 hexadecimal characters or name@example.com</source> <extracomment>Tox ID format description</extracomment> <translation type="unfinished">Ou 76 caracteres hexadecimais ou nome@exemplo.com</translation> </message> <message> <source>Message</source> <extracomment>The message you send in friend requests</extracomment> <translation type="unfinished">Mensagem</translation> </message> <message> <source>Open</source> <extracomment>Button to choose a file with a list of contacts to import</extracomment> <translation type="unfinished"></translation> </message> <message> <source>Send friend requests</source> <translation type="unfinished"></translation> </message> <message> <source>%1 here! Tox me maybe?</source> <extracomment>Default message in friend requests if the field is left blank. Write something appropriate!</extracomment> <translation type="unfinished">Ola, %1 aqui! Gostaria de me adicionar no Tox?</translation> </message> <message> <source>Import a list of contacts, one Tox ID per line</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <source>Ready to import %n contact(s), click send to confirm</source> <extracomment>Shows the number of contacts we&apos;re about to import from a file (at least one)</extracomment> <translation type="unfinished"> <numerusform></numerusform> <numerusform></numerusform> </translation> </message> <message> <source>Import contacts</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AdvancedForm</name> <message> <source>Advanced</source> <translation>Avançado</translation> </message> <message> <source>Unless you %1 know what you are doing, please do %2 change anything here. Changes made here may lead to problems with qTox, and even to loss of your data, e.g. history.</source> <translation>A menos que você %1 saiva o que está fazendo, por favor %2 faça alterações aqui. Mudanças podem levar a problemas com o qTox, e até perda de suas informações, como histórico.</translation> </message> <message> <source>really</source> <translation>realmente</translation> </message> <message> <source>not</source> <translation>não</translation> </message> <message> <source>IMPORTANT NOTE</source> <translation>NOTA IMPORTANTE</translation> </message> <message> <source>Reset settings</source> <translation>Redefinir configurações</translation> </message> <message> <source>All settings will be reset to default. Are you sure?</source> <translation>Todas configurações serão redefinidas para o padrão. Deseja prosseguir?</translation> </message> <message> <source>Yes</source> <translation>Sim</translation> </message> <message> <source>No</source> <translation>Não</translation> </message> <message> <source>Call active</source> <comment>popup title</comment> <translation>Chamada ativa</translation> </message> <message> <source>You can&apos;t disconnect while a call is active!</source> <comment>popup text</comment> <translation>Você não pode desconectar enquanto uma chamada estiver ativa!</translation> </message> <message> <source>Save File</source> <translation>Salvar Arquivo</translation> </message> <message> <source>Logs (*.log)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AdvancedSettings</name> <message> <source>Save settings to the working directory instead of the usual conf dir</source> <extracomment>describes makeToxPortable checkbox</extracomment> <translation>Armazena as configurações no diretório atual ao invés do diretório de configurações prédefinido</translation> </message> <message> <source>Make Tox portable</source> <translation>Deixe o Tox portável</translation> </message> <message> <source>Reset to default settings</source> <translation>Restaurar às configurações padrões</translation> </message> <message> <source>Portable</source> <translation>Portátil</translation> </message> <message> <source>Connection Settings</source> <translation>Configuraçẽs de Conexão</translation> </message> <message> <source>Enable IPv6 (recommended)</source> <extracomment>Text on a checkbox to enable IPv6</extracomment> <translation>Habilitar IPv6 (recomendado)</translation> </message> <message> <source>Disabling this allows, e.g., toxing over Tor. It adds load to the Tox network however, so uncheck only when necessary.</source> <extracomment>force tcp checkbox tooltip</extracomment> <translation>Desabilitar esta opção permite, por exemplo, utilizar a rede Tor. Ela adiciona mais dados à rede Tor no entanto, portanto desmarque apenas se necessário.</translation> </message> <message> <source>Enable UDP (recommended)</source> <extracomment>Text on checkbox to disable UDP</extracomment> <translation>Habilitar UDP (recomendado)</translation> </message> <message> <source>Proxy type:</source> <translation>Tipo de proxy:</translation> </message> <message> <source>Address:</source> <extracomment>Text on proxy addr label</extracomment> <translation>Endereço:</translation> </message> <message> <source>Port:</source> <extracomment>Text on proxy port label</extracomment> <translation>Porta:</translation> </message> <message> <source>None</source> <translation>Nenhum</translation> </message> <message> <source>SOCKS5</source> <translation>SOCKS5</translation> </message> <message> <source>HTTP</source> <translation>HTTP</translation> </message> <message> <source>Reconnect</source> <comment>reconnect button</comment> <translation>Reconectar</translation> </message> <message> <source>Debug</source> <translation type="unfinished"></translation> </message> <message> <source>Export Debug Log</source> <translation type="unfinished"></translation> </message> <message> <source>Copy Debug Log</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ChatForm</name> <message> <source>Load chat history...</source> <translation>Carregar histórico de conversas...</translation> </message> <message> <source>Send a file</source> <translation>Enviar um arquivo</translation> </message> <message> <source>qTox wasn&apos;t able to open %1</source> <translation>qTox não foi capaz de abrir %1</translation> </message> <message> <source>%1 calling</source> <translation>%1 chamando</translation> </message> <message> <source>End video call</source> <translation>Terminar chamada de vídeo</translation> </message> <message> <source>End audio call</source> <translation>Terminar chamada de áudio</translation> </message> <message> <source>Mute microphone</source> <translation>Silenciar microfone</translation> </message> <message> <source>Mute call</source> <translation>Silenciar chamada</translation> </message> <message> <source>Cancel video call</source> <translation>Cancelar chamada de vídeo</translation> </message> <message> <source>Cancel audio call</source> <translation>Cancelar chamada de áudio</translation> </message> <message> <source>Start audio call</source> <translation>Iniciar chamada de áudio</translation> </message> <message> <source>Start video call</source> <translation>Iniciar chamada de vídeo</translation> </message> <message> <source>Unmute microphone</source> <translation>Desmutar microfone</translation> </message> <message> <source>Unmute call</source> <translation>Desmutar chamada</translation> </message> <message> <source>Failed to send file &quot;%1&quot;</source> <translation>Falha ao enviar o arquivo &quot;%1&quot;</translation> </message> <message> <source>Failed to open temporary file</source> <comment>Temporary file for screenshot</comment> <translation>Não foi possível abir o arquivo temporário</translation> </message> <message> <source>qTox wasn&apos;t able to save the screenshot</source> <translation>qTox não conseguiu salvar a imagem capturada</translation> </message> <message> <source>Call with %1 ended. %2</source> <translation>Chamada para %1 terminada. %2</translation> </message> <message> <source>Call duration: </source> <translation>Duração da chamada: </translation> </message> <message> <source>Unable to open</source> <translation>Impossível abrir</translation> </message> <message> <source>Bad idea</source> <translation>Má idéia</translation> </message> <message> <source>Calling %1</source> <translation>Chamando %1</translation> </message> <message> <source>%1 is typing</source> <translation>%1 está digitando</translation> </message> <message> <source>Copy</source> <translation>Copiar</translation> </message> <message> <source>You&apos;re trying to send a sequential file, which is not going to work!</source> <translation type="unfinished"></translation> </message> <message> <source>away</source> <comment>contact status</comment> <translation type="unfinished">ausente</translation> </message> <message> <source>busy</source> <comment>contact status</comment> <translation type="unfinished">ocupado</translation> </message> <message> <source>offline</source> <comment>contact status</comment> <translation type="unfinished">offline</translation> </message> <message> <source>online</source> <comment>contact status</comment> <translation type="unfinished">online</translation> </message> <message> <source>%1 is now %2</source> <comment>e.g. &quot;Dubslow is now online&quot;</comment> <translation type="unfinished">%1 agora é %2</translation> </message> <message> <source>Can&apos;t start video call</source> <translation type="unfinished"></translation> </message> <message> <source>Can&apos;t start audio call</source> <translation type="unfinished"></translation> </message> <message> <source>Microphone can be muted only during a call</source> <translation type="unfinished"></translation> </message> <message> <source>Sound can be disabled only during a call</source> <translation type="unfinished"></translation> </message> <message> <source>Export to file</source> <translation type="unfinished"></translation> </message> <message> <source>Save chat log</source> <translation type="unfinished">Armazenar histórico da conversa</translation> </message> <message> <source>Call with %1 ended unexpectedly. %2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ChatLog</name> <message> <source>Copy</source> <translation>Copiar</translation> </message> <message> <source>Select all</source> <translatorcomment>Tudo ou todos?</translatorcomment> <translation>Selecionar tudo</translation> </message> <message> <source>pending</source> <translatorcomment>Plural? Singular?</translatorcomment> <translation>pendente</translation> </message> </context> <context> <name>ChatTextEdit</name> <message> <source>Type your message here...</source> <translation>Digite sua mensagem aqui...</translation> </message> </context> <context> <name>CircleWidget</name> <message> <source>Rename circle</source> <comment>Menu for renaming a circle</comment> <translation>Renomear círculo</translation> </message> <message> <source>Remove circle</source> <comment>Menu for removing a circle</comment> <translation>Remover círculo</translation> </message> <message> <source>Open all in new window</source> <translation>Abrir tudo em uma nova janela</translation> </message> </context> <context> <name>Core</name> <message> <source>Toxing on qTox</source> <translation>Toxing com qTox</translation> </message> <message> <source>/me offers friendship, &quot;%1&quot;</source> <translation>/me oferece contato, &quot;%1&quot;</translation> </message> <message> <source>Invalid Tox ID</source> <comment>Error while sending friendship request</comment> <translation type="unfinished"></translation> </message> <message> <source>You need to write a message with your request</source> <comment>Error while sending friendship request</comment> <translation type="unfinished">Você deve escrever uma mensagem junto do pedido</translation> </message> <message> <source>Your message is too long!</source> <comment>Error while sending friendship request</comment> <translation type="unfinished">Sua mensagem é muito longa!</translation> </message> <message> <source>Friend is already added</source> <comment>Error while sending friendship request</comment> <translation type="unfinished">Contato já adicionado</translation> </message> </context> <context> <name>FileTransferWidget</name> <message> <source>Form</source> <translation type="unfinished">Formulário</translation> </message> <message> <source>10Mb</source> <translation>10Mb</translation> </message> <message> <source>0kb/s</source> <translation>0kb/s</translation> </message> <message> <source>ETA:10:10</source> <translation>T:10:10</translation> </message> <message> <source>Filename</source> <translation>Nome do arquivo</translation> </message> <message> <source>Waiting to send...</source> <comment>file transfer widget</comment> <translation>Esperando para enviar...</translation> </message> <message> <source>Accept to receive this file</source> <comment>file transfer widget</comment> <translation>Aceite recebimento deste arquivo</translation> </message> <message> <source>Location not writable</source> <comment>Title of permissions popup</comment> <translation>Impossível gravar aqui</translation> </message> <message> <source>You do not have permission to write that location. Choose another, or cancel the save dialog.</source> <comment>text of permissions popup</comment> <translation>Você não possui permissão de escrita aqui. Escolha outro local ou cancele a operação.</translation> </message> <message> <source>Resuming...</source> <comment>file transfer widget</comment> <translation>Continuando...</translation> </message> <message> <source>Cancel transfer</source> <translation>Cancelar transferência</translation> </message> <message> <source>Pause transfer</source> <translation>Pausar transferência</translation> </message> <message> <source>Resume transfer</source> <translation>Continuar transferência</translation> </message> <message> <source>Accept transfer</source> <translation>Aceitar transferência</translation> </message> <message> <source>Save a file</source> <comment>Title of the file saving dialog</comment> <translation>Salvar arquivo</translation> </message> <message> <source>Paused</source> <comment>file transfer widget</comment> <translation>Pausado</translation> </message> <message> <source>Open file</source> <translation>Abrir arquivo</translation> </message> <message> <source>Open file directory</source> <translation>Abrir pasta do arquivo</translation> </message> </context> <context> <name>FilesForm</name> <message> <source>Downloads</source> <translation>Recebidos</translation> </message> <message> <source>Uploads</source> <translation>Enviados</translation> </message> <message> <source>Transferred Files</source> <comment>&quot;Headline&quot; of the window</comment> <translation>Transferências</translation> </message> </context> <context> <name>FriendListWidget</name> <message> <source>Today</source> <translation type="unfinished">Hoje</translation> </message> <message> <source>Yesterday</source> <translation type="unfinished">Ontem</translation> </message> <message> <source>Last 7 days</source> <translation type="unfinished">Últimos 7 dias</translation> </message> <message> <source>This month</source> <translation type="unfinished">Este mês</translation> </message> <message> <source>Older than 6 Months</source> <translation type="unfinished">Mais de 6 Meses</translation> </message> <message> <source>Never</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FriendRequestDialog</name> <message> <source>Friend request</source> <comment>Title of the window to aceept/deny a friend request</comment> <translation>Solicitação de contato</translation> </message> <message> <source>Someone wants to make friends with you</source> <translation>Alguém quer adicionar você como contato</translation> </message> <message> <source>User ID:</source> <translation>ID do usuário:</translation> </message> <message> <source>Friend request message:</source> <translation>Mensagem de requisição contato:</translation> </message> <message> <source>Accept</source> <comment>Accept a friend request</comment> <translation>Aceitar</translation> </message> <message> <source>Reject</source> <comment>Reject a friend request</comment> <translation>Rejeitar</translation> </message> </context> <context> <name>FriendWidget</name> <message> <source>Invite to group</source> <comment>Menu to invite a friend to a groupchat</comment> <translation>Convidar para grupo</translation> </message> <message> <source>Move to circle...</source> <comment>Menu to move a friend into a different circle</comment> <translation>Mover para círculo...</translation> </message> <message> <source>To new circle</source> <translation>Para um novo círculo</translation> </message> <message> <source>Remove from circle &apos;%1&apos;</source> <translation>Remover do círculo &quot;%1&quot;</translation> </message> <message> <source>Move to circle &quot;%1&quot;</source> <translation>Mover para o círculo &quot;%1&quot;</translation> </message> <message> <source>Set alias...</source> <translation>Apelido...</translation> </message> <message> <source>Auto accept files from this friend</source> <comment>context menu entry</comment> <translation>Aceitar arquivos automaticamente deste contato</translation> </message> <message> <source>Remove friend</source> <comment>Menu to remove the friend from our friendlist</comment> <translation>Remover contato</translation> </message> <message> <source>Choose an auto accept directory</source> <comment>popup title</comment> <translation>Escolher um diretório para aceitar arquivos automaticamente</translation> </message> <message> <source>New message</source> <translation>Nova mensagem</translation> </message> <message> <source>Online</source> <translation>Conectado</translation> </message> <message> <source>Away</source> <translation>Ausente</translation> </message> <message> <source>Busy</source> <translation>Ocupado</translation> </message> <message> <source>Offline</source> <translation>Desconectado</translation> </message> <message> <source>Open chat in new window</source> <translation>Abrir conversa em uma nova janela</translation> </message> <message> <source>Remove chat from this window</source> <translation>Retirar conversa desta janela</translation> </message> <message> <source>To new group</source> <translation>Para um novo grupo</translation> </message> <message> <source>Invite to group &apos;%1&apos;</source> <translation>Convidar ao grupo &apos;%1&apos;</translation> </message> <message> <source>Show details</source> <translation>Mostrar detalhes</translation> </message> </context> <context> <name>GUI</name> <message> <source>Enter your password</source> <translation>Informe sua senha</translation> </message> <message> <source>Decrypt</source> <translation>Descriptografar</translation> </message> <message> <source>You must enter a non-empty password:</source> <translation>Você deve informar uma senha:</translation> </message> </context> <context> <name>GeneralForm</name> <message> <source>General</source> <translation>Geral</translation> </message> <message> <source>Choose an auto accept directory</source> <comment>popup title</comment> <translation>Escolher um diretório para aceitar arquivos automaticamente</translation> </message> </context> <context> <name>GeneralSettings</name> <message> <source>General Settings</source> <translation>Configurações Gerais</translation> </message> <message> <source>The translation may not load until qTox restarts.</source> <translation>A tradução pode não ser atualizada antes do qTox ser reinicializado.</translation> </message> <message> <source>Show system tray icon</source> <translation>Mostrar ícone na bandeja</translation> </message> <message> <source>Enable light tray icon.</source> <comment>toolTip for light icon setting</comment> <translation>Habilitar ícone da bandeja claro.</translation> </message> <message> <source>qTox will start minimized in tray.</source> <comment>toolTip for Start in tray setting</comment> <translation>O qTox vai iniciar minimizado na bandeja.</translation> </message> <message> <source>Start in tray</source> <translation>Inicializar na bandeja</translation> </message> <message> <source>After pressing close (X) qTox will minimize to tray, instead of closing itself.</source> <comment>toolTip for close to tray setting</comment> <translation>Após clicar em fechar (X), o qTox será minimizado para a bandeja ao em vez de fechar.</translation> </message> <message> <source>Close to tray</source> <translation>Fechar para a bandeja</translation> </message> <message> <source>After pressing minimize (_) qTox will minimize itself to tray, instead of system taskbar.</source> <comment>toolTip for minimize to tray setting</comment> <translation>Após clicar em minimizar (_) o qTox será minimizado para a bandeja, ao invés da barra de tarefas.</translation> </message> <message> <source>Minimize to tray</source> <translation>Minimizar para a bandeja</translation> </message> <message> <source>Light icon</source> <translation>Ícone claro</translation> </message> <message> <source>Language:</source> <translation>Idioma:</translation> </message> <message> <source>Check for updates on startup</source> <translation>Verificar por atualizações na inicialização</translation> </message> <message> <source>Set where files will be saved.</source> <translation>Defina onde os arquivos serão salvos.</translation> </message> <message> <source>Your status is changed to Away after set period of inactivity.</source> <translation>Seu status é alterado para Ausente após o período de inatividade.</translation> </message> <message> <source>Auto away after (0 to disable):</source> <translation>Ausente após (0 para desabilitar):</translation> </message> <message> <source>Play sound</source> <translation>Tocar som</translation> </message> <message> <source>Show contacts&apos; status changes</source> <translation>Mostrar alterações no status de contatos</translation> </message> <message> <source>Faux offline messaging</source> <translation>Simular envio de mensagens &quot;offline&quot;</translation> </message> <message> <source>Set to 0 to disable</source> <translation>Defina 0 para desativar</translation> </message> <message> <source>You can set this on a per-friend basis by right clicking them.</source> <comment>autoaccept cb tooltip</comment> <translation>Você pode definir esta configuração por contato clicando com o botão direito sobre eles.</translation> </message> <message> <source>Autoaccept files</source> <translation>Aceitar arquivos automaticamente</translation> </message> <message> <source>Autostart</source> <translation>Iniciar automaticamente</translation> </message> <message> <source>On new message:</source> <translation>Ao receber uma nova mensagem:</translation> </message> <message> <source>Start qTox on operating system startup (current profile).</source> <translation>Iniciar qTox com o sistema operacional (usando atual perfil).</translation> </message> <message> <source>Default directory to save files:</source> <translation>Diretório de arquivos salvos padrão:</translation> </message> <message> <source>Play sound while Busy</source> <translation>Reproduzir som enquanto Ocupado</translation> </message> </context> <context> <name>GenericChatForm</name> <message> <source>Send message</source> <translation>Enviar mensagem</translation> </message> <message> <source>Smileys</source> <translation>Emoticons</translation> </message> <message> <source>Send file(s)</source> <translation>Enviar arquivo(s)</translation> </message> <message> <source>Save chat log</source> <translation>Armazenar histórico da conversa</translation> </message> <message> <source>Send a screenshot</source> <translation>Enviar captura de tela</translation> </message> <message> <source>Clear displayed messages</source> <translation>Remover mensagens</translation> </message> <message> <source>Not sent</source> <translation>Não enviado</translation> </message> <message> <source>Cleared</source> <translation>Removidas</translation> </message> <message> <source>Start audio call</source> <translation>Iniciar chamada de áudio</translation> </message> <message> <source>Accept audio call</source> <translation>Aceitar chamada de áudio</translation> </message> <message> <source>End audio call</source> <translation>Finalizar chamada de audio</translation> </message> <message> <source>Start video call</source> <translation>Iniciar chamada de vídeo</translation> </message> <message> <source>Accept video call</source> <translation>Aceitar chamada de vídeo</translation> </message> <message> <source>End video call</source> <translation>Finalizar chamada de vídeo</translation> </message> <message> <source>Quote selected text</source> <translation>Citar texto selecionado</translation> </message> <message> <source>Copy link address</source> <translation type="unfinished"></translation> </message> </context> <context> <name>GenericNetCamView</name> <message> <source>Tox video</source> <translation>Vídeo Tox</translation> </message> <message> <source>Show Messages</source> <translation>Mostrar mensagens</translation> </message> <message> <source>Hide Messages</source> <translation>Esconder mensagens</translation> </message> </context> <context> <name>Group</name> <message> <source>&lt;Empty&gt;</source> <comment>Placeholder when someone&apos;s name in a group chat is empty</comment> <translation>&lt;Vazio&gt;</translation> </message> </context> <context> <name>GroupChatForm</name> <message> <source>Start audio call</source> <translation>Iniciar chamada de áudio</translation> </message> <message> <source>Mute microphone</source> <translation>Silenciar microfone</translation> </message> <message> <source>Unmute microphone</source> <translation>Reativar microfone</translation> </message> <message> <source>Mute call</source> <translation>Silenciar chamada</translation> </message> <message> <source>Unmute call</source> <translation>Desmutar chamada</translation> </message> <message> <source>End audio call</source> <translation>Terminar chamada de áudio</translation> </message> <message> <source>%1 users in chat</source> <comment>Number of users in chat</comment> <translation>%1 usuários no grupo</translation> </message> <message> <source>1 user in chat</source> <comment>Number of users in chat</comment> <translation>1 usuário em chat</translation> </message> </context> <context> <name>GroupInviteForm</name> <message> <source>Groups</source> <translation>Grupos</translation> </message> <message> <source>Create new group</source> <translation>Criar um novo grupo</translation> </message> <message> <source>Group invites</source> <translation>Convites à grupos</translation> </message> </context> <context> <name>GroupInviteWidget</name> <message> <source>Invited by %1 on %2 at %3.</source> <translation type="unfinished"></translation> </message> <message> <source>Join</source> <translation type="unfinished"></translation> </message> <message> <source>Decline</source> <translation type="unfinished"></translation> </message> </context> <context> <name>GroupWidget</name> <message> <source>%1 users in chat</source> <translation>%1 usuários no grupo</translation> </message> <message> <source>Set title...</source> <translation>Defina o título...</translation> </message> <message> <source>Quit group</source> <comment>Menu to quit a groupchat</comment> <translation>Sair do grupo</translation> </message> <message> <source>Open chat in new window</source> <translation>Abrir conversa em outra janela</translation> </message> <message> <source>Remove chat from this window</source> <translation type="unfinished">Retirar conversa desta janela</translation> </message> <message> <source>1 user in chat</source> <translation type="unfinished">1 usuário em chat</translation> </message> </context> <context> <name>IdentitySettings</name> <message> <source>Public Information</source> <translation>Informações Públicas</translation> </message> <message> <source>Tox ID</source> <translation>ID Tox</translation> </message> <message> <source>This bunch of characters tells other Tox clients how to contact you. Share it with your friends to communicate.</source> <comment>Tox ID tooltip</comment> <translation>Este conjunto de caracteres informa a outros clientes Tox como contactar você. Compartilhe com seus contatos para se comunicar.</translation> </message> <message> <source>Your Tox ID (click to copy)</source> <translation>Seu ID Tox (clique para copiar)</translation> </message> <message> <source>This QR code contains your Tox ID. You may share this with your friends as well.</source> <translation>Este código QR contém seu ID Tox. Você pode compartilhá-lo com seus amigos.</translation> </message> <message> <source>Save image</source> <translation>Salvar imagem</translation> </message> <message> <source>Copy image</source> <translation>Copiar imagem</translation> </message> <message> <source>Profile</source> <translation>Perfil</translation> </message> <message> <source>Rename profile.</source> <comment>tooltip for renaming profile button</comment> <translation>Renomear perfil.</translation> </message> <message> <source>Delete profile.</source> <comment>delete profile button tooltip</comment> <translation>Remover perfil.</translation> </message> <message> <source>Go back to the login screen</source> <comment>tooltip for logout button</comment> <translation>Voltar a tela inicial</translation> </message> <message> <source>Logout</source> <comment>import profile button</comment> <translation>Encerrar sessão</translation> </message> <message> <source>Remove password</source> <translation>Remover senha</translation> </message> <message> <source>Change password</source> <translation>Mudar a senha</translation> </message> <message> <source>Allows you to export your Tox profile to a file. Profile does not contain your history.</source> <comment>tooltip for profile exporting button</comment> <translation>Permite exportar seu perfil Tox para um arquivo. O perfil não contem o seu histórico.</translation> </message> <message> <source>Rename</source> <comment>rename profile button</comment> <translation>Renomear</translation> </message> <message> <source>Export</source> <comment>export profile button</comment> <translation>Exportar</translation> </message> <message> <source>Delete</source> <comment>delete profile button</comment> <translation>Excluir</translation> </message> <message> <source>Server</source> <translation type="unfinished"></translation> </message> <message> <source>Hide my name from the public list</source> <translation type="unfinished"></translation> </message> <message> <source>Register</source> <translation type="unfinished"></translation> </message> <message> <source>Your password</source> <translation type="unfinished"></translation> </message> <message> <source>Update</source> <translation type="unfinished">Atualizar</translation> </message> <message> <source>Register on ToxMe</source> <translation type="unfinished"></translation> </message> <message> <source>Name for the ToxMe service.</source> <comment>Tooltip for the `Username` ToxMe field.</comment> <translation type="unfinished"></translation> </message> <message> <source>Optional. Something about you. Or your cat.</source> <comment>Tooltip for the Biography text.</comment> <translation type="unfinished"></translation> </message> <message> <source>Optional. Something about you. Or your cat.</source> <comment>Tooltip for the Biography field.</comment> <translation type="unfinished"></translation> </message> <message> <source>ToxMe service to register on.</source> <translation type="unfinished"></translation> </message> <message> <source>If not set, ToxMe entries are publicly visible.</source> <comment>Tooltip for the `Hide my name from public list` ToxMe checkbox.</comment> <translation type="unfinished"></translation> </message> <message> <source>Remove your password and encryption from your profile.</source> <comment>Tooltip for the `Remove password` button.</comment> <translation type="unfinished"></translation> </message> <message> <source>Name input</source> <translation type="unfinished"></translation> </message> <message> <source>Name visible to contacts</source> <translation type="unfinished"></translation> </message> <message> <source>Status message input</source> <translation type="unfinished"></translation> </message> <message> <source>Status message visible to contacts</source> <translation type="unfinished"></translation> </message> <message> <source>Your Tox ID</source> <translation type="unfinished"></translation> </message> <message> <source>Save QR image as file</source> <translation type="unfinished"></translation> </message> <message> <source>Copy QR image to clipboard</source> <translation type="unfinished"></translation> </message> <message> <source>ToxMe username to be shown on ToxMe</source> <translation type="unfinished"></translation> </message> <message> <source>Optional ToxMe biography to be shown on ToxMe</source> <translation type="unfinished"></translation> </message> <message> <source>ToxMe service address</source> <translation type="unfinished"></translation> </message> <message> <source>Visibility on the ToxMe service</source> <translation type="unfinished"></translation> </message> <message> <source>Password</source> <translation type="unfinished"></translation> </message> <message> <source>Update ToxMe entry</source> <translation type="unfinished"></translation> </message> <message> <source>Rename profile.</source> <translation type="unfinished">Renomear perfil.</translation> </message> <message> <source>Delete profile.</source> <translation type="unfinished">Remover perfil.</translation> </message> <message> <source>Export profile</source> <translation type="unfinished">Exportar perfil</translation> </message> <message> <source>Remove password from profile</source> <translation type="unfinished"></translation> </message> <message> <source>Change profile password</source> <translation type="unfinished"></translation> </message> <message> <source>My name:</source> <translation type="unfinished"></translation> </message> <message> <source>My status:</source> <translation type="unfinished"></translation> </message> <message> <source>My username</source> <translation type="unfinished"></translation> </message> <message> <source>My biography</source> <translation type="unfinished"></translation> </message> <message> <source>My profile</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LoadHistoryDialog</name> <message> <source>Load History Dialog</source> <translation>Carregar Histórico</translation> </message> <message> <source>Load history from:</source> <translation>Carregar histórico de:</translation> </message> <message> <source>%1 messages</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LoginScreen</name> <message> <source>Username:</source> <translation>Usuário:</translation> </message> <message> <source>Password:</source> <translation>Senha:</translation> </message> <message> <source>Confirm:</source> <translation>Confirmar:</translation> </message> <message> <source>Password strength: %p%</source> <translation type="unfinished">Segurança da senha: %p%</translation> </message> <message> <source>If the profile does not have a password, qTox can skip the login screen</source> <translation>Se o perfil não tiver uma senha, qTox pode pular a tela de entrada</translation> </message> <message> <source>New Profile</source> <translation>Novo Perfil</translation> </message> <message> <source>Couldn&apos;t create a new profile</source> <translation>Não foi possível criar um novo perfil</translation> </message> <message> <source>The username must not be empty.</source> <translation>O nome de usuário não pode ser vazio.</translation> </message> <message> <source>The password must be at least 6 characters long.</source> <translation>A senha deve ter pelo menos 6 caracterers.</translation> </message> <message> <source>The passwords you&apos;ve entered are different. Please make sure to enter same password twice.</source> <translation>As senhas digitadas diferem. Certifique-se de que você entrou a mesma senha duas vezes.</translation> </message> <message> <source>A profile with this name already exists.</source> <translation>Um perfil com este nome já existe.</translation> </message> <message> <source>Unknown error: Couldn&apos;t create a new profile. If you encountered this error, please report it.</source> <translation>Erro desconhecido: não foi possível criar perfil. Por favor, reporte este erro.</translation> </message> <message> <source>Couldn&apos;t load this profile</source> <translation>Não foi possível carregar o perfil</translation> </message> <message> <source>This profile is already in use.</source> <translation>Este perfil já está em uso.</translation> </message> <message> <source>Profile already in use. Close other clients.</source> <translation>Perfil em uso. Feche outros clientes.</translation> </message> <message> <source>Wrong password.</source> <translation>Senha incorreta.</translation> </message> <message> <source>Create Profile</source> <translation type="unfinished"></translation> </message> <message> <source>Load automatically</source> <translation type="unfinished"></translation> </message> <message> <source>Import</source> <translation type="unfinished"></translation> </message> <message> <source>Load</source> <translation type="unfinished">Carregar</translation> </message> <message> <source>Load Profile</source> <translation type="unfinished"></translation> </message> <message> <source>Password protected profiles can&apos;t be automatically loaded.</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t load profile</source> <translation type="unfinished"></translation> </message> <message> <source>There is no selected profile. You may want to create one.</source> <translation type="unfinished"></translation> </message> <message> <source>Username input field</source> <translation type="unfinished"></translation> </message> <message> <source>Password input field, you can leave it empty (no password), or type at least 6 characters</source> <translation type="unfinished"></translation> </message> <message> <source>Password confirmation field</source> <translation type="unfinished"></translation> </message> <message> <source>Create a new profile button</source> <translation type="unfinished"></translation> </message> <message> <source>Profile list</source> <translation type="unfinished"></translation> </message> <message> <source>List of profiles</source> <translation type="unfinished"></translation> </message> <message> <source>Password input</source> <translation type="unfinished"></translation> </message> <message> <source>Load automatically checkbox</source> <translation type="unfinished"></translation> </message> <message> <source>Import profile</source> <translation type="unfinished">Importar perfil</translation> </message> <message> <source>Load selected profile button</source> <translation type="unfinished"></translation> </message> <message> <source>New profile creation page</source> <translation type="unfinished"></translation> </message> <message> <source>Loading existing profile page</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainWindow</name> <message> <source>Your name</source> <translation>Seu nome</translation> </message> <message> <source>Your status</source> <translation>Seu status</translation> </message> <message> <source>...</source> <translation>...</translation> </message> <message> <source>Add friends</source> <translation>Adicionar contatos</translation> </message> <message> <source>Create a group chat</source> <translation>Criar um grupo</translation> </message> <message> <source>View completed file transfers</source> <translation>Ver transferências de arquivos completadas</translation> </message> <message> <source>Change your settings</source> <translation>Alterar suas configurações</translation> </message> <message> <source>Close</source> <translation>Fechar</translation> </message> <message> <source>Open profile</source> <translation type="unfinished"></translation> </message> <message> <source>Open profile page when clicked</source> <translation type="unfinished"></translation> </message> <message> <source>Status message input</source> <translation type="unfinished"></translation> </message> <message> <source>Set your status message that will be shown to others</source> <translation type="unfinished"></translation> </message> <message> <source>Status</source> <translation type="unfinished">Status</translation> </message> <message> <source>Set availability status</source> <translation type="unfinished"></translation> </message> <message> <source>Contact search</source> <translation type="unfinished"></translation> </message> <message> <source>Contact search input for known friends</source> <translation type="unfinished"></translation> </message> <message> <source>Sorting and visibility</source> <translation type="unfinished"></translation> </message> <message> <source>Set friends sorting and visibility</source> <translation type="unfinished"></translation> </message> <message> <source>Open Add friends page</source> <translation type="unfinished"></translation> </message> <message> <source>Groupchat</source> <translation type="unfinished"></translation> </message> <message> <source>Open groupchat management page</source> <translation type="unfinished"></translation> </message> <message> <source>File transfers history</source> <translation type="unfinished"></translation> </message> <message> <source>Open File transfers history</source> <translation type="unfinished"></translation> </message> <message> <source>Settings</source> <translation type="unfinished">Configurações</translation> </message> <message> <source>Open Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Nexus</name> <message> <source>Images (%1)</source> <comment>filetype filter</comment> <translation>Imagens (%1)</translation> </message> <message> <source>View</source> <comment>OS X Menu bar</comment> <translation type="unfinished">Visualizar</translation> </message> <message> <source>Window</source> <comment>OS X Menu bar</comment> <translation type="unfinished">Janela</translation> </message> <message> <source>Minimize</source> <comment>OS X Menu bar</comment> <translation type="unfinished">Minimizar</translation> </message> <message> <source>Bring All to Front</source> <comment>OS X Menu bar</comment> <translation type="unfinished">Trazer Todos para a Frente</translation> </message> <message> <source>Exit Fullscreen</source> <translation type="unfinished">Sair de Tela Cheia</translation> </message> <message> <source>Enter Fullscreen</source> <translation type="unfinished">Entrar em Tela Cheia</translation> </message> </context> <context> <name>NotificationEdgeWidget</name> <message numerus="yes"> <source>Unread message(s)</source> <translation> <numerusform>Mensagem não lida</numerusform> <numerusform>Mensagens não lidas</numerusform> </translation> </message> </context> <context> <name>PasswordEdit</name> <message> <source>CAPS-LOCK ENABLED</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PrivacyForm</name> <message> <source>Privacy</source> <translation>Privacidade</translation> </message> <message> <source>Confirmation</source> <translation type="unfinished"></translation> </message> <message> <source>Do you want to permanently delete all chat history?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PrivacySettings</name> <message> <source>Your friends will be able to see when you are typing.</source> <comment>tooltip for typing notifications setting</comment> <translation>Seus contatos poderão ver quando você estiver digitando.</translation> </message> <message> <source>Send typing notifications</source> <translation>Enviar notificação de digitação</translation> </message> <message> <source>Keep chat history</source> <translation>Guardar histórico de conversas</translation> </message> <message> <source>NoSpam is part of your Tox ID. If you are being spammed with friend requests, you should change your NoSpam. People will be unable to add you with your old ID, but you will keep your current friends.</source> <comment>toolTip for nospam</comment> <translation>NoSpam faz parte de seu ID Tox. Se você estiver recebendo muitas solicitações indesejadas, você deve mudar seu NoSpam. Não será possível lhe adicionar com seu ID antigo, mas você manterá sua lista de amigos.</translation> </message> <message> <source>NoSpam</source> <translation>NoSpam</translation> </message> <message> <source>NoSpam is a part of your ID that can be changed at will. If you are getting spammed with friend requests, change the NoSpam.</source> <translation>NoSpam faz parte de seu ID Tox e pode ser mudado a vontade. Se você estiver recebendo muitas solicitações indesejadas, mude seu NoSpam.</translation> </message> <message> <source>Generate random NoSpam</source> <translation>Gerar NoSpam aleatório</translation> </message> <message> <source>Chat history keeping is still in development. Save format changes are possible, which may result in data loss.</source> <comment>toolTip for Keep History setting</comment> <translation>O histórico de conversas ainda está em desenvolvimento. Mudanças no arquivo salvo podem ocorrer, isso pode resultar em perda de dados.</translation> </message> <message> <source>Privacy</source> <translation type="unfinished">Privacidade</translation> </message> <message> <source>BlackList</source> <translation type="unfinished"></translation> </message> <message> <source>Filter group message by group member&apos;s public key. Put public key here, one per line.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Profile</name> <message> <source>Failed to derive key from password, the profile won&apos;t use the new password.</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t change password on the database, it might be corrupted or use the old password.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ProfileForm</name> <message> <source>Choose a profile picture</source> <translation>Escolha uma imagem para o perfil</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> <message> <source>Unable to open this file.</source> <translation type="unfinished">Não foi possível abrir este arquivo.</translation> </message> <message> <source>Unable to read this image.</source> <translation>Não foi possível ler esta imagem.</translation> </message> <message> <source>The supplied image is too large. Please use another image.</source> <translation>A imagem é muito grande. Por favor, escolha outra.</translation> </message> <message> <source>Rename &quot;%1&quot;</source> <comment>renaming a profile</comment> <translation>Renomear &quot;%1&quot;</translation> </message> <message> <source>Couldn&apos;t rename the profile to &quot;%1&quot;</source> <translation>Não foi possível renomear o perfil para &quot;%1&quot;</translation> </message> <message> <source>Location not writable</source> <comment>Title of permissions popup</comment> <translation>Impossível gravar aqui</translation> </message> <message> <source>You do not have permission to write that location. Choose another, or cancel the save dialog.</source> <comment>text of permissions popup</comment> <translation>Você não possui permissão de escrita aqui. Escolha outro local ou cancele a operação.</translation> </message> <message> <source>Failed to copy file</source> <translation>Falha ao copiar o arquivo</translation> </message> <message> <source>The file you chose could not be written to.</source> <translation>O arquivo que você escolheu não pôde ser escrito.</translation> </message> <message> <source>Really delete profile?</source> <comment>deletion confirmation title</comment> <translation type="unfinished">Realmente remover perfil?</translation> </message> <message> <source>Are you sure you want to delete this profile?</source> <comment>deletion confirmation text</comment> <translation>Tem certeza de que deseja remover este perfil?</translation> </message> <message> <source>Save</source> <comment>save qr image</comment> <translation>Salvar</translation> </message> <message> <source>Save QrCode (*.png)</source> <comment>save dialog filter</comment> <translation>Salvar código QR (*.png)</translation> </message> <message> <source>Nothing to remove</source> <translation>Nada para remover</translation> </message> <message> <source>Your profile does not have a password!</source> <translation>Seu perfil não possui uma senha!</translation> </message> <message> <source>Really delete password?</source> <comment>deletion confirmation title</comment> <translation>Realmente remover senha?</translation> </message> <message> <source>Please enter a new password.</source> <translation>Por favor, insira uma nova senha.</translation> </message> <message> <source>Current profile: </source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Files could not be deleted!</source> <comment>deletion failed title</comment> <translation type="unfinished"></translation> </message> <message> <source>Register (processing)</source> <translation type="unfinished"></translation> </message> <message> <source>Update (processing)</source> <translation type="unfinished"></translation> </message> <message> <source>Done!</source> <translation type="unfinished"></translation> </message> <message> <source>Account %1@%2 updated successfully</source> <translation type="unfinished"></translation> </message> <message> <source>Successfully added %1@%2 to the database. Save your password</source> <translation type="unfinished"></translation> </message> <message> <source>Toxme error</source> <translation type="unfinished"></translation> </message> <message> <source>Register</source> <translation type="unfinished"></translation> </message> <message> <source>Update</source> <translation type="unfinished">Atualizar</translation> </message> <message> <source>Change password</source> <comment>button text</comment> <translation type="unfinished">Mudar a senha</translation> </message> <message> <source>Set profile password</source> <comment>button text</comment> <translation type="unfinished"></translation> </message> <message> <source>Current profile location: %1</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t change password</source> <translation type="unfinished"></translation> </message> <message> <source>This bunch of characters tells other Tox clients how to contact you. Share it with your friends to communicate. This ID includes the NoSpam code (in blue), and the checksum (in gray).</source> <translation type="unfinished"></translation> </message> <message> <source>Empty path is unavaliable</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to rename</source> <translation type="unfinished">Não foi possível renomear</translation> </message> <message> <source>Profile already exists</source> <translation type="unfinished">O perfil já existe</translation> </message> <message> <source>A profile named &quot;%1&quot; already exists.</source> <translation type="unfinished">Um perfil chamada &quot;%1&quot; já existe.</translation> </message> <message> <source>Empty name</source> <translation type="unfinished"></translation> </message> <message> <source>Empty name is unavaliable</source> <translation type="unfinished"></translation> </message> <message> <source>Empty path</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t change password on the database, it might be corrupted or use the old password.</source> <translation type="unfinished"></translation> </message> <message> <source>Export profile</source> <translation type="unfinished">Exportar perfil</translation> </message> <message> <source>Tox save file (*.tox)</source> <extracomment>save dialog filter</extracomment> <translation type="unfinished">Arquivo Tox (*.tox)</translation> </message> <message> <source>The following files could not be deleted:</source> <extracomment>deletion failed text part 1</extracomment> <translation type="unfinished"></translation> </message> <message> <source>Please manually remove them.</source> <extracomment>deletion failed text part 2</extracomment> <translation type="unfinished"></translation> </message> <message> <source>Are you sure you want to delete your password?</source> <extracomment>deletion confirmation text</extracomment> <translation type="unfinished">Tem certeza de que deseja remover sua senha?</translation> </message> </context> <context> <name>ProfileImporter</name> <message> <source>Import profile</source> <comment>import dialog title</comment> <translation type="unfinished">Importar perfil</translation> </message> <message> <source>Tox save file (*.tox)</source> <comment>import dialog filter</comment> <translation type="unfinished">Arquivo Tox (*.tox)</translation> </message> <message> <source>Ignoring non-Tox file</source> <comment>popup title</comment> <translation type="unfinished">Ignorando arquivo não Tox</translation> </message> <message> <source>Warning: You have chosen a file that is not a Tox save file; ignoring.</source> <comment>popup text</comment> <translation type="unfinished"></translation> </message> <message> <source>Profile already exists</source> <comment>import confirm title</comment> <translation type="unfinished">O perfil já existe</translation> </message> <message> <source>A profile named &quot;%1&quot; already exists. Do you want to erase it?</source> <comment>import confirm text</comment> <translation type="unfinished">Um perfil chamado &quot;%1&quot; já existe. Deseja sobrescrevê-lo?</translation> </message> <message> <source>File doesn&apos;t exist</source> <translation type="unfinished"></translation> </message> <message> <source>Profile doesn&apos;t exist</source> <translation type="unfinished"></translation> </message> <message> <source>Profile imported</source> <translation type="unfinished">Perfil importado</translation> </message> <message> <source>%1.tox was successfully imported</source> <translation type="unfinished">%1.tox importado com sucesso</translation> </message> </context> <context> <name>QApplication</name> <message> <source>Ok</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished">Cancelar</translation> </message> <message> <source>Yes</source> <translation type="unfinished">Sim</translation> </message> <message> <source>No</source> <translation type="unfinished">Não</translation> </message> <message> <source>LTR</source> <comment>Translate this string to the string &apos;RTL&apos; in right-to-left languages (for example Hebrew and Arabic) to get proper widget layout</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>QMessageBox</name> <message> <source>Couldn&apos;t add friend</source> <translation type="unfinished">Não foi possível adicionar amigo</translation> </message> <message> <source>%1 is not a valid Toxme address.</source> <translation type="unfinished"></translation> </message> <message> <source>You can&apos;t add yourself as a friend!</source> <comment>When trying to add your own Tox ID as friend</comment> <translation type="unfinished">Você não pode adicionar a si mesmo como contato!</translation> </message> </context> <context> <name>QObject</name> <message> <source>Update</source> <comment>The title of a message box</comment> <translation>Atualizar</translation> </message> <message> <source>An update is available, do you want to download it now? It will be installed when qTox restarts.</source> <translation>Uma atualização está disponível, você deseja baixá-la agora? Ela será instalada quando o qTox for reiniciado.</translation> </message> <message> <source>Tox URI to parse</source> <translation>UTI Tox para interpretar</translation> </message> <message> <source>Starts new instance and loads specified profile.</source> <translation>Inicia uma nova instância e carrega o perfil especificado.</translation> </message> <message> <source>profile</source> <translation>perfil</translation> </message> <message> <source>Default</source> <translation>Padrão</translation> </message> <message> <source>Blue</source> <translation>Azul</translation> </message> <message> <source>Olive</source> <translation>Verde-oliva</translation> </message> <message> <source>Red</source> <translation>Vermelho</translation> </message> <message> <source>Violet</source> <translation>Violeta</translation> </message> <message> <source>Incoming call...</source> <translation>Recebendo chamada...</translation> </message> <message> <source>%1 here! Tox me maybe?</source> <comment>Default message in Tox URI friend requests. Write something appropriate!</comment> <translation>Ola, %1 aqui! Gostaria de me adicionar no Tox?</translation> </message> <message> <source>Version %1, %2</source> <translation type="unfinished"></translation> </message> <message> <source>Server doesn&apos;t support Toxme</source> <translation type="unfinished"></translation> </message> <message> <source>You&apos;re making too many requests. Wait an hour and try again</source> <translation type="unfinished"></translation> </message> <message> <source>This name is already in use</source> <translation type="unfinished"></translation> </message> <message> <source>This Tox ID is already registered under another name</source> <translation type="unfinished"></translation> </message> <message> <source>Please don&apos;t use a space in your name</source> <translation type="unfinished"></translation> </message> <message> <source>Password incorrect</source> <translation type="unfinished"></translation> </message> <message> <source>You can&apos;t use this name</source> <translation type="unfinished"></translation> </message> <message> <source>Name not found</source> <translation type="unfinished"></translation> </message> <message> <source>Tox ID not sent</source> <translation type="unfinished"></translation> </message> <message> <source>That user does not exist</source> <translation type="unfinished"></translation> </message> <message> <source>Error</source> <translation type="unfinished">Erro</translation> </message> <message> <source>qTox couldn&apos;t open your chat logs, they will be disabled.</source> <translation type="unfinished"></translation> </message> <message> <source>None</source> <comment>No camera device set</comment> <translation type="unfinished">Nenhum</translation> </message> <message> <source>Desktop</source> <comment>Desktop as a camera input for screen sharing</comment> <translation type="unfinished"></translation> </message> <message> <source>Problem with HTTPS connection</source> <translation type="unfinished"></translation> </message> <message> <source>Internal ToxMe error</source> <translation type="unfinished"></translation> </message> <message> <source>Reformatting text in progress..</source> <translation type="unfinished"></translation> </message> <message> <source>Starts new instance and opens the login screen.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>RemoveFriendDialog</name> <message> <source>Remove friend</source> <translation type="unfinished">Remover contato</translation> </message> <message> <source>Also remove chat history</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Are you sure you want to remove %1 from your contacts list?</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all chat history with the friend if set</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ScreenshotGrabber</name> <message> <source>Click and drag to select a region. Press %1 to hide/show qTox window, or %2 to cancel.</source> <comment>Help text shown when no region has been selected yet</comment> <translation type="unfinished"></translation> </message> <message> <source>Space</source> <comment>[Space] key on the keyboard</comment> <translation type="unfinished"></translation> </message> <message> <source>Escape</source> <comment>[Escape] key on the keyboard</comment> <translation type="unfinished"></translation> </message> <message> <source>Press %1 to send a screenshot of the selection, %2 to hide/show qTox window, or %3 to cancel.</source> <comment>Help text shown when a region has been selected</comment> <translation type="unfinished"></translation> </message> <message> <source>Enter</source> <comment>[Enter] key on the keyboard</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>SetPasswordDialog</name> <message> <source>Set your password</source> <translation>Informe sua senha</translation> </message> <message> <source>The password is too short</source> <translation>Senha muito curta</translation> </message> <message> <source>The password doesn&apos;t match.</source> <translation>Senha não coincide.</translation> </message> <message> <source>Confirm:</source> <translation type="unfinished">Confirmar:</translation> </message> <message> <source>Password:</source> <translation type="unfinished">Senha:</translation> </message> <message> <source>Password strength: %p%</source> <translation type="unfinished">Segurança da senha: %p%</translation> </message> <message> <source>Confirm password</source> <translation type="unfinished"></translation> </message> <message> <source>Confirm password input</source> <translation type="unfinished"></translation> </message> <message> <source>Password input</source> <translation type="unfinished"></translation> </message> <message> <source>Password input field, minimum 6 characters long</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Settings</name> <message> <source>Circle #%1</source> <translation>Círculo #%1</translation> </message> </context> <context> <name>ToxURIDialog</name> <message> <source>Add a friend</source> <comment>Title of the window to add a friend through Tox URI</comment> <translation>Adicionar um contato</translation> </message> <message> <source>Do you want to add %1 as a friend?</source> <translation>Você deseja adicionar %1 como seu contato?</translation> </message> <message> <source>User ID:</source> <translation>ID do usuário:</translation> </message> <message> <source>Friend request message:</source> <translation>Mensagem de requisição contato:</translation> </message> <message> <source>Send</source> <comment>Send a friend request</comment> <translation>Enviar</translation> </message> <message> <source>Cancel</source> <comment>Don&apos;t send a friend request</comment> <translation>Cancelar</translation> </message> </context> <context> <name>UserInterfaceForm</name> <message> <source>None</source> <translation type="unfinished">Nenhum</translation> </message> <message> <source>User Interface</source> <translation type="unfinished"></translation> </message> </context> <context> <name>UserInterfaceSettings</name> <message> <source>Chat</source> <translation type="unfinished">Conversas</translation> </message> <message> <source>Base font:</source> <translation type="unfinished"></translation> </message> <message> <source>px</source> <translation type="unfinished"></translation> </message> <message> <source>Size: </source> <translation type="unfinished"></translation> </message> <message> <source>New text styling preference may not load until qTox restarts.</source> <translation type="unfinished"></translation> </message> <message> <source>Text Style format:</source> <translation type="unfinished"></translation> </message> <message> <source>Select text styling preference.</source> <translation type="unfinished"></translation> </message> <message> <source>Plaintext</source> <translation type="unfinished"></translation> </message> <message> <source>Show formatting characters</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t show formatting characters</source> <translation type="unfinished"></translation> </message> <message> <source>New message</source> <translation type="unfinished">Nova mensagem</translation> </message> <message> <source>Open qTox&apos;s window when you receive a new message and no window is open yet.</source> <comment>tooltip for Show window setting</comment> <translation type="unfinished"></translation> </message> <message> <source>Open window</source> <translation type="unfinished"></translation> </message> <message> <source>Focus qTox when you receive message.</source> <comment>toolTip for Focus window setting</comment> <translation type="unfinished">Alterar o foco para o qTox ao receber mensagens.</translation> </message> <message> <source>Focus window</source> <translation type="unfinished">Colocar janela em foco</translation> </message> <message> <source>Contact list</source> <translation type="unfinished"></translation> </message> <message> <source>Always notify about new messages in groupchats.</source> <comment>toolTip for Group chat always notify</comment> <translation type="unfinished">Sempre notificar sobre novas mensagens em grupos de conversa.</translation> </message> <message> <source>Group chats always notify</source> <translation type="unfinished">Notificação de conversas em grupo</translation> </message> <message> <source>If checked, groupchats will be placed at the top of the friends list, otherwise, they&apos;ll be placed below online friends.</source> <comment>toolTip for groupchat positioning</comment> <translation type="unfinished">Se marcada, conversas em grupo serão colocadas no topo de sua lista de amigos. Caso contrário, estarão abaixo dos amigos conectados.</translation> </message> <message> <source>Place groupchats at top of friend list</source> <translation type="unfinished">Colocar conversas em grupo no topo da lista de amigos</translation> </message> <message> <source>Your contact list will be shown in compact mode.</source> <comment>toolTip for compact layout setting</comment> <translation type="unfinished">Sua lista de contatos será exibida em modo compacto.</translation> </message> <message> <source>Compact contact list</source> <translation type="unfinished">Lista de contatos compacta</translation> </message> <message> <source>Multiple windows mode</source> <translation type="unfinished"></translation> </message> <message> <source>Open each chat in an individual window</source> <translation type="unfinished"></translation> </message> <message> <source>Emoticons</source> <translation type="unfinished"></translation> </message> <message> <source>Use emoticons</source> <translation type="unfinished">Usar emoticons</translation> </message> <message> <source>Smiley Pack:</source> <extracomment>Text on smiley pack label</extracomment> <translation type="unfinished">Pacote de emoticons:</translation> </message> <message> <source>Emoticon size:</source> <translation type="unfinished">Tamanho dos emoticons:</translation> </message> <message> <source> px</source> <translation type="unfinished"> px</translation> </message> <message> <source>Theme</source> <translation type="unfinished">Tema</translation> </message> <message> <source>Style:</source> <translation type="unfinished">Estilo:</translation> </message> <message> <source>Theme color:</source> <translation type="unfinished">Cor do tema:</translation> </message> <message> <source>Timestamp format:</source> <translation type="unfinished">Formato de hora:</translation> </message> <message> <source>Date format:</source> <translation type="unfinished">Formato de datas:</translation> </message> </context> <context> <name>Widget</name> <message> <source>Online</source> <translation>Conectados</translation> </message> <message> <source>Add new circle...</source> <translation>Adicionar novo círculo...</translation> </message> <message> <source>By Name</source> <translation>Por Nome</translation> </message> <message> <source>By Activity</source> <translation>Por Atividade</translation> </message> <message> <source>All</source> <translation>Todos</translation> </message> <message> <source>Offline</source> <translation>Desconectados</translation> </message> <message> <source>Friends</source> <translation>Amigos</translation> </message> <message> <source>Groups</source> <translation>Grupos</translation> </message> <message> <source>Search Contacts</source> <translation>Buscar Contatos</translation> </message> <message> <source>Online</source> <comment>Button to set your status to &apos;Online&apos;</comment> <translation>Online</translation> </message> <message> <source>Away</source> <comment>Button to set your status to &apos;Away&apos;</comment> <translation>Ausente</translation> </message> <message> <source>Busy</source> <comment>Button to set your status to &apos;Busy&apos;</comment> <translation>Ocupado</translation> </message> <message> <source>toxcore failed to start with your proxy settings. qTox cannot run; please modify your settings and restart.</source> <comment>popup text</comment> <translation>O Toxcore falhou ao inicializar suas configurações de proxy. O qTox não pode ser executado, por favor modifique suas configurações e reinicialize o aplicativo.</translation> </message> <message> <source>File</source> <translation>Arquivo</translation> </message> <message> <source>Edit Profile</source> <translation>Editar Perfil</translation> </message> <message> <source>Change Status</source> <translation type="unfinished">Mudar Status</translation> </message> <message> <source>Log out</source> <translation>Sair</translation> </message> <message> <source>Edit</source> <translation>Editar</translation> </message> <message> <source>Filter...</source> <translation>Filtrar...</translation> </message> <message> <source>Contacts</source> <translation>Contatos</translation> </message> <message> <source>Add Contact...</source> <translation>Adicionar Contato...</translation> </message> <message> <source>Next Conversation</source> <translation>Próxima Conversa</translation> </message> <message> <source>Previous Conversation</source> <translation>Conversa Anterior</translation> </message> <message> <source>Executable file</source> <comment>popup title</comment> <translation>Arquivo executável</translation> </message> <message> <source>You have asked qTox to open an executable file. Executable files can potentially damage your computer. Are you sure want to open this file?</source> <comment>popup text</comment> <translation>Você pediu ao qTox para abrir um arquivo executável. Executáveis podem potencialmente danificar seu computador. Tem certeza de que deseja abrir este arquivo?</translation> </message> <message> <source>Couldn&apos;t request friendship</source> <translation>Não foi possível adicionar o contato</translation> </message> <message> <source>%1 has set the title to %2</source> <translation>%1 alterou o título para %2</translation> </message> <message> <source>Status</source> <translation type="unfinished">Status</translation> </message> <message> <source>Message failed to send</source> <translation>Falha no envio da mensagem</translation> </message> <message> <source>toxcore failed to start, the application will terminate after you close this message.</source> <translation type="unfinished"></translation> </message> <message> <source>Your name</source> <translation type="unfinished">Seu nome</translation> </message> <message> <source>Your status</source> <translation type="unfinished">Seu status</translation> </message> <message> <source>&lt;Empty&gt;</source> <comment>Placeholder when someone&apos;s name in a group chat is empty</comment> <translation type="unfinished">&lt;Vazio&gt;</translation> </message> <message> <source>Groupchat #%1</source> <translation type="unfinished"></translation> </message> <message> <source>Create new group...</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <source>%n New Friend Request(s)</source> <translation type="unfinished"> <numerusform></numerusform> <numerusform></numerusform> </translation> </message> <message numerus="yes"> <source>%n New Group Invite(s)</source> <translation type="unfinished"> <numerusform></numerusform> <numerusform></numerusform> </translation> </message> <message> <source>Logout</source> <comment>Tray action menu to logout user</comment> <translation type="unfinished">Encerrar sessão</translation> </message> <message> <source>Exit</source> <comment>Tray action menu to exit tox</comment> <translation type="unfinished"></translation> </message> <message> <source>Show</source> <comment>Tray action menu to show qTox window</comment> <translation type="unfinished"></translation> </message> <message> <source>Add friend</source> <comment>title of the window</comment> <translation type="unfinished">Adicionar contato</translation> </message> <message> <source>Group invites</source> <comment>title of the window</comment> <translation type="unfinished">Convites à grupos</translation> </message> <message> <source>File transfers</source> <comment>title of the window</comment> <translation type="unfinished">Transferências de arquivo</translation> </message> <message> <source>Settings</source> <comment>title of the window</comment> <translation type="unfinished">Configurações</translation> </message> <message> <source>My profile</source> <comment>title of the window</comment> <translation type="unfinished"></translation> </message> </context> </TS>
noavarice/qTox
translations/pt.ts
TypeScript
gpl-3.0
105,009
/* * Overchan Android (Meta Imageboard Client) * Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nya.miku.wishmaster.chans.dvach; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import nya.miku.wishmaster.api.ChanModule; import nya.miku.wishmaster.api.models.PostModel; import nya.miku.wishmaster.api.models.UrlPageModel; import nya.miku.wishmaster.api.util.RegexUtils; public class DvachSearchReader implements Closeable { private final ChanModule _chan; private final Reader _in; private StringBuilder readBuffer = new StringBuilder(); private List<PostModel> result; private static final char[] FILTER_OPEN = "<li class=\"found\">".toCharArray(); private static final char[] FILTER_CLOSE = "</li>".toCharArray(); private static final Pattern HREF_PATTERN = Pattern.compile("<a href=\"(.*?)\"", Pattern.DOTALL); private static final Pattern SUBJ_PATTERN = Pattern.compile("<a(?:[^>]*)>(.*?)</a>", Pattern.DOTALL); public DvachSearchReader(Reader reader, ChanModule chan) { _in = reader; _chan = chan; } public DvachSearchReader(InputStream in, ChanModule chan) { this(new BufferedReader(new InputStreamReader(in)), chan); } public PostModel[] readSerachPage() throws IOException { result = new ArrayList<>(); int pos = 0; int len = FILTER_OPEN.length; int curChar; while ((curChar = _in.read()) != -1) { if (curChar == FILTER_OPEN[pos]) { ++pos; if (pos == len) { handlePost(readUntilSequence(FILTER_CLOSE)); pos = 0; } } else { if (pos != 0) pos = curChar == FILTER_OPEN[0] ? 1 : 0; } } return result.toArray(new PostModel[result.size()]); } private void handlePost(String post) { Matcher mHref = HREF_PATTERN.matcher(post); if (mHref.find()) { try { PostModel postModel = new PostModel(); UrlPageModel url = _chan.parseUrl(_chan.fixRelativeUrl(mHref.group(1))); postModel.number = url.postNumber == null ? url.threadNumber : url.postNumber; postModel.parentThread = url.threadNumber; postModel.name = ""; Matcher mSubj = SUBJ_PATTERN.matcher(post); if (mSubj.find()) postModel.subject = RegexUtils.trimToSpace(mSubj.group(1)); else postModel.subject = ""; if (post.contains("<p>")) postModel.comment = post.substring(post.indexOf("<p>")); else postModel.comment = ""; result.add(postModel); } catch (Exception e) {} } } private String readUntilSequence(char[] sequence) throws IOException { int len = sequence.length; if (len == 0) return ""; readBuffer.setLength(0); int pos = 0; int curChar; while ((curChar = _in.read()) != -1) { readBuffer.append((char) curChar); if (curChar == sequence[pos]) { ++pos; if (pos == len) break; } else { if (pos != 0) pos = curChar == sequence[0] ? 1 : 0; } } int buflen = readBuffer.length(); if (buflen >= len) { readBuffer.setLength(buflen - len); return readBuffer.toString(); } else { return ""; } } @Override public void close() throws IOException { _in.close(); } }
miku-nyan/Overchan-Android
src/nya/miku/wishmaster/chans/dvach/DvachSearchReader.java
Java
gpl-3.0
4,523
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MedicineBox : MonoBehaviour, IItem { public void Pickup(PlayerInventory inventory) { if (inventory.owner.health + 100f > 200f) return; else { inventory.owner.health += 100f; Destroy(transform.parent.gameObject); } } public void Equip(PlayerInventory inventory) { //to do } public void Throw() { //to do } }
Danila24ru/CourseGame
Assets/Code/MedicineBox.cs
C#
gpl-3.0
570
from random import random, randint from PIL import Image, ImageDraw, ImageFont import perlin def draw_background(setup) : canvas = setup['canvas'] image = Image.new('RGBA', canvas, tuple(setup['color']['back'])) background = Image.new('RGBA', canvas, (0,0,0,0)) draw = ImageDraw.Draw(background) stars = [[ int(p * random()) for p in canvas ] for x in range(400) ] scale = lambda x, r : x + r * (min(canvas) / 320) color = (255, 255, 255, 100) for x, y in stars : r = random() draw.ellipse([x, y, scale(x, r), scale(y, r)], fill=color) return Image.alpha_composite(image, background) def apply_noise(image, setup) : generator = perlin.Perlin() octaves = 5 persistence = 5 coef = 30 width, height = setup['canvas'][0], setup['canvas'][1] list_of_pixels = list(image.getdata()) for i, pixel in enumerate(list_of_pixels) : if pixel != (0, 0, 0, 0) : noise = generator.OctavePerlin((i % width) / coef, i / (height * coef), 0, 1, 5) new_pixel = [ int(x * (1 + noise)) for x in pixel[:3] ] new_pixel.append(pixel[3]) list_of_pixels[i] = tuple(new_pixel) image = Image.new(image.mode, image.size) image.putdata(list_of_pixels) return image def apply_ray_effect(sun_image, setup) : canvas = setup['canvas'] width, height = setup['canvas'][0], setup['canvas'][1] decay = 0.8 density = 1.2 samples = 128 center = [ x / 2 for x in setup['canvas'] ] list_of_pixels = list(sun_image.getdata()) new_image = [] print("starting postprocessing...") for y in range(height) : print("\rjob completed {0:.2f}%".format(round(100 * (y / height), 2)), flush=True, end="") for x in range(width) : tc = [x, y] delta = [ (x - center[0]) / (samples * density), (y - center[1]) / (samples * density) ] color = list_of_pixels[x + y * width] illumination = 1 for m in range(samples) : tc = [ tc[0] - delta[0], tc[1] - delta[1]] add_color = tuple( illumination * x for x in list_of_pixels[int(tc[0]) + int(tc[1]) * width] ) illumination *= decay color = tuple( x + y for x, y in zip(color, add_color)) new_image.append(tuple(int(x) for x in color)) image = Image.new(sun_image.mode, sun_image.size) image.putdata(new_image) return image def draw_sun(image, setup) : canvas = setup['canvas'] sun_image = Image.new('RGBA', canvas, (0,0,0,0)) draw = ImageDraw.Draw(sun_image) draw.ellipse(setup['sun'], fill=tuple(setup['color']['base'])) sun_image = apply_noise(sun_image, setup) sun_image = apply_ray_effect(sun_image, setup) return Image.alpha_composite(image, sun_image) def create_sun(setup) : canvas, size = setup['canvas'], setup['size'] d = min([x * 0.08 * 5 * size for x in canvas]) planet = [ (x - d) / 2 for x in canvas ] planet.append(planet[0] + d) planet.append(planet[1] + d) setup['sun'] = planet setup['diam'] = d setup['rad'] = d / 2 setup['center'] = [ planet[0] + d / 2, planet[1] + d / 2 ] def sun_setup(setup) : tmp_setup = {} tmp_setup['color'] = {} tmp_setup['color']['base'] = setup[2] tmp_setup['color']['back'] = [ int(x * 0.05) for x in setup[2] ] tmp_setup['canvas'] = [ x * 2 for x in setup[0] ] tmp_setup['size'] = setup[1] / (255 * 2) return tmp_setup def sun(setup) : setup = sun_setup(setup) create_sun(setup) image = draw_background(setup) image = draw_sun(image, setup) canvas = [ int(x / 2) for x in setup['canvas'] ] resized = image.resize(canvas, Image.ANTIALIAS) resized.save("test.png") setup = ((1200, 750), 128, (180, 120, 100)) sun(setup)
vojtatom/planets
sun.py
Python
gpl-3.0
3,499
#!/usr/bin/python import pygame import math import random import sys import PixelPerfect from pygame.locals import * from water import Water from menu import Menu from game import Game from highscores import Highscores from options import Options import util from locals import * import health import cloud import mine import steamboat import pirateboat import shark import seagull def init(): health.init() steamboat.init() shark.init() pirateboat.init() cloud.init() mine.init() seagull.init() def main(): global SCREEN_FULLSCREEN pygame.init() util.load_config() if len(sys.argv) > 1: for arg in sys.argv: if arg == "-np": Variables.particles = False elif arg == "-na": Variables.alpha = False elif arg == "-nm": Variables.music = False elif arg == "-ns": Variables.sound = False elif arg == "-f": SCREEN_FULLSCREEN = True scr_options = 0 if SCREEN_FULLSCREEN: scr_options += FULLSCREEN screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),scr_options ,32) pygame.display.set_icon(util.load_image("kuvake")) pygame.display.set_caption("Trip on the Funny Boat") init() joy = None if pygame.joystick.get_count() > 0: joy = pygame.joystick.Joystick(0) joy.init() try: util.load_music("JDruid-Trip_on_the_Funny_Boat") if Variables.music: pygame.mixer.music.play(-1) except: # It's not a critical problem if there's no music pass pygame.time.set_timer(NEXTFRAME, 1000 / FPS) # 30 fps Water.global_water = Water() main_selection = 0 while True: main_selection = Menu(screen, ("New Game", "High Scores", "Options", "Quit"), main_selection).run() if main_selection == 0: # New Game selection = Menu(screen, ("Story Mode", "Endless Mode")).run() if selection == 0: # Story score = Game(screen).run() Highscores(screen, score).run() elif selection == 1: # Endless score = Game(screen, True).run() Highscores(screen, score, True).run() elif main_selection == 1: # High Scores selection = 0 while True: selection = Menu(screen, ("Story Mode", "Endless Mode", "Endless Online"), selection).run() if selection == 0: # Story Highscores(screen).run() elif selection == 1: # Endless Highscores(screen, endless = True).run() elif selection == 2: # Online Highscores(screen, endless = True, online = True).run() else: break elif main_selection == 2: # Options selection = Options(screen).run() else: #if main_selection == 3: # Quit return if __name__ == '__main__': main()
italomaia/turtle-linux
games/FunnyBoat/run_game.py
Python
gpl-3.0
3,190
// Copyright (C) 2013 Johan Hake // // This file is part of DOLFIN. // // DOLFIN is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // DOLFIN is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with DOLFIN. If not, see <http://www.gnu.org/licenses/>. // // First added: 2013-11-07 // Last changed: 2013-11-07 #include <dolfin/function/Function.h> #include <dolfin/function/FunctionSpace.h> #include "assign.h" #include "FunctionAssigner.h" //----------------------------------------------------------------------------- void dolfin::assign(boost::shared_ptr<Function> receiving_func, boost::shared_ptr<const Function> assigning_func) { // Instantiate FunctionAssigner and call assign const FunctionAssigner assigner(receiving_func->function_space(), assigning_func->function_space()); assigner.assign(receiving_func, assigning_func); } //----------------------------------------------------------------------------- void dolfin::assign(boost::shared_ptr<Function> receiving_func, std::vector<boost::shared_ptr<const Function> > assigning_funcs) { // Instantiate FunctionAssigner and call assign std::vector<boost::shared_ptr<const FunctionSpace> > assigning_spaces; for (std::size_t i = 0; i < assigning_funcs.size(); i++) assigning_spaces.push_back(assigning_funcs[i]->function_space()); const FunctionAssigner assigner(receiving_func->function_space(), assigning_spaces); assigner.assign(receiving_func, assigning_funcs); } //----------------------------------------------------------------------------- void dolfin::assign(std::vector<boost::shared_ptr<Function> > receiving_funcs, boost::shared_ptr<const Function> assigning_func) { // Instantiate FunctionAssigner and call assign std::vector<boost::shared_ptr<const FunctionSpace> > receiving_spaces; for (std::size_t i = 0; i < receiving_funcs.size(); i++) receiving_spaces.push_back(receiving_funcs[i]->function_space()); const FunctionAssigner assigner(receiving_spaces, assigning_func->function_space()); assigner.assign(receiving_funcs, assigning_func); } //-----------------------------------------------------------------------------
maciekswat/dolfin_1.3.0
dolfin/function/assign.cpp
C++
gpl-3.0
2,642
#!/usr/bin/env python2 # # Copyright 2016 Philipp Winter <phw@nymity.ch> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Turn pcap into csv file. Extract timestamp, source IP address, and query name of all DNS queries in the given pcap, and turn it into a CSV. """ import sys import scapy.all as scapy # We exclude the following two measurement hosts. MEASUREMENT_HOSTS = frozenset(["92.243.1.186", "198.83.85.34"]) def process_file(pcap_file): packets = scapy.rdpcap(pcap_file) for packet in packets: if not packet.haslayer(scapy.IP): continue if not packet.haslayer(scapy.DNSQR): continue query = packet[scapy.DNSQR].qname src_addr = packet[scapy.IP].src # Skip DNS response. if src_addr in MEASUREMENT_HOSTS: continue print "%s,%s,%s" % (packet.time, packet[scapy.IP].src, query.lower()) return 0 if __name__ == "__main__": if len(sys.argv) != 2: print >> sys.stderr, "\nUsage: %s PCAP_FILE\n" % sys.argv[0] sys.exit(1) pcap_file = sys.argv[1] sys.exit(process_file(pcap_file))
NullHypothesis/tor-dns-tools
dns-pcap-to-csv.py
Python
gpl-3.0
1,724
/** * Created by gjrwcs on 10/25/2016. */ 'use strict'; /** * Game Behavior and Logic for Warp * @module pulsar.warp */ var warp = require('angular').module('pulsar.warp', []); const ADT = require('../app.dependency-tree.js').ADT; ADT.warp = { Level: 'warp.Level', WarpField: 'warp.WarpField', Bar: 'warp.Bar', State: 'warp.State', }; require('./bar.factory'); require('./game.controller'); require('./hud.directive'); require('./level-loader.svc'); require('./level.svc'); require('./scoring.svc'); require('./ship.svc'); require('./ship-effects.svc'); require('./warp-field.factory'); require('./warp-field-cache.svc'); require('./warp-field-draw.svc'); require('./state.svc'); module.exports = warp;
thunder033/RMWA
pulsar/app/warp/index.js
JavaScript
gpl-3.0
742
// MapAround - .NET tools for developing web and desktop mapping applications // Copyright (coffee) 2009-2012 OOO "GKR" // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; If not, see <http://www.gnu.org/licenses/> /*=========================================================================== ** ** File: ShapeFile.cs ** ** Copyright (c) Complex Solution Group. ** ** Description: Classes that provides access to the shape-file reading and writing ** =============================================================================*/ namespace MapAround.IO { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.IO; using System.Text; using System.Collections; using System.Linq; using MapAround.Geometry; using MapAround.IO.Handlers; using MapAround.Mapping; /// <summary> /// Types of shape file. /// </summary> public enum ShapeType { /// <summary> /// Null shape. /// </summary> NullShape = 0, /// <summary> /// Point. /// </summary> Point = 1, /// <summary> /// Polyline. /// </summary> Polyline = 3, /// <summary> /// Polygon. /// </summary> Polygon = 5, /// <summary> /// Multipoint. /// </summary> Multipoint = 8 // Unsupported: // PointZ = 11, // PolyLineZ = 13, // PolygonZ = 15, // MultiPointZ = 18, // PointM = 21, // PolyLineM = 23, // PolygonM = 25, // MultiPointM = 28, // MultiPatch = 31 } /// <summary> /// Represents a header of shape file. /// </summary> public class ShapeFileHeader { #region Private fields private int _fileCode; private int _fileLength; private int _version; private int _shapeType; private double _minX; private double _minY; private double _maxX; private double _maxY; #endregion /// <summary> /// Initializes a new instance of MapAround.IO.ShapeFileHeader. /// </summary> public ShapeFileHeader() { } #region Properties /// <summary> /// Gets a length of header in bytes. /// </summary> public static int Length { get { return 100; } } /// <summary> /// Gets or sets a shape-file code. /// Should be equal to 9994. /// </summary> public int FileCode { get { return _fileCode; } set { _fileCode = value; } } /// <summary> /// Gets or sets a length of file. /// </summary> public int FileLength { get { return _fileLength; } set { _fileLength = value; } } /// <summary> /// Gets or sets the format version. /// </summary> public int Version { get { return _version; } set { _version = value; } } /// <summary> /// Gets or sets an integer defining a type of shape-file. /// </summary> public int ShapeType { get { return _shapeType; } set { _shapeType = value; } } /// <summary> /// Gets or sets a minimal X value of shapes /// storing in shape file. /// </summary> public double MinX { get { return _minX; } set { _minX = value; } } /// <summary> /// Gets or sets a minimal Y value of shapes /// storing in shape file. /// </summary> public double MinY { get { return _minY; } set { _minY = value; } } /// <summary> /// Gets or sets a maximal X value of shapes /// storing in shape file. /// </summary> public double MaxX { get { return _maxX; } set { _maxX = value; } } /// <summary> /// Gets or sets a maximal Y value of shapes /// storing in shape file. /// </summary> public double MaxY { get { return _maxY; } set { _maxY = value; } } #endregion Properties #region Public methods /// <summary> /// Returns a System.String that represents the current MapAround.IO.ShapeFileHeader. /// </summary> /// <returns>A System.String that represents the current MapAround.IO.ShapeFileHeader</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("ShapeFileHeader: FileCode={0}, FileLength={1}, Version={2}, ShapeType={3}", this._fileCode, this._fileLength, this._version, this._shapeType); return sb.ToString(); } /// <summary> /// Sets a bounds of all shapes in file. /// </summary> /// <param name="Bounds">A bounding rectangle defining the bounds</param> public void SetBounds(BoundingRectangle Bounds) { this.MinX = Bounds.MinX; this.MinY = Bounds.MinY; this.MaxX = Bounds.MaxX; this.MaxY = Bounds.MaxY; } /// <summary> /// Sets a bounds of all shapes in file. /// </summary> /// <param name="headerBounds">A header wrom which to take a bounds</param> public void SetBounds(ShapeFileHeader headerBounds) { this.MinX = headerBounds.MinX; this.MinY = headerBounds.MinY; this.MaxX = headerBounds.MaxX; this.MaxY = headerBounds.MaxY; } #endregion Public methods /// <summary> /// Writes this header to the stream. /// </summary> /// <param name="file">A System.IO.BinaryWriter instance to write the header</param> /// <param name="ShapeType">Shape type</param> internal void Write(BigEndianBinaryWriter file, ShapeType ShapeType) { if (file == null) throw new ArgumentNullException("file"); if (this.FileLength == -1) throw new InvalidOperationException("The header properties need to be set before writing the header record."); int pos = 0; file.WriteIntBE(this.FileCode); pos += 4; for (int i = 0; i < 5; i++) { file.WriteIntBE(0);//Skip unused part of header pos += 4; } file.WriteIntBE(this.FileLength); pos += 4; file.Write(this.Version); pos += 4; file.Write(int.Parse(Enum.Format(typeof(ShapeType), ShapeType, "d"))); pos += 4; // Write the bounding box file.Write(this.MinX); file.Write(this.MinY); file.Write(this.MaxX); file.Write(this.MaxY); pos += 8 * 4; // Skip remaining unused bytes for (int i = 0; i < 4; i++) { file.Write(0.0); // Skip unused part of header pos += 8; } } } /// <summary> /// Represents a record of shape file. /// </summary> public class ShapeFileRecord { #region Private fields private int _recordNumber; private int _contentLength; private int _shapeType; private double _minX; private double _minY; private double _maxX; private double _maxY; private long _offset; private Collection<int> _parts = new Collection<int>(); private Collection<ICoordinate> _points = new Collection<ICoordinate>(); private DataRow _attributes; #endregion #region Constructor /// <summary> /// Initializes a new instance of the MapAround.IO.ShapeFileRecord /// </summary> public ShapeFileRecord() { } #endregion Constructor #region Properties /// <summary> /// Gets or sets an offset of this record /// from begining of file. /// </summary> public long Offset { get { return _offset; } set { _offset = value; } } /// <summary> /// Gets or sets a number of this record. /// </summary> public int RecordNumber { get { return _recordNumber; } set { _recordNumber = value; } } /// <summary> /// Gets or sets the length (in bytes) of this record. /// </summary> public int ContentLength { get { return _contentLength; } set { _contentLength = value; } } /// <summary> /// Gets or sets the shape type. /// </summary> public int ShapeType { get { return _shapeType; } set { _shapeType = value; } } /// <summary> /// Gets or sets the minimum X value. /// </summary> public double MinX { get { return _minX; } set { _minX = value; } } /// <summary> /// Gets or sets the minimum Y value. /// </summary> public double MinY { get { return _minY; } set { _minY = value; } } /// <summary> /// Gets or sets the maximum X value. /// </summary> public double MaxX { get { return _maxX; } set { _maxX = value; } } /// <summary> /// Gets or sets the maximum Y value. /// </summary> public double MaxY { get { return _maxY; } set { _maxY = value; } } /// <summary> /// Gets a number of parts of the geometry. /// </summary> public int NumberOfParts { get { return _parts.Count; } } /// <summary> /// Gets a number of points of the geometry. /// </summary> public int NumberOfPoints { get { return _points.Count; } } /// <summary> /// Gets a collection containing the indices of /// coordinate sequences corresponding parts of /// geometry. /// </summary> public Collection<int> Parts { get { return _parts; } } /// <summary> /// Gets a collection of coordinates of /// the geometry. /// </summary> public Collection<ICoordinate> Points { get { return _points; } } /// <summary> /// Gets or sets an attributes row associated /// with this record. /// </summary> public DataRow Attributes { get { return _attributes; } set { _attributes = value; } } #endregion Properties #region Public methods /// <summary> /// Returns a System.String that represents the current MapAround.IO.ShapeFileRecord. /// </summary> /// <returns>A System.String that represents the current MapAround.IO.ShapeFilerecord</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("ShapeFileRecord: RecordNumber={0}, ContentLength={1}, ShapeType={2}", this._recordNumber, this._contentLength, this._shapeType); return sb.ToString(); } #endregion Public methods } /// <summary> /// Represents an information of reading shape file. /// </summary> public class ShapeFileReadInfo { #region Private fields private string _fileName; private ShapeFile _shapeFile; private Stream _stream; private int _numBytesRead; private int _recordIndex; #endregion /// <summary> /// Initializes a new instance of the MapAround.IO.ShapeFileReadInfo. /// </summary> public ShapeFileReadInfo() { } #region Properties /// <summary> /// Gets or sets the file name. /// </summary> public string FileName { get { return _fileName; } set { _fileName = value; } } /// <summary> /// Gets or sets a reference to read MapAround.IO.ShapeFile. /// </summary> public ShapeFile ShapeFile { get { return _shapeFile; } set { _shapeFile = value; } } /// <summary> /// Gets or sets a stream from which to read MapAround.IO.ShapeFile. /// </summary> public Stream Stream { get { return _stream; } set { _stream = value; } } /// <summary> /// Gets or sets a number of bytes read. /// </summary> public int NumberOfBytesRead { get { return _numBytesRead; } set { _numBytesRead = value; } } /// <summary> /// Gets or sets a number of current record. /// </summary> public int RecordIndex { get { return _recordIndex; } set { _recordIndex = value; } } #endregion Properties #region Public methods /// <summary> /// Returns a System.String that represents the current MapAround.IO.ShapeFileReadInfo. /// </summary> /// <returns>A System.String that represents the current MapAround.IO.ShapeFileReadInfo</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("ShapeFileReadInfo: FileName={0}, ", this._fileName); sb.AppendFormat("NumberOfBytesRead={0}, RecordIndex={1}", this._numBytesRead, this._recordIndex); return sb.ToString(); } #endregion } /// <summary> /// Represents an ESRI Shape-file. /// Implements methods for reading and writing. /// </summary> public class ShapeFile { private const int _expectedFileCode = 9994; #region Private fields // header private ShapeFileHeader _fileHeader = new ShapeFileHeader(); private DbaseFileHeader _dbaseHeader; private Collection<ShapeFileRecord> _records = new Collection<ShapeFileRecord>(); private List<string> _attributeNames = new List<string>(); private Encoding _attributesEncoding = Encoding.UTF8; #endregion #region Constructor /// <summary> /// Initializes a new instance of MapAround.IO.Shapefile. /// </summary> public ShapeFile() { } #endregion Constructor #region Properties /// <summary> /// Gets or sets a header of dBase file /// (attributes file). /// </summary> public DbaseFileHeader DbaseHeader { get { return _dbaseHeader; } set { _dbaseHeader = value; } } /// <summary> /// Gets an object representing the header of this shape file. /// </summary> public ShapeFileHeader FileHeader { get { return this._fileHeader; } } /// <summary> /// Gets a collection containing the attribute names. /// </summary> public ReadOnlyCollection<string> AttributeNames { get { return _attributeNames.AsReadOnly(); } } /// <summary> /// Gets a collection containing the records of this shape file. /// </summary> public Collection<ShapeFileRecord> Records { get { return _records; } } /// <summary> /// Gets or sets an encoding of attributes. /// </summary> public Encoding AttributesEncoding { get { return _attributesEncoding; } set { _attributesEncoding = value; } } #endregion #region Public methods #region Read /// <summary> /// Reads a shape-file data (geometries and attributes). /// </summary> /// <param name="fileName">The file name</param> /// <param name="bounds">The bounding rectangle. Only those records are read, /// which bounding rectangles intersect with this rectangle</param> public void Read(string fileName, BoundingRectangle bounds) { if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName"); string indexFile = fileName.Replace(".shp", ".shx"); indexFile = indexFile.Replace(".SHP", ".SHX"); int[] offsets; // .shx-ôàéë íåîáõîäèì ïî ñïåöèôèêàöèè, íî ïðî÷åñòü shape-ôàéë ìîæíî è áåç íåãî. if (File.Exists(indexFile)) offsets = ReadIndex(indexFile); else offsets = new int[] { }; this.ReadShapes(fileName, offsets, bounds); string dbaseFile = fileName.Replace(".shp", ".dbf"); dbaseFile = dbaseFile.Replace(".SHP", ".DBF"); //!!! this.ReadAttributes(dbaseFile); } /// <summary> /// Reads the index of shape-file. /// </summary> /// <param name="fileName">The file name</param> public int[] ReadIndex(string fileName) { using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { ReadHeader(stream); int featureCount = (2 * this._fileHeader.FileLength - 100) / 8; int[] offsets = new int[featureCount]; stream.Seek(100, 0); for (int x = 0; x < featureCount; ++x) { offsets[x] = 2 * stream.ReadInt32BE();// ReadInt32_BE(stream); stream.Seek(stream.Position + 4, 0); } return offsets; } } /// <summary> /// Reads the shapes of shape-file. /// </summary> /// <param name="fileName">The file name</param> /// <param name="offsets">An array containing offsets of the records to read</param> /// <param name="bounds">The bounding rectangle. Only those records are read, /// which bounding rectangles intersect with this rectangle</param> public void ReadShapes(string fileName, int[] offsets, BoundingRectangle bounds) { using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { try { this.ReadShapes(stream, offsets, bounds); } catch { stream.Flush(); stream.Close(); } } } /// <summary> /// Reads the shapes from specified stream. /// </summary> /// <param name="stream">A System.IO.Stream instance to read shapes</param> /// <param name="offsets">An array containing the offset of records to read</param> /// <param name="bounds">The bounding rectangle. Only those records are read, /// which bounding rectangles intersect with this rectangle</param> public void ReadShapes(Stream stream, int[] offsets, BoundingRectangle bounds) { this.ReadHeader(stream); this._records.Clear(); if (offsets.Length == 0) { while (true) { try { this.ReadRecord(stream, null, bounds); } catch (IOException) { break; } } } else { int i = 0; foreach (int offset in offsets) { //!!!!! int lPos = offset;// -4 * i; this.ReadRecord(stream, lPos, bounds); i++; } } } /// <summary> /// Reads the header oe shape-file. /// <remarks> /// Headers are placed into .shp and .shx files. /// </remarks> /// </summary> /// <param name="stream">A System.IO.Stream instance to read</param> public void ReadHeader(Stream stream) { // êîä ôîðìàòà this._fileHeader.FileCode = stream.ReadInt32BE();// ShapeFile.ReadInt32_BE(stream); if (this._fileHeader.FileCode != ShapeFile._expectedFileCode) { string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, "Invalid FileCode encountered. Expecting {0}.", ShapeFile._expectedFileCode); throw new InvalidDataException(msg); } stream.ReadInt32BE();//ShapeFile.ReadInt32_BE(stream); stream.ReadInt32BE();//ShapeFile.ReadInt32_BE(stream); stream.ReadInt32BE();//ShapeFile.ReadInt32_BE(stream); stream.ReadInt32BE();//ShapeFile.ReadInt32_BE(stream); stream.ReadInt32BE();//ShapeFile.ReadInt32_BE(stream); this._fileHeader.FileLength = stream.ReadInt32BE();// ShapeFile.ReadInt32_BE(stream); this._fileHeader.Version = stream.ReadInt32();// ShapeFile.ReadInt32_LE(stream); this._fileHeader.ShapeType = stream.ReadInt32();// ShapeFile.ReadInt32_LE(stream); this._fileHeader.MinX = stream.ReadDouble();// ShapeFile.ReadDouble64_LE(stream); this._fileHeader.MinY = stream.ReadDouble();// ShapeFile.ReadDouble64_LE(stream); this._fileHeader.MaxX = stream.ReadDouble();// ShapeFile.ReadDouble64_LE(stream); this._fileHeader.MaxY = stream.ReadDouble();// ShapeFile.ReadDouble64_LE(stream); if (Math.Abs(this._fileHeader.MaxX - this._fileHeader.MinX) < 1) { this._fileHeader.MinX -= 5; this._fileHeader.MaxX += 5; } if (Math.Abs(this._fileHeader.MaxY - this._fileHeader.MinY) < 1) { this._fileHeader.MinY -= 5; this._fileHeader.MaxY += 5; } stream.Seek(100, SeekOrigin.Begin); } /// <summary> /// Reads a record from the specified stream. /// </summary> /// <param name="stream">A System.IO.Stream instance to read</param> /// <param name="recordOffset">An offset of record</param> /// <param name="bounds">An object representing a bounds of the reading area</param> public ShapeFileRecord ReadRecord(Stream stream, int? recordOffset, BoundingRectangle bounds) { #region old //if (recordOffset != null) // stream.Seek(recordOffset.Value, 0); //ShapeFileRecord record = new ShapeFileRecord(); //record.Offset = stream.Position; //// çàãîëîâîê çàïèñè //record.RecordNumber = ShapeFile.ReadInt32_BE(stream); //record.ContentLength = ShapeFile.ReadInt32_BE(stream); //// òèï ãåîìåòðè÷åñêîé ôèãóðû //record.ShapeType = ShapeFile.ReadInt32_LE(stream); //bool wasRead = false; //switch (record.ShapeType) //{ // case (int)ShapeType.NullShape: // break; // case (int)ShapeType.Point: // wasRead = ShapeFile.ReadPoint(stream, bounds, record); // break; // case (int)ShapeType.PolyLine: // wasRead = ShapeFile.ReadPolygon(stream, bounds, record); // break; // case (int)ShapeType.Polygon: // wasRead = ShapeFile.ReadPolygon(stream, bounds, record); // break; // case (int)ShapeType.Multipoint: // wasRead = ShapeFile.ReadMultipoint(stream, bounds, record); // break; // default: // { // string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, "ShapeType {0} is not supported.", (int)record.ShapeType); // throw new InvalidDataException(msg); // } //} //if (wasRead) //{ // this._records.Add(record); // return record; //} //else return null; #endregion #region New if (recordOffset != null) stream.Seek(recordOffset.Value, 0); ShapeFileRecord record = new ShapeFileRecord(); record.Offset = stream.Position; // çàãîëîâîê çàïèñè //BigEndianBinaryReader reader = new BigEndianBinaryReader(stream); //record.RecordNumber = reader.ReadInt32BE();// ShapeFile.ReadInt32_BE(stream); //record.ContentLength = reader.ReadInt32BE();// ShapeFile.ReadInt32_BE(stream); record.RecordNumber = stream.ReadInt32BE();// ShapeFile.ReadInt32_BE(stream); record.ContentLength = stream.ReadInt32BE();// ShapeFile.ReadInt32_BE(stream); // òèï ãåîìåòðè÷åñêîé ôèãóðû record.ShapeType = stream.ReadInt32();//.ReadInt32BE();// ShapeFile.ReadInt32_LE(stream); ShapeHandler handler = ShapeFile.GetShapeHandler((ShapeType)record.ShapeType); if (handler.Read(stream, bounds, record)) { this._records.Add(record); return record; } else return null; #endregion } /// <summary> /// Reads a dBase file and merges dBase records with shapes. /// </summary> /// <param name="dbaseFile">The dBase file name</param> public void ReadAttributes(string dbaseFile) { if (string.IsNullOrEmpty(dbaseFile)) throw new ArgumentNullException("dbaseFile"); // îòñóòñòâèå ôàéëà àòðèáóòîâ - íå îøèáêà if (!File.Exists(dbaseFile)) return; using (DbaseReader reader = new DbaseReader(dbaseFile)) { reader.Open(); if (reader.DbaseHeader.Encoding == Encoding.UTF8) reader.DbaseHeader.Encoding = _attributesEncoding; // ÷òåíèå íàèìåíîâàíèé àòðèáóòîâ DataTable schema = reader.GetSchemaTable(); _attributeNames.Clear(); for (int i = 0; i < schema.Rows.Count; i++) _attributeNames.Add(schema.Rows[i]["ColumnName"].ToString()); // ÷òåíèå çíà÷åíèé àòðèáóòîâ DataTable table = reader.NewTable; for (int i = 0; i < Records.Count; i++) table.Rows.Add(reader.GetRow((uint)_records[i].RecordNumber - 1, table)); //byte lEndFile = reader.ReadByte(); //if (lEndFile != default(byte)) //{ //} MergeAttributes(table); } } #endregion /// <summary> /// Returns a System.String that represents the current MapAround.IO.ShapeFiler. /// </summary> /// <returns>A System.String that represents the current MapAround.IO.ShapeFile</returns> public override string ToString() { return "ShapeFile: " + this._fileHeader.ToString(); } #region Write /// <summary> /// Writes the attribute file. /// </summary> /// <param name="featureCollection">A collection containing features which attributes is to be written</param> /// <param name="dbaseFile">file attributes</param> public void WriteAttributes(string dbaseFile, ICollection<Feature> featureCollection) { if (this._dbaseHeader == null) throw new NullReferenceException("dbaseHeader"); if (string.IsNullOrEmpty(dbaseFile)) throw new ArgumentNullException("dbaseFile"); //if there is no file attributes - create if (!File.Exists(dbaseFile)) { Stream file = File.Create(dbaseFile); file.Close(); } this.RecountColumnLengths(this._dbaseHeader, featureCollection); this.RecountRecords(this._dbaseHeader,featureCollection); DbaseWriter dbaseWriter = new DbaseWriter(dbaseFile, this._dbaseHeader); //dbaseWriter.WriteHeader();//this._dbaseHeader); try { //this.RecountColumnLengths(this._dbaseHeader, featureCollection); dbaseWriter.WriteHeader();//this._dbaseHeader); int j = 0; foreach (Feature feature in featureCollection) { ArrayList values = new ArrayList(); for (int i = 0; i < dbaseWriter.Header.NumFields; i++) values.Add(feature[dbaseWriter.Header.DBaseColumns[i].Name]);// attribs[Header.Fields[i].Name]); dbaseWriter.Write(values, j); j++; } //end of file dbaseWriter.Write((byte)26); } finally { dbaseWriter.Close(); } } /// <summary> /// Writes shapes. /// </summary> /// <param name="filename">The string value defining shape file name without .shp extension</param> /// <param name="geometryCollection"> MapAround.Geometry.GeometryCollection instance containing /// the geometries to write to shape file</param> public void WriteShapes(string filename, GeometryCollection geometryCollection) { if(geometryCollection.HasDifferentTypeInstances) throw new ArgumentException("Geometries in the shape file should be the instances of the same type.", "geometryCollection"); using (FileStream shpStream = new FileStream(filename + ".shp", FileMode.Create)) { using (FileStream shxStream = new FileStream(filename + ".shx", FileMode.Create)) { BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream);//, Encoding.ASCII); BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream);//, Encoding.ASCII); // body type and a handler Handlers.ShapeHandler handler = ShapeFile.GetShapeHandler(ShapeFile.GetShapeType(geometryCollection[0]));//.Geometries[0])); int numShapes = geometryCollection.Count; // calc the length of the shp file, so it can put in the header. int shpLength = 50; for (int i = 0; i < numShapes; i++) { IGeometry body = (IGeometry)geometryCollection[i];//.Geometries[i]; shpLength += 4; // length of header in WORDS shpLength += handler.GetLength(body); // length of shape in WORDS } int shxLength = 50 + (4 * numShapes); // write the .shp header ShapeFileHeader shpHeader = new ShapeFileHeader(); shpHeader.FileLength = shpLength; // get envelope in external coordinates BoundingRectangle bounds = geometryCollection.GetBoundingRectangle(); shpHeader.SetBounds(bounds); shpHeader.FileCode = 9994; shpHeader.ShapeType = (int)ShapeFile.GetShapeType(geometryCollection[0]);//.Geometries[0]); shpHeader.Write(shpBinaryWriter, ShapeFile.GetShapeType(geometryCollection[0])); // write the .shx header ShapeFileHeader shxHeader = new ShapeFileHeader(); shxHeader.FileLength = shxLength; shxHeader.SetBounds(shpHeader);//.Bounds = shpHeader.Bounds; // assumes Geometry type of the first item will the same for all other items in the collection. shxHeader.FileCode = 9994; shxHeader.ShapeType = (int)ShapeFile.GetShapeType(geometryCollection[0]); shxHeader.Write(shxBinaryWriter, ShapeFile.GetShapeType(geometryCollection[0])); // write the individual records. int _pos = 50; // header length in WORDS for (int i = 0; i < numShapes; i++) { IGeometry body = geometryCollection[i];//.Geometries[i]; int recordLength = handler.GetLength(body); shpBinaryWriter.WriteIntBE(i + 1); shpBinaryWriter.WriteIntBE(recordLength); shxBinaryWriter.WriteIntBE(_pos); shxBinaryWriter.WriteIntBE(recordLength); _pos += 4; // length of header in WORDS handler.Write(body, shpBinaryWriter);//, geometryFactory); _pos += recordLength; // length of shape in WORDS } shxBinaryWriter.Flush(); shxBinaryWriter.Close(); shpBinaryWriter.Flush(); shpBinaryWriter.Close(); } } } /// <summary> /// Writes a collection of features into the shape-file. /// </summary> /// <param name="fileName">The string defining file name without .shp extension</param> /// <param name="features">The collection of features to write</param> public void Write(string fileName, ICollection<Feature> features) { // Test if the Header is initialized if (this._dbaseHeader == null) throw new ApplicationException("Dbase header should be set first."); // Write shp and shx IGeometry[] geometries = new IGeometry[features.Count]; int index = 0; foreach (Feature feature in features) geometries[index++] = feature.Geometry; GeometryCollection geomTmp = new GeometryCollection(geometries); string shpFile = fileName; string dbfFile = fileName + ".dbf"; this.WriteShapes(shpFile, geomTmp); this.WriteAttributes(dbfFile, features); } #endregion #endregion #region Private methods private static bool isRecordInView(BoundingRectangle bounds, ShapeFileRecord record) { if (bounds != null && !bounds.IsEmpty()) { if (!bounds.Intersects( new BoundingRectangle(PlanimetryEnvironment.NewCoordinate(record.MinX, record.MinY), PlanimetryEnvironment.NewCoordinate(record.MaxX, record.MaxY)))) return false; } return true; } /// <summary> /// Merges attribute rows with the shape file records. /// </summary> /// <param name="table">The system.Data.DataTable instance containing the attribute values</param> private void MergeAttributes(DataTable table) { int index = 0; foreach (DataRow row in table.Rows) { if (index >= _records.Count) break; _records[index].Attributes = row; ++index; } } /// <summary> /// Computes the sizes of attribute fileds taking into accound /// attribute values of the features. /// </summary> /// <param name="DbaseHeader">The header of the dBase attribute file</param> /// <param name="Features">Enumerator of features</param> private void RecountColumnLengths(DbaseFileHeader DbaseHeader, IEnumerable Features) { foreach (DbaseFieldDescriptor field in DbaseHeader.DBaseColumns) { var fieldValues = Features.OfType<Feature>().Select(f => f[field.Name]); DbaseHeader.RecountColumnLength(field, fieldValues); } } /// <summary> /// Computes the count of DBF records /// </summary> /// <param name="DbaseHeader">The header of the dBase attribute file</param> /// <param name="Features">Enumerator of features</param> private void RecountRecords(DbaseFileHeader DbaseHeader, IEnumerable Features) { DbaseHeader.NumRecords = Features.Cast<Feature>().Count(); } #endregion Private methods #region Static Methods /// <summary> /// Gets a stub of dBase file header /// </summary> /// <param name="feature">The feature</param> /// <param name="count">The record count</param> /// <param name="attributeNames">A list containing the attribute names</param> /// <returns>A stub of dBase file header</returns> public static DbaseFileHeader GetDbaseHeader(Feature feature, List<string> attributeNames, int count) { //string[] names = feature.Layer.FeatureAttributeNames.ToArray();// attribs.GetNames(); string[] names = attributeNames.ToArray();// attribs.GetNames(); DbaseFileHeader header = new DbaseFileHeader(); header.NumRecords = count; int i = 0; foreach (string name in names) { Type type = feature.Attributes[i].GetType();// attribs.GetType(name); header.AddColumn(name, type); i++; } header.Encoding = System.Text.ASCIIEncoding.ASCII; return header; } /// <summary> /// Generates a dBase file header. /// </summary> /// <param name="dbFields">An array containing the dBase filed descriptors</param> /// <param name="count">The record count</param> /// <returns>A stub of dBase file header</returns> public static DbaseFileHeader GetDbaseHeader(DbaseFieldDescriptor[] dbFields, int count) { DbaseFileHeader header = new DbaseFileHeader(); header.NumRecords = count; foreach (DbaseFieldDescriptor dbField in dbFields) header.AddColumn(dbField.Name, dbField.DbaseType, dbField.DataType, dbField.Length, dbField.DecimalCount); return header; } /// <summary> /// Gets the header from a dbf file. /// </summary> /// <param name="dbfFile">The DBF file.</param> /// <returns>The dBase file header</returns> public static DbaseFileHeader GetDbaseHeader(string dbfFile) { if (!File.Exists(dbfFile)) throw new FileNotFoundException(dbfFile + " not found"); DbaseFileHeader header = new DbaseFileHeader(); header.Read(new BinaryReader(new FileStream(dbfFile, FileMode.Open, FileAccess.Read, FileShare.Read))); return header; } /// <summary> /// Returns the appropriate class to convert a shaperecord to an MapAround geometry given the type of shape. /// </summary> /// <param name="type">The shape file type.</param> /// <returns>An instance of the appropriate handler to convert the shape record to a Geometry</returns> internal static ShapeHandler GetShapeHandler(ShapeType type) { switch (type) { case ShapeType.Point: //case ShapeGeometryType.PointM: //case ShapeGeometryType.PointZ: //case ShapeGeometryType.PointZM: return new PointHandler(); case ShapeType.Polygon: //case ShapeGeometryType.PolygonM: //case ShapeGeometryType.PolygonZ: //case ShapeGeometryType.PolygonZM: return new PolygonHandler(); case ShapeType.Polyline: //.LineString: //case ShapeGeometryType.LineStringM: //case ShapeGeometryType.LineStringZ: //case ShapeGeometryType.LineStringZM: return new MultiLineHandler(); case ShapeType.Multipoint: //case ShapeGeometryType.MultiPointM: //case ShapeGeometryType.MultiPointZ: //case ShapeGeometryType.MultiPointZM: return new MultiPointHandler(); default: string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, "ShapeType {0} is not supported.", (int)type); throw new InvalidDataException(msg); } } /// <summary> /// Given a geomtery object, returns the equilivent shape file type. /// </summary> /// <param name="geom">A Geometry object.</param> /// <returns>The equilivent for the geometry object.</returns> public static ShapeType GetShapeType(IGeometry geom) { if (geom is PointD) return ShapeType.Point; if (geom is Polygon) return ShapeType.Polygon; //if (geom is IMultiPolygon) // return ShapeGeometryType.Polygon; if (geom is LinePath) return ShapeType.Polyline;//.LineString; if (geom is Polyline) return ShapeType.Polyline;//.LineString; if (geom is MultiPoint) return ShapeType.Multipoint; return ShapeType.NullShape; } #endregion } }
gkrsu/maparound.core
src/MapAround.Core/IO/ShapeFile.cs
C#
gpl-3.0
43,817
/* Copyright (c) 2012 Richard Klancer <rpk@pobox.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global $ console */ var x = 0, y = 0, intervalID, INTERVAL_LENGTH = 200; // ms // define console as a noop if not defined if (typeof console === 'undefined') console = { log: function() {} }; function postJoystickPosition() { $.post('/joystick', { x: x, y: y }); } function startSending() { intervalID = setInterval(postJoystickPosition, INTERVAL_LENGTH); } function stopSending() { // one last time postJoystickPosition(); clearInterval(intervalID); } // draws "joystick", updates x and y function joystickGo() { // Just do the dead simplest thing right now -- we have one draggable element, and no encapsulation var dragInfo = {}, centerX, centerY, radialLimit, radialLimitSquared; function updatePosition(_x, _y) { x = _x / radialLimit; y = - _y / radialLimit; console.log(x,y); } function centerKnob() { var $el = $(dragInfo.element), width = $('#background').width(); $el.animate({ left: width/2, top: width/2 }, 200); updatePosition(0, 0); } function dragStart(evt) { dragInfo.dragging = true; evt.preventDefault(); var $el = $(dragInfo.element), offset = $el.offset(), width = $el.width(), cx = offset.left + width/2 - centerX, cy = offset.top + width/2 - centerY; dragInfo.dx = evt.pageX - cx; dragInfo.dy = evt.pageY - cy; startSending(); } function drag(evt) { if ( ! dragInfo.dragging ) return; evt.preventDefault(); var $el = $(dragInfo.element), offset = $el.offset(), width = $el.width(), // find the current center of the element cx = offset.left + width/2 - centerX, cy = offset.top + width/2 - centerY, newcx = evt.pageX - dragInfo.dx, newcy = evt.pageY - dragInfo.dy, newRadiusSquared = newcx*newcx + newcy*newcy, scale; if (newRadiusSquared > radialLimitSquared) { scale = Math.sqrt( radialLimitSquared / newRadiusSquared ); newcx *= scale; newcy *= scale; } updatePosition(newcx, newcy); offset.left += (newcx - cx); offset.top += (newcy - cy); $(dragInfo.element).offset(offset); } function dragEnd() { dragInfo.dragging = false; centerKnob(); stopSending(); } function adjustDimensions() { var $background = $('#background'), $knob = $('#knob'), offset = $background.offset(), width = $background.width(); makeCircular($background); makeCircular($knob); centerX = width/2 + offset.left; centerY = width/2 + offset.top; radialLimit = (width - $knob.width()) / 2; radialLimitSquared = radialLimit * radialLimit; } function makeCircular($el) { var width = $el.width(); // Android 2 browser doesn't seem to understand percentage border-radius, so we need to set it // via an inline style once we know the width $el.css({ height: width, borderRadius: width/2 }); } function wrapForTouch(f) { return function(evt) { if (evt.originalEvent && evt.originalEvent.touches && evt.originalEvent.touches.length === 1) { evt.pageX = evt.originalEvent.touches[0].pageX; evt.pageY = evt.originalEvent.touches[0].pageY; } return f(evt); }; } $(function() { var $background = $('#background'), $knob = $('#knob'); adjustDimensions(); dragInfo.element = $knob[0]; $knob.bind('touchstart mousedown', wrapForTouch(dragStart)); $(document).bind('touchmove mousemove', wrapForTouch(drag)); $(document).bind('touchend mouseup', wrapForTouch(dragEnd)); $background.bind('mousedown', function() { return false; }); $(window).bind('resize', adjustDimensions); }); } // and...go: joystickGo();
rascalmicro/control-freak
public/static/js/joystick.js
JavaScript
gpl-3.0
4,902
/* This file is part of KUMobile. KUMobile is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. KUMobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with KUMobile. If not, see <http://www.gnu.org/licenses/>. */ /****************************************************************************** * Contains all news related functions for loading and controlling the news page. * * @class KUMobile.News ******************************************************************************/ KUMobile.News = { /****************************************************************************** * Current page number as referenced from the news website. * * @attribute page * @type {int} * @for KUMobile.News * @default 0 ******************************************************************************/ page: 0, /****************************************************************************** * Number of pages to load from the news website after a trigger event occurs. * * @attribute PAGES_TO_LOAD * @type {int} * @for KUMobile.News * @default 2 ******************************************************************************/ PAGES_TO_LOAD: 2, /****************************************************************************** * Is the news page loading? * * @attribute loading * @type {boolean} * @for KUMobile.News * @default false ******************************************************************************/ loading: false, /****************************************************************************** * Designates the minimum number of pixels that the user can scroll * (calculated from the bottom) before another load event is triggered. * * @attribute LOAD_THRESHOLD_PX * @type {int} * @for KUMobile.News * @default 660 ******************************************************************************/ LOAD_THRESHOLD_PX: 660, /****************************************************************************** * How many pages that need to be downloaded still. This is used to asynchronously * download pages. * * @attribute queue * @type {int} * @for KUMobile.News * @default 0 * @private ******************************************************************************/ queue: 0, /****************************************************************************** * Contains the current list of article DOM <li> tag items that still need * to be added to the DOM (much faster to add all at once after load * is done downloading). This helps prevent the application from seeming to * hang or become unresponsive. * * @attribute listQueue * @type {Array} * @for KUMobile.News * @private ******************************************************************************/ listQueue: [], /****************************************************************************** * Contains the current list of pages DOM data-role="page" * items that still need to be added to the DOM (much faster to * add all at once after load is done downloading). This helps * prevent the app from seeming to hang or become unresponsive. * * @attribute pageQueue * @type {Array} * @for KUMobile.News * @private ******************************************************************************/ pageQueue: [], /****************************************************************************** * Triggered when the news page is first initialized based on jQuery Mobile * pageinit event. * * @event pageInit * @for KUMobile.News ******************************************************************************/ pageInit: function(event){ KUMobile.News.initialized = true; // Check overflow scroll position $('#news-scroller').on("scroll", KUMobile.News.scroll); }, /****************************************************************************** * Triggered when the news page is first created based on jQuery Mobile * pagecreate event. This is called after the page itself is created but * before any jQuery Mobile styling is applied. * * @event pageCreate * @for KUMobile.News ******************************************************************************/ pageCreate: function(event){ // Resize and get first page $(window).trigger("throttledresize"); KUMobile.News.loadNextPage(); }, /****************************************************************************** * Triggered when regular scroll event happens in news scroller window. It * is used to check if the user is *near* the bottom of the page, so more * content can be loaded (simulate *infinite scrolling*). * * @event scroll * @for KUMobile.News ******************************************************************************/ scroll: function(event){ // Get scroll position var scrollPosition = $('#news-scroller').scrollTop() + $('#news-scroller').outerHeight(); // Break threshold? if($('#news-list').height() < (KUMobile.News.LOAD_THRESHOLD_PX + $('#news-scroller').scrollTop() + $('#news-scroller').outerHeight()) && $('#news').is(':visible') && !(KUMobile.News.loading)){ // Get the next page! KUMobile.News.loadNextPage(); } }, /****************************************************************************** * Loads and displays the next set of news items. * * @method loadNextPage * @for KUMobile.News * @example * KUMobile.News.loadNextPage(); ******************************************************************************/ loadNextPage: function (){ if(!this.loading){ // Now loading this.loading = true; // Empty queue? if(this.queue <= 0){ // Initialize the queue // start with default pages // show loading indicator! this.queue = KUMobile.News.PAGES_TO_LOAD; KUMobile.showLoading("news-header"); } /** Success **/ var success = function(items){ // Increment page KUMobile.News.page++; // Setup data for(var index = 0; index < items.length; index++){ // Current item and template var item = items[index]; var captionTpl = Handlebars.getTemplate("news-item"); var pageTpl = Handlebars.getTemplate("dynamic-page"); var pageId = 'news-' + KUMobile.News.page + '-' + index; var info = item.author; info += (info == "")? item.date: " | " + item.date; // Caption data var captionHtml = captionTpl({ "title": item.title, "imgUrl": (item.imgUrl=="")?("img/default_icon.jpg"):(item.imgUrl), "info": info, "pageId": pageId }); // Page data var pageHtml = pageTpl({ "link": item.detailsUrl, "pageId": pageId, "headerTitle": "News", "scrollerId": pageId + "-scroller" }); // Register event $(document).on("pagecreate",'#' + pageId, KUMobile.News.articlePageCreate); // Add list item to queue KUMobile.News.listQueue[KUMobile.News.listQueue.length] = captionHtml; KUMobile.News.pageQueue[KUMobile.News.pageQueue.length] = pageHtml; } // Flush? if(--KUMobile.News.queue <= 0){ // Not loading KUMobile.hideLoading("news-header"); KUMobile.News.loading = false; // Go through all list items for (var index = 0; index < KUMobile.News.listQueue.length; index++){ // Append to news list $(KUMobile.News.listQueue[index]).appendTo("#news-list"); } // Go through all page items for (var index = 0; index < KUMobile.News.pageQueue.length; index++){ // Append to news list $(KUMobile.News.pageQueue[index]).appendTo("body"); } // Setup link opener KUMobile.safeBinder("click", ".dynamic-news-events-page .scroller a", function(e){ // Android open? Otherwise use _system target if (KUMobile.Config.isAndroid) navigator.app.loadUrl($(this).attr('href'), {openExternal : true}); else window.open($(this).attr('href'), '_system'); // Prevent default e.preventDefault(); return false; }); // Check for new articles only during initialization if(KUMobile.News.initialized != true){ // Get read news var news_list = window.localStorage.getItem("ku_news_read"); // Make empty or parse array if(news_list != null){ try{ // Parse news array news_list = JSON.parse(news_list); } catch(object){ news_list = []; } // Go through each list item $("#news-list li a div.main-text").each(function(i){ // Get id var id = $("h1", this).text().trim(); var found = false; // Search for match for (var readIndex = 0; readIndex < news_list.length; readIndex++){ if (id == news_list[readIndex]) found = true; } // Not found? if (!found){ KUMobile.addNewIndicator("#news-listitem a div.main-text"); KUMobile.addNewIndicator(this); } }); } } // Refresh and clear both lists if(KUMobile.News.initialized) $('#news-list').listview('refresh'); KUMobile.News.listQueue = []; KUMobile.News.pageQueue = []; } // More news to be downloaded! else { // Load more KUMobile.News.loading = false; KUMobile.News.loadNextPage(); } }; /** Fail **/ var failure = function(error){ // Not loading anymore presumably.. KUMobile.hideLoading("news-header"); KUMobile.News.loading = false; KUMobile.safeAlert("Error", "Sorry the news could not be loaded. Check your" + " internet connection. If the issue persists then please report the bug.", "ok"); }; // Get next page KU.News.nextPage(success, failure); } }, /****************************************************************************** * Called on create of an article page. Mainly this function just * attempts to download the article and show it. * * @event articlePageCreate * @for KUMobile.News ******************************************************************************/ articlePageCreate: function(event){ // Now loading KUMobile.News.loading = true; KUMobile.showLoading(this.id); var identifier = this.id; var success = function(article){ var articleTpl = Handlebars.getTemplate("news-article"); var html = articleTpl({ "title": article.title, "info": article.headerInfo }); $(html).appendTo("#" + identifier + "-scroller"); mainParagraph = KUMobile.sanitize(article.mainHtml); // Fix max width and height mainParagraph.find('*').css("max-width", "100%").css("height","auto"); // Remove hard-coded width from table mainParagraph.find('table').css('width',''); mainParagraph.css('padding','4px'); // Remove "Related" fields mainParagraph.find("h3").each(function(i){ // Related header if($(this).text() === "Related:"){ // Find all links under it $(this).parent().parent().parent().find("tr td ul li a").each(function(j){ // Remove! $(this).parent().parent().parent().parent().remove(); }); // Remove related! $(this).parent().parent().remove(); } }); // Fix youtube videos mainParagraph.find("embed").each(function(i){ if($(this).attr("src") != undefined && $(this).attr("src").indexOf("youtube") > -1){ // Complex regex var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; var match = $(this).attr("src").match(regExp); // Match? if (match && match[2].length == 11) { var id = match[2]; var youtubeFrame = $("<iframe></iframe>",{ "width":"100%", "height":"auto", "src":"http://www.youtube.com/embed/" + id + "?version=3&rel=0&amp;controls=0&amp;showinfo=0", "frameborder":"0", "allowfullscreen":"true" }); $(this).parent().append(youtubeFrame); $(this).remove(); } } }); // Append mainParagraph.appendTo("#" + identifier + "-scroller"); // Resize when new elements load $(mainParagraph).find('*').load(function(){ $(window).trigger("resize");}); // Resize anyways! in case there was nothing to load from above $(window).trigger("resize"); // Done loading! KUMobile.hideLoading(identifier); KUMobile.News.loading = false; } var failure = function(error){ // Not loading anymore presumably.. KUMobile.hideLoading(identifier); KUMobile.News.loading = false; KUMobile.safeAlert("Error", "Sorry the news could not be loaded. Check your" + " internet connection. If the issue persists then please report the bug.", "ok"); } // Get the article! KU.News.downloadArticle($('#' + identifier).attr("kulink"), success, failure) } };
garrickbrazil/kumobile
www/js/news.js
JavaScript
gpl-3.0
17,619
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * "PCPIN Chat 6" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Callback function to execute after confirm box receives "OK". */ var confirmboxCallback=''; /** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string') { document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); } } /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function hideConfirmBox(ok) { document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
Dark1revan/chat1
js/base/confirmbox.js
JavaScript
gpl-3.0
2,595
/* * FlightIntel for Pilots * * Copyright 2012 Nadeem Hasan <nhasan@nadmm.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nadmm.airports.wx; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.nadmm.airports.FragmentBase; import com.nadmm.airports.ImageViewActivity; import com.nadmm.airports.R; public abstract class WxMapFragmentBase extends FragmentBase { private String mAction; private BroadcastReceiver mReceiver; private IntentFilter mFilter; private String[] mWxTypeCodes; private String[] mWxTypeNames; private String[] mWxMapCodes; private String[] mWxMapNames; private String mLabel; private String mTitle; private String mHelpText; private View mPendingRow; private Spinner mSpinner; public WxMapFragmentBase( String action, String[] mapCodes, String[] mapNames ) { mAction = action; mWxMapCodes = mapCodes; mWxMapNames = mapNames; mWxTypeCodes = null; mWxTypeNames = null; } public WxMapFragmentBase( String action, String[] mapCodes, String[] mapNames, String[] typeCodes, String[] typeNames ) { mAction = action; mWxMapCodes = mapCodes; mWxMapNames = mapNames; mWxTypeCodes = typeCodes; mWxTypeNames = typeNames; } @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setHasOptionsMenu( false ); mReceiver = new BroadcastReceiver() { @Override public void onReceive( Context context, Intent intent ) { String action = intent.getAction(); if ( action.equals( mAction ) ) { String type = intent.getStringExtra( NoaaService.TYPE ); if ( type.equals( NoaaService.TYPE_IMAGE ) ) { showWxMap( intent ); } } } }; mFilter = new IntentFilter(); mFilter.addAction( mAction ); } @Override public void onResume() { mPendingRow = null; LocalBroadcastManager bm = LocalBroadcastManager.getInstance( getActivity() ); bm.registerReceiver( mReceiver, mFilter ); super.onResume(); } @Override public void onPause() { LocalBroadcastManager bm = LocalBroadcastManager.getInstance( getActivity() ); bm.unregisterReceiver( mReceiver ); super.onPause(); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { View v = inflate( R.layout.wx_map_detail_view ); if ( mLabel != null && mLabel.length() > 0 ) { TextView tv = (TextView) v.findViewById( R.id.wx_map_label ); tv.setText( mLabel ); tv.setVisibility( View.VISIBLE ); } if ( mHelpText != null && mHelpText.length() > 0 ) { TextView tv = (TextView) v.findViewById( R.id.help_text ); tv.setText( mHelpText ); tv.setVisibility( View.VISIBLE ); } OnClickListener listener = new OnClickListener() { @Override public void onClick( View v ) { if ( mPendingRow == null ) { mPendingRow = v; String code = getMapCode( v ); requestWxMap( code ); } } }; LinearLayout layout = (LinearLayout) v.findViewById( R.id.wx_map_layout ); for ( int i = 0; i < mWxMapCodes.length; ++i ) { View row = addProgressRow( layout, mWxMapNames[ i ] ); row.setTag( mWxMapCodes[ i ] ); row.setOnClickListener( listener ); row.setBackgroundResource( R.drawable.row_selector_middle ); } if ( mWxTypeCodes != null ) { TextView tv = (TextView) v.findViewById( R.id.wx_map_type_label ); tv.setVisibility( View.VISIBLE ); layout = (LinearLayout) v.findViewById( R.id.wx_map_type_layout ); layout.setVisibility( View.VISIBLE ); mSpinner = (Spinner) v.findViewById( R.id.map_type ); ArrayAdapter<String> adapter = new ArrayAdapter<String>( getActivity(), android.R.layout.simple_spinner_item, mWxTypeNames ); adapter.setDropDownViewResource( R.layout.support_simple_spinner_dropdown_item ); mSpinner.setAdapter( adapter ); } return v; } private void requestWxMap( String code ) { setProgressBarVisible( true ); Intent service = getServiceIntent(); service.setAction( mAction ); service.putExtra( NoaaService.TYPE, NoaaService.TYPE_IMAGE ); service.putExtra( NoaaService.IMAGE_CODE, code ); if ( mSpinner != null ) { int pos = mSpinner.getSelectedItemPosition(); service.putExtra( NoaaService.IMAGE_TYPE, mWxTypeCodes[ pos ] ); } setServiceParams( service ); getActivity().startService( service ); } protected void setServiceParams( Intent intent ) { } private void showWxMap( Intent intent ) { String path = intent.getStringExtra( NoaaService.RESULT ); if ( path != null ) { Intent view = new Intent( getActivity(), WxImageViewActivity.class ); view.putExtra( ImageViewActivity.IMAGE_PATH, path ); if ( mTitle != null ) { view.putExtra( ImageViewActivity.IMAGE_TITLE, mTitle ); } else { view.putExtra( ImageViewActivity.IMAGE_TITLE, getActivity().getTitle() ); } String code = intent.getStringExtra( NoaaService.IMAGE_CODE ); String name = getDisplayText( code ); if ( name != null ) { view.putExtra( ImageViewActivity.IMAGE_SUBTITLE, name ); } startActivity( view ); } else { mPendingRow = null; } setProgressBarVisible( false ); } protected String getMapCode( View v ) { return (String) v.getTag(); } protected String getDisplayText( String code ) { for ( int i = 0; i < mWxMapCodes.length; ++i ) { if ( code.equals( mWxMapCodes[ i ] ) ) { return mWxMapNames[ i ]; } } return ""; } protected void setLabel( String label ) { mLabel = label; } protected void setTitle( String title ) { mTitle = title; } protected void setHelpText( String text ) { mHelpText = text; } private void setProgressBarVisible( boolean visible ) { if ( mPendingRow != null ) { View view = mPendingRow.findViewById( R.id.progress ); view.setVisibility( visible? View.VISIBLE : View.INVISIBLE ); } } protected abstract Intent getServiceIntent(); }
postalservice14/Airports
src/main/java/com/nadmm/airports/wx/WxMapFragmentBase.java
Java
gpl-3.0
8,030
/** * Copyright (C) 2012 HTWG Konstanz, Oliver Haase * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Stub class generated by rmic, do not edit. // Contents subject to change without notice. package de.htwg_konstanz.rmi.registry; public final class RemoteRegistry_Stub extends java.rmi.server.RemoteStub implements java.rmi.registry.Registry, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { new java.rmi.server.Operation("void bind(java.lang.String, java.rmi.Remote)"), new java.rmi.server.Operation("java.lang.String list()[]"), new java.rmi.server.Operation("java.rmi.Remote lookup(java.lang.String)"), new java.rmi.server.Operation("void rebind(java.lang.String, java.rmi.Remote)"), new java.rmi.server.Operation("void unbind(java.lang.String)") }; private static final long interfaceHash = 4905912898345647071L; // constructors public RemoteRegistry_Stub() { super(); } public RemoteRegistry_Stub(java.rmi.server.RemoteRef ref) { super(ref); } // methods from remote interfaces // implementation of bind(String, Remote) public void bind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2) throws java.rmi.AccessException, java.rmi.AlreadyBoundException, java.rmi.RemoteException { try { java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); try { java.io.ObjectOutput out = call.getOutputStream(); out.writeObject($param_String_1); out.writeObject($param_Remote_2); } catch (java.io.IOException e) { throw new java.rmi.MarshalException("error marshalling arguments", e); } ref.invoke(call); ref.done(call); } catch (java.lang.RuntimeException e) { throw e; } catch (java.rmi.RemoteException e) { throw e; } catch (java.rmi.AlreadyBoundException e) { throw e; } catch (java.lang.Exception e) { throw new java.rmi.UnexpectedException("undeclared checked exception", e); } } // implementation of list() public java.lang.String[] list() throws java.rmi.AccessException, java.rmi.RemoteException { try { java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); ref.invoke(call); java.lang.String[] $result; try { java.io.ObjectInput in = call.getInputStream(); $result = (java.lang.String[]) in.readObject(); } catch (java.io.IOException e) { throw new java.rmi.UnmarshalException("error unmarshalling return", e); } catch (java.lang.ClassNotFoundException e) { throw new java.rmi.UnmarshalException("error unmarshalling return", e); } finally { ref.done(call); } return $result; } catch (java.lang.RuntimeException e) { throw e; } catch (java.rmi.RemoteException e) { throw e; } catch (java.lang.Exception e) { throw new java.rmi.UnexpectedException("undeclared checked exception", e); } } // implementation of lookup(String) public java.rmi.Remote lookup(java.lang.String $param_String_1) throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException { try { java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); try { java.io.ObjectOutput out = call.getOutputStream(); out.writeObject($param_String_1); } catch (java.io.IOException e) { throw new java.rmi.MarshalException("error marshalling arguments", e); } ref.invoke(call); java.rmi.Remote $result; try { java.io.ObjectInput in = call.getInputStream(); $result = (java.rmi.Remote) in.readObject(); } catch (java.io.IOException e) { throw new java.rmi.UnmarshalException("error unmarshalling return", e); } catch (java.lang.ClassNotFoundException e) { throw new java.rmi.UnmarshalException("error unmarshalling return", e); } finally { ref.done(call); } return $result; } catch (java.lang.RuntimeException e) { throw e; } catch (java.rmi.RemoteException e) { throw e; } catch (java.rmi.NotBoundException e) { throw e; } catch (java.lang.Exception e) { throw new java.rmi.UnexpectedException("undeclared checked exception", e); } } // implementation of rebind(String, Remote) public void rebind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2) throws java.rmi.AccessException, java.rmi.RemoteException { try { java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); try { java.io.ObjectOutput out = call.getOutputStream(); out.writeObject($param_String_1); out.writeObject($param_Remote_2); } catch (java.io.IOException e) { throw new java.rmi.MarshalException("error marshalling arguments", e); } ref.invoke(call); ref.done(call); } catch (java.lang.RuntimeException e) { throw e; } catch (java.rmi.RemoteException e) { throw e; } catch (java.lang.Exception e) { throw new java.rmi.UnexpectedException("undeclared checked exception", e); } } // implementation of unbind(String) public void unbind(java.lang.String $param_String_1) throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException { try { java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 4, interfaceHash); try { java.io.ObjectOutput out = call.getOutputStream(); out.writeObject($param_String_1); } catch (java.io.IOException e) { throw new java.rmi.MarshalException("error marshalling arguments", e); } ref.invoke(call); ref.done(call); } catch (java.lang.RuntimeException e) { throw e; } catch (java.rmi.RemoteException e) { throw e; } catch (java.rmi.NotBoundException e) { throw e; } catch (java.lang.Exception e) { throw new java.rmi.UnexpectedException("undeclared checked exception", e); } } }
htwg/UCE_deprecated
icermi/src/de/htwg_konstanz/rmi/registry/RemoteRegistry_Stub.java
Java
gpl-3.0
6,645
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AutoMapper; using MvcAutoMapper.Controllers.Base; namespace MvcAutoMapper.Controllers { public class HomeController : BaseController { public HomeController(IMapper mapper) : base(mapper) { } public ActionResult Index() { return View(); } } }
JRRN/.Net
AutoMapperConfig/MvcAutoMapper/Controllers/HomeController.cs
C#
gpl-3.0
433
package org.qii.weiciyuan.bean.android; import java.io.Serializable; import java.util.TreeSet; /** * User: qii * Date: 13-3-23 */ public class TimeLinePosition implements Serializable { public TimeLinePosition(int position, int top) { this.position = position; this.top = top; } public int position = 0; public int top = 0; public TreeSet<Long> newMsgIds = null; @Override public String toString() { StringBuilder stringBuilder = new StringBuilder().append("position:").append(position) .append("; top=").append(top); return stringBuilder.toString(); } }
xuyazhou18/siciyuan
src/org/qii/weiciyuan/bean/android/TimeLinePosition.java
Java
gpl-3.0
645
using System.Collections.Generic; namespace LanAdept.Models { public class IndexTeamModel { public List<TeamDemandeModel> Teams { get; set; } } }
ADEPT-Informatique/LanAdept
LanAdept/Models/Team/IndexTeamModel.cs
C#
gpl-3.0
157