repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Res2013/MyCleanArchitecture | MyCleanArchitecture/Library/src/androidTest/java/herry/library/ExampleInstrumentedTest.java | 735 | package herry.library;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("herry.library.test", appContext.getPackageName());
}
}
| gpl-3.0 |
csbernath/DataCommander | Foundation/.NetStandard-2.0/Data/IDataParameterValue.cs | 121 | namespace Foundation.Data
{
public interface IDataParameterValue
{
object ValueObject { get; }
}
} | gpl-3.0 |
jantman/puppet-archlinux-macbookretina | spec/spec_helper_acceptance.rb | 1099 | require 'beaker-rspec'
require 'beaker/puppet_install_helper'
require 'beaker/module_install_helper'
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# pacman update
hosts.each do |h|
on h, 'pacman -Syu --noconfirm' unless ENV['BEAKER_provision'] == 'no'
run_puppet_install_helper unless ENV['BEAKER_provision'] == 'no'
install_module_dependencies_on(h)
on h, puppet('module', 'install', 'jantman-archlinux_workstation')
# on ArchLinux, install_module_on(hosts) installs in /etc/puppet/modules
# instead of /etc/puppetlabs/code/modules
copy_module_to(h, source: proj_root, module_name: 'archlinux_macbookretina', target_module_path: '/etc/puppetlabs/code/modules')
on h, 'mkdir -p /etc/facter/facts.d'
scp_to(h, File.join(proj_root, 'spec', 'acceptance_test_fact_overrides.yaml'), '/etc/facter/facts.d/acceptance_test_overrides.yaml')
end
end
end
| gpl-3.0 |
OpenSID/OpenSID | donjo-app/controllers/buku_umum/Pengurus.php | 7138 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
* File ini:
*
* Controller untuk modul Pengaturan > Pengurus
*
* donjo-app/controllers/Pengurus.php
*
*/
/*
* File ini bagian dari:
*
* OpenSID
*
* Sistem informasi desa sumber terbuka untuk memajukan desa
*
* Aplikasi dan source code ini dirilis berdasarkan lisensi GPL V3
*
* Hak Cipta 2009 - 2015 Combine Resource Institution (http://lumbungkomunitas.net/)
* Hak Cipta 2016 - 2020 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
*
* Dengan ini diberikan izin, secara gratis, kepada siapa pun yang mendapatkan salinan
* dari perangkat lunak ini dan file dokumentasi terkait ("Aplikasi Ini"), untuk diperlakukan
* tanpa batasan, termasuk hak untuk menggunakan, menyalin, mengubah dan/atau mendistribusikan,
* asal tunduk pada syarat berikut:
*
* Pemberitahuan hak cipta di atas dan pemberitahuan izin ini harus disertakan dalam
* setiap salinan atau bagian penting Aplikasi Ini. Barang siapa yang menghapus atau menghilangkan
* pemberitahuan ini melanggar ketentuan lisensi Aplikasi Ini.
*
* PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN, BAIK TERSURAT MAUPUN
* TERSIRAT. PENULIS ATAU PEMEGANG HAK CIPTA SAMA SEKALI TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN ATAU
* KEWAJIBAN APAPUN ATAS PENGGUNAAN ATAU LAINNYA TERKAIT APLIKASI INI.
*
* @package OpenSID
* @author Tim Pengembang OpenDesa
* @copyright Hak Cipta 2009 - 2015 Combine Resource Institution (http://lumbungkomunitas.net/)
* @copyright Hak Cipta 2016 - 2020 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
* @license http://www.gnu.org/licenses/gpl.html GPL V3
* @link https://github.com/OpenSID/OpenSID
*/
class Pengurus extends Admin_Controller {
private $_set_page;
private $_list_session;
public function __construct()
{
parent::__construct();
$this->load->model(['pamong_model', 'penduduk_model', 'config_model', 'referensi_model', 'wilayah_model']);
$this->modul_ini = 301;
$this->sub_modul_ini = 302;
$this->_set_page = ['20', '50', '100'];
$this->_list_session = ['status', 'cari'];
}
public function clear()
{
$this->session->unset_userdata($this->_list_session);
$this->session->per_page = $this->_set_page[0];
redirect('pengurus');
}
public function index($p = 1)
{
foreach ($this->_list_session as $list)
{
$data[$list] = $this->session->$list ?: '';
}
$per_page = $this->input->post('per_page');
if (isset($per_page)) $this->session->per_page = $per_page;
$data['func'] = 'index';
$data['set_page'] = $this->_set_page;
$data['per_page'] = $this->session->per_page;
$data['paging'] = $this->pamong_model->paging($p);
$data['main'] = $this->pamong_model->list_data($data['paging']->offset, $data['paging']->per_page);
$data['keyword'] = $this->pamong_model->autocomplete();
$data['main_content'] = 'home/pengurus';
$data['subtitle'] = "Buku Aparat Pemerintah Desa";
$data['selected_nav'] = 'aparat';
$this->set_minsidebar(1);
$this->load->view('header', $this->header);
$this->load->view('nav');
$this->load->view('bumindes/umum/main', $data);
$this->load->view('footer');
}
public function form($id = 0)
{
$this->redirect_hak_akses('u');
$id_pend = $this->input->post('id_pend');
if ($id)
{
$data['pamong'] = $this->pamong_model->get_data($id);
if (!isset($id_pend)) $id_pend = $data['pamong']['id_pend'];
$data['form_action'] = site_url("pengurus/update/$id");
}
else
{
$data['pamong'] = NULL;
$data['form_action'] = site_url("pengurus/insert");
}
$data['atasan'] = $this->pamong_model->list_atasan($id);
$data['penduduk'] = $this->pamong_model->list_penduduk($id_pend ?? 0);
$data['pendidikan_kk'] = $this->referensi_model->list_data('tweb_penduduk_pendidikan_kk');
$data['agama'] = $this->referensi_model->list_data('tweb_penduduk_agama');
if (!empty($id_pend))
$data['individu'] = $this->penduduk_model->get_penduduk($id_pend);
else
$data['individu'] = NULL;
$this->render('home/pengurus_form', $data);
}
public function filter($filter)
{
$this->redirect_hak_akses('u');
$value = $this->input->post($filter);
if ($value != '')
$this->session->$filter = $value;
else $this->session->unset_userdata($filter);
redirect('pengurus');
}
public function insert()
{
$this->redirect_hak_akses('u');
$this->pamong_model->insert();
redirect('pengurus');
}
public function update($id = 0)
{
$this->redirect_hak_akses('u');
$this->pamong_model->update($id);
redirect('pengurus');
}
public function delete($id = 0)
{
$this->redirect_hak_akses('h');
$outp = $this->pamong_model->delete($id);
redirect('pengurus');
}
public function delete_all()
{
$this->redirect_hak_akses('h');
$this->pamong_model->delete_all();
redirect('pengurus');
}
public function ttd($id = 0, $val = 0)
{
$this->redirect_hak_akses('u');
$this->pamong_model->ttd('pamong_ttd', $id, $val);
redirect('pengurus');
}
public function ub($id = 0, $val = 0)
{
$this->redirect_hak_akses('u');
$this->pamong_model->ttd('pamong_ub', $id, $val);
redirect('pengurus');
}
public function urut($p = 1, $id = 0, $arah = 0)
{
$this->redirect_hak_akses('u');
$this->pamong_model->urut($id, $arah);
redirect("pengurus/index/$p");
}
public function lock($id = 0, $val = 1)
{
$this->redirect_hak_akses('u');
$this->pamong_model->lock($id, $val);
redirect("pengurus");
}
/*
* $aksi = cetak/unduh
*/
public function dialog($aksi = 'cetak')
{
$data['aksi'] = $aksi;
$data['pamong'] = $this->pamong_model->list_data();
$data['pamong_ttd'] = $this->pamong_model->get_ub();
$data['pamong_ketahui'] = $this->pamong_model->get_ttd();
$data['form_action'] = site_url("pengurus/daftar/$aksi");
$this->load->view('global/ttd_pamong', $data);
}
/*
* $aksi = cetak/unduh
*/
public function daftar($aksi = 'cetak')
{
$data['pamong_ttd'] = $this->pamong_model->get_data($this->input->post('pamong_ttd'));
$data['pamong_ketahui'] = $this->pamong_model->get_data($this->input->post('pamong_ketahui'));
$data['desa'] = $this->config_model->get_data();
$data['main'] = $this->pamong_model->list_data();
$this->load->view('home/'.$aksi, $data);
}
public function bagan($ada_bpd = '')
{
$data['desa'] = $this->config_model->get_data();
$data['bagan'] = $this->pamong_model->list_bagan();
$data['ada_bpd'] = ! empty($ada_bpd);
$this->render('home/bagan', $data);
}
public function atur_bagan()
{
$this->redirect_hak_akses('u');
$data['atasan'] = $this->pamong_model->list_atasan();
$data['form_action'] = site_url("pengurus/update_bagan");
$this->load->view('home/ajax_atur_bagan', $data);
}
public function update_bagan()
{
$this->redirect_hak_akses('u');
$post = $this->input->post();
$this->pamong_model->update_bagan($post);
redirect('pengurus');
}
public function atur_bagan_layout()
{
$this->redirect_hak_akses('u');
$data = [
'judul' => 'Atur Ukuran Bagan',
'kategori' => ['conf_bagan']
];
$this->load->view('global/modal_setting', $data);
}
}
| gpl-3.0 |
davidmp/sgeupeu | sgeupeu/src/java/sge/modelo/Temporada.java | 1047 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sge.modelo;
public class Temporada {
int idtemporada;
String inicio;
String descripcion;
String fin;
String estado;
public int getIdtemporada() {
return idtemporada;
}
public void setIdtemporada(int idtemporada) {
this.idtemporada = idtemporada;
}
public String getInicio() {
return inicio;
}
public void setInicio(String inicio) {
this.inicio = inicio;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getFin() {
return fin;
}
public void setFin(String fin) {
this.fin = fin;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
} | gpl-3.0 |
marcinkowalczyk/cgrates | engine/users_test.go | 24030 | /*
Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH
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 engine
import (
"reflect"
"testing"
"time"
"github.com/cgrates/cgrates/utils"
)
var testMap = UserMap{
table: map[string]map[string]string{
"test:user": map[string]string{"t": "v"},
":user": map[string]string{"t": "v"},
"test:": map[string]string{"t": "v"},
"test1:user1": map[string]string{"t": "v", "x": "y"},
"test:masked": map[string]string{"t": "v"},
},
index: make(map[string]map[string]bool),
properties: map[string]*prop{
"test:masked": &prop{masked: true},
},
}
var testMap2 = UserMap{
table: map[string]map[string]string{
"an:u1": map[string]string{"a": "b", "c": "d"},
"an:u2": map[string]string{"a": "b"},
},
index: make(map[string]map[string]bool),
properties: map[string]*prop{
"an:u2": &prop{weight: 10},
},
}
func TestUsersAdd(t *testing.T) {
tm := newUserMap(dataStorage, nil)
var r string
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
tm.SetUser(up, &r)
p, found := tm.table[up.GetId()]
if r != utils.OK ||
!found ||
p["t"] != "v" ||
len(tm.table) != 1 ||
len(p) != 1 {
t.Error("Error setting user: ", tm, len(tm.table))
}
}
func TestUsersUpdate(t *testing.T) {
tm := newUserMap(dataStorage, nil)
var r string
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
tm.SetUser(up, &r)
p, found := tm.table[up.GetId()]
if r != utils.OK ||
!found ||
p["t"] != "v" ||
len(tm.table) != 1 ||
len(p) != 1 {
t.Error("Error setting user: ", tm)
}
up.Profile["x"] = "y"
tm.UpdateUser(up, &r)
p, found = tm.table[up.GetId()]
if r != utils.OK ||
!found ||
p["x"] != "y" ||
len(tm.table) != 1 ||
len(p) != 2 {
t.Error("Error updating user: ", tm)
}
}
func TestUsersUpdateNotFound(t *testing.T) {
tm := newUserMap(dataStorage, nil)
var r string
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
tm.SetUser(up, &r)
up.UserName = "test1"
err = tm.UpdateUser(up, &r)
if err != utils.ErrNotFound {
t.Error("Error detecting user not found on update: ", err)
}
}
func TestUsersUpdateInit(t *testing.T) {
tm := newUserMap(dataStorage, nil)
var r string
up := &UserProfile{
Tenant: "test",
UserName: "user",
}
tm.SetUser(up, &r)
up = &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
tm.UpdateUser(up, &r)
p, found := tm.table[up.GetId()]
if r != utils.OK ||
!found ||
p["t"] != "v" ||
len(tm.table) != 1 ||
len(p) != 1 {
t.Error("Error updating user: ", tm)
}
}
func TestUsersRemove(t *testing.T) {
tm := newUserMap(dataStorage, nil)
var r string
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
tm.SetUser(up, &r)
p, found := tm.table[up.GetId()]
if r != utils.OK ||
!found ||
p["t"] != "v" ||
len(tm.table) != 1 ||
len(p) != 1 {
t.Error("Error setting user: ", tm)
}
tm.RemoveUser(up, &r)
p, found = tm.table[up.GetId()]
if r != utils.OK ||
found ||
len(tm.table) != 0 {
t.Error("Error removing user: ", tm)
}
}
func TestUsersGetFull(t *testing.T) {
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetFullMasked(t *testing.T) {
up := &UserProfile{
Tenant: "test",
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetFullUnMasked(t *testing.T) {
up := &UserProfile{
Tenant: "test",
Masked: true,
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 4 {
for _, r := range results {
t.Logf("U: %+v", r)
}
t.Error("error getting users: ", results)
}
}
func TestUsersGetTenant(t *testing.T) {
up := &UserProfile{
Tenant: "testX",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 1 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetUserName(t *testing.T) {
up := &UserProfile{
Tenant: "test",
UserName: "userX",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 1 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetNotFoundProfile(t *testing.T) {
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"o": "p",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingTenant(t *testing.T) {
up := &UserProfile{
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingUserName(t *testing.T) {
up := &UserProfile{
Tenant: "test",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingId(t *testing.T) {
up := &UserProfile{
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 4 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingIdTwo(t *testing.T) {
up := &UserProfile{
Profile: map[string]string{
"t": "v",
"x": "y",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 4 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingIdTwoSort(t *testing.T) {
up := &UserProfile{
Profile: map[string]string{
"t": "v",
"x": "y",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 4 {
t.Error("error getting users: ", results)
}
if results[0].GetId() != "test1:user1" {
t.Errorf("Error sorting profiles: %+v", results[0])
}
}
func TestUsersGetMissingIdTwoSortWeight(t *testing.T) {
up := &UserProfile{
Profile: map[string]string{
"a": "b",
"c": "d",
},
}
results := UserProfiles{}
testMap2.GetUsers(up, &results)
if len(results) != 2 {
t.Error("error getting users: ", results)
}
if results[0].GetId() != "an:u2" {
t.Errorf("Error sorting profiles: %+v", results[0])
}
}
func TestUsersAddIndex(t *testing.T) {
var r string
testMap.AddIndex([]string{"t"}, &r)
if r != utils.OK ||
len(testMap.index) != 1 ||
len(testMap.index[utils.ConcatenatedKey("t", "v")]) != 5 {
t.Error("error adding index: ", testMap.index)
}
}
func TestUsersAddIndexFull(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
if r != utils.OK ||
len(testMap.index) != 7 ||
len(testMap.index[utils.ConcatenatedKey("t", "v")]) != 5 {
t.Error("error adding index: ", testMap.index)
}
}
func TestUsersAddIndexNone(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"test"}, &r)
if r != utils.OK ||
len(testMap.index) != 0 {
t.Error("error adding index: ", testMap.index)
}
}
func TestUsersGetFullindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetTenantindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Tenant: "testX",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 1 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetUserNameindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Tenant: "test",
UserName: "userX",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 1 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetNotFoundProfileindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"o": "p",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingTenantindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingUserNameindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Tenant: "test",
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 3 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingIdindex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Profile: map[string]string{
"t": "v",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 4 {
t.Error("error getting users: ", results)
}
}
func TestUsersGetMissingIdTwoINdex(t *testing.T) {
var r string
testMap.index = make(map[string]map[string]bool) // reset index
testMap.AddIndex([]string{"t", "x", "UserName", "Tenant"}, &r)
up := &UserProfile{
Profile: map[string]string{
"t": "v",
"x": "y",
},
}
results := UserProfiles{}
testMap.GetUsers(up, &results)
if len(results) != 4 {
t.Error("error getting users: ", results)
}
}
func TestUsersAddUpdateRemoveIndexes(t *testing.T) {
tm := newUserMap(dataStorage, nil)
var r string
tm.AddIndex([]string{"t"}, &r)
if len(tm.index) != 0 {
t.Error("error adding indexes: ", tm.index)
}
tm.SetUser(&UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}, &r)
if len(tm.index) != 1 || !tm.index["t:v"]["test:user"] {
t.Error("error adding indexes: ", tm.index)
}
tm.SetUser(&UserProfile{
Tenant: "test",
UserName: "best",
Profile: map[string]string{
"t": "v",
},
}, &r)
if len(tm.index) != 1 ||
!tm.index["t:v"]["test:user"] ||
!tm.index["t:v"]["test:best"] {
t.Error("error adding indexes: ", tm.index)
}
tm.UpdateUser(&UserProfile{
Tenant: "test",
UserName: "best",
Profile: map[string]string{
"t": "v1",
},
}, &r)
if len(tm.index) != 2 ||
!tm.index["t:v"]["test:user"] ||
!tm.index["t:v1"]["test:best"] {
t.Error("error adding indexes: ", tm.index)
}
tm.UpdateUser(&UserProfile{
Tenant: "test",
UserName: "best",
Profile: map[string]string{
"t": "v",
},
}, &r)
if len(tm.index) != 1 ||
!tm.index["t:v"]["test:user"] ||
!tm.index["t:v"]["test:best"] {
t.Error("error adding indexes: ", tm.index)
}
tm.RemoveUser(&UserProfile{
Tenant: "test",
UserName: "best",
Profile: map[string]string{
"t": "v",
},
}, &r)
if len(tm.index) != 1 ||
!tm.index["t:v"]["test:user"] ||
tm.index["t:v"]["test:best"] {
t.Error("error adding indexes: ", tm.index)
}
tm.RemoveUser(&UserProfile{
Tenant: "test",
UserName: "user",
Profile: map[string]string{
"t": "v",
},
}, &r)
if len(tm.index) != 0 {
t.Error("error adding indexes: ", tm.index)
}
}
func TestUsersUsageRecordGetLoadUserProfile(t *testing.T) {
userService = &UserMap{
table: map[string]map[string]string{
"test:user": map[string]string{utils.TOR: "01", "RequestType": "1", "Direction": "*out", "Category": "c1", "Account": "dan", "Subject": "0723", "Destination": "+401", "SetupTime": "s1", "AnswerTime": "t1", "Usage": "10"},
":user": map[string]string{utils.TOR: "02", "RequestType": "2", "Direction": "*out", "Category": "c2", "Account": "ivo", "Subject": "0724", "Destination": "+402", "SetupTime": "s2", "AnswerTime": "t2", "Usage": "11"},
"test:": map[string]string{utils.TOR: "03", "RequestType": "3", "Direction": "*out", "Category": "c3", "Account": "elloy", "Subject": "0725", "Destination": "+403", "SetupTime": "s3", "AnswerTime": "t3", "Usage": "12"},
"test1:user1": map[string]string{utils.TOR: "04", "RequestType": "4", "Direction": "*out", "Category": "call", "Account": "rif", "Subject": "0726", "Destination": "+404", "SetupTime": "s4", "AnswerTime": "t4", "Usage": "13"},
},
index: make(map[string]map[string]bool),
}
ur := &UsageRecord{
ToR: utils.USERS,
RequestType: utils.USERS,
Direction: "*out",
Tenant: "",
Category: "call",
Account: utils.USERS,
Subject: utils.USERS,
Destination: utils.USERS,
SetupTime: utils.USERS,
AnswerTime: utils.USERS,
Usage: "13",
}
err := LoadUserProfile(ur, "")
if err != nil {
t.Error("Error loading user profile: ", err)
}
expected := &UsageRecord{
ToR: "04",
RequestType: "4",
Direction: "*out",
Tenant: "",
Category: "call",
Account: "rif",
Subject: "0726",
Destination: "+404",
SetupTime: "s4",
AnswerTime: "t4",
Usage: "13",
}
if !reflect.DeepEqual(ur, expected) {
t.Errorf("Expected: %+v got: %+v", expected, ur)
}
}
func TestUsersExternalCDRGetLoadUserProfileExtraFields(t *testing.T) {
userService = &UserMap{
table: map[string]map[string]string{
"test:user": map[string]string{utils.TOR: "01", "RequestType": "1", "Direction": "*out", "Category": "c1", "Account": "dan", "Subject": "0723", "Destination": "+401", "SetupTime": "s1", "AnswerTime": "t1", "Usage": "10"},
":user": map[string]string{utils.TOR: "02", "RequestType": "2", "Direction": "*out", "Category": "c2", "Account": "ivo", "Subject": "0724", "Destination": "+402", "SetupTime": "s2", "AnswerTime": "t2", "Usage": "11"},
"test:": map[string]string{utils.TOR: "03", "RequestType": "3", "Direction": "*out", "Category": "c3", "Account": "elloy", "Subject": "0725", "Destination": "+403", "SetupTime": "s3", "AnswerTime": "t3", "Usage": "12"},
"test1:user1": map[string]string{utils.TOR: "04", "RequestType": "4", "Direction": "*out", "Category": "call", "Account": "rif", "Subject": "0726", "Destination": "+404", "SetupTime": "s4", "AnswerTime": "t4", "Usage": "13", "Test": "1"},
},
index: make(map[string]map[string]bool),
}
ur := &ExternalCDR{
ToR: utils.USERS,
RequestType: utils.USERS,
Direction: "*out",
Tenant: "",
Category: "call",
Account: utils.USERS,
Subject: utils.USERS,
Destination: utils.USERS,
SetupTime: utils.USERS,
AnswerTime: utils.USERS,
Usage: "13",
ExtraFields: map[string]string{
"Test": "1",
},
}
err := LoadUserProfile(ur, "ExtraFields")
if err != nil {
t.Error("Error loading user profile: ", err)
}
expected := &ExternalCDR{
ToR: "04",
RequestType: "4",
Direction: "*out",
Tenant: "",
Category: "call",
Account: "rif",
Subject: "0726",
Destination: "+404",
SetupTime: "s4",
AnswerTime: "t4",
Usage: "13",
ExtraFields: map[string]string{
"Test": "1",
},
}
if !reflect.DeepEqual(ur, expected) {
t.Errorf("Expected: %+v got: %+v", expected, ur)
}
}
func TestUsersExternalCDRGetLoadUserProfileExtraFieldsNotFound(t *testing.T) {
userService = &UserMap{
table: map[string]map[string]string{
"test:user": map[string]string{utils.TOR: "01", "RequestType": "1", "Direction": "*out", "Category": "c1", "Account": "dan", "Subject": "0723", "Destination": "+401", "SetupTime": "s1", "AnswerTime": "t1", "Usage": "10"},
":user": map[string]string{utils.TOR: "02", "RequestType": "2", "Direction": "*out", "Category": "c2", "Account": "ivo", "Subject": "0724", "Destination": "+402", "SetupTime": "s2", "AnswerTime": "t2", "Usage": "11"},
"test:": map[string]string{utils.TOR: "03", "RequestType": "3", "Direction": "*out", "Category": "c3", "Account": "elloy", "Subject": "0725", "Destination": "+403", "SetupTime": "s3", "AnswerTime": "t3", "Usage": "12"},
"test1:user1": map[string]string{utils.TOR: "04", "RequestType": "4", "Direction": "*out", "Category": "call", "Account": "rif", "Subject": "0726", "Destination": "+404", "SetupTime": "s4", "AnswerTime": "t4", "Usage": "13", "Test": "2"},
},
index: make(map[string]map[string]bool),
}
ur := &ExternalCDR{
ToR: utils.USERS,
RequestType: utils.USERS,
Direction: "*out",
Tenant: "",
Category: "call",
Account: utils.USERS,
Subject: utils.USERS,
Destination: utils.USERS,
SetupTime: utils.USERS,
AnswerTime: utils.USERS,
Usage: "13",
ExtraFields: map[string]string{
"Test": "1",
},
}
err := LoadUserProfile(ur, "ExtraFields")
if err != utils.ErrUserNotFound {
t.Error("Error detecting err in loading user profile: ", err)
}
}
func TestUsersExternalCDRGetLoadUserProfileExtraFieldsSet(t *testing.T) {
userService = &UserMap{
table: map[string]map[string]string{
"test:user": map[string]string{utils.TOR: "01", "RequestType": "1", "Direction": "*out", "Category": "c1", "Account": "dan", "Subject": "0723", "Destination": "+401", "SetupTime": "s1", "AnswerTime": "t1", "Usage": "10"},
":user": map[string]string{utils.TOR: "02", "RequestType": "2", "Direction": "*out", "Category": "c2", "Account": "ivo", "Subject": "0724", "Destination": "+402", "SetupTime": "s2", "AnswerTime": "t2", "Usage": "11"},
"test:": map[string]string{utils.TOR: "03", "RequestType": "3", "Direction": "*out", "Category": "c3", "Account": "elloy", "Subject": "0725", "Destination": "+403", "SetupTime": "s3", "AnswerTime": "t3", "Usage": "12"},
"test1:user1": map[string]string{utils.TOR: "04", "RequestType": "4", "Direction": "*out", "Category": "call", "Account": "rif", "Subject": "0726", "Destination": "+404", "SetupTime": "s4", "AnswerTime": "t4", "Usage": "13", "Test": "1", "Best": "BestValue"},
},
index: make(map[string]map[string]bool),
}
ur := &ExternalCDR{
ToR: utils.USERS,
RequestType: utils.USERS,
Direction: "*out",
Tenant: "",
Category: "call",
Account: utils.USERS,
Subject: utils.USERS,
Destination: utils.USERS,
SetupTime: utils.USERS,
AnswerTime: utils.USERS,
Usage: "13",
ExtraFields: map[string]string{
"Test": "1",
"Best": utils.USERS,
},
}
err := LoadUserProfile(ur, "ExtraFields")
if err != nil {
t.Error("Error loading user profile: ", err)
}
expected := &ExternalCDR{
ToR: "04",
RequestType: "4",
Direction: "*out",
Tenant: "",
Category: "call",
Account: "rif",
Subject: "0726",
Destination: "+404",
SetupTime: "s4",
AnswerTime: "t4",
Usage: "13",
ExtraFields: map[string]string{
"Test": "1",
"Best": "BestValue",
},
}
if !reflect.DeepEqual(ur, expected) {
t.Errorf("Expected: %+v got: %+v", expected, ur)
}
}
func TestUsersCallDescLoadUserProfile(t *testing.T) {
userService = &UserMap{
table: map[string]map[string]string{
"cgrates.org:dan": map[string]string{"RequestType": "*prepaid", "Category": "call1", "Account": "dan", "Subject": "dan", "Cli": "+4986517174963"},
"cgrates.org:danvoice": map[string]string{utils.TOR: "*voice", "RequestType": "*prepaid", "Category": "call1", "Account": "dan", "Subject": "0723"},
"cgrates:rif": map[string]string{"RequestType": "*postpaid", "Direction": "*out", "Category": "call", "Account": "rif", "Subject": "0726"},
},
index: make(map[string]map[string]bool),
}
startTime := time.Now()
cd := &CallDescriptor{
TOR: "*sms",
Tenant: utils.USERS,
Category: utils.USERS,
Subject: utils.USERS,
Account: utils.USERS,
Destination: "+4986517174963",
TimeStart: startTime,
TimeEnd: startTime.Add(time.Duration(1) * time.Minute),
ExtraFields: map[string]string{"Cli": "+4986517174963"},
}
expected := &CallDescriptor{
TOR: "*sms",
Tenant: "cgrates.org",
Category: "call1",
Account: "dan",
Subject: "dan",
Destination: "+4986517174963",
TimeStart: startTime,
TimeEnd: startTime.Add(time.Duration(1) * time.Minute),
ExtraFields: map[string]string{"Cli": "+4986517174963"},
}
err := LoadUserProfile(cd, "ExtraFields")
if err != nil {
t.Error("Error loading user profile: ", err)
}
if !reflect.DeepEqual(expected, cd) {
t.Errorf("Expected: %+v got: %+v", expected, cd)
}
}
func TestUsersCDRLoadUserProfile(t *testing.T) {
userService = &UserMap{
table: map[string]map[string]string{
"cgrates.org:dan": map[string]string{"RequestType": "*prepaid", "Category": "call1", "Account": "dan", "Subject": "dan", "Cli": "+4986517174963"},
"cgrates.org:danvoice": map[string]string{utils.TOR: "*voice", "RequestType": "*prepaid", "Category": "call1", "Account": "dan", "Subject": "0723"},
"cgrates:rif": map[string]string{"RequestType": "*postpaid", "Direction": "*out", "Category": "call", "Account": "rif", "Subject": "0726"},
},
index: make(map[string]map[string]bool),
}
startTime := time.Now()
cdr := &CDR{
ToR: "*sms",
RequestType: utils.USERS,
Tenant: utils.USERS,
Category: utils.USERS,
Account: utils.USERS,
Subject: utils.USERS,
Destination: "+4986517174963",
SetupTime: startTime,
AnswerTime: startTime,
Usage: time.Duration(1) * time.Minute,
ExtraFields: map[string]string{"Cli": "+4986517174963"},
}
expected := &CDR{
ToR: "*sms",
RequestType: "*prepaid",
Tenant: "cgrates.org",
Category: "call1",
Account: "dan",
Subject: "dan",
Destination: "+4986517174963",
SetupTime: startTime,
AnswerTime: startTime,
Usage: time.Duration(1) * time.Minute,
ExtraFields: map[string]string{"Cli": "+4986517174963"},
}
err := LoadUserProfile(cdr, "ExtraFields")
if err != nil {
t.Error("Error loading user profile: ", err)
}
if !reflect.DeepEqual(expected, cdr) {
t.Errorf("Expected: %+v got: %+v", expected, cdr)
}
}
| gpl-3.0 |
ronin-ruby/ronin-asm | spec/spec_helper.rb | 208 | require 'rspec'
require 'ronin/asm/version'
include Ronin
include Ronin::ASM
RSpec.configure do |specs|
specs.treat_symbols_as_metadata_keys_with_true_values = true
specs.filter_run_excluding :yasm
end
| gpl-3.0 |
themiwi/freefoam-debian | src/OpenFOAM/db/functionObjects/IOOutputFilter/IOOutputFilter.H | 3737 | /*---------------------------------------------------------------------------* \
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::IOOutputFilter
Description
IOdictionary wrapper around OutputFilter to allow them to read from
their associated dictionaries.
SourceFiles
IOOutputFilter.C
\*---------------------------------------------------------------------------*/
#ifndef IOOutputFilter_H
#define IOOutputFilter_H
#include <OpenFOAM/IOdictionary.H>
#include <OpenFOAM/pointFieldFwd.H>
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Forward declaration of classes
class mapPolyMesh;
/*---------------------------------------------------------------------------*\
Class IOOutputFilter Declaration
\*---------------------------------------------------------------------------*/
template<class OutputFilter>
class IOOutputFilter
:
public IOdictionary,
public OutputFilter
{
// Private Member Functions
// Disallow default bitwise copy construct and assignment
IOOutputFilter(const IOOutputFilter&);
void operator=(const IOOutputFilter&);
public:
// Constructors
//- Construct for given objectRegistry and dictionary
// Allow dictionary to be optional
// Allow the possibility to load fields from files
IOOutputFilter
(
const word& outputFilterName,
const objectRegistry&,
const fileName& dictName = OutputFilter::typeName() + "Dict",
const IOobject::readOption rOpt = IOobject::MUST_READ,
const bool loadFromFile = false
);
//- Destructor
virtual ~IOOutputFilter();
// Member Functions
//- Return name
virtual const word& name() const
{
return IOdictionary::name();
}
//- Read the probes
virtual bool read();
//- Sample and write
virtual void write();
//- Update for changes of mesh
virtual void updateMesh(const mapPolyMesh& mpm)
{
read();
OutputFilter::updateMesh(mpm);
}
//- Update for changes of mesh
virtual void movePoints(const pointField& points)
{
read();
OutputFilter::movePoints(points);
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
# include "IOOutputFilter.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************ vim: set sw=4 sts=4 et: ************************ //
| gpl-3.0 |
SynergyMC/PlotSquared | Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java | 13609 | package com.plotsquared.bukkit.listeners.worldedit;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetQueue;
import com.plotsquared.bukkit.BukkitMain;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.WEManager;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Selection;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class WEListener implements Listener {
public final Set<String> other = new HashSet<>(Arrays.asList("undo", "redo"));
private final Set<String> rad1 = new HashSet<>(
Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size"));
private final Set<String> rad2 = new HashSet<>(Arrays.asList("fill", "fillr", "removenear", "remove"));
private final Set<String> rad2_1 = new HashSet<>(Arrays.asList("hcyl", "cyl"));
private final Set<String> rad2_2 = new HashSet<>(Arrays.asList("sphere", "pyramid"));
private final Set<String> rad2_3 = Collections.singleton("brush smooth");
private final Set<String> rad3_1 = Collections.singleton("brush gravity");
private final Set<String> rad3_2 = new HashSet<>(Arrays.asList("brush sphere", "brush cylinder"));
private final Set<String> region = new HashSet<>(
Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count",
"distr",
"regen", "copy", "cut", "green", "setbiome"));
private final Set<String> regionExtend = Collections.singleton("stack");
private final Set<String> restricted = Collections.singleton("up");
public String reduceCmd(String cmd, boolean single) {
if (cmd.startsWith("/worldedit:/")) {
return cmd.substring(12);
}
if (cmd.startsWith("/worldedit:")) {
return cmd.substring(11);
}
if (cmd.startsWith("//")) {
return cmd.substring(2);
}
if (single && cmd.startsWith("/")) {
return cmd.substring(1);
}
return cmd;
}
public int getInt(String s) {
try {
int max = 0;
String[] split = s.split(",");
for (String rad : split) {
int val = Integer.parseInt(rad);
if (val > max) {
max = val;
}
}
return max;
} catch (NumberFormatException ignored) {
return 0;
}
}
public boolean checkVolume(PlotPlayer player, long volume, long max, Cancellable e) {
if (volume > max) {
MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", String.valueOf(volume)).replaceAll("%max%", String.valueOf(max)));
e.setCancelled(true);
}
if (Permissions.hasPermission(player, "plots.worldedit.bypass")) {
MainUtil.sendMessage(player, C.WORLDEDIT_BYPASS);
}
return true;
}
public boolean checkSelection(Player p, PlotPlayer pp, int modifier, long max, Cancellable e) {
Selection selection = BukkitMain.worldEdit.getSelection(p);
if (selection == null) {
return true;
}
BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector();
BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector();
HashSet<RegionWrapper> mask = WEManager.getMask(pp);
RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ());
if (Settings.REQUIRE_SELECTION) {
String arg = null;
if (!WEManager.regionContains(region, mask)) {
arg = "pos1 + pos2";
} else if (!WEManager.maskContains(mask, pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ())) {
arg = "pos1";
} else if (!WEManager.maskContains(mask, pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
arg = "pos2";
}
if (arg != null) {
e.setCancelled(true);
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, arg);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (!WEManager.regionContains(region, mask)) {
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, "pos1 + pos2");
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
}
long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ()))
* modifier;
return checkVolume(pp, volume, max, e);
}
public boolean delay(final Player player, final String command, boolean delayed) {
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
return false;
}
boolean free = SetQueue.IMP.addTask(null);
if (free) {
if (delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command);
Bukkit.getServer().dispatchCommand(player, command.substring(1));
} else {
return false;
}
} else {
if (!delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_DELAYED);
}
SetQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
delay(player, command, true);
}
});
}
return true;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerCommand(PlayerCommandPreprocessEvent e) {
WorldEditPlugin worldedit = BukkitMain.worldEdit;
if (worldedit == null) {
HandlerList.unregisterAll(this);
return true;
}
Player p = e.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(p);
if (!PS.get().hasPlotArea(p.getWorld().getName())) {
return true;
}
String message = e.getMessage();
String cmd = message.toLowerCase();
String[] split = cmd.split(" ");
long maxVolume = Settings.WE_MAX_VOLUME;
long maxIterations = Settings.WE_MAX_ITERATIONS;
if (pp.getAttribute("worldedit")) {
return true;
}
boolean single = true;
if (split.length >= 2) {
String reduced = reduceCmd(split[0], single);
String reduced2 = reduceCmd(split[0] + ' ' + split[1], single);
if (this.rad1.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
long volume = getInt(split[1]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
if (this.rad2.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
long volume = getInt(split[2]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad2_1.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 4) {
long volume = getInt(split[2]) * getInt(split[3]);
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad2_2.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
long radius = getInt(split[2]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad2_3.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
if (split.length == 4) {
int iterations = getInt(split[3]);
if (iterations > maxIterations) {
MainUtil.sendMessage(pp,
C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", String.valueOf(iterations)).replaceAll("%max%",
String.valueOf(maxIterations)));
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
}
long radius = getInt(split[2]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad3_1.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
int i = 2;
if (split[i].equalsIgnoreCase("-h")) {
i = 3;
}
long radius = getInt(split[i]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad3_2.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 4) {
int i = 3;
if (split[i].equalsIgnoreCase("-h")) {
i = 4;
}
long radius = getInt(split[i]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.regionExtend.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, getInt(split[1]), maxVolume, e);
}
}
String reduced = reduceCmd(split[0], single);
if (Settings.WE_BLACKLIST.contains(reduced)) {
MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE);
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
}
if (this.restricted.contains(reduced)) {
Plot plot = pp.getCurrentPlot();
if ((plot != null) && plot.isAdded(pp.getUUID())) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return true;
}
e.setCancelled(true);
MainUtil.sendMessage(pp, C.NO_PLOT_PERMS);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (this.region.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, 1, maxVolume, e);
}
if (this.other.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
}
return true;
}
}
| gpl-3.0 |
hamish2014/optTune | optTune/paretoArchives/paretoArchive2D_noise.py | 19031 | """
2D pareto front data structure for noisy optimization environments.
More specifically, designed for bi-objective problems where
- the first objective is noise-free, and
- only the second objective has noise present.
These 2D paretoArchives are design for problems which are typically encountered in multi-objective control parameter tuning applications.
"""
import numpy, copy
from scipy import stats
class _design_sample_prototype:
def __init__(self, xv, f1_val, f2_vals):
self.xv = xv
self.f1_val = f1_val
self.f2_vals = f2_vals
self.fv = numpy.array( [ f1_val, f2_vals.mean() ] )
self.init_extra()
def init_extra(self):
pass
def __eq__(self, b):
return (self.fv == b.fv).all() and (self.xv == b.xv).all()
def dominates(self, design):
'dominates according to direct mean values, could be acceptable large f2 samples...'
a = self.fv
b = design.fv
return (a[0] <= b[0] and a[1] <= b[1]) and (a[0]<b[0] or a[1]<b[1])
def probability_of_f2_being_better_than(self, design):
raise notImplemented
def f2_better(self, design, confidenceLevel):
raise notImplemented
def to_string(self):
if not hasattr(self,'_string_repr'):
v = [self.f1_val] + [len(self.xv)] + self.xv.tolist() \
+ [len(self.f2_vals)] + self.f2_vals.tolist()
if hasattr(self,'U_i'):
v = v + [self.U_i.shape[0]]
for i, r in enumerate(self.U_i):
if not numpy.isnan(r[0]):
v = v + [i] + r.tolist()
self._string_repr = numpy.array(v).tostring()
return self._string_repr
class _paretoArchive2D_noise_prototype:
'''
prototype/model/parent class, varing factor between class is the design/decision class :
'''
#designClass = design_sample
#repr_name = '_rep2D_noise_prototype'
def __init__(self):
"""
needs to define at least
"""
self.designs = []
self.search_list = []
self.N = 0
#counters - nod equals number of designs
self.nod_inspected = 0
self.nod_dominance_check_only = 0
self.nod_rejected = 0
self.no_dominance_probability_checks = 0
def list_loc(self, fv_dim1):
"binary search to locate comparison point."
search_list = self.search_list
lb, ub = 0, len(search_list)-1
while ub - lb > 1:
mp = (ub + lb)/2
if search_list[mp] < fv_dim1:
lb = mp #try make sure lb is always less than fv_dim1, and hence non dominated ...
else:
ub = mp
if search_list[ub] == fv_dim1 and search_list[lb] < fv_dim1:
return ub
else: #search_list[lb] == fv_dim1
return lb
def add_design(self, design, loc, adjust_bounds):
self.designs.insert(loc, design )
self.search_list.insert(loc, design.f1_val)
if adjust_bounds:
self.lower_bound = min(self.lower_bound, design.f1_val)
self.upper_bound = max(self.upper_bound, design.f1_val)
self.N = self.N + 1
def del_design(self, index):
del self.designs[index], self.search_list[index]
self.nod_rejected = self.nod_rejected + 1
self.N = self.N - 1
def inspect_design(self, xv, f1_val, f2_vals):
"""
inspects designs and returns True if design/decision is non-dominated in which cases its added to the current non-dominated set, or False is return if the design is dominated by the current non-dominated set
"""
self._inspect_design_core(self.designClass(xv, f1_val, f2_vals))
def _inspect_design_core(self, candidateDesign):
self.nod_inspected = self.nod_inspected + 1
f1_val = candidateDesign.f1_val
if len(self.designs) == 0:
self.designs = [ candidateDesign ]
self.search_list = [f1_val]
self.lower_bound = f1_val
self.upper_bound = f1_val
self.N = 1
return True
if self.lower_bound <= f1_val and f1_val <= self.upper_bound:
ind = self.list_loc(f1_val)
if not self.designs[ind].dominates(candidateDesign):
if f1_val > self.designs[ind].f1_val :
self.add_design(candidateDesign, ind+1, False)
check_ind = ind + 2
else:
self.add_design(candidateDesign, ind, False)
check_ind = ind + 1
while check_ind < len(self.designs) and candidateDesign.dominates( self.designs[check_ind] ):
self.del_design(check_ind)
if check_ind == len(self.designs):
self.upper_bound = f1_val
return True
else :
self.nod_rejected = self.nod_rejected + 1
return False
elif f1_val < self.lower_bound:
self.add_design(candidateDesign, 0, True)
while 1 < len(self.designs) and candidateDesign.dominates( self.designs[1] ):
self.del_design(1)
if len(self.designs) == 1:
self.upper_bound = f1_val
return True
else: # self.upper_bound < fv[0]
if not self.designs[-1].dominates(candidateDesign):
self.add_design(candidateDesign, len(self.designs), True)
return True
else:
self.nod_rejected = self.nod_rejected + 1
def dominates(self, f1_val, f2_vals, confidenceLevel=0.90):
"""check if front dominates design/decision according to f2_mean value"""
candidateDesign = self.designClass(None, f1_val, f2_vals)
self.nod_dominance_check_only = self.nod_dominance_check_only + 1
if len(self.designs) == 0 or f1_val < self.lower_bound:
return False
if self.lower_bound <= f1_val and f1_val <= self.upper_bound:
ind = self.list_loc(f1_val)
else: #f1_val > self.upper_bound
ind = -1
return self.designs[ind].dominates( candidateDesign )
def probably_dominates(self, f1_val, f2_vals, confidenceLevel=0.90):
"""check if front dominates design/decision with f1_val and f2_vals is dominated at the prescibed confidence (0 - 1)"""
candidateDesign = self.designClass(None, f1_val, f2_vals)
self.no_dominance_probability_checks = self.no_dominance_probability_checks + 1
if len(self.designs) == 0 or f1_val < self.lower_bound:
return False
if self.lower_bound <= f1_val and f1_val <= self.upper_bound:
ind = self.list_loc(f1_val)
else: #f1_val > self.upper_bound
ind = -1
return self.designs[ind].f2_better( candidateDesign , confidenceLevel )
def dominance_probability(self, f1_val, f2_vals):
'returns the likelihood of design (comprised of f1_val & f2_vals) being dominated'
candidateDesign = self.designClass(None, f1_val, f2_vals)
self.no_dominance_probability_checks = self.no_dominance_probability_checks + 1
if len(self.designs) == 0 or f1_val < self.lower_bound:
return 0.0
if self.lower_bound <= f1_val and f1_val <= self.upper_bound:
ind = self.list_loc(f1_val)
else: #f1_val > self.upper_bound
ind = -1
return self.designs[ind].probability_of_f2_being_better_than( candidateDesign )
def lower_bounds(self):
return numpy.array([self.designs[0].fv[0], self.designs[-1].fv[1]])
def upper_bounds(self):
return numpy.array([self.designs[-1].fv[0], self.designs[0].fv[1]])
def flush(self):
del self.designs[:]
def hyper_volume(self, HV_bound ):
'Calculated the hypervolume bound between, the pareto front and an HV_bound'
start_ind = 0
#trimming points outside HV_bounds
while self.designs[start_ind].fv[1] > HV_bound[1] and start_ind < len(self.designs)-1 :
start_ind = start_ind + 1
end_ind = len(self.designs)-1
while self.designs[end_ind].fv[0] > HV_bound[0] and 0 < end_ind :
end_ind = end_ind - 1
HV = 0.0
if start_ind < end_ind:
for i in range(start_ind, end_ind + 1):
if i == start_ind:
wid = HV_bound[1] - self.designs[i].fv[1]
else:
wid = self.designs[i-1].fv[1] - self.designs[i].fv[1]
HV = HV + wid * ( HV_bound[0] - self.designs[i].fv[0])
assert HV >= 0.0
return HV
def __getstate__(self):
odict = self.__dict__.copy() # copy the dict since we change it
del odict['designs'], odict['search_list']
odict['design_f1'] = numpy.array([ d.f1_val for d in self.designs])
odict['design_f2'] = numpy.array([ d.f2_vals for d in self.designs])
odict['design_xv'] = numpy.array([d.xv for d in self.designs])
return odict
def __setstate__(self, dict):
dict['designs'] = [ self.designClass(xv,f1,f2) for xv,f1,f2 in
zip(dict['design_xv'],dict['design_f1'],dict['design_f2']) ]
dict['search_list'] = [d.f1_val for d in dict['designs']]
self.__dict__.update(dict)
def __eq__(self, b):
'very slow ...'
return all( b_design in self.designs for b_design in b.designs ) and all( d in b.designs for d in self.designs )
def __repr__(self):
return """< %s : size: %i, designs inspected: %i, designs rejected: %i, dominance checks %i, probabily dominates checks %i >""" % (self.repr_name, len(self.designs), self.nod_inspected, self.nod_rejected, self.nod_dominance_check_only + self.nod_inspected, self.no_dominance_probability_checks )
def copy(self):
import copy
return copy.deepcopy(self)
def copy_pareto_front_only(self):
'removes f2_vals, as to return a paretoArchive greatly reduced in size'
import copy
r = self.__class__()
for d in reversed(self.designs): #reversed for quick adding.
r.inspect_design( copy.copy(d.xv), d.fv[0], numpy.array([d.fv[1]]) )
return r
def best_design(self, f1=None, f2=None):
'''
return the best decision/design vector according either f1 or f2 but not both!
if f1, then design selected according to list_loc
'''
assert f1 <> f2
if f1 <> None:
ind = self.list_loc( f1 )
return self.designs[ind].xv.copy()
else:
raise NotImplementedError,"f2 arguement not implemented"
class paretoArchive2D_WTT_design(_design_sample_prototype):
'uses Welch T test to determine dominance_probability_f2'
def init_extra(self):
self.f2_mean = self.fv[1] # which equals f2_vals.mean()
self.f2_std = self.f2_vals.std(ddof=1)
def probability_of_f2_being_better_than(self, design):
m1 = self.f2_mean
s1 = self.f2_std
n1 = len(self.f2_vals)
m2 = design.f2_mean
s2 = design.f2_std
n2 = len(design.f2_vals)
t = -(m1 - m2) / ( s1**2/n1 + s2**2/n2 ) ** 0.5
return stats.zprob(t)
def f2_better(self, design, confidenceLevel):
return self.probability_of_f2_being_better_than(design) >= confidenceLevel
class paretoArchive2D_WTT(_paretoArchive2D_noise_prototype):
designClass = paretoArchive2D_WTT_design
repr_name = 'paretoArchive2D_WTT'
class paretoArchive2D_WTT_design_ev(_design_sample_prototype):
'''
Assume equal variance as to speed up f2_better calculations.
'''
def init_extra(self):
self.f2_mean = self.fv[1]
self.n = len(self.f2_vals)
def probability_of_f2_being_better_than(self, design):
if not hasattr( self, 'std'):
self.std = self.f2_vals.std(ddof=1)
std = self.std
m1 = self.f2_mean
m2 = design.f2_mean
n1 = len(self.f2_vals)
n2 = len(design.f2_vals)
t = -(m1 - m2) * std / ( 1.0/n1 + 1.0/n2 ) **0.5
def f2_better_init(self, confidenceLevel):
self.confidenceLevel = confidenceLevel
self.std = self.f2_vals.std(ddof=1)
self.cut_off_values = self.f2_mean + stats.norm.ppf(confidenceLevel) * self.std * ( 1.0 / self.n + 1.0 / numpy.arange(1.0, self.n + 1) ) ** 0.5
#print( self.f2_mean, confidenceLevel, self.cut_off_values )
def f2_better(self, design, confidenceLevel):
if not hasattr(self, 'confidenceLevel'):
self.f2_better_init(confidenceLevel)
else:
assert self.confidenceLevel == confidenceLevel
return self.cut_off_values[design.n-1] < design.f2_mean
class paretoArchive2D_WTT_ev(_paretoArchive2D_noise_prototype):
designClass = paretoArchive2D_WTT_design_ev
repr_name = 'paretoArchive2D_WTT_ev'
def plot_paretoArchive_CO(self, confidenceLevel, sampleSizes ):
import pylab
for d in self.designs:
d.f2_better_init(confidenceLevel)
ss_totals = [ sum(sampleSizes[:i+1]) for i in range(len(sampleSizes)-1) ]
for i,ss in enumerate(ss_totals):
gclr = 0.3 + 0.7 / len(ss_totals) * i
x= [d.f1_val for d in self.designs]
y= [d.cut_off_values[ss-1] for d in self.designs]
pylab.plot(x, y, color=(0,gclr,0), label = "ss %2i" % ss)
pylab.title('Cut off values for different sample sizes')
pylab.ylabel('f2 (noisy)')
pylab.xlabel('f1 (no noise)')
pylab.legend()
class _design_MWUT(_design_sample_prototype):
''' uses the Man-whitney u test for statisical tests '''
def probability_of_f2_being_better_than(self, design):
u, prob = stats.mannwhitneyu(self.f2_vals, design.f2_vals)
if self.fv[1] < design.fv[1] :
return 1 - prob
else:
return prob
def f2_better(self, design, confidenceLevel):
try:
return self.probability_of_f2_being_better_than(design) >= confidenceLevel
except ValueError, msg:
if str(msg) == 'All numbers are identical in amannwhitneyu': #then odds problem solved to machine percision, so take already evaluated sample
return len(self.f2_vals) < len(design.f2_vals)
else:
raise ValueError, msg
class paretoArchive2D_MWUT(_paretoArchive2D_noise_prototype):
''' uses the Man-whitney u test for statisical tests '''
designClass = _design_MWUT
repr_name = 'paretoArchive2D_MWUT'
if __name__ == '__main__':
print('Basic tests for the paretoArchive2D_noise module')
import pickle, time
from matplotlib import pyplot
plotKeys = ['go','b+','rx','m^']
class TestingPoint:
def __init__(self, label, f1, f2_mean, f2_vals):
self.label = label
self.f1 = f1
self.f2_mean = f2_mean
self.f2_vals = f2_vals
points = []
def add_exp_curve(a, b, label, f2_noise_generator, f1_pnts=100, f1_min=0, f1_max=1):
for f1 in numpy.linspace(f1_min, f1_max, f1_pnts):
points.append( TestingPoint( label, f1, numpy.exp(a*f1 +b),
numpy.exp(a*f1 +b) + f2_noise_generator() ))
noise_fun = lambda : numpy.random.randn(50)/10
add_exp_curve( -1, 0 , 0, noise_fun, 100)
add_exp_curve( -2, 0.2, 1, noise_fun, 90)
add_exp_curve( -3, 0.9, 2, noise_fun, 80)
add_exp_curve( -3, 1.0, 3, noise_fun, 80)
pyplot.subplot(1,2,1)
for p in points:
pyplot.plot([p.f1],[p.f2_mean],plotKeys[p.label])
pyplot.title('true mean values')
pyplot.subplot(1,2,2)
for p in points:
pyplot.plot([p.f1],[p.f2_vals.mean()],plotKeys[p.label])
pyplot.title('mean of f2 samples')
def test_paretoArchive(paretoArchiveClass, sampleInc):
#first construct paretoArchive based on mean values only
print('testing %s' % paretoArchiveClass)
paretoArchive = paretoArchiveClass()
for p in points:
paretoArchive.inspect_design( p.label, p.f1, p.f2_vals )
print(' %i of %i designs found to be non-dominated.' % (paretoArchive.N, len(points)))
#pyplot.figure()
#for d in paretoArchive.designs:
# pyplot.plot([d.fv[0]], [d.fv[1]], plotKeys[d.xv])
ss_max = len(paretoArchive.designs[0].f2_vals)
cL = 0.90
print('%10s %20s %20s %20s' % ('confidenceLevel','evals. saved','false eliminations','time taken'))
for cL in [0.4, 0.6, 0.75, 0.90, 0.95, 0.99]:
ss = sampleInc
mask = [True for p in points ]
if hasattr(paretoArchive.designs[0],'f2_better_init'):
for d in paretoArchive.designs:
d.f2_better_init(cL)
counter_saving = 0
counter_miss = 0
counter_time = 0
while ss < ss_max:
A = []
t_mark = time.time()
for p, check in zip(points, mask):
if check :
A.append( paretoArchive.probably_dominates( p.f1, p.f2_vals[:ss] , cL ))
else:
A.append( False )
#stats
counter_time = counter_time + time.time() - t_mark
for p,check,a in zip(points, mask, A):
if check:
if a:
if paretoArchive.dominates( p.f1, p.f2_vals[:ss] ):
counter_saving = counter_saving + ss_max - ss
else:
counter_miss = counter_miss + 1
ss = ss + sampleInc
print('%8.2f %20i %20i %24.5f' % (cL,counter_saving,counter_miss,counter_time))
#pickling test & auditing
assert paretoArchive == pickle.loads(pickle.dumps(paretoArchive))
no_reals = sum([ 1 + 1 + len(d.f2_vals) + 2 for d in paretoArchive.designs ])
pickle_s_full = pickle.dumps(paretoArchive, protocol=1)
template = '%20s : no reals bytes %8i, no bytes pickle str %8i, effiency %4.3f'
print(template % ('full pickle',no_reals*8,len(pickle_s_full),
1.0*no_reals*8/len(pickle_s_full)))
no_reals_pf = sum([ 1 + 1 + 1 + 2 for d in paretoArchive.designs ])
pickle_pf_only = pickle.dumps(paretoArchive.copy_pareto_front_only(), protocol=1)
print(template % ('pickle pf_only',no_reals_pf*8,len(pickle_pf_only),
1.0*no_reals_pf*8/len(pickle_pf_only)))
print(paretoArchive)
return paretoArchive
test_paretoArchive( paretoArchive2D_WTT, 10 )
test_paretoArchive( paretoArchive2D_WTT_ev, 10 )
paretoArchive = test_paretoArchive( paretoArchive2D_MWUT, 10 )
pyplot.show()
| gpl-3.0 |
donatellosantoro/Llunatic | jep-2.4.1/src/org/nfunk/jep/function/PostfixMathCommand.java | 3746 | /*****************************************************************************
JEP 2.4.1, Extensions 1.1.1
April 30 2007
(c) Copyright 2007, Nathan Funk and Richard Morris
See LICENSE-*.txt for license information.
*****************************************************************************/
package org.nfunk.jep.function;
import java.util.*;
import org.nfunk.jep.*;
/**
* Function classes extend this class. It is an implementation of the
* PostfixMathCommandI interface.
* <p>
* It includes a numberOfParameters member, that is checked when parsing the
* expression. This member should be initialized to an appropriate value for
* all classes extending this class. If an arbitrary number of parameters
* should be allowed, initialize this member to -1.
*/
public class PostfixMathCommand implements PostfixMathCommandI {
/**
* Number of parameters a the function requires. Initialize this value to
* -1 if any number of parameters should be allowed.
*/
protected int numberOfParameters;
/**
* Number of parameters to be used for the next run() invocation. Applies
* only if the required umber of parameters is variable
* (numberOfParameters = -1).
*/
protected int curNumberOfParameters;
/**
* Creates a new PostfixMathCommand class.
*/
public PostfixMathCommand() {
numberOfParameters = 0;
curNumberOfParameters = 0;
}
/**
* Check whether the stack is not null, throw a ParseException if it is.
*/
protected void checkStack(Stack inStack) throws ParseException {
/* Check if stack is null */
if (null == inStack) {
throw new ParseException("Stack argument null");
}
}
/**
* Return the required number of parameters.
*/
public int getNumberOfParameters() {
return numberOfParameters;
}
/**
* Sets the number of current number of parameters used in the next call
* of run(). This method is only called when the reqNumberOfParameters is
* -1.
*/
public void setCurNumberOfParameters(int n) {
curNumberOfParameters = n;
}
/**
* Checks the number of parameters of the function.
* Functions which set numberOfParameter=-1 should overload this method
* @param n number of parameters function will be called with.
* @return False if an illegal number of parameters is supplied, true otherwise.
*/
public boolean checkNumberOfParameters(int n) {
if (numberOfParameters == -1) return true;
return (numberOfParameters == n);
}
/**
* Throws an exception because this method should never be called under
* normal circumstances. Each function should use it's own run() method
* for evaluating the function. This includes popping off the parameters
* from the stack, and pushing the result back on the stack.
*/
public void run(Stack s) throws ParseException {
throw new ParseException("run() method of PostfixMathCommand called");
}
public String getXQueryName() {
return "";
}
public String getSQLName(Node node, JEP jepExpression) {
return null;
}
protected String getValue(Node node, JEP jepExpression) {
if (node instanceof ASTVarNode) {
Variable var = jepExpression.getVar(((ASTVarNode) node).getVarName());
return var.getDescription().toString();
}
if (node instanceof ASTConstant) {
return "'" + ((ASTConstant) node).getValue().toString() + "'";
}
return node.toString();
}
}
| gpl-3.0 |
fearless359/simpleinvoices_zend2 | extensions/sub_customer/si_classes/SubCustomers.php | 4254 | <?php
namespace extensions\sub_customer\si_classes;
use si_classes\DomainId;
class SubCustomers {
/**
* Add extension database field if not present.
* @return boolean true if no DB error; otherwise false.
*/
public static function addParentCustomerId() {
global $config, $pdoDb;
if (checkFieldExists($config->database->params->dbname, "customers", "parent_customer_id")) return true;
try {
$sql = "ALTER TABLE `" . TB_PREFIX . "customers`
ADD `parent_customer_id` INT(11) NULL AFTER `custom_field4`;";
$pdoDb->query($sql);
} catch (Exception $e) {
error_log("SubCustomers.php - addParentCustomerId(): " .
"Unable to perform request: sql[$sql]. " . print_r($e->getMessage(),true));
return false;
}
return true;
}
/**
* Add a new <b>si_customers</b> record.
* @return boolean <b>true</b> if record successfully added; otherwise <b>false</b>.
*/
public static function insertCustomer() {
global $config, $pdoDb;
$pdoDb->addSimpleWhere("name", $_POST['name'], "AND");
$pdoDb->addSimpleWhere("domain_id", DomainId::get());
$rows = $pdoDb->request("SELECT", "customers");
if (!empty($rows)) {
echo '<h1>The name you specified already exists.</h1>';
return false; // Name already exists.
}
$saved = false;
try {
$excludeFields = array("id");
if (empty($_POST['credit_card_number'])) {
$excludeFields[] = 'credit_card_number';
} else {
$key = $config->encryption->default->key;
$enc = new \Encryption();
$_POST['credit_card_number'] = $enc->encrypt($key, $_POST['credit_card_number']);
}
$pdoDb->setExcludedFields($excludeFields);
$pdoDb->request('INSERT', 'customers');
$saved = true;
} catch (Exception $e) {
error_log("Unable to add the new " . TB_PREFIX . "customers record. Error reported: " . $e->getMessage());
echo '<h1>Unable to add the new ' . TB_PREFIX . 'customer record.</h1>';
}
return $saved;
}
/**
* Update an existing <b>si_customers</b> record.
* @return boolean <b>true</b> if update is successful; otherwise <b>false</b>.
*/
public static function updateCustomer() {
global $config, $pdoDb;
$saved = false;
try {
$excludedFields = array('id', 'domain_id');
if (empty($_POST['credit_card_number'])) {
$excludedFields[] = 'credit_card_number';
} else {
$key = $config->encryption->default->key;
$enc = new \Encryption();
$_POST['credit_card_number'] = $enc->encrypt($key, $_POST['credit_card_number']);
}
$pdoDb->setExcludedFields($excludedFields);
$pdoDb->addSimpleWhere("id", $_GET['id']);
$pdoDb->request('UPDATE', 'customers');
$saved = true;
} catch (Exception $e) {
echo '<h1>Unable to update the ' . TB_PREFIX . 'customer record.</h1>';
error_log("Unable to update the " . TB_PREFIX . "customers record. Error reported: " . $e->getMessage());
}
return $saved;
}
/**
* Get a <b>sub-customer</b> records associated with a specific <b>parent_customer_id</b>.
* @param number $parent_id ID of parent to which sub-customers are associated.
* @throws Exception If database access error occurs.
* @return <b>si_customer</b> records retrieved.
*/
public static function getSubCustomers($parent_id) {
global $pdoDb;
try {
$pdoDb->addSimpleWhere("parent_customer_id", $parent_id, "AND");
$pdoDb->addSimpleWhere("domain_id", DomainId::get());
$rows = $pdoDb->request("SELECT", "customers");
} catch (PDOException $pde) {
$str = "SubCustomers - getSubCustomers(): " . $pde->getMessage();
error_log($str);
throw new \Exception($str);
}
return $rows;
}
}
| gpl-3.0 |
jkevlorayna/sams | core/header.php | 1236 | <!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Student Attendance Management System Administrator</title>
<!-- Bootstrap core CSS -->
<link href="<?php echo $path; ?>css/bootstrap.css" rel="stylesheet">
<link href="<?php echo $path; ?>css/select.css" rel="stylesheet">
<link href="<?php echo $path; ?>css/angular-growl.css" rel="stylesheet">
<link href="<?php echo $path; ?>css/select2/select2.css" rel="stylesheet">
<link href="<?php echo $path; ?>fonts/font-awesome-4/css/font-awesome.min.css" rel="stylesheet" >
<link href="<?php echo $path; ?>css/style.css" rel="stylesheet" />
<link href="<?php echo $path; ?>css/tablesort.css" rel="stylesheet" />
<link href="<?php echo $path; ?>css/jasny-bootstrap.css" rel="stylesheet" />
<link href="<?php echo $path; ?>css/lightbox.css" rel="stylesheet" />
<link href="<?php echo $path; ?>css/sass/custom.css" rel="stylesheet" />
<link href="<?php echo $path; ?>css/loading-bar.css" rel="stylesheet" />
<link href="<?php echo $path; ?>css/print.css" rel="stylesheet" />
</head> | gpl-3.0 |
nickkolok/chas-ege | zdn/misc_nines2022/2/main.js | 57 | window.nomer=sl(1,1);
window.comment='Параболы';
| gpl-3.0 |
OpenFn/OpenFn-Site | db/migrate/20140704211041_add_settings_to_user.rb | 255 | class AddSettingsToUser < ActiveRecord::Migration
def change
add_column :users, :odk_username, :string
add_column :users, :odk_password, :string
add_column :users, :sf_username, :string
add_column :users, :sf_password, :string
end
end
| gpl-3.0 |
kolrabi/DesktopBooru | Sources/Database/Queries/Config/Set.cs | 577 | using System;
using System.Data.Common;
using System.Data;
namespace Booru.Queries.Config
{
public class Set : DatabaseQuery
{
private Set (string key, string value) : base(
"INSERT OR REPLACE INTO " + ConfigTableName + " " +
" (name, value) " +
" VALUES (@name, @value)"
)
{
this.AddParameter (DbType.String, "name", key);
this.AddParameter (DbType.String, "value", value);
this.Prepare ();
}
public static void Execute(string key, string value)
{
new Set(key, value).ExecuteNonQuery ();
}
}
}
| gpl-3.0 |
alternativeTime/unicarb_static | app/models/glycosuite/GeneralSites.java | 1351 | package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;
import play.mvc.Content;
import com.avaje.ebean.*;
/**
* Sites entity managed by Ebean
*/
@SuppressWarnings("serial")
@Entity
@Table(name="general_sites", schema="glycosuite")
public class GeneralSites extends Model {
@Id
public Long id;
public String protein_name;
public String swiss_prot;
public String amino_acid_position;
public String glyco_aa;
public String glyco_aa_site;
@OneToMany
public List<StructureToSiteGeneral> strSiteGeneral;
@ManyToOne
public Proteins proteins;
public static Finder<Long,GeneralSites> find = new Finder<Long,GeneralSites>(Long.class, GeneralSites.class);
public static List<GeneralSites> findProteinsGeneral(String protein) {
return
find.where().ilike("swiss_prot", "%" + protein + "%").findList();
}
public static List<GeneralSites> findStructuresGeneral(String protein, String site) {
return
find.where().ilike("swiss_prot", protein).ilike("glyco_aa_site", site).findList();
}
public static List<GeneralSites> findProteinsGeneralName(String protein) {
return
find.where().ilike("protein_name", protein).findList();
}
}
| gpl-3.0 |
jpahullo/planetsim | src/planet/test/serialize/LoadSerializedFile.java | 1518 | package planet.test.serialize;
import planet.commonapi.Network;
import planet.generic.commonapi.GenericApp;
import planet.generic.commonapi.factory.GenericFactory;
import planet.generic.commonapi.factory.Topology;
import planet.test.TestNames;
import planet.util.Properties;
/**
* Builds a network based with a serialized network specified in the
* properties file.
* @author Ruben Mondejar
* @author Jordi Pujol
*/
public class LoadSerializedFile {
/**
* Loads a serialized network from the specified serialized file
* at properties file.
* @param args Waiting nothing.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//init context
//arguments: properties file, application level, events, results, serialization
GenericApp.start("../conf/master.properties",TestNames.SERIALIZE_LOADSERIALIZEDFILE,true,false,false,true);
if (!Properties.factoriesNetworkTopology.equalsIgnoreCase(Topology.SERIALIZED))
throw new Error ("This test must only run under a Serialized network.");
System.out.println("Properties.serializedFile = "+Properties.serializedInputFile);
//loads network.
long t1,t2;
t1 = System.currentTimeMillis();
Network net = GenericFactory.buildNetwork();
t2 = System.currentTimeMillis();
int steps = net.getSimulatedSteps();
System.out.println("Load time ["+((t2-t1)/1000)+"] seconds for ["+net.size()+"] nodes with ["+steps+"] steps.");
}
}
| gpl-3.0 |
brangerbriz/webroutes | nw-app/telegeography-data/internetexchanges/metro-areas/madrid.js | 809 | {"buildings":[{"latitude":"40.490159","address":["c/ Lezama 4","c/ Lezama, 4","Madrid, Spain, E28034"],"longitude":"-3.690178","offset":"background:url('images/markers.png') no-repeat -1166px 0;","id":19423},{"latitude":"40.4391411","address":["Calle Albasanz 71","Madrid, Spain, E28037"],"longitude":"-3.6214827","offset":"background:url('images/markers.png') no-repeat -1166px 0;","id":9892},{"latitude":"40.4474865","address":["Calle Yecora 4","Madrid, Spain, 28022"],"longitude":"-3.5738085","offset":"background:url('images/markers.png') no-repeat -1166px 0;","id":10237},{"latitude":"40.4658459","address":["CPD Banesto","Calle de Mesena 80 ","Madrid, Spain, 28033"],"longitude":"-3.6628253","offset":"background:url('images/markers.png') no-repeat -1166px 0;","id":8163}],"name":"Madrid","id":"madrid"} | gpl-3.0 |
Graylog2/graylog2-server | graylog-storage-elasticsearch6/src/test/java/org/graylog/storage/elasticsearch6/views/searchtypes/eventlist/ESEventListTest.java | 5318 | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
package org.graylog.storage.elasticsearch6.views.searchtypes.eventlist;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.searchbox.core.SearchResult;
import io.searchbox.core.search.aggregation.MetricAggregation;
import org.graylog.events.event.EventDto;
import org.graylog.plugins.views.search.Query;
import org.graylog.plugins.views.search.SearchJob;
import org.graylog.storage.elasticsearch6.views.ESGeneratedQueryContext;
import org.graylog.storage.elasticsearch6.views.searchtypes.ESEventList;
import org.graylog.plugins.views.search.searchtypes.events.EventList;
import org.graylog.plugins.views.search.searchtypes.events.EventSummary;
import org.graylog2.plugin.Tools;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.mockito.Mockito.mock;
import static org.assertj.core.api.Assertions.assertThat;
public class ESEventListTest {
@Test
public void testSortingOfStreamsInDoExtractResult() {
final ESEventList esEventList = new TestESEventList();
final SearchJob searchJob = mock(SearchJob.class);
final Query query = mock(Query.class);
final SearchResult searchResult = mock(SearchResult.class);
final MetricAggregation metricAggregation = mock(MetricAggregation.class);
final ESGeneratedQueryContext queryContext = mock(ESGeneratedQueryContext.class);
final EventList eventList = EventList.builder()
.id("search-type-id")
.streams(ImmutableSet.of("stream-id-1", "stream-id-2"))
.build();
final EventList.Result eventResult = (EventList.Result) esEventList.doExtractResult(searchJob, query, eventList, searchResult,
metricAggregation, queryContext);
assertThat(eventResult.events()).containsExactly(
eventSummary("find-1", ImmutableSet.of("stream-id-1")),
eventSummary("find-2", ImmutableSet.of("stream-id-2")),
eventSummary("find-3", ImmutableSet.of("stream-id-1", "stream-id-2"))
);
}
final private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
final private static DateTime timestamp = formatter.parseDateTime("2019-03-30 14:00:00");
private EventSummary eventSummary(String id, Set<String> streams) {
return EventSummary.builder()
.id(id)
.message("message")
.streams(streams)
.timestamp(DateTime.parse(timestamp.toString(Tools.ES_DATE_FORMAT_FORMATTER), Tools.ES_DATE_FORMAT_FORMATTER))
.alert(false)
.build();
}
static class TestESEventList extends ESEventList {
private Map<String, Object> hit(String id, ArrayList<String> streams) {
return ImmutableMap.of(
EventDto.FIELD_ID, id,
EventDto.FIELD_MESSAGE, "message",
EventDto.FIELD_SOURCE_STREAMS, streams,
EventDto.FIELD_EVENT_TIMESTAMP, timestamp.toString(Tools.ES_DATE_FORMAT_FORMATTER),
EventDto.FIELD_ALERT, false
);
}
@Override
protected List<Map<String, Object>> extractResult(SearchResult result) {
final ArrayList<String> list1 = new ArrayList<>(); list1.add("stream-id-1");
final ArrayList<String> list2 = new ArrayList<>(); list2.add("stream-id-2");
final ArrayList<String> list3 = new ArrayList<>(); list3.add("stream-id-1"); list3.add("stream-id-2");
final ArrayList<String> list4 = new ArrayList<>(); list4.add("stream-id-3");
final ArrayList<String> list5 = new ArrayList<>(); list5.add("stream-id-1"); list5.add("stream-id-3");
final ArrayList<String> list6 = new ArrayList<>(); list6.add("stream-id-2"); list6.add("stream-id-3");
final ArrayList<String> list7 = new ArrayList<>(); list7.add("stream-id-1"); list7.add("stream-id-2");
list7.add("stream-id-3");
return ImmutableList.of(
hit("find-1", list1),
hit("find-2", list2),
hit("find-3", list3),
hit("do-not-find-1", list4),
hit("do-not-find-2", list5),
hit("do-not-find-3", list6),
hit("do-not-find-4", list7)
);
}
}
}
| gpl-3.0 |
Hikarikun92/Windows-Kinect-Control | Kinect/KinectApp/Camera.xaml.cs | 3369 | /*
Copyright (C) 2014 Lucas José dos Santos Souza
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/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Kinect;
using System.Runtime.InteropServices;
using System.Windows.Interop;
namespace KinectApp
{
/// <summary>
/// Interaction logic for Camera.xaml
/// </summary>
public partial class Camera : Window
{
KinectSensor sensor;
public Camera(KinectSensor sensor)
{
InitializeComponent();
this.sensor = sensor;
}
//Tira os botões de minimizar, maximizar e fechar da janela
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
sensor.ColorStream.Disable();
//Do not close application
e.Cancel = true;
Visibility = Visibility.Hidden;
}
private void OnLoad(object sender, RoutedEventArgs e)
{
sensor.ColorFrameReady += sensor_ColorFrameReady;
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
//Gera uma imagem 640x480 com os dados do stream de cores
void sensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
{
using (ColorImageFrame cif = e.OpenColorImageFrame())
{
if (cif == null) return;
byte[] cbytes = new byte[cif.PixelDataLength];
cif.CopyPixelDataTo(cbytes);
int stride = cif.Width * 4;
imgKinect.Source = BitmapImage.Create(640, 480, 96, 96, PixelFormats.Bgr32, null, cbytes, stride);
}
}
private void Window_Activated(object sender, EventArgs e)
{
sensor.ColorStream.Enable();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
sensor.ColorStream.Disable();
Hide();
}
}
}
| gpl-3.0 |
penguinflyer5234/egoboo | egolib/src/egolib/Core/StringUtilities.hpp | 7184 | //********************************************************************************************
//*
//* This file is part of Egoboo.
//*
//* Egoboo 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.
//*
//* Egoboo 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 Egoboo. If not, see <http://www.gnu.org/licenses/>.
//*
//********************************************************************************************
/// @file egolib/Core/StringUtilities.hpp
/// @brief String utility functions (splitting, trimming, case conversion, ...)
/// @author Michael Heilmann
#pragma once
#include "egolib/platform.h"
namespace Ego
{
using namespace std;
/**
* @brief
* Convert a character to upper case.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* the upper case character
* @todo
* Rename to @a toUpper.
*/
template <class CharType>
inline CharType toupper(CharType chr, const std::locale& lc = locale())
{
return std::toupper(chr, lc);
}
/**
* @brief
* In-place convert a string to upper case.
* @param str
* the string
* @param lc
* the locale to use. Default is std::locale().
* @todo
* Rename to @a toUpper.
*/
template <typename CharType>
inline void toupper(basic_string<CharType>& str, const locale& lc = locale())
{
// Capture lc by reference, capture nothing else.
auto f = [&lc](const CharType chr) -> CharType { return Ego::toupper(chr, lc); };
transform(str.begin(), str.end(), str.begin(), f);
}
/**
* @brief
* Convert a character to lower case.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* the lower case character
* @todo
* Rename to @a toLower.
*/
template <class CharType>
inline CharType tolower(CharType chr, const locale& lc = locale())
{
return std::tolower(chr, lc);
}
/**
* @brief
* In-place convert a string to lower case.
* @param str
* the string
* @param lc
* the locale to use. Default is std::locale().
* @todo
* Rename to @a toLower.
*/
template <class CharType>
inline void tolower(basic_string<CharType>& str, const locale& lc = locale())
{
// Capture lc by reference, capture nothing else.
auto f = [&lc] (const CharType chr) -> CharType { return Ego::tolower(chr, lc); };
transform(str.begin(), str.end(), str.begin(), f);
}
/**
* @brief
* Get if a character is an alphabetic character.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* @a true if the character is an alphabetic character, @a false otherwise
* @todo
* Rename to @a isAlpha.
*/
template <class CharType>
inline bool isalpha(CharType chr, const std::locale& lc = locale())
{
return std::isalpha(chr, lc);
}
/**
* @brief
* Get if a character is a printable character.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* @a true if the character is a printable character, @a false otherwise
* @todo
* Rename to @a isPrint.
*/
template <class CharType>
inline bool isprint(CharType chr, const std::locale& lc = std::locale())
{
return std::isprint(chr, lc);
}
/**
* @brief
* Get if a character is a digit character.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* @a true if the character is a digit character, @a false otherwise
* @todo
* Rename to @a isDigit.
*/
template <class CharType>
inline bool isdigit(CharType chr, const std::locale& lc = std::locale())
{
return std::isdigit(chr, lc);
}
/**
* @brief
* Get if a character is a control character.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* @a true if the character is a control character, @a false otherwise
* @todo
* Rename to @a isCntrl.
*/
template <class CharType>
inline bool iscntrl(CharType chr, const std::locale& lc = std::locale())
{
return std::iscntrl(chr, lc);
}
/**
* @brief
* Get if a character is a whitespace character.
* @param chr
* the character
* @param lc
* the locale to use. Default is std::locale().
* @return
* @a true if the character is a whitespace character, @a false otherwise
* @todo
* Rename to @a isSpace.
*/
template <class CharType>
inline bool isspace(CharType chr, const std::locale& lc = locale())
{
return std::isspace(chr, lc);
}
/**
* @brief
* Trim leading and trailing spaces.
* @param str
* the string
* @param lc
* the locale to use. Default is std::locale().
* @return
* a string equal to @a str but with leading and trailing spaces removed
*/
template <typename CharType>
inline std::basic_string<CharType> trim(const std::basic_string<CharType>& str, const locale& lc = locale())
{
// Capture lc by reference, capture nothing else.
auto f = [&lc](const CharType chr) { return Ego::isspace(chr, lc); };
auto front = std::find_if_not(str.begin(), str.end(), f);
return std::basic_string<CharType>(front, std::find_if_not(str.rbegin(), typename std::basic_string<CharType>::const_reverse_iterator(front), f).base());
}
/**
* @brief
* Split a string.
* @param str
* the string
* @param delims
* a string of delimiters
* @return
* a list of tokens
*/
template <typename CharType>
vector< basic_string<CharType> > split(const basic_string<CharType>& str, const basic_string<CharType>& delims)
{
vector< basic_string<CharType> > v;
typename basic_string<CharType>::size_type start = 0;
auto pos = str.find_first_of(delims, start);
while (pos != basic_string<CharType>::npos)
{
if (pos > start) // If the contents before the delimiter are non-empty, add them.
{
v.emplace_back(str, start, pos - start);
}
start = pos + 1;
v.emplace_back(str, start - 1, 1); // At the delimiter itself.
pos = str.find_first_of(delims, start);
}
if (start < str.length()) // If the contents before the end are non-empty, add them.
{
v.emplace_back(str, start, str.length() - start);
}
return v; // Return value optimization/move semantics hopefully kick-in here.
}
/**
* @brief
* Get if a string is a suffix of another string.
* @param string
* the string
* @param suf
* the suffix
* @return
* @a true if the string ends with the suffix,
* @a false otherwise
*/
template <typename CharType>
bool isSuffix(const basic_string<CharType>& string, const basic_string<CharType>& suffix) {
if (suffix.size() > string.size()) return false;
return std::equal(suffix.rbegin(), suffix.rend(), string.rbegin());
}
} // namespace Ego
| gpl-3.0 |
Pantare/sun-rising---the-forgotten-shadows | Assets/Scripts/MotherShip.cs | 6373 | using UnityEngine;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MotherShip : MonoBehaviour
{
[Range(0f, 50f)]
public float speed; //Velocidad maxima de la nave.
[Range(0f, 5000f)]
public float currentSpeed; //Velocidad de la nave, esta puede aumentar o disminuir segun lo desee el jugador.
public float health; //Vida maxima de la nave.
public float currentHealth; //Vida de la nave esta varia dependiendo del daño recibido.
public float detectionRange; //Rango de deteccion.
public List<Transform> weapons; //Lista que guarda las posiciones en donde se colocaran las armas de la nave.
public GameObject weapon; //Prefab del tipo de arma que usara la nave.
public GameObject explosion; //Prefab del explosión.
float rotationSpeed; //Velocidad de rotación de la nave incrementa o disminuye dependiendo la variable currentSpeed.
Rigidbody MS_RB; //Variable correspondiente al rigidbody de la nave.;
List<string> targetTag; //Lista correspondiente a los tags de las naves (Enemy/Ally/Player).
public List<Transform> allytargets; //Lista que guarda todos los AI-Players hostiles.
public List<Transform> targets; //Lista que guarda todos los AI-Players aliados.
AI_BehaviourScript aiBehavior;
[HideInInspector]
public bool hit;
void Awake()
{
aiBehavior = GetComponent<AI_BehaviourScript>();
gameObject.AddComponent<Rigidbody>();
MS_RB = GetComponent<Rigidbody>();
MS_RB.mass = health;
MS_RB.isKinematic = false;
MS_RB.useGravity = false;
}
void Start()
{
currentSpeed = speed;
currentHealth = health;
targetTag = new List<string>();
weapons = new List<Transform>();
SetWeapon();
if (transform.tag == "EnemyMotherShip")
{
targetTag.Add("Player");
targetTag.Add("Ally");
targetTag.Add("AllyMotherShip");
}
if (transform.tag == "AllyMotherShip")
{
targetTag.Add("EnemyMotherShip");
targetTag.Add("Enemy");
}
float tgtfound = 0;
for (int i = 0; i < targetTag.Count; i++)
tgtfound = GameObject.FindGameObjectsWithTag(targetTag[i]).LongLength;
StartCoroutine(GetTargets());
StartCoroutine(SendTargetPosition());
}
void Update ()
{
if (currentHealth <= 0)
{
Destroy(gameObject);
foreach (Transform point in weapons)
Instantiate(explosion, point.position, point.rotation);
}
transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
}
/// <summary>
/// Este método es el encargado de detectar todos los objetivos existentes en el nivel, dependiendo del tag del
/// AI-Player, si el AI-Player tiene tag enemy, adquirirá como objetivos todos los demas Ai-PLayer con tags de
/// Ally o Player. Dentro de este se conjuntan en una sola lista todos los objetos previamente localizados.
/// </summary>
IEnumerator GetTargets()
{
while (true)
{
foreach (GameObject ally in GameObject.FindGameObjectsWithTag("Ally"))
allytargets.Add(ally.transform);
allytargets = allytargets.Distinct().ToList();
targets = new List<Transform>();
for (int i = 0; i < targetTag.Count; i++)
foreach (GameObject toAttack in GameObject.FindGameObjectsWithTag(targetTag[i]))
if (toAttack.tag == targetTag[i])
targets.Add(toAttack.transform);
yield return new WaitForSeconds(1.5f);
}
}
/// <summary>
/// Este método se encarga de dar la orden de atacar a las naves de escolta si es que la nave madre
/// carece de armamento.
/// </summary>
IEnumerator SendTargetPosition()
{
while (true)
{
if (targets.Count != 0)
{
Transform tgt = aiBehavior.selecNearTarget(targets);
float nearestHostile = Vector3.Distance(transform.position, tgt.position);
if (nearestHostile < detectionRange)
foreach (Transform ally in allytargets)
{
if (weapons.Count == 0)
ally.SendMessage("Pursuit", true);
}
}
yield return new WaitForSeconds(2f);
}
}
/// <summary>
/// Este método es el encargado de colocar en su debido lugar las armas de cada nave instanciando
/// el prefab de cannon.
/// </summary>
void SetWeapon()
{
foreach (GameObject cannonSlot in GameObject.FindGameObjectsWithTag("cannonSlot"))
{
weapons.Add(cannonSlot.transform);
}
foreach(Transform cannon in weapons)
{
GameObject newCann = (GameObject)Instantiate(weapon, cannon.position, cannon.rotation);
newCann.transform.SetParent(transform);
newCann.name = weapon.name;
}
}
/// <summary>
/// Método encargado de determinar el daño causado por el impacto de los proyectiles enemigos.
/// </summary>
/// <param name="dmg">Variable que determina el daño recibido.</param>
/// <returns>Regresa la cantidad de vida resultante despues de cada impacto recibido.</returns>
public float DamageRecieved(float dmg)
{
currentHealth -= dmg;
hit = true;
return currentHealth;
}
void OnCollisionEnter(Collision col)
{
if (col.transform.tag == "Enemy" || col.transform.tag == "Ally" || col.transform.tag == transform.tag)
{
hit = true;
col.rigidbody.SendMessage("DamageRecieved", currentHealth);
}
else
hit = false;
}
}
| gpl-3.0 |
philvbprogrammer/XrmToolBox | XrmToolBox.PluginsStore/Extensions.cs | 1394 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using XrmToolBox.Extensibility;
using XrmToolBox.Extensibility.Interfaces;
namespace XrmToolBox.PluginsStore
{
public static class FileInfoExtensions
{
/// <summary>
/// Checks if the current file contains types that implement
/// IXrmToolBoxPlugin interface
/// </summary>
/// <param name="fi">Current file info</param>
/// <returns>Value that indicates if the current file contains types that implement
/// IXrmToolBoxPlugin interface</returns>
public static bool ImplementsXrmToolBoxPlugin(this FileInfo fi)
{
try
{
var assembly = Assembly.LoadFile(fi.FullName);
foreach (var type in assembly.GetTypes())
{
if (type.GetInterfaces().Contains(typeof(IXrmToolBoxPlugin)))
{
return true;
}
}
return false;
}
catch (Exception error)
{
var lm = new LogManager(typeof(Store));
lm.LogError($"Unable to check if {fi.Name} is implementing interface IXrmToolBoxPlugin: {error.Message}");
return false;
}
}
}
}
| gpl-3.0 |
mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/Wb.Lpw.Protocol/LogCodes/Services/Inventory/RemoveItemFromPlayerInventory/Info.cs | 762 | // Decompiled with JetBrains decompiler
// Type: Wb.Lpw.Platform.Protocol.LogCodes.Services.Inventory.RemoveItemFromPlayerInventory.Info
// Assembly: Wb.Lpw.Protocol, Version=2.13.83.0, Culture=neutral, PublicKeyToken=null
// MVID: A621984F-C936-438B-B744-D121BF336087
// Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Wb.Lpw.Protocol.dll
using Wb.Lpw.Platform.Protocol.LogCodes;
namespace Wb.Lpw.Platform.Protocol.LogCodes.Services.Inventory.RemoveItemFromPlayerInventory
{
public abstract class Info
{
public static LogCode Success = new LogCode("Services", "Inventory", "RemoveItemFromPlayerInventory", Severity.Info, "Success", 629214);
}
}
| gpl-3.0 |
dave-billin/moos-ivp-uidaho | projects/pVehicleID/src/pVehicleIDMain.cpp | 2360 | //=============================================================================
/* Copyright (C) 2012 Brandt Pedrow
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 MoosAppMain.cpp
@brief
Execution entry point for the MOOS application
@author Brandt Pedrow
@par Created For
The University of Idaho Microelectronics Research and Communications
Institute (MRCI)
*/
//=============================================================================
#include "MOOS/libMOOS/MOOSLib.h" // MOOS core libraries
#include <stdio.h>
#include <string.h>
#include "pVehicleID.h"
//================================
// Prototypes
//================================
void PrintUsageInfo(void);
//=============================================================================
/** Creates an instance of the application and runs it */
int main(int argc, char * argv[])
{
const char * sMissionFile = "pVehicleID.moos";
const char * sMOOSName = "pVehicleID";
switch(argc)
{
// DB: This application is implemented as a singleton! Don't support
// running multiple instances under different process names!
//case 3:
// sMOOSName = argv[2];
case 2:
sMissionFile = argv[1];
break;
default:
PrintUsageInfo();
return 0;
}
// Create and launch the application
pVehicleID AppObject;
AppObject.Run((char *) sMOOSName, (char *) sMissionFile);
return 0;
}
void PrintUsageInfo( void )
{
printf( "\n\npMVehicleID version %0.2f\n"
"Written by Brandt Pedrow\n"
"USAGE: pMissionManager MISSION_FILE\n"
"\n"
"MISSION_FILE\n"
"\tMOOS mission file containing application parameters\n"
"\n",
APPLICATION_SOFTWARE_VERSION );
}
| gpl-3.0 |
konamith/wm-bus-api | wm-bus-dao/wm-bus-dao-support/src/main/java/com/hundsun/wm/api/dao/support/core/Channel.java | 371 | package com.hundsun.wm.api.dao.support.core;
/**
* 适配层向外部接口发送请求的通道
*
* @author liuming
*
* @param <P>
* 入参
* @param <R>
* 出参
*/
public interface Channel<P, R> {
/**
* 发送一个请求,同步接收返回结果
*
* @param parameter 入参
* @return 出参
*/
R send(P parameter);
} | gpl-3.0 |
jesusc/eclectic | plugins/org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappingsLexer.java | 58194 | package org.eclectic.frontend.parser.antlr.internal;
// Hack: Use our own Lexer superclass by means of import.
// Currently there is no other way to specify the superclass for the lexer.
import org.eclipse.xtext.parser.antlr.Lexer;
import org.antlr.runtime.*;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
@SuppressWarnings("all")
public class InternalMappingsLexer extends Lexer {
public static final int RULE_ID=4;
public static final int T__29=29;
public static final int T__28=28;
public static final int T__27=27;
public static final int T__26=26;
public static final int T__25=25;
public static final int T__24=24;
public static final int T__23=23;
public static final int T__22=22;
public static final int RULE_ANY_OTHER=10;
public static final int T__21=21;
public static final int T__20=20;
public static final int EOF=-1;
public static final int RULE_SL_COMMENT=8;
public static final int RULE_ML_COMMENT=7;
public static final int T__30=30;
public static final int T__19=19;
public static final int T__31=31;
public static final int T__32=32;
public static final int RULE_STRING=5;
public static final int T__16=16;
public static final int T__33=33;
public static final int T__15=15;
public static final int T__34=34;
public static final int T__18=18;
public static final int T__35=35;
public static final int T__17=17;
public static final int T__36=36;
public static final int T__12=12;
public static final int T__11=11;
public static final int T__14=14;
public static final int T__13=13;
public static final int RULE_INT=6;
public static final int RULE_WS=9;
// delegates
// delegators
public InternalMappingsLexer() {;}
public InternalMappingsLexer(CharStream input) {
this(input, new RecognizerSharedState());
}
public InternalMappingsLexer(CharStream input, RecognizerSharedState state) {
super(input,state);
}
public String getGrammarFileName() { return "../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g"; }
// $ANTLR start "T__11"
public final void mT__11() throws RecognitionException {
try {
int _type = T__11;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:11:7: ( 'mappings' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:11:9: 'mappings'
{
match("mappings");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__11"
// $ANTLR start "T__12"
public final void mT__12() throws RecognitionException {
try {
int _type = T__12;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:12:7: ( '(' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:12:9: '('
{
match('(');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__12"
// $ANTLR start "T__13"
public final void mT__13() throws RecognitionException {
try {
int _type = T__13;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:13:7: ( ')' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:13:9: ')'
{
match(')');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__13"
// $ANTLR start "T__14"
public final void mT__14() throws RecognitionException {
try {
int _type = T__14;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:14:7: ( '->' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:14:9: '->'
{
match("->");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__14"
// $ANTLR start "T__15"
public final void mT__15() throws RecognitionException {
try {
int _type = T__15;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:15:7: ( ':' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:15:9: ':'
{
match(':');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__15"
// $ANTLR start "T__16"
public final void mT__16() throws RecognitionException {
try {
int _type = T__16;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:16:7: ( 'uses' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:16:9: 'uses'
{
match("uses");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__16"
// $ANTLR start "T__17"
public final void mT__17() throws RecognitionException {
try {
int _type = T__17;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:17:7: ( 'as' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:17:9: 'as'
{
match("as");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__17"
// $ANTLR start "T__18"
public final void mT__18() throws RecognitionException {
try {
int _type = T__18;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:18:7: ( 'delegate' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:18:9: 'delegate'
{
match("delegate");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__18"
// $ANTLR start "T__19"
public final void mT__19() throws RecognitionException {
try {
int _type = T__19;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:19:7: ( 'from' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:19:9: 'from'
{
match("from");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__19"
// $ANTLR start "T__20"
public final void mT__20() throws RecognitionException {
try {
int _type = T__20;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:20:7: ( ',' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:20:9: ','
{
match(',');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__20"
// $ANTLR start "T__21"
public final void mT__21() throws RecognitionException {
try {
int _type = T__21;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:21:7: ( 'to' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:21:9: 'to'
{
match("to");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__21"
// $ANTLR start "T__22"
public final void mT__22() throws RecognitionException {
try {
int _type = T__22;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:22:7: ( '!' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:22:9: '!'
{
match('!');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__22"
// $ANTLR start "T__23"
public final void mT__23() throws RecognitionException {
try {
int _type = T__23;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:23:7: ( '.' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:23:9: '.'
{
match('.');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__23"
// $ANTLR start "T__24"
public final void mT__24() throws RecognitionException {
try {
int _type = T__24;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:24:7: ( 'end' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:24:9: 'end'
{
match("end");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__24"
// $ANTLR start "T__25"
public final void mT__25() throws RecognitionException {
try {
int _type = T__25;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:25:7: ( '[' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:25:9: '['
{
match('[');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__25"
// $ANTLR start "T__26"
public final void mT__26() throws RecognitionException {
try {
int _type = T__26;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:26:7: ( ']' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:26:9: ']'
{
match(']');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__26"
// $ANTLR start "T__27"
public final void mT__27() throws RecognitionException {
try {
int _type = T__27;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:27:7: ( '@' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:27:9: '@'
{
match('@');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__27"
// $ANTLR start "T__28"
public final void mT__28() throws RecognitionException {
try {
int _type = T__28;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:28:7: ( '^' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:28:9: '^'
{
match('^');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__28"
// $ANTLR start "T__29"
public final void mT__29() throws RecognitionException {
try {
int _type = T__29;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:29:7: ( 'linking' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:29:9: 'linking'
{
match("linking");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__29"
// $ANTLR start "T__30"
public final void mT__30() throws RecognitionException {
try {
int _type = T__30;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:30:7: ( '=' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:30:9: '='
{
match('=');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__30"
// $ANTLR start "T__31"
public final void mT__31() throws RecognitionException {
try {
int _type = T__31;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:31:7: ( '*' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:31:9: '*'
{
match('*');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__31"
// $ANTLR start "T__32"
public final void mT__32() throws RecognitionException {
try {
int _type = T__32;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:32:7: ( '<-' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:32:9: '<-'
{
match("<-");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__32"
// $ANTLR start "T__33"
public final void mT__33() throws RecognitionException {
try {
int _type = T__33;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:33:7: ( 'convert' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:33:9: 'convert'
{
match("convert");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__33"
// $ANTLR start "T__34"
public final void mT__34() throws RecognitionException {
try {
int _type = T__34;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:34:7: ( 'true' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:34:9: 'true'
{
match("true");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__34"
// $ANTLR start "T__35"
public final void mT__35() throws RecognitionException {
try {
int _type = T__35;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:35:7: ( 'false' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:35:9: 'false'
{
match("false");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__35"
// $ANTLR start "T__36"
public final void mT__36() throws RecognitionException {
try {
int _type = T__36;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:36:7: ( '-' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:36:9: '-'
{
match('-');
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "T__36"
// $ANTLR start "RULE_ID"
public final void mRULE_ID() throws RecognitionException {
try {
int _type = RULE_ID;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2030:9: ( ( '^' )? ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )* )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2030:11: ( '^' )? ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )*
{
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2030:11: ( '^' )?
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0=='^') ) {
alt1=1;
}
switch (alt1) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2030:11: '^'
{
match('^');
}
break;
}
if ( (input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2030:40: ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' )*
loop2:
do {
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0>='0' && LA2_0<='9')||(LA2_0>='A' && LA2_0<='Z')||LA2_0=='_'||(LA2_0>='a' && LA2_0<='z')) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:
{
if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop2;
}
} while (true);
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_ID"
// $ANTLR start "RULE_INT"
public final void mRULE_INT() throws RecognitionException {
try {
int _type = RULE_INT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2032:10: ( ( '0' .. '9' )+ )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2032:12: ( '0' .. '9' )+
{
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2032:12: ( '0' .. '9' )+
int cnt3=0;
loop3:
do {
int alt3=2;
int LA3_0 = input.LA(1);
if ( ((LA3_0>='0' && LA3_0<='9')) ) {
alt3=1;
}
switch (alt3) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2032:13: '0' .. '9'
{
matchRange('0','9');
}
break;
default :
if ( cnt3 >= 1 ) break loop3;
EarlyExitException eee =
new EarlyExitException(3, input);
throw eee;
}
cnt3++;
} while (true);
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_INT"
// $ANTLR start "RULE_STRING"
public final void mRULE_STRING() throws RecognitionException {
try {
int _type = RULE_STRING;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:13: ( ( '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"' | '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\'' ) )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:15: ( '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"' | '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\'' )
{
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:15: ( '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"' | '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\'' )
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0=='\"') ) {
alt6=1;
}
else if ( (LA6_0=='\'') ) {
alt6=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:16: '\"' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )* '\"'
{
match('\"');
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:20: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\"' ) ) )*
loop4:
do {
int alt4=3;
int LA4_0 = input.LA(1);
if ( (LA4_0=='\\') ) {
alt4=1;
}
else if ( ((LA4_0>='\u0000' && LA4_0<='!')||(LA4_0>='#' && LA4_0<='[')||(LA4_0>=']' && LA4_0<='\uFFFF')) ) {
alt4=2;
}
switch (alt4) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:21: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' )
{
match('\\');
if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||(input.LA(1)>='t' && input.LA(1)<='u') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
case 2 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:66: ~ ( ( '\\\\' | '\"' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop4;
}
} while (true);
match('\"');
}
break;
case 2 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:86: '\\'' ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )* '\\''
{
match('\'');
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:91: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' ) | ~ ( ( '\\\\' | '\\'' ) ) )*
loop5:
do {
int alt5=3;
int LA5_0 = input.LA(1);
if ( (LA5_0=='\\') ) {
alt5=1;
}
else if ( ((LA5_0>='\u0000' && LA5_0<='&')||(LA5_0>='(' && LA5_0<='[')||(LA5_0>=']' && LA5_0<='\uFFFF')) ) {
alt5=2;
}
switch (alt5) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:92: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | 'u' | '\"' | '\\'' | '\\\\' )
{
match('\\');
if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||(input.LA(1)>='t' && input.LA(1)<='u') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
case 2 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2034:137: ~ ( ( '\\\\' | '\\'' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop5;
}
} while (true);
match('\'');
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_STRING"
// $ANTLR start "RULE_ML_COMMENT"
public final void mRULE_ML_COMMENT() throws RecognitionException {
try {
int _type = RULE_ML_COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2036:17: ( '/*' ( options {greedy=false; } : . )* '*/' )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2036:19: '/*' ( options {greedy=false; } : . )* '*/'
{
match("/*");
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2036:24: ( options {greedy=false; } : . )*
loop7:
do {
int alt7=2;
int LA7_0 = input.LA(1);
if ( (LA7_0=='*') ) {
int LA7_1 = input.LA(2);
if ( (LA7_1=='/') ) {
alt7=2;
}
else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) {
alt7=1;
}
}
else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) {
alt7=1;
}
switch (alt7) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2036:52: .
{
matchAny();
}
break;
default :
break loop7;
}
} while (true);
match("*/");
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_ML_COMMENT"
// $ANTLR start "RULE_SL_COMMENT"
public final void mRULE_SL_COMMENT() throws RecognitionException {
try {
int _type = RULE_SL_COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:17: ( '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )? )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:19: '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )?
{
match("//");
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:24: (~ ( ( '\\n' | '\\r' ) ) )*
loop8:
do {
int alt8=2;
int LA8_0 = input.LA(1);
if ( ((LA8_0>='\u0000' && LA8_0<='\t')||(LA8_0>='\u000B' && LA8_0<='\f')||(LA8_0>='\u000E' && LA8_0<='\uFFFF')) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:24: ~ ( ( '\\n' | '\\r' ) )
{
if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
break loop8;
}
} while (true);
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:40: ( ( '\\r' )? '\\n' )?
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0=='\n'||LA10_0=='\r') ) {
alt10=1;
}
switch (alt10) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:41: ( '\\r' )? '\\n'
{
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:41: ( '\\r' )?
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='\r') ) {
alt9=1;
}
switch (alt9) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2038:41: '\\r'
{
match('\r');
}
break;
}
match('\n');
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_SL_COMMENT"
// $ANTLR start "RULE_WS"
public final void mRULE_WS() throws RecognitionException {
try {
int _type = RULE_WS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2040:9: ( ( ' ' | '\\t' | '\\r' | '\\n' )+ )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2040:11: ( ' ' | '\\t' | '\\r' | '\\n' )+
{
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2040:11: ( ' ' | '\\t' | '\\r' | '\\n' )+
int cnt11=0;
loop11:
do {
int alt11=2;
int LA11_0 = input.LA(1);
if ( ((LA11_0>='\t' && LA11_0<='\n')||LA11_0=='\r'||LA11_0==' ') ) {
alt11=1;
}
switch (alt11) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:
{
if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;}
}
break;
default :
if ( cnt11 >= 1 ) break loop11;
EarlyExitException eee =
new EarlyExitException(11, input);
throw eee;
}
cnt11++;
} while (true);
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_WS"
// $ANTLR start "RULE_ANY_OTHER"
public final void mRULE_ANY_OTHER() throws RecognitionException {
try {
int _type = RULE_ANY_OTHER;
int _channel = DEFAULT_TOKEN_CHANNEL;
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2042:16: ( . )
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:2042:18: .
{
matchAny();
}
state.type = _type;
state.channel = _channel;
}
finally {
}
}
// $ANTLR end "RULE_ANY_OTHER"
public void mTokens() throws RecognitionException {
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:8: ( T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | RULE_ID | RULE_INT | RULE_STRING | RULE_ML_COMMENT | RULE_SL_COMMENT | RULE_WS | RULE_ANY_OTHER )
int alt12=33;
alt12 = dfa12.predict(input);
switch (alt12) {
case 1 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:10: T__11
{
mT__11();
}
break;
case 2 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:16: T__12
{
mT__12();
}
break;
case 3 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:22: T__13
{
mT__13();
}
break;
case 4 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:28: T__14
{
mT__14();
}
break;
case 5 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:34: T__15
{
mT__15();
}
break;
case 6 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:40: T__16
{
mT__16();
}
break;
case 7 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:46: T__17
{
mT__17();
}
break;
case 8 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:52: T__18
{
mT__18();
}
break;
case 9 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:58: T__19
{
mT__19();
}
break;
case 10 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:64: T__20
{
mT__20();
}
break;
case 11 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:70: T__21
{
mT__21();
}
break;
case 12 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:76: T__22
{
mT__22();
}
break;
case 13 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:82: T__23
{
mT__23();
}
break;
case 14 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:88: T__24
{
mT__24();
}
break;
case 15 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:94: T__25
{
mT__25();
}
break;
case 16 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:100: T__26
{
mT__26();
}
break;
case 17 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:106: T__27
{
mT__27();
}
break;
case 18 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:112: T__28
{
mT__28();
}
break;
case 19 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:118: T__29
{
mT__29();
}
break;
case 20 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:124: T__30
{
mT__30();
}
break;
case 21 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:130: T__31
{
mT__31();
}
break;
case 22 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:136: T__32
{
mT__32();
}
break;
case 23 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:142: T__33
{
mT__33();
}
break;
case 24 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:148: T__34
{
mT__34();
}
break;
case 25 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:154: T__35
{
mT__35();
}
break;
case 26 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:160: T__36
{
mT__36();
}
break;
case 27 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:166: RULE_ID
{
mRULE_ID();
}
break;
case 28 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:174: RULE_INT
{
mRULE_INT();
}
break;
case 29 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:183: RULE_STRING
{
mRULE_STRING();
}
break;
case 30 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:195: RULE_ML_COMMENT
{
mRULE_ML_COMMENT();
}
break;
case 31 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:211: RULE_SL_COMMENT
{
mRULE_SL_COMMENT();
}
break;
case 32 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:227: RULE_WS
{
mRULE_WS();
}
break;
case 33 :
// ../org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/internal/InternalMappings.g:1:235: RULE_ANY_OTHER
{
mRULE_ANY_OTHER();
}
break;
}
}
protected DFA12 dfa12 = new DFA12(this);
static final String DFA12_eotS =
"\1\uffff\1\40\2\uffff\1\44\1\uffff\4\40\1\uffff\1\40\2\uffff\1\40"+
"\3\uffff\1\64\1\40\2\uffff\1\36\1\40\2\uffff\3\36\2\uffff\1\40\6"+
"\uffff\1\40\1\101\3\40\1\uffff\1\105\1\40\2\uffff\1\40\4\uffff\1"+
"\40\3\uffff\1\40\5\uffff\2\40\1\uffff\3\40\1\uffff\1\40\1\120\3"+
"\40\1\124\1\40\1\126\1\40\1\130\1\uffff\3\40\1\uffff\1\40\1\uffff"+
"\1\135\1\uffff\4\40\1\uffff\4\40\1\146\1\147\1\150\1\151\4\uffff";
static final String DFA12_eofS =
"\152\uffff";
static final String DFA12_minS =
"\1\0\1\141\2\uffff\1\76\1\uffff\2\163\1\145\1\141\1\uffff\1\157"+
"\2\uffff\1\156\3\uffff\1\101\1\151\2\uffff\1\55\1\157\2\uffff\2"+
"\0\1\52\2\uffff\1\160\6\uffff\1\145\1\60\1\154\1\157\1\154\1\uffff"+
"\1\60\1\165\2\uffff\1\144\4\uffff\1\156\3\uffff\1\156\5\uffff\1"+
"\160\1\163\1\uffff\1\145\1\155\1\163\1\uffff\1\145\1\60\1\153\1"+
"\166\1\151\1\60\1\147\1\60\1\145\1\60\1\uffff\1\151\1\145\1\156"+
"\1\uffff\1\141\1\uffff\1\60\1\uffff\1\156\1\162\1\147\1\164\1\uffff"+
"\1\147\1\164\1\163\1\145\4\60\4\uffff";
static final String DFA12_maxS =
"\1\uffff\1\141\2\uffff\1\76\1\uffff\2\163\1\145\1\162\1\uffff\1"+
"\162\2\uffff\1\156\3\uffff\1\172\1\151\2\uffff\1\55\1\157\2\uffff"+
"\2\uffff\1\57\2\uffff\1\160\6\uffff\1\145\1\172\1\154\1\157\1\154"+
"\1\uffff\1\172\1\165\2\uffff\1\144\4\uffff\1\156\3\uffff\1\156\5"+
"\uffff\1\160\1\163\1\uffff\1\145\1\155\1\163\1\uffff\1\145\1\172"+
"\1\153\1\166\1\151\1\172\1\147\1\172\1\145\1\172\1\uffff\1\151\1"+
"\145\1\156\1\uffff\1\141\1\uffff\1\172\1\uffff\1\156\1\162\1\147"+
"\1\164\1\uffff\1\147\1\164\1\163\1\145\4\172\4\uffff";
static final String DFA12_acceptS =
"\2\uffff\1\2\1\3\1\uffff\1\5\4\uffff\1\12\1\uffff\1\14\1\15\1\uffff"+
"\1\17\1\20\1\21\2\uffff\1\24\1\25\2\uffff\1\33\1\34\3\uffff\1\40"+
"\1\41\1\uffff\1\33\1\2\1\3\1\4\1\32\1\5\5\uffff\1\12\2\uffff\1\14"+
"\1\15\1\uffff\1\17\1\20\1\21\1\22\1\uffff\1\24\1\25\1\26\1\uffff"+
"\1\34\1\35\1\36\1\37\1\40\2\uffff\1\7\3\uffff\1\13\12\uffff\1\16"+
"\3\uffff\1\6\1\uffff\1\11\1\uffff\1\30\4\uffff\1\31\10\uffff\1\23"+
"\1\27\1\1\1\10";
static final String DFA12_specialS =
"\1\0\31\uffff\1\2\1\1\116\uffff}>";
static final String[] DFA12_transitionS = {
"\11\36\2\35\2\36\1\35\22\36\1\35\1\14\1\32\4\36\1\33\1\2\1\3"+
"\1\25\1\36\1\12\1\4\1\15\1\34\12\31\1\5\1\36\1\26\1\24\2\36"+
"\1\21\32\30\1\17\1\36\1\20\1\22\1\30\1\36\1\7\1\30\1\27\1\10"+
"\1\16\1\11\5\30\1\23\1\1\6\30\1\13\1\6\5\30\uff85\36",
"\1\37",
"",
"",
"\1\43",
"",
"\1\46",
"\1\47",
"\1\50",
"\1\52\20\uffff\1\51",
"",
"\1\54\2\uffff\1\55",
"",
"",
"\1\60",
"",
"",
"",
"\32\40\4\uffff\1\40\1\uffff\32\40",
"\1\65",
"",
"",
"\1\70",
"\1\71",
"",
"",
"\0\73",
"\0\73",
"\1\74\4\uffff\1\75",
"",
"",
"\1\77",
"",
"",
"",
"",
"",
"",
"\1\100",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\1\102",
"\1\103",
"\1\104",
"",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\1\106",
"",
"",
"\1\107",
"",
"",
"",
"",
"\1\110",
"",
"",
"",
"\1\111",
"",
"",
"",
"",
"",
"\1\112",
"\1\113",
"",
"\1\114",
"\1\115",
"\1\116",
"",
"\1\117",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\1\121",
"\1\122",
"\1\123",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\1\125",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\1\127",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"",
"\1\131",
"\1\132",
"\1\133",
"",
"\1\134",
"",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"",
"\1\136",
"\1\137",
"\1\140",
"\1\141",
"",
"\1\142",
"\1\143",
"\1\144",
"\1\145",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"\12\40\7\uffff\32\40\4\uffff\1\40\1\uffff\32\40",
"",
"",
"",
""
};
static final short[] DFA12_eot = DFA.unpackEncodedString(DFA12_eotS);
static final short[] DFA12_eof = DFA.unpackEncodedString(DFA12_eofS);
static final char[] DFA12_min = DFA.unpackEncodedStringToUnsignedChars(DFA12_minS);
static final char[] DFA12_max = DFA.unpackEncodedStringToUnsignedChars(DFA12_maxS);
static final short[] DFA12_accept = DFA.unpackEncodedString(DFA12_acceptS);
static final short[] DFA12_special = DFA.unpackEncodedString(DFA12_specialS);
static final short[][] DFA12_transition;
static {
int numStates = DFA12_transitionS.length;
DFA12_transition = new short[numStates][];
for (int i=0; i<numStates; i++) {
DFA12_transition[i] = DFA.unpackEncodedString(DFA12_transitionS[i]);
}
}
static class DFA12 extends DFA {
public DFA12(BaseRecognizer recognizer) {
this.recognizer = recognizer;
this.decisionNumber = 12;
this.eot = DFA12_eot;
this.eof = DFA12_eof;
this.min = DFA12_min;
this.max = DFA12_max;
this.accept = DFA12_accept;
this.special = DFA12_special;
this.transition = DFA12_transition;
}
public String getDescription() {
return "1:1: Tokens : ( T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | RULE_ID | RULE_INT | RULE_STRING | RULE_ML_COMMENT | RULE_SL_COMMENT | RULE_WS | RULE_ANY_OTHER );";
}
public int specialStateTransition(int s, IntStream _input) throws NoViableAltException {
IntStream input = _input;
int _s = s;
switch ( s ) {
case 0 :
int LA12_0 = input.LA(1);
s = -1;
if ( (LA12_0=='m') ) {s = 1;}
else if ( (LA12_0=='(') ) {s = 2;}
else if ( (LA12_0==')') ) {s = 3;}
else if ( (LA12_0=='-') ) {s = 4;}
else if ( (LA12_0==':') ) {s = 5;}
else if ( (LA12_0=='u') ) {s = 6;}
else if ( (LA12_0=='a') ) {s = 7;}
else if ( (LA12_0=='d') ) {s = 8;}
else if ( (LA12_0=='f') ) {s = 9;}
else if ( (LA12_0==',') ) {s = 10;}
else if ( (LA12_0=='t') ) {s = 11;}
else if ( (LA12_0=='!') ) {s = 12;}
else if ( (LA12_0=='.') ) {s = 13;}
else if ( (LA12_0=='e') ) {s = 14;}
else if ( (LA12_0=='[') ) {s = 15;}
else if ( (LA12_0==']') ) {s = 16;}
else if ( (LA12_0=='@') ) {s = 17;}
else if ( (LA12_0=='^') ) {s = 18;}
else if ( (LA12_0=='l') ) {s = 19;}
else if ( (LA12_0=='=') ) {s = 20;}
else if ( (LA12_0=='*') ) {s = 21;}
else if ( (LA12_0=='<') ) {s = 22;}
else if ( (LA12_0=='c') ) {s = 23;}
else if ( ((LA12_0>='A' && LA12_0<='Z')||LA12_0=='_'||LA12_0=='b'||(LA12_0>='g' && LA12_0<='k')||(LA12_0>='n' && LA12_0<='s')||(LA12_0>='v' && LA12_0<='z')) ) {s = 24;}
else if ( ((LA12_0>='0' && LA12_0<='9')) ) {s = 25;}
else if ( (LA12_0=='\"') ) {s = 26;}
else if ( (LA12_0=='\'') ) {s = 27;}
else if ( (LA12_0=='/') ) {s = 28;}
else if ( ((LA12_0>='\t' && LA12_0<='\n')||LA12_0=='\r'||LA12_0==' ') ) {s = 29;}
else if ( ((LA12_0>='\u0000' && LA12_0<='\b')||(LA12_0>='\u000B' && LA12_0<='\f')||(LA12_0>='\u000E' && LA12_0<='\u001F')||(LA12_0>='#' && LA12_0<='&')||LA12_0=='+'||LA12_0==';'||(LA12_0>='>' && LA12_0<='?')||LA12_0=='\\'||LA12_0=='`'||(LA12_0>='{' && LA12_0<='\uFFFF')) ) {s = 30;}
if ( s>=0 ) return s;
break;
case 1 :
int LA12_27 = input.LA(1);
s = -1;
if ( ((LA12_27>='\u0000' && LA12_27<='\uFFFF')) ) {s = 59;}
else s = 30;
if ( s>=0 ) return s;
break;
case 2 :
int LA12_26 = input.LA(1);
s = -1;
if ( ((LA12_26>='\u0000' && LA12_26<='\uFFFF')) ) {s = 59;}
else s = 30;
if ( s>=0 ) return s;
break;
}
NoViableAltException nvae =
new NoViableAltException(getDescription(), 12, _s, input);
error(nvae);
throw nvae;
}
}
} | gpl-3.0 |
erickvla/mySat | src/org/mysat/persistence/daos/PersonaDao.java | 2509 | /**
*
*/
package org.mysat.persistence.daos;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mysat.Constants;
import org.mysat.persistence.entities.Persona;
/**
* @author imac
*
*/
public class PersonaDao extends AbstractDao<Persona, Long> implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3542134649305920795L;
public PersonaDao() {
managedClass = Persona.class;
}
public List<Persona> findAll() {
List<Persona> itemsList = (List<Persona>)getListFromNamedQuery(Constants.NAMED_QUERY_PERSONA_FIND_ALL);
return itemsList;
}
public List<Persona> findByNombreLike(String nombre) {
Map<String, String> params = null;
List<Persona> itemsList = null;
if (nombre != null) {
params = new HashMap<String, String>();
params.put("nombre", getParamLike(nombre));
itemsList = (List<Persona>)getListFromNamedQueryParams(Constants.NAMED_QUERY_PERSONA_FIND_BY_NOMBRE_LIKE, params);
}
return itemsList;
}
public List<Persona> findByApellidoLike(String apellido) {
Map<String, String> params = null;
List<Persona> itemsList = null;
if (apellido != null) {
params = new HashMap<String, String>();
params.put("apellido", getParamLike(apellido));
itemsList = (List<Persona>)getListFromNamedQueryParams(Constants.NAMED_QUERY_PERSONA_FIND_BY_APELLIDO_LIKE, params);
}
return itemsList;
}
public Persona findById(long id) {
Persona item = null;
if (id > 0) {
item = super.findById(id);
}
return item;
}
public Persona findByNombre(String nombre) {
Map<String, String> params = null;
Persona item = null;
if (nombre != null) {
params = new HashMap<String, String>();
params.put("nombre", nombre);
item = (Persona)getItemFromNamedQueryParams(Constants.NAMED_QUERY_PERSONA_FIND_BY_NOMBRE, params);
}
return item;
}
public Persona findByApellido(String apellido) {
Map<String, String> params = null;
Persona item = null;
if (apellido != null) {
params = new HashMap<String, String>();
params.put("apellido", apellido);
item = (Persona)getItemFromNamedQueryParams(Constants.NAMED_QUERY_PERSONA_FIND_BY_APELLIDO, params);
}
return item;
}
public void insert(Persona item) {
super.insert(item);
}
public void update(Persona item) {
super.update(item);
}
public void delete(Persona item) {
super.delete(item.getId());
}
}
| gpl-3.0 |
Ayuntamiento-Zaragoza/dxf2gml-catastro | catastro/utils.py | 283 | # -*- coding: utf-8 -*-
import os
def handle_uploaded_file(f, target):
path = os.path.dirname(target)
if not os.path.isdir(path):
os.makedirs(path)
with open(target, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
| gpl-3.0 |
sigecoin/sigecoin | test/hash_tests.cpp | 5671 | // Copyright (c) 2017 SIGE developer
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "hash.h"
#include "utilstrencodings.h"
#include "test/test_sigecoin.h"
#include <vector>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(hash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(murmurhash3)
{
#define T(expected, seed, data) BOOST_CHECK_EQUAL(MurmurHash3(seed, ParseHex(data)), expected)
// Test MurmurHash3 with various inputs. Of course this is retested in the
// bloom filter tests - they would fail if MurmurHash3() had any problems -
// but is useful for those trying to implement Sigecoin libraries as a
// source of test data for their MurmurHash3() primitive during
// development.
//
// The magic number 0xFBA4C795 comes from CBloomFilter::Hash()
T(0x00000000, 0x00000000, "");
T(0x6a396f08, 0xFBA4C795, "");
T(0x81f16f39, 0xffffffff, "");
T(0x514e28b7, 0x00000000, "00");
T(0xea3f0b17, 0xFBA4C795, "00");
T(0xfd6cf10d, 0x00000000, "ff");
T(0x16c6b7ab, 0x00000000, "0011");
T(0x8eb51c3d, 0x00000000, "001122");
T(0xb4471bf8, 0x00000000, "00112233");
T(0xe2301fa8, 0x00000000, "0011223344");
T(0xfc2e4a15, 0x00000000, "001122334455");
T(0xb074502c, 0x00000000, "00112233445566");
T(0x8034d2a0, 0x00000000, "0011223344556677");
T(0xb4698def, 0x00000000, "001122334455667788");
#undef T
}
/*
SipHash-2-4 output with
k = 00 01 02 ...
and
in = (empty string)
in = 00 (1 byte)
in = 00 01 (2 bytes)
in = 00 01 02 (3 bytes)
...
in = 00 01 02 ... 3e (63 bytes)
from: https://131002.net/siphash/siphash24.c
*/
uint64_t siphash_4_2_testvec[] = {
0x726fdb47dd0e0e31, 0x74f839c593dc67fd, 0x0d6c8009d9a94f5a, 0x85676696d7fb7e2d,
0xcf2794e0277187b7, 0x18765564cd99a68d, 0xcbc9466e58fee3ce, 0xab0200f58b01d137,
0x93f5f5799a932462, 0x9e0082df0ba9e4b0, 0x7a5dbbc594ddb9f3, 0xf4b32f46226bada7,
0x751e8fbc860ee5fb, 0x14ea5627c0843d90, 0xf723ca908e7af2ee, 0xa129ca6149be45e5,
0x3f2acc7f57c29bdb, 0x699ae9f52cbe4794, 0x4bc1b3f0968dd39c, 0xbb6dc91da77961bd,
0xbed65cf21aa2ee98, 0xd0f2cbb02e3b67c7, 0x93536795e3a33e88, 0xa80c038ccd5ccec8,
0xb8ad50c6f649af94, 0xbce192de8a85b8ea, 0x17d835b85bbb15f3, 0x2f2e6163076bcfad,
0xde4daaaca71dc9a5, 0xa6a2506687956571, 0xad87a3535c49ef28, 0x32d892fad841c342,
0x7127512f72f27cce, 0xa7f32346f95978e3, 0x12e0b01abb051238, 0x15e034d40fa197ae,
0x314dffbe0815a3b4, 0x027990f029623981, 0xcadcd4e59ef40c4d, 0x9abfd8766a33735c,
0x0e3ea96b5304a7d0, 0xad0c42d6fc585992, 0x187306c89bc215a9, 0xd4a60abcf3792b95,
0xf935451de4f21df2, 0xa9538f0419755787, 0xdb9acddff56ca510, 0xd06c98cd5c0975eb,
0xe612a3cb9ecba951, 0xc766e62cfcadaf96, 0xee64435a9752fe72, 0xa192d576b245165a,
0x0a8787bf8ecb74b2, 0x81b3e73d20b49b6f, 0x7fa8220ba3b2ecea, 0x245731c13ca42499,
0xb78dbfaf3a8d83bd, 0xea1ad565322a1a0b, 0x60e61c23a3795013, 0x6606d7e446282b93,
0x6ca4ecb15c5f91e1, 0x9f626da15c9625f3, 0xe51b38608ef25f57, 0x958a324ceb064572
};
BOOST_AUTO_TEST_CASE(siphash)
{
CSipHasher hasher(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x726fdb47dd0e0e31ull);
static const unsigned char t0[1] = {0};
hasher.Write(t0, 1);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x74f839c593dc67fdull);
static const unsigned char t1[7] = {1,2,3,4,5,6,7};
hasher.Write(t1, 7);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x93f5f5799a932462ull);
hasher.Write(0x0F0E0D0C0B0A0908ULL);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x3f2acc7f57c29bdbull);
static const unsigned char t2[2] = {16,17};
hasher.Write(t2, 2);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x4bc1b3f0968dd39cull);
static const unsigned char t3[9] = {18,19,20,21,22,23,24,25,26};
hasher.Write(t3, 9);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x2f2e6163076bcfadull);
static const unsigned char t4[5] = {27,28,29,30,31};
hasher.Write(t4, 5);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x7127512f72f27cceull);
hasher.Write(0x2726252423222120ULL);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0x0e3ea96b5304a7d0ull);
hasher.Write(0x2F2E2D2C2B2A2928ULL);
BOOST_CHECK_EQUAL(hasher.Finalize(), 0xe612a3cb9ecba951ull);
BOOST_CHECK_EQUAL(SipHashUint256(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL, uint256S("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")), 0x7127512f72f27cceull);
// Check test vectors from spec, one byte at a time
CSipHasher hasher2(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL);
for (uint8_t x=0; x<ARRAYLEN(siphash_4_2_testvec); ++x)
{
BOOST_CHECK_EQUAL(hasher2.Finalize(), siphash_4_2_testvec[x]);
hasher2.Write(&x, 1);
}
// Check test vectors from spec, eight bytes at a time
CSipHasher hasher3(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL);
for (uint8_t x=0; x<ARRAYLEN(siphash_4_2_testvec); x+=8)
{
BOOST_CHECK_EQUAL(hasher3.Finalize(), siphash_4_2_testvec[x]);
hasher3.Write(uint64_t(x)|(uint64_t(x+1)<<8)|(uint64_t(x+2)<<16)|(uint64_t(x+3)<<24)|
(uint64_t(x+4)<<32)|(uint64_t(x+5)<<40)|(uint64_t(x+6)<<48)|(uint64_t(x+7)<<56));
}
CHashWriter ss(SER_DISK, CLIENT_VERSION);
CMutableTransaction tx;
// Note these tests were originally written with tx.nVersion=1
// and the test would be affected by default tx version bumps if not fixed.
tx.nVersion = 1;
ss << tx;
BOOST_CHECK_EQUAL(SipHashUint256(1, 2, ss.GetHash()), 0x79751e980c2a0a35ULL);
}
BOOST_AUTO_TEST_SUITE_END()
| gpl-3.0 |
Libertual/api-server | middlewares/authMidlw.js | 731 |
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../config/main');
function isAuth(req, res, next) {
// console.log(req.headers);
if (!req.headers.authorization) return res.status(403).send({ message: 'No estás conectado.' });
const token = req.header('Authorization').split(' ')[1];
const payload = jwt.decode(token, config.SECRET_TOKEN, true);
// console.log("Payload: " + JSON.stringify(payload));
if (payload.exp <= moment().unix()) {
res.status(401).send({ message: 'La sesión ha expirado' });
} else {
req.user = payload.sub;
// console.log('req.user');
// console.log(req.user);
next();
}
return true;
}
module.exports = { isAuth };
| gpl-3.0 |
wp-plugins/uiform-form-builder | modules/formbuilder/views/fields/templates/prevpanel_submitbtn.php | 2956 | <?php
/**
* Intranet
*
* PHP version 5
*
* @category PHP
* @package Rocket_form
* @author Softdiscover <info@softdiscover.com>
* @copyright 2015 Softdiscover
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @link http://www.uiform.com/wordpress-form-builder
*/
if (!defined('ABSPATH')) {exit('No direct script access allowed');}
ob_start();
?>
<?php
$id_field=(!empty($id))?$id:'';
?>
<div id="<?php echo $id_field;?>" data-typefield="20" class="uiform-submitbtn uiform-field uiform-field-childs">
<div class="uiform-field-wrap uiform-field-move">
<div class="rkfm-row">
<div class="rkfm-col-sm-2" style="display: none;">
<div class="uifm-control-label">
<label class="control-label">
<span
data-field-option="uifm-help-block"
class="uifm-label-helpblock uifm-f-option">
<span class="fa fa-question-circle"></span>
</span>
<span data-field-store="label-text"
data-field-option="uifm-label"
class="uifm-label uifm-f-option"><?php echo __('Textbox label','FRocket_admin'); ?></span>
<span data-field-store="sublabel-text"
data-field-option="uifm-sublabel"
class="uifm-sublabel uifm-f-option"><?php echo __('Textbox sublabel','FRocket_admin'); ?></span>
</label>
</div>
</div>
<div class="rkfm-col-sm-10">
<div class="uifm-input-container">
<input
class="btn uifm-txtbox-inp-val"
type="submit"
value="Submit button">
</div>
<div data-field-option="uifm-help-block" style="display: none;" class="uifm-help-block uifm-f-option">
<?php echo __('Help block text','FRocket_admin'); ?>
</div>
</div>
</div>
<?php echo $quick_options;?>
</div>
</div>
<?php
$cntACmp = ob_get_contents();
/*$cntACmp = str_replace("\n", '', $cntACmp);
$cntACmp = str_replace("\t", '', $cntACmp);
$cntACmp = str_replace("\r", '', $cntACmp);
$cntACmp = str_replace("//-->", ' ', $cntACmp);
$cntACmp = str_replace("//<!--", ' ', $cntACmp);
@$cntACmp = eregi_replace("[[:space:]]+", " ", $cntACmp);*/
ob_end_clean();
echo $cntACmp;
?>
| gpl-3.0 |
urashima9616/Leetcode_Python | Leet130_SurroundedRegions2.py | 2294 | import Queue
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board:
return
rowdim = len(board)
coldim = len(board[0])
openlist = Queue.Queue()
for i in xrange(rowdim):
for j in xrange(coldim):
if board[i][j] == 'X' or board[i][j] == 'Y':
continue
if (i == 0 and j == 0) or (i == rowdim-1 and j == coldim - 1):
board[i][j] = 'Y'
continue
if i == rowdim- 1 or j == coldim -1 or i == 0 or j == 0: # boundary
if board[i][j] == 'O':
board[i][j] = 'Y'
openlist.put(self.getNeighbors(i, j, rowdim, coldim))
while not openlist.empty():
for each in openlist.get():
if not each:
continue
if board[each[0]][each[1]] == 'O':
board[each[0]][each[1]] = 'Y'
openlist.put(self.getNeighbors(each[0], each[1], rowdim, coldim))
for i in xrange(rowdim):
for j in xrange(coldim):
if board[i][j] == 'Y':
board[i][j] = 'O'
elif board[i][j] == 'O':
board[i][j] = 'X'
def getNeighbors(self, row, col, rowdim, coldim):
neighbors = [[row-1, col],[row+1, col],[row,col-1],[row, col+1]]
if row == 0 and rowdim > 1:
return [neighbors[1]]
if row == rowdim -1:
return [neighbors[0]]
if col == 0 and coldim > 1:
return [neighbors[3]]
if col == coldim -1:
return [neighbors[2]]
return neighbors
Solve = Solution()
board = [['X','X','X','X'], ['X', 'O', 'O','X'], ['X','X','O','X'],['X','O','X','X']]
#board = ["X","O","X","X","OXOX","XOXO","OXOX","XOXO","OXOX"]
#board = [["O","X", "X","O","X"], ["X","O","O","X","O"], ["X","O","X","O","X"], ["O","X","O","O","O"],["X","X","O","X","O"]]
Solve.solve(board)
print "done"
| gpl-3.0 |
gtri-iead/org.gtri.util.scala | xsdbuilder/src/main/scala/org/gtri/util/scala/xsdbuilder/elements/XsdSimpleType.scala | 2244 | package org.gtri.util.scala.xsdbuilder.elements
import org.gtri.util.scala.statemachine._
import org.gtri.util.xsddatatypes._
import org.gtri.util.xsddatatypes.XsdCodes._
import org.gtri.util.xsddatatypes.XsdConstants._
import org.gtri.util.scala.xsdbuilder.XmlParser._
import org.gtri.util.scala.xmlbuilder.{XmlNamespaceContext, XmlElement}
import org.gtri.util.scala.xsdbuilder.XsdAllOrNone
import org.gtri.util.scala.xsdbuilder.elements.XsdGenVal._
case class XsdSimpleType(
optId : Option[XsdId] = None,
name : XsdName,
optFinal : Option[XsdAllOrNone[SimpleTypeFinalCode]] = None,
optMetadata : Option[XsdElement.Metadata] = None
) extends XsdElement {
def optValue = None
def util = XsdSimpleType.util
def toAttributesMap(context: Seq[XmlNamespaceContext]) = {
{
optId.map { (ATTRIBUTES.ID.QNAME -> _.toString) } ::
Some(ATTRIBUTES.NAME.QNAME -> name.toString) ::
optFinal.map { (ATTRIBUTES.FINAL.QNAME -> _.toString) } ::
Nil
}.flatten.toMap
}
}
object XsdSimpleType {
implicit object util extends XsdElementUtil[XsdSimpleType] {
def qName = ELEMENTS.SIMPLETYPE.QNAME
def parser[EE >: XsdSimpleType](context: Seq[XmlNamespaceContext]) : Parser[XmlElement,EE] = {
for{
element <- Parser.tell[XmlElement]
optId <- optionalAttributeParser(ATTRIBUTES.ID.QNAME, Try.parser(XsdId.parseString))
name <- requiredAttributeParser(ATTRIBUTES.NAME.QNAME,Try.parser(XsdName.parseString), Some(genRandomName _))
optFinal <- optionalAttributeParser(ATTRIBUTES.FINAL.QNAME, XsdAllOrNone.parser(Try.parser(SimpleTypeFinalCode.parseString)))
} yield
XsdSimpleType(
optId = optId,
name = name,
optFinal = optFinal,
optMetadata = Some(XsdElement.Metadata(element))
)
}
def attributes = Set(
ATTRIBUTES.ID.QNAME,
ATTRIBUTES.NAME.QNAME,
ATTRIBUTES.FINAL.QNAME
)
def allowedChildElements(children: Seq[XsdElementUtil[XsdElement]]) = {
Seq(
XsdAnnotation.util,
XsdSimpleTypeRestriction.util
)
}
}
} | gpl-3.0 |
Vespapp/vespapp-web | api/migrations/0032_auto_20160721_1004.py | 423 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-07-21 08:04
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0031_appversion_last'),
]
operations = [
migrations.RenameField(
model_name='appversion',
old_name='last',
new_name='is_last',
),
]
| gpl-3.0 |
dbs-leipzig/foodbroker_ruby | model/customer.rb | 278 | class Customer < ERPMasterData
def Customer.duck
Customer.new :kind
end
def initialize kind
@name = "#{NAMES[:customer][:adj].sample} #{NAMES[:customer][:noun].sample} #{NAMES[:cities].sample}"
super kind
DomainData.add2stats 1,0
end
end | gpl-3.0 |
SQLPower/power-matchmaker | regress/ca/sqlpower/matchmaker/munge/TestingAbstractMungeStep.java | 1256 | /*
* Copyright (c) 2008, SQL Power Group Inc.
*
* This file is part of DQguru
*
* DQguru 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.
*
* DQguru 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 ca.sqlpower.matchmaker.munge;
/**
* A bare bones test implementation of an AbstractMungeStep for
* unit testing purposes only.
*/
public class TestingAbstractMungeStep extends AbstractMungeStep {
public TestingAbstractMungeStep() {
super("Testing Abstract Munge Step", true);
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public int hashCode() {
return 0;
}
public Boolean doCall() throws Exception {
return true;
}
}
| gpl-3.0 |
h-asai/AnswersheetAnalysis | AnswerSheetAnalysis/Common/RelayCommand.cs | 1813 | using System;
using System.Windows.Input;
using System.Diagnostics;
namespace AnswerSheetAnalysis
{
/// <summary>
/// Relay command that catches events
/// </summary>
public class RelayCommand : ICommand
{
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
/// <summary>
/// Initialization
/// </summary>
/// <param name="execute"></param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Initialization
/// </summary>
/// <param name="execute"></param>
/// <param name="canExecute"></param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
/// <summary>
///
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
/// <summary>
///
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
///
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
_execute(parameter);
}
}
}
| gpl-3.0 |
srnsw/xena | plugins/project/ext/src/mpxj/src/net/sf/mpxj/mpx/MPXTaskField.java | 20712 | /*
* file: MPXTaskField.java
* author: Jon Iles
* copyright: (c) Packwood Software 2005
* date: 20-Feb-2006
*/
/*
* This library 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 2.1 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package net.sf.mpxj.mpx;
import net.sf.mpxj.TaskField;
/**
* Utility class used to map between the integer values held in an MPX file
* to represent a task field, and the enumerated type used to represent
* task fields in MPXJ.
*/
final class MPXTaskField
{
/**
* Retrieve an instance of the TaskField class based on the data read from an
* MPX file.
*
* @param value value from an MS Project file
* @return TaskField instance
*/
public static TaskField getMpxjField(int value)
{
TaskField result = null;
if (value >= 0 && value < MPX_MPXJ_ARRAY.length)
{
result = MPX_MPXJ_ARRAY[value];
}
return (result);
}
/**
* Retrieve the integer value used to represent a task field in an
* MPX file.
*
* @param value MPXJ task field value
* @return MPX field value
*/
public static int getMpxField(int value)
{
int result = 0;
if (value >= 0 && value < MPXJ_MPX_ARRAY.length)
{
result = MPXJ_MPX_ARRAY[value];
}
return (result);
}
private static final int PERCENTAGE_COMPLETE = 44;
private static final int PERCENTAGE_WORK_COMPLETE = 25;
private static final int ACTUAL_COST = 32;
private static final int ACTUAL_DURATION = 42;
private static final int ACTUAL_FINISH = 59;
private static final int ACTUAL_START = 58;
private static final int ACTUAL_WORK = 22;
private static final int BASELINE_COST = 31;
private static final int BASELINE_DURATION = 41;
private static final int BASELINE_FINISH = 57;
private static final int BASELINE_START = 56;
private static final int BASELINE_WORK = 21;
private static final int BCWP = 86;
private static final int BCWS = 85;
private static final int CONFIRMED = 135;
private static final int CONSTRAINT_DATE = 68;
private static final int CONSTRAINT_TYPE = 91;
private static final int CONTACT = 15;
private static final int COST = 30;
private static final int COST1 = 36;
private static final int COST2 = 37;
private static final int COST3 = 38;
private static final int COST_VARIANCE = 34;
private static final int CREATE_DATE = 125;
private static final int CRITICAL = 82;
private static final int CV = 88;
private static final int DELAY = 92;
private static final int DURATION = 40;
private static final int DURATION1 = 46;
private static final int DURATION2 = 47;
private static final int DURATION3 = 48;
private static final int DURATION_VARIANCE = 45;
private static final int EARLY_FINISH = 53;
private static final int EARLY_START = 52;
private static final int FINISH = 51;
private static final int FINISH1 = 61;
private static final int FINISH2 = 63;
private static final int FINISH3 = 65;
private static final int FINISH4 = 127;
private static final int FINISH5 = 129;
private static final int FINISH_VARIANCE = 67;
private static final int TYPE = 80;
private static final int FIXED_COST = 35;
private static final int FLAG1 = 110;
private static final int FLAG2 = 111;
private static final int FLAG3 = 112;
private static final int FLAG4 = 113;
private static final int FLAG5 = 114;
private static final int FLAG6 = 115;
private static final int FLAG7 = 116;
private static final int FLAG8 = 117;
private static final int FLAG9 = 118;
private static final int FLAG10 = 119;
private static final int FREE_SLACK = 93;
private static final int HIDE_BAR = 123;
private static final int ID = 90;
private static final int LATE_FINISH = 55;
private static final int LATE_START = 54;
private static final int LINKED_FIELDS = 122;
private static final int MARKED = 83;
private static final int MILESTONE = 81;
private static final int NAME = 1;
//private static final int NOTES = 14;
private static final int NUMBER1 = 140;
private static final int NUMBER2 = 141;
private static final int NUMBER3 = 142;
private static final int NUMBER4 = 143;
private static final int NUMBER5 = 144;
private static final int OBJECTS = 121;
private static final int OUTLINE_LEVEL = 3;
private static final int OUTLINE_NUMBER = 99;
private static final int PREDECESSORS = 70;
private static final int PRIORITY = 95;
private static final int PROJECT = 97;
private static final int REMAINING_COST = 33;
private static final int REMAINING_DURATION = 43;
private static final int REMAINING_WORK = 23;
private static final int RESOURCE_GROUP = 16;
private static final int RESOURCE_INITIALS = 73;
private static final int RESOURCE_NAMES = 72;
private static final int RESUME = 151;
private static final int RESUME_NO_EARLIER_THAN = 152;
private static final int ROLLUP = 84;
private static final int START = 50;
private static final int START1 = 60;
private static final int START2 = 62;
private static final int START3 = 64;
private static final int START4 = 126;
private static final int START5 = 128;
private static final int START_VARIANCE = 66;
private static final int STOP = 150;
private static final int SUBPROJECT_NAME = 96;
private static final int SUCCESSORS = 71;
private static final int SUMMARY = 120;
private static final int SV = 87;
private static final int TEXT1 = 4;
private static final int TEXT2 = 5;
private static final int TEXT3 = 6;
private static final int TEXT4 = 7;
private static final int TEXT5 = 8;
private static final int TEXT6 = 9;
private static final int TEXT7 = 10;
private static final int TEXT8 = 11;
private static final int TEXT9 = 12;
private static final int TEXT10 = 13;
private static final int TOTAL_SLACK = 94;
private static final int UNIQUE_ID = 98;
private static final int UNIQUE_ID_PREDECESSORS = 74;
private static final int UNIQUE_ID_SUCCESSORS = 75;
private static final int UPDATE_NEEDED = 136;
private static final int WBS = 2;
private static final int WORK = 20;
private static final int WORK_VARIANCE = 24;
public static final int MAX_FIELDS = 153;
private static final TaskField[] MPX_MPXJ_ARRAY = new TaskField[MAX_FIELDS];
static
{
MPX_MPXJ_ARRAY[PERCENTAGE_COMPLETE] = TaskField.PERCENT_COMPLETE;
MPX_MPXJ_ARRAY[PERCENTAGE_WORK_COMPLETE] = TaskField.PERCENT_WORK_COMPLETE;
MPX_MPXJ_ARRAY[ACTUAL_COST] = TaskField.ACTUAL_COST;
MPX_MPXJ_ARRAY[ACTUAL_DURATION] = TaskField.ACTUAL_DURATION;
MPX_MPXJ_ARRAY[ACTUAL_FINISH] = TaskField.ACTUAL_FINISH;
MPX_MPXJ_ARRAY[ACTUAL_START] = TaskField.ACTUAL_START;
MPX_MPXJ_ARRAY[ACTUAL_WORK] = TaskField.ACTUAL_WORK;
MPX_MPXJ_ARRAY[BASELINE_COST] = TaskField.BASELINE_COST;
MPX_MPXJ_ARRAY[BASELINE_DURATION] = TaskField.BASELINE_DURATION;
MPX_MPXJ_ARRAY[BASELINE_FINISH] = TaskField.BASELINE_FINISH;
MPX_MPXJ_ARRAY[BASELINE_START] = TaskField.BASELINE_START;
MPX_MPXJ_ARRAY[BASELINE_WORK] = TaskField.BASELINE_WORK;
MPX_MPXJ_ARRAY[BCWP] = TaskField.BCWP;
MPX_MPXJ_ARRAY[BCWS] = TaskField.BCWS;
MPX_MPXJ_ARRAY[CONFIRMED] = TaskField.CONFIRMED;
MPX_MPXJ_ARRAY[CONSTRAINT_DATE] = TaskField.CONSTRAINT_DATE;
MPX_MPXJ_ARRAY[CONSTRAINT_TYPE] = TaskField.CONSTRAINT_TYPE;
MPX_MPXJ_ARRAY[CONTACT] = TaskField.CONTACT;
MPX_MPXJ_ARRAY[COST] = TaskField.COST;
MPX_MPXJ_ARRAY[COST1] = TaskField.COST1;
MPX_MPXJ_ARRAY[COST2] = TaskField.COST2;
MPX_MPXJ_ARRAY[COST3] = TaskField.COST3;
MPX_MPXJ_ARRAY[COST_VARIANCE] = TaskField.COST_VARIANCE;
MPX_MPXJ_ARRAY[CREATE_DATE] = TaskField.CREATED;
MPX_MPXJ_ARRAY[CRITICAL] = TaskField.CRITICAL;
MPX_MPXJ_ARRAY[CV] = TaskField.CV;
MPX_MPXJ_ARRAY[DELAY] = TaskField.LEVELING_DELAY;
MPX_MPXJ_ARRAY[DURATION] = TaskField.DURATION;
MPX_MPXJ_ARRAY[DURATION1] = TaskField.DURATION1;
MPX_MPXJ_ARRAY[DURATION2] = TaskField.DURATION2;
MPX_MPXJ_ARRAY[DURATION3] = TaskField.DURATION3;
MPX_MPXJ_ARRAY[DURATION_VARIANCE] = TaskField.DURATION_VARIANCE;
MPX_MPXJ_ARRAY[EARLY_FINISH] = TaskField.EARLY_FINISH;
MPX_MPXJ_ARRAY[EARLY_START] = TaskField.EARLY_START;
MPX_MPXJ_ARRAY[FINISH] = TaskField.FINISH;
MPX_MPXJ_ARRAY[FINISH1] = TaskField.FINISH1;
MPX_MPXJ_ARRAY[FINISH2] = TaskField.FINISH2;
MPX_MPXJ_ARRAY[FINISH3] = TaskField.FINISH3;
MPX_MPXJ_ARRAY[FINISH4] = TaskField.FINISH4;
MPX_MPXJ_ARRAY[FINISH5] = TaskField.FINISH5;
MPX_MPXJ_ARRAY[FINISH_VARIANCE] = TaskField.FINISH_VARIANCE;
MPX_MPXJ_ARRAY[TYPE] = TaskField.TYPE;
MPX_MPXJ_ARRAY[FIXED_COST] = TaskField.FIXED_COST;
MPX_MPXJ_ARRAY[FLAG1] = TaskField.FLAG1;
MPX_MPXJ_ARRAY[FLAG2] = TaskField.FLAG2;
MPX_MPXJ_ARRAY[FLAG3] = TaskField.FLAG3;
MPX_MPXJ_ARRAY[FLAG4] = TaskField.FLAG4;
MPX_MPXJ_ARRAY[FLAG5] = TaskField.FLAG5;
MPX_MPXJ_ARRAY[FLAG6] = TaskField.FLAG6;
MPX_MPXJ_ARRAY[FLAG7] = TaskField.FLAG7;
MPX_MPXJ_ARRAY[FLAG8] = TaskField.FLAG8;
MPX_MPXJ_ARRAY[FLAG9] = TaskField.FLAG9;
MPX_MPXJ_ARRAY[FLAG10] = TaskField.FLAG10;
MPX_MPXJ_ARRAY[FREE_SLACK] = TaskField.FREE_SLACK;
MPX_MPXJ_ARRAY[HIDE_BAR] = TaskField.HIDEBAR;
MPX_MPXJ_ARRAY[ID] = TaskField.ID;
MPX_MPXJ_ARRAY[LATE_FINISH] = TaskField.LATE_FINISH;
MPX_MPXJ_ARRAY[LATE_START] = TaskField.LATE_START;
MPX_MPXJ_ARRAY[LINKED_FIELDS] = TaskField.LINKED_FIELDS;
MPX_MPXJ_ARRAY[MARKED] = TaskField.MARKED;
MPX_MPXJ_ARRAY[MILESTONE] = TaskField.MILESTONE;
MPX_MPXJ_ARRAY[NAME] = TaskField.NAME;
//MPX_MPXJ_ARRAY[NOTES] = TaskField.NOTES;
MPX_MPXJ_ARRAY[NUMBER1] = TaskField.NUMBER1;
MPX_MPXJ_ARRAY[NUMBER2] = TaskField.NUMBER2;
MPX_MPXJ_ARRAY[NUMBER3] = TaskField.NUMBER3;
MPX_MPXJ_ARRAY[NUMBER4] = TaskField.NUMBER4;
MPX_MPXJ_ARRAY[NUMBER5] = TaskField.NUMBER5;
MPX_MPXJ_ARRAY[OBJECTS] = TaskField.OBJECTS;
MPX_MPXJ_ARRAY[OUTLINE_LEVEL] = TaskField.OUTLINE_LEVEL;
MPX_MPXJ_ARRAY[OUTLINE_NUMBER] = TaskField.OUTLINE_NUMBER;
MPX_MPXJ_ARRAY[PREDECESSORS] = TaskField.PREDECESSORS;
MPX_MPXJ_ARRAY[PRIORITY] = TaskField.PRIORITY;
MPX_MPXJ_ARRAY[PROJECT] = TaskField.PROJECT;
MPX_MPXJ_ARRAY[REMAINING_COST] = TaskField.REMAINING_COST;
MPX_MPXJ_ARRAY[REMAINING_DURATION] = TaskField.REMAINING_DURATION;
MPX_MPXJ_ARRAY[REMAINING_WORK] = TaskField.REMAINING_WORK;
MPX_MPXJ_ARRAY[RESOURCE_GROUP] = TaskField.RESOURCE_GROUP;
MPX_MPXJ_ARRAY[RESOURCE_INITIALS] = TaskField.RESOURCE_INITIALS;
MPX_MPXJ_ARRAY[RESOURCE_NAMES] = TaskField.RESOURCE_NAMES;
MPX_MPXJ_ARRAY[RESUME] = TaskField.RESUME;
MPX_MPXJ_ARRAY[RESUME_NO_EARLIER_THAN] = TaskField.RESUME;
MPX_MPXJ_ARRAY[ROLLUP] = TaskField.ROLLUP;
MPX_MPXJ_ARRAY[START] = TaskField.START;
MPX_MPXJ_ARRAY[START1] = TaskField.START1;
MPX_MPXJ_ARRAY[START2] = TaskField.START2;
MPX_MPXJ_ARRAY[START3] = TaskField.START3;
MPX_MPXJ_ARRAY[START4] = TaskField.START4;
MPX_MPXJ_ARRAY[START5] = TaskField.START5;
MPX_MPXJ_ARRAY[START_VARIANCE] = TaskField.START_VARIANCE;
MPX_MPXJ_ARRAY[STOP] = TaskField.STOP;
MPX_MPXJ_ARRAY[SUBPROJECT_NAME] = TaskField.SUBPROJECT_FILE;
MPX_MPXJ_ARRAY[SUCCESSORS] = TaskField.SUCCESSORS;
MPX_MPXJ_ARRAY[SUMMARY] = TaskField.SUMMARY;
MPX_MPXJ_ARRAY[SV] = TaskField.SV;
MPX_MPXJ_ARRAY[TEXT1] = TaskField.TEXT1;
MPX_MPXJ_ARRAY[TEXT2] = TaskField.TEXT2;
MPX_MPXJ_ARRAY[TEXT3] = TaskField.TEXT3;
MPX_MPXJ_ARRAY[TEXT4] = TaskField.TEXT4;
MPX_MPXJ_ARRAY[TEXT5] = TaskField.TEXT5;
MPX_MPXJ_ARRAY[TEXT6] = TaskField.TEXT6;
MPX_MPXJ_ARRAY[TEXT7] = TaskField.TEXT7;
MPX_MPXJ_ARRAY[TEXT8] = TaskField.TEXT8;
MPX_MPXJ_ARRAY[TEXT9] = TaskField.TEXT9;
MPX_MPXJ_ARRAY[TEXT10] = TaskField.TEXT10;
MPX_MPXJ_ARRAY[TOTAL_SLACK] = TaskField.TOTAL_SLACK;
MPX_MPXJ_ARRAY[UNIQUE_ID] = TaskField.UNIQUE_ID;
MPX_MPXJ_ARRAY[UNIQUE_ID_PREDECESSORS] = TaskField.UNIQUE_ID_PREDECESSORS;
MPX_MPXJ_ARRAY[UNIQUE_ID_SUCCESSORS] = TaskField.UNIQUE_ID_SUCCESSORS;
MPX_MPXJ_ARRAY[UPDATE_NEEDED] = TaskField.UPDATE_NEEDED;
MPX_MPXJ_ARRAY[WBS] = TaskField.WBS;
MPX_MPXJ_ARRAY[WORK] = TaskField.WORK;
MPX_MPXJ_ARRAY[WORK_VARIANCE] = TaskField.WORK_VARIANCE;
}
private static final int[] MPXJ_MPX_ARRAY = new int[TaskField.MAX_VALUE];
static
{
MPXJ_MPX_ARRAY[TaskField.PERCENT_COMPLETE_VALUE] = PERCENTAGE_COMPLETE;
MPXJ_MPX_ARRAY[TaskField.PERCENT_WORK_COMPLETE_VALUE] = PERCENTAGE_WORK_COMPLETE;
MPXJ_MPX_ARRAY[TaskField.ACTUAL_COST_VALUE] = ACTUAL_COST;
MPXJ_MPX_ARRAY[TaskField.ACTUAL_DURATION_VALUE] = ACTUAL_DURATION;
MPXJ_MPX_ARRAY[TaskField.ACTUAL_FINISH_VALUE] = ACTUAL_FINISH;
MPXJ_MPX_ARRAY[TaskField.ACTUAL_START_VALUE] = ACTUAL_START;
MPXJ_MPX_ARRAY[TaskField.ACTUAL_WORK_VALUE] = ACTUAL_WORK;
MPXJ_MPX_ARRAY[TaskField.BASELINE_COST_VALUE] = BASELINE_COST;
MPXJ_MPX_ARRAY[TaskField.BASELINE_DURATION_VALUE] = BASELINE_DURATION;
MPXJ_MPX_ARRAY[TaskField.BASELINE_FINISH_VALUE] = BASELINE_FINISH;
MPXJ_MPX_ARRAY[TaskField.BASELINE_START_VALUE] = BASELINE_START;
MPXJ_MPX_ARRAY[TaskField.BASELINE_WORK_VALUE] = BASELINE_WORK;
MPXJ_MPX_ARRAY[TaskField.BCWP_VALUE] = BCWP;
MPXJ_MPX_ARRAY[TaskField.BCWS_VALUE] = BCWS;
MPXJ_MPX_ARRAY[TaskField.CONFIRMED_VALUE] = CONFIRMED;
MPXJ_MPX_ARRAY[TaskField.CONSTRAINT_DATE_VALUE] = CONSTRAINT_DATE;
MPXJ_MPX_ARRAY[TaskField.CONSTRAINT_TYPE_VALUE] = CONSTRAINT_TYPE;
MPXJ_MPX_ARRAY[TaskField.CONTACT_VALUE] = CONTACT;
MPXJ_MPX_ARRAY[TaskField.COST_VALUE] = COST;
MPXJ_MPX_ARRAY[TaskField.COST1_VALUE] = COST1;
MPXJ_MPX_ARRAY[TaskField.COST2_VALUE] = COST2;
MPXJ_MPX_ARRAY[TaskField.COST3_VALUE] = COST3;
MPXJ_MPX_ARRAY[TaskField.COST_VARIANCE_VALUE] = COST_VARIANCE;
MPXJ_MPX_ARRAY[TaskField.CREATED_VALUE] = CREATE_DATE;
MPXJ_MPX_ARRAY[TaskField.CRITICAL_VALUE] = CRITICAL;
MPXJ_MPX_ARRAY[TaskField.CV_VALUE] = CV;
MPXJ_MPX_ARRAY[TaskField.LEVELING_DELAY_VALUE] = DELAY;
MPXJ_MPX_ARRAY[TaskField.DURATION_VALUE] = DURATION;
MPXJ_MPX_ARRAY[TaskField.DURATION1_VALUE] = DURATION1;
MPXJ_MPX_ARRAY[TaskField.DURATION2_VALUE] = DURATION2;
MPXJ_MPX_ARRAY[TaskField.DURATION3_VALUE] = DURATION3;
MPXJ_MPX_ARRAY[TaskField.DURATION_VARIANCE_VALUE] = DURATION_VARIANCE;
MPXJ_MPX_ARRAY[TaskField.EARLY_FINISH_VALUE] = EARLY_FINISH;
MPXJ_MPX_ARRAY[TaskField.EARLY_START_VALUE] = EARLY_START;
MPXJ_MPX_ARRAY[TaskField.FINISH_VALUE] = FINISH;
MPXJ_MPX_ARRAY[TaskField.FINISH1_VALUE] = FINISH1;
MPXJ_MPX_ARRAY[TaskField.FINISH2_VALUE] = FINISH2;
MPXJ_MPX_ARRAY[TaskField.FINISH3_VALUE] = FINISH3;
MPXJ_MPX_ARRAY[TaskField.FINISH4_VALUE] = FINISH4;
MPXJ_MPX_ARRAY[TaskField.FINISH5_VALUE] = FINISH5;
MPXJ_MPX_ARRAY[TaskField.FINISH_VARIANCE_VALUE] = FINISH_VARIANCE;
MPXJ_MPX_ARRAY[TaskField.TYPE_VALUE] = TYPE;
MPXJ_MPX_ARRAY[TaskField.FIXED_COST_VALUE] = FIXED_COST;
MPXJ_MPX_ARRAY[TaskField.FLAG1_VALUE] = FLAG1;
MPXJ_MPX_ARRAY[TaskField.FLAG2_VALUE] = FLAG2;
MPXJ_MPX_ARRAY[TaskField.FLAG3_VALUE] = FLAG3;
MPXJ_MPX_ARRAY[TaskField.FLAG4_VALUE] = FLAG4;
MPXJ_MPX_ARRAY[TaskField.FLAG5_VALUE] = FLAG5;
MPXJ_MPX_ARRAY[TaskField.FLAG6_VALUE] = FLAG6;
MPXJ_MPX_ARRAY[TaskField.FLAG7_VALUE] = FLAG7;
MPXJ_MPX_ARRAY[TaskField.FLAG8_VALUE] = FLAG8;
MPXJ_MPX_ARRAY[TaskField.FLAG9_VALUE] = FLAG9;
MPXJ_MPX_ARRAY[TaskField.FLAG10_VALUE] = FLAG10;
MPXJ_MPX_ARRAY[TaskField.FREE_SLACK_VALUE] = FREE_SLACK;
MPXJ_MPX_ARRAY[TaskField.HIDEBAR_VALUE] = HIDE_BAR;
MPXJ_MPX_ARRAY[TaskField.ID_VALUE] = ID;
MPXJ_MPX_ARRAY[TaskField.LATE_FINISH_VALUE] = LATE_FINISH;
MPXJ_MPX_ARRAY[TaskField.LATE_START_VALUE] = LATE_START;
MPXJ_MPX_ARRAY[TaskField.LINKED_FIELDS_VALUE] = LINKED_FIELDS;
MPXJ_MPX_ARRAY[TaskField.MARKED_VALUE] = MARKED;
MPXJ_MPX_ARRAY[TaskField.MILESTONE_VALUE] = MILESTONE;
MPXJ_MPX_ARRAY[TaskField.NAME_VALUE] = NAME;
//MPXJ_MPX_ARRAY[TaskField.NOTES_VALUE] = NOTES;
MPXJ_MPX_ARRAY[TaskField.NUMBER1_VALUE] = NUMBER1;
MPXJ_MPX_ARRAY[TaskField.NUMBER2_VALUE] = NUMBER2;
MPXJ_MPX_ARRAY[TaskField.NUMBER3_VALUE] = NUMBER3;
MPXJ_MPX_ARRAY[TaskField.NUMBER4_VALUE] = NUMBER4;
MPXJ_MPX_ARRAY[TaskField.NUMBER5_VALUE] = NUMBER5;
MPXJ_MPX_ARRAY[TaskField.OBJECTS_VALUE] = OBJECTS;
MPXJ_MPX_ARRAY[TaskField.OUTLINE_LEVEL_VALUE] = OUTLINE_LEVEL;
MPXJ_MPX_ARRAY[TaskField.OUTLINE_NUMBER_VALUE] = OUTLINE_NUMBER;
MPXJ_MPX_ARRAY[TaskField.PREDECESSORS_VALUE] = PREDECESSORS;
MPXJ_MPX_ARRAY[TaskField.PRIORITY_VALUE] = PRIORITY;
MPXJ_MPX_ARRAY[TaskField.PROJECT_VALUE] = PROJECT;
MPXJ_MPX_ARRAY[TaskField.REMAINING_COST_VALUE] = REMAINING_COST;
MPXJ_MPX_ARRAY[TaskField.REMAINING_DURATION_VALUE] = REMAINING_DURATION;
MPXJ_MPX_ARRAY[TaskField.REMAINING_WORK_VALUE] = REMAINING_WORK;
MPXJ_MPX_ARRAY[TaskField.RESOURCE_GROUP_VALUE] = RESOURCE_GROUP;
MPXJ_MPX_ARRAY[TaskField.RESOURCE_INITIALS_VALUE] = RESOURCE_INITIALS;
MPXJ_MPX_ARRAY[TaskField.RESOURCE_NAMES_VALUE] = RESOURCE_NAMES;
MPXJ_MPX_ARRAY[TaskField.RESUME_VALUE] = RESUME;
MPXJ_MPX_ARRAY[TaskField.RESUME_VALUE] = RESUME_NO_EARLIER_THAN;
MPXJ_MPX_ARRAY[TaskField.ROLLUP_VALUE] = ROLLUP;
MPXJ_MPX_ARRAY[TaskField.START_VALUE] = START;
MPXJ_MPX_ARRAY[TaskField.START1_VALUE] = START1;
MPXJ_MPX_ARRAY[TaskField.START2_VALUE] = START2;
MPXJ_MPX_ARRAY[TaskField.START3_VALUE] = START3;
MPXJ_MPX_ARRAY[TaskField.START4_VALUE] = START4;
MPXJ_MPX_ARRAY[TaskField.START5_VALUE] = START5;
MPXJ_MPX_ARRAY[TaskField.START_VARIANCE_VALUE] = START_VARIANCE;
MPXJ_MPX_ARRAY[TaskField.STOP_VALUE] = STOP;
MPXJ_MPX_ARRAY[TaskField.SUBPROJECT_FILE_VALUE] = SUBPROJECT_NAME;
MPXJ_MPX_ARRAY[TaskField.SUCCESSORS_VALUE] = SUCCESSORS;
MPXJ_MPX_ARRAY[TaskField.SUMMARY_VALUE] = SUMMARY;
MPXJ_MPX_ARRAY[TaskField.SV_VALUE] = SV;
MPXJ_MPX_ARRAY[TaskField.TEXT1_VALUE] = TEXT1;
MPXJ_MPX_ARRAY[TaskField.TEXT2_VALUE] = TEXT2;
MPXJ_MPX_ARRAY[TaskField.TEXT3_VALUE] = TEXT3;
MPXJ_MPX_ARRAY[TaskField.TEXT4_VALUE] = TEXT4;
MPXJ_MPX_ARRAY[TaskField.TEXT5_VALUE] = TEXT5;
MPXJ_MPX_ARRAY[TaskField.TEXT6_VALUE] = TEXT6;
MPXJ_MPX_ARRAY[TaskField.TEXT7_VALUE] = TEXT7;
MPXJ_MPX_ARRAY[TaskField.TEXT8_VALUE] = TEXT8;
MPXJ_MPX_ARRAY[TaskField.TEXT9_VALUE] = TEXT9;
MPXJ_MPX_ARRAY[TaskField.TEXT10_VALUE] = TEXT10;
MPXJ_MPX_ARRAY[TaskField.TOTAL_SLACK_VALUE] = TOTAL_SLACK;
MPXJ_MPX_ARRAY[TaskField.UNIQUE_ID_VALUE] = UNIQUE_ID;
MPXJ_MPX_ARRAY[TaskField.UNIQUE_ID_PREDECESSORS_VALUE] = UNIQUE_ID_PREDECESSORS;
MPXJ_MPX_ARRAY[TaskField.UNIQUE_ID_SUCCESSORS_VALUE] = UNIQUE_ID_SUCCESSORS;
MPXJ_MPX_ARRAY[TaskField.UPDATE_NEEDED_VALUE] = UPDATE_NEEDED;
MPXJ_MPX_ARRAY[TaskField.WBS_VALUE] = WBS;
MPXJ_MPX_ARRAY[TaskField.WORK_VALUE] = WORK;
MPXJ_MPX_ARRAY[TaskField.WORK_VARIANCE_VALUE] = WORK_VARIANCE;
}
}
| gpl-3.0 |
HkB115/RefineCraft | RefineCraft/src/net/refination/refinecraft/commands/Commandtpa.java | 1647 | package net.refination.refinecraft.commands;
import net.refination.refinecraft.User;
import org.bukkit.Server;
import static net.refination.refinecraft.I18n.tl;
public class Commandtpa extends RefineCraftCommand {
public Commandtpa() {
super("tpa");
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
User player = getPlayer(server, user, args, 0);
if (user.getName().equalsIgnoreCase(player.getName())) {
throw new NotEnoughArgumentsException();
}
if (!player.isTeleportEnabled()) {
throw new Exception(tl("teleportDisabled", player.getDisplayName()));
}
if (user.getWorld() != player.getWorld() && RC.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("refinecraft.worlds." + player.getWorld().getName())) {
throw new Exception(tl("noPerm", "refinecraft.worlds." + player.getWorld().getName()));
}
if (!player.isIgnoredPlayer(user)) {
player.requestTeleport(user, false);
player.sendMessage(tl("teleportRequest", user.getDisplayName()));
player.sendMessage(tl("typeTpaccept"));
player.sendMessage(tl("typeTpdeny"));
if (RC.getSettings().getTpaAcceptCancellation() != 0) {
player.sendMessage(tl("teleportRequestTimeoutInfo", RC.getSettings().getTpaAcceptCancellation()));
}
}
user.sendMessage(tl("requestSent", player.getDisplayName()));
}
}
| gpl-3.0 |
Tony-Hao/Valx | W_utility/log.py | 750 | # logging utlities
import logging
from datetime import datetime
# define the script global logger
def ext_print (name):
tnow = datetime.now()
name = '['+str(tnow)+'] ' +name
return name
#Usage:
#from utility.log import strd_logger
#from cgi import log
#log = strd_logger ('XXXX')
#log.error ('XXX')
#log.info ('XXX')
# define the script global logger
def strd_logger (name):
log = logging.getLogger (name)
log.setLevel (logging.INFO)
#formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(message)s', "%Y-%m-%d %H:%M:%S")
formatter = logging.Formatter('[%(asctime)s.%(msecs)d %(levelname)s] %(message)s','%Y-%m-%d,%H:%M:%S')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
return log
| gpl-3.0 |
Bleno/portfolio | portfolio/views/login.py | 1980 | # -*- encoding: utf-8 -*-
from colander import Schema, SchemaNode, String
from deform.widget import PasswordWidget, TextInputWidget, CheckboxWidget
from deform import Button
from pyramid.httpexceptions import HTTPFound
from pyramid.security import Allow
from pyramid.security import forget
from pyramid.security import remember
from pyramid.view import view_config
from pyramid_deform import FormView
from portfolio.models.user import User
from portfolio.br.user_br import UserBR
class LoginSchema(Schema):
username = SchemaNode(String(), title="User name",
widget=TextInputWidget(placeholder='Usuário',
css_class="input-block-level",))
password = SchemaNode(String(), title="Password",
widget=PasswordWidget(css_class="input-block-level",
placeholder="Usuário"))
remember = SchemaNode(String(), widget=CheckboxWidget(),
title='Remember me')
@view_config(name='login', renderer='../templates/login.pt')
class Login(FormView):
schema = LoginSchema()
button_edit = Button(name='reset', title=None, type='reset',
value='Reset', disabled=False,
css_class=None)
buttons = ('login',button_edit)
form_options = (('formid', 'pyramid-deform'),
('css_class', "form-signin"))
title = "Log in"
def login_success(self, appstruct):
user = User( str_login=appstruct['username'],
str_password= appstruct['password'])
userBr = UserBR()
srov = userBr.checkUser(user)
if srov.status:
self.request.session['usuario'] = srov.data.str_login
return HTTPFound(location = "/")
else:
return self.bad_login()
def bad_login(self):
self.request.session.flash(
"Your username/password combination is incorrect.", "error")
| gpl-3.0 |
rask004/AndroidMotionRecorder | app/src/main/java/com/rolandjamesaskew/portifolio/android/devicesensorsrecorder/fragment/AvailableSensorsFragment.java | 6524 | package com.rolandjamesaskew.portifolio.android.devicesensorsrecorder.fragment;
import android.content.Context;
import android.hardware.Sensor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import com.rolandjamesaskew.portifolio.android.devicesensorsrecorder.R;
import com.rolandjamesaskew.portifolio.android.devicesensorsrecorder.fragment.contracts.SensorFragmentCallbackManager;
import com.rolandjamesaskew.shared.android.fragment.superclass.SensorListFragment;
import com.rolandjamesaskew.shared.android.hardware.model.ModelManager;
import com.rolandjamesaskew.shared.android.hardware.model.SensorModel;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link AvailableSensorsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link AvailableSensorsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AvailableSensorsFragment extends SensorListFragment
implements SensorFragmentCallbackManager {
private static final String ARGS_SENSORS = "com.rolandjamesaskew.fragment.availablesensors.SensorTypes";
private Spinner mAvailableSensorsListSpinner;
private ImageButton mAddSensorButton;
private boolean mUiEnabled;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment AccelerometerFragment.
*/
public static AvailableSensorsFragment newInstance(ArrayList<Integer> pSensorTypes) {
AvailableSensorsFragment fragment = new AvailableSensorsFragment();
Bundle args = new Bundle();
args.putIntegerArrayList(ARGS_SENSORS, pSensorTypes);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
List<Integer> sensorTypes = getArguments().getIntegerArrayList(ARGS_SENSORS);
if (sensorTypes == null) {
sensorTypes = new ArrayList<>();
}
mSensors = new ArrayList<>();
List<Sensor> sensors;
List<SensorModel> selectedSensors = ModelManager.getInstance().getSensorModels();
// get all existing sensors as defined by the sensor types.
// remove sensors present in the ModelManager - these are selected sensors, not available sensors.
// load the remaining models as available sensors.
for (int type: sensorTypes)
{
sensors = mManager.getSensorList(type);
for (Sensor s: sensors)
{
// compare each sensor to the selected sensor models
boolean sensorIsSelected = false;
for (SensorModel selectedSensor: selectedSensors)
{
// a matching model means don't make this sensor available, it is already selected.
if (selectedSensor.equals(s))
{
sensorIsSelected = true;
break;
}
}
// any sensor not selected is to be made available.
if (!sensorIsSelected)
{
mSensors.add(SensorModel.newInstance(s));
}
}
}
mUiEnabled = true;
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater pInflater, ViewGroup pContainer,
Bundle pSavedInstanceState) {
// Inflate the layout for this fragment
View v = pInflater.inflate(R.layout.fragment_available_sensors, pContainer, false);
mAvailableSensorsListSpinner = (Spinner) v.findViewById(R.id.available_sensors_list_spinner);
mAddSensorButton = (ImageButton) v.findViewById(R.id.add_sensor_button);
ArrayAdapter<SensorModel> adapter =
new ArrayAdapter<>(getActivity(), R.layout.sensor_spinner);
adapter.setDropDownViewResource(R.layout.sensor_spinner_dropdown_item);
mAvailableSensorsListSpinner.setAdapter(adapter);
updateUI();
if (!mSensors.isEmpty())
{
mAvailableSensorsListSpinner.setSelection(0);
}
mAddSensorButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View pView) {
SensorModel model = (SensorModel) mAvailableSensorsListSpinner.getSelectedItem();
if (model != null)
{
ModelManager.getInstance().addSensor(model);
mListener.notifyAddSensor(model);
mSensors.remove(model);
updateUI();
}
}
});
return v;
}
/**
* Add or Remove a sensor to the Spinner, mana
*/
protected void updateUI()
{
ArrayAdapter<SensorModel> adapter =
(ArrayAdapter<SensorModel>) mAvailableSensorsListSpinner.getAdapter();
adapter.clear();
if (mSensors.isEmpty())
{
mAvailableSensorsListSpinner.setEnabled(false);
mAddSensorButton.setEnabled(false);
}
else
{
for (SensorModel model: mSensors)
{
adapter.add(model);
}
adapter.notifyDataSetChanged();
mAvailableSensorsListSpinner.setEnabled(mUiEnabled);
mAddSensorButton.setEnabled(mUiEnabled);
}
}
@Override
public void onAttach(Context pContext) {
super.onAttach(pContext);
if (pContext instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) pContext;
} else {
throw new RuntimeException(pContext.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void sensorsReadyForRecording(boolean pEnabled) {
mUiEnabled = pEnabled;
updateUI();
}
@Override
public void updateSensor(SensorModel pModel) {
mSensors.add(pModel);
updateUI();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void notifyAddSensor(SensorModel pModel);
}
}
| gpl-3.0 |
rfsantos1996/LobsterCraft | src/main/java/com/jabyftw/lobstercraft/commands/player/RepairCommand.java | 2201 | package com.jabyftw.lobstercraft.commands.player;
import com.jabyftw.easiercommands.CommandExecutor;
import com.jabyftw.easiercommands.CommandHandler;
import com.jabyftw.easiercommands.SenderType;
import com.jabyftw.lobstercraft.player.OnlinePlayer;
import com.jabyftw.lobstercraft.Permissions;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
/**
* Copyright (C) 2015 Rafael Sartori for PacocaCraft Plugin
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* <p>
* Email address: rafael.sartori96@gmail.com
*/
public class RepairCommand extends CommandExecutor {
public RepairCommand() {
super("repair", Permissions.PLAYER_REPAIR.toString(), "Permite ao jogador reparar seus itens", "/repair");
}
@CommandHandler(senderType = SenderType.PLAYER)
private boolean onRepair(OnlinePlayer onlinePlayer) {
ItemStack itemInHand = onlinePlayer.getPlayer().getInventory().getItemInMainHand();
// Check if item exists
if (itemInHand == null || itemInHand.getType() == Material.AIR) {
onlinePlayer.getPlayer().sendMessage("§cVocê não tem item na sua mão!");
return true;
}
// Check if it is possible to be repaired
if (itemInHand.getType().isBlock() || itemInHand.getType().getMaxDurability() == 0) {
onlinePlayer.getPlayer().sendMessage("§cEste item não pode ser reparado!");
} else {
itemInHand.setDurability((short) 0);
onlinePlayer.getPlayer().sendMessage("§6Item reparado! §4<3");
}
return true;
}
}
| gpl-3.0 |
ruimaciel/femp | gui/src/ui/dialogs/NodeActionsDialog.c++ | 1008 | #include "NodeActionsDialog.h++"
#include "LoadPatternDialog.h++"
#include <QAbstractItemView>
NodeActionsDialog::NodeActionsDialog(LoadPatternsModel& model, QWidget* parent)
: QDialog(parent)
{
setupUi(this);
this->comboBoxLoadPattern->setModel(&model);
}
size_t
NodeActionsDialog::getLoadPattern()
{
//TODO must get some sort of sanity check
return this->comboBoxLoadPattern->currentIndex();
}
fem::Point3D
NodeActionsDialog::getForce()
{
fem::Point3D p;
p.data[0] = this->doubleSpinBoxFx->value();
p.data[1] = this->doubleSpinBoxFy->value();
p.data[2] = this->doubleSpinBoxFz->value();
return p;
}
fem::Point3D
NodeActionsDialog::getDisplacement()
{
fem::Point3D p;
p.data[0] = this->doubleSpinBoxDx->value();
p.data[1] = this->doubleSpinBoxDy->value();
p.data[2] = this->doubleSpinBoxDz->value();
return p;
}
void NodeActionsDialog::loadPatternCreated(size_t, fem::LoadPattern const&)
{
this->comboBoxLoadPattern->view()->reset();
}
| gpl-3.0 |
hospage/tynod | perfilWrk.php | 10425 | <!DOCTYPE html>
<?php
session_start();
if($_SESSION['tipoUsuario'] == "usuarios")
{
echo '<script>window.location = "perfilUsr.php"</script>';
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/booty.css">
<link rel="stylesheet" type="text/css" href="css/animate.css">
<link rel="stylesheet" type="text/css" href="css/perfil.css">
<link rel="stylesheet" type="text/css" href="css/generalTynod.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome-4.6.3/css/font-awesome.css">
</head>
<body style = "background-color: #d9d9d9;">
<p class = "tipoUsr"></p>
<script src = "js/jquery-3.1.0.js"></script>
<script src = "js/geo/jquery.simpleWeather.min.js"></script>
<script src = "js/bootstrap.js" ></script>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class = "fa fa-times"></i></button>
<h4 class="modal-title" class = "display-4">Cambio de foto de perfil</h4>
</div>
<div class="modal-body">
<div class = "muestraFoto">
<img class = "imgNueva">
</div>
<form action="upImg.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
</div>
<div class = "barraMenu">
<div class = "centro">
<h4 class = "ftTynod"><img src="logos/LogoLlave.png" class = "imgLogo">TyNod</h4>
<div class = "buscarPeque">
<center>
<button id = "btnBuscar"><i class = "fa fa-search"></i></button>
</center>
</div>
<div class = "divBuscar">
<form action = "busqueda.php" method = "post"><input type = "text" name = "buscar" class = "txtBuscar" >
<button type = "submit" class = "buscar"><i class = "fa fa-search"></i></button>
</form>
</div>
<ul style = "float: right; color: black; margin-top: -30px; text-align: right; font-size: 30px;">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class = "fa fa-cog" style = "color: #f2f2f2;"></i></a>
<ul class="dropdown-menu">
<li><a href="#" class = "rmLink" >Configuración de la cuenta</a></li>
<li><a class = "rmLink" href="#" id = "linkSalir"> Salir </a></li>
</ul>
</li>
</ul>
<div id = "divIcons">
<a href = "mensajes.php" class = "rmLink mensajes"><i class = "fa fa-send"></i></a>
<a href = "#" class = "rmLink" id = "linkHome"><i class = "fa fa-home"></i></a>
</div>
</div>
</div>
<div class = "showUpBuscarC">
<div class = "centro" style = "padding: 5px;">
<i class = "fa fa-search"></i><input type = "text" class = "txtShowUp">
</div>
</div>
<div class = "centro" style = "padding: 0px;">
<img src="logos/PortadaDefault.png" style="max-width: 100%; padding: 0; margin-top: -2px;">
<div class = "divFondo">
<div id = "divImg"><img src = "logos/defaultUserLogo.png" class = "imgPerfil" alt = "imagen del usuario"/></div>
<p class = "ftNombre" id = "nombre"></p>
<p class = "ftProfesion" id = "idProfesion">
<div class = "divEstrellas">
<i class = "fa fa-star fa-2x" id = "estrella5"></i>
<i class = "fa fa-star fa-2x" id = "estrella4"></i>
<i class = "fa fa-star fa-2x" id = "estrella3"></i>
<i class = "fa fa-star fa-2x" id = "estrella2"></i>
<i class = "fa fa-star fa-2x" id = "estrella1"></i>
</div>
<div class = "portaBotones">
<button class = "btnModificar">
<i class = "fa fa-pencil"></i> Modifica tu perfil
</button>
<button class = "btnSubirImg" data-toggle="modal" data-target="#myModal"><i class = "fa fa-picture-o"></i> Modifica tu foto</button>
</div>
</div>
</div>
<center>
<div class = "divGN">
<button class = "btnGuardar" id = "btnGuardar"><i class = "fa fa-save"></i> Guardar Cambios</button>
<button class = "btnNoGuardar" id = "btnNoGuardar"><i class = "fa fa-reply-all"></i> Salir </button>
</div>
</center>
</div>
<div class = "centro" style = "padding: 0px;">
<center>
<?php
$contador = 0;
$vals = ['Descripción', 'Horarios'];
$textareas = ['Desc', 'Horarios'];
for($contador = 0; $contador < sizeof($vals); $contador++)
{
echo '<div class = "contenedorDatos"><p class = "ftTitulo2">'.$vals[$contador].'</p> <p id = "p'.$textareas[$contador].'" class = "pEdits"></p> <textarea class = "perfil" id = "txt'.$textareas[$contador].'"></textarea></div>';
}
?>
</center>
</div>
<script>
var tipoUsr = obtenerUsr();
var isOpen = true;
var btnShow = false;
var muestraBtns = false;
$(document).ready(function(){
checaLocalizacion(cargaCaja);
escondeCajaBuscar();
escondeElementos(['tipoUsr', 'showUpBuscarC', 'muestraFoto', 'perfil', 'divGN']);
tipoUsr = $('.tipoUsr').html();
cargaDatosUsuario();
});
$(window).resize(function(){
escondeCajaBuscar();
});
$('#btnBuscar').on('click', function(){
btnShow = !btnShow;
if(btnShow)
{
$('.showUpBuscarC').show();
}
else
{
$('.showUpBuscarC').hide();
}
console.log(tipoUsr);
});
$('#linkHome').on('click', function(){
window.location = 'perfilWrk.php';
});
$('#linkSalir').on('click', function(){
$.get('php/terminate.php', function(){
window.location = "index.php";
})
});
$('.btnModificar').on('click', function(){
muestraBtns = !muestraBtns;
if(muestraBtns)
{
$('.divGN').fadeIn();
$('.perfil').show();
$('.pEdits').hide();
}
else
{
escondeEdits();
}
});
$('#btnNoGuardar').on('click', function(){
escondeEdits();
muestraBtns = !muestraBtns;
});
$('#btnGuardar').on('click', function(){
$.post('php/guardaData.php', {descripcion: $('#txtDesc').val(), horarios: $('#txtHorarios').val()}, function(callback){
window.location = 'perfilWrk.php';
})
})
/* codigo obtenido de jsfiddle */
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
$('.muestraFoto').show();
$('.imgNueva').attr('src', e.target.result);
};
/* fin de codigo recopilado */
function escondeEdits()
{
$('.divGN').fadeOut();
$('.perfil').hide();
$('.pEdits').show();
}
function escondeCajaBuscar()
{
var anchoVentana = $(window).width();
if(anchoVentana < 600)
{
$('.divBuscar').hide();
$('.buscarPeque').show();
}
else
{
$('.divBuscar').show();
$('.buscarPeque').hide();
$('.showUpBuscarC').hide();
}
if(anchoVentana < 1080)
{
$('.contenedorDatos').css('width', '1000px');
}
else
{
$('.contenedorDatos').css('width', '650px');
}
}
var cargaCaja = function(weather){
var cadena = "Buscar profesionistas en " + weather.city + ", " + weather.region + ", " + weather.country;
$('.txtBuscar').attr('placeholder', cadena);
};
function cargaDatosUsuario()
{
$.post('php/obtenerDatos.php', function(callback){
var datos = callback.split(",");
$('#nombre').html(datos[0]);
var pass = {select: 'Profesion', tabla: 'prestadores', where: 'id', valor: datos[2], tipoVal: 'numerico'};
$.post('php/consulta.php', {datos: pass} , function(nyes){
console.log(nyes);
var profesiones = nyes.split(', ');
var indice = 0;
var profesionesArregladas = [];
var alb = "";
for(indice = 0; indice < profesiones.length ; indice++)
{
if(profesiones[indice].includes('alb'))
{
profesionesArregladas.push("albañil");
}
else
{
profesionesArregladas.push(profesiones[indice]);
}
}
$('#idProfesion').html(profesionesArregladas.join(", "));
});
var paraImagen = {select: 'foto', tabla: 'prestadores', where: 'id', valor: datos[2], tipoVal: 'numerico'};
$.post('php/consulta.php', {datos: paraImagen}, function(back){
console.log(back);
$('.imgPerfil').attr('src', 'imagenes/'+back);
});
console.log(datos[3]);
var txtDesc = {select: 'descripcion', tabla: datos[3], where: 'id', valor: datos[2], tipoVal: 'numerico'};
$.post('php/consulta.php', {datos: txtDesc}, function(cback){
$('#txtDesc').html(cback);
$('#pDesc').html(cback);
});
var txtHorarios = {select: 'horarios', tabla: datos[3], where: 'id', valor: datos[2], tipoVal: 'numerico'};
$.post('php/consulta.php', {datos: txtHorarios}, function(cback){
$('#txtHorarios').html(cback);
$('#pHorarios').html(cback);
});
});
}
function obtenerUsr()
{
$.post('php/obtenerTipoUsr.php', {var: 'foo'}, function(callback){
$('.tipoUsr').html(callback);
});
return $('.tipoUsr').html();
}
function escondeElementos(elementos)
{
elementos.forEach(function(elemento){
$('.'+elemento).hide();
});
}
function cargaLocalizacion(location, funcion) {
$.simpleWeather({
location: location,
woeid: undefined,
unit: 'c',
success: function(weather) {
funcion(weather);
},
error: function(error) {
$("#weather-info").html('<p>'+error+'</p>');
}
});
}
function checaLocalizacion(funcion)
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
cargaLocalizacion(position.coords.latitude+','+position.coords.longitude, funcion); //load weather using your lat/lng coordinates
});
}
else
{
$('#weather-info').html('Sorry, geolocation is not supported by your web browser :-(');
}
}
</script>
</body>
</html> | gpl-3.0 |
coldfix/pystif | pystif/pitip.py | 2067 | """
Python Information Theoretic Inequality Prover
Usage:
pitip VARNAMES CHECK [-p]
Options:
-p, --prove Show proof
"""
import numpy as np
from .core.app import application
from .core.io import System, column_varname_labels
from .core.it import elemental_inequalities, elemental_forms
def _format_dual_coef(system, index, coef):
expr = system.row_names[index]
if np.isclose(coef, 1):
return expr
if np.isclose(coef, round(coef)):
coef = int(round(coef))
return "{} * {}".format(expr, coef)
def format_dual_vector(system, vec):
formatted = (
_format_dual_coef(system, index, coef)
for index, coef in enumerate(vec)
if not np.isclose(coef, 0))
by_quant_len = lambda s: (-len(s.split()[0]), s)
return " " + "\n+ ".join(sorted(formatted, key=by_quant_len))
def get_term_counts(system, vec):
d = {}
for coef, cat in zip(vec, system.row_categ):
if np.isclose(coef, round(coef)):
coef = int(round(coef))
if coef != 0:
d.setdefault(cat, 0)
d[cat] += coef
return [d[i] for i in sorted(d, reverse=True)]
def indent(lines, amount, ch=' '):
padding = amount * ch
return padding + ('\n'+padding).join(lines.split('\n'))
@application
def main(app):
opts = app.opts
varnames = opts['VARNAMES']
num_vars = len(varnames)
system = System(np.array(list(elemental_inequalities(num_vars))),
column_varname_labels(varnames))
check = System.load(opts['CHECK'])
system, _ = system.slice(check.columns, fill=True)
system.row_names = [f.fmt(varnames) for f in elemental_forms(num_vars)]
system.row_categ = [len(n)/2-1 + (n[0]=='H')
for n in system.row_names]
lp = system.lp()
for ineq in check.matrix:
valid = lp.implies(ineq, embed=True)
print(valid)
if valid:
print(indent(format_dual_vector(system, lp.get_dual_solution()), 4))
print(get_term_counts(system, lp.get_dual_solution()))
| gpl-3.0 |
openqbit/Systems-Insurance | OpenQbit.InsuranceSystem.git/OpenQbit.Insurance.Service.WebApi/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs | 6497 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace OpenQbit.Insurance.Service.WebApi.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type.
/// </summary>
/// <param name="mediaType">The media type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
ActionName = String.Empty;
ControllerName = String.Empty;
MediaType = mediaType;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
: this(mediaType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ParameterType = type;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
: this(sampleDirection, controllerName, actionName, parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
MediaType = mediaType;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| gpl-3.0 |
aaujon/dolibarr | htdocs/fourn/class/fournisseur.product.class.php | 24707 | <?php
/* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2011 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2009-2014 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
*
* 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 htdocs/fourn/class/fournisseur.product.class.php
* \ingroup produit
* \brief File of class to manage predefined suppliers products
*/
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/priceparser.class.php';
/**
* Class to manage predefined suppliers products
*/
class ProductFournisseur extends Product
{
var $db;
var $error;
var $product_fourn_price_id; // id of ligne product-supplier
var $id; // product id
var $fourn_ref; // deprecated
var $ref_supplier; // ref supplier (can be set by get_buyprice)
var $vatrate_supplier; // default vat rate for this supplier/qty/product (can be set by get_buyprice)
var $fourn_qty; // quantity for price (can be set by get_buyprice)
var $fourn_pu; // unit price for quantity (can be set by get_buyprice)
var $fourn_price; // price for quantity
var $fourn_remise_percent; // discount for quantity (percent)
var $fourn_remise; // discount for quantity (amount)
var $product_fourn_id; // supplier id
var $fk_availability; // availability delay
var $fourn_unitprice;
var $fourn_tva_npr;
var $fk_supplier_price_expression;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
function __construct($db)
{
$this->db = $db;
}
/**
* Remove all prices for this couple supplier-product
*
* @param int $id_fourn Supplier Id
* @return int < 0 if error, > 0 if ok
*/
function remove_fournisseur($id_fourn)
{
$ok=1;
$this->db->begin();
$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql.= " WHERE fk_product = ".$this->id." AND fk_soc = ".$id_fourn;
dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG);
$resql2=$this->db->query($sql);
if (! $resql2)
{
$this->error=$this->db->lasterror();
$ok=0;
}
if ($ok)
{
$this->db->commit();
return 1;
}
else
{
$this->db->rollback();
return -1;
}
}
/**
* Remove a price for a couple supplier-product
*
* @param int $rowid Line id of price
* @return int <0 if KO, >0 if OK
*/
function remove_product_fournisseur_price($rowid)
{
global $conf;
$this->db->begin();
$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql.= " WHERE rowid = ".$rowid;
dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$this->db->commit();
return 1;
}
else
{
$this->error=$this->db->lasterror();
$this->db->rollback();
return -1;
}
}
/**
* Modify the purchase price for a supplier
*
* @param int $qty Min quantity for which price is valid
* @param float $buyprice Purchase price for the quantity min
* @param User $user Object user user made changes
* @param string $price_base_type HT or TTC
* @param Societe $fourn Supplier
* @param int $availability Product availability
* @param string $ref_fourn Supplier ref
* @param float $tva_tx VAT rate
* @param string $charges costs affering to product
* @param float $remise_percent Discount regarding qty (percent)
* @param float $remise Discount regarding qty (amount)
* @param int $newnpr Set NPR or not
* @return int <0 if KO, >=0 if OK
*/
function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges=0, $remise_percent=0, $remise=0, $newnpr=0)
{
global $conf;
// Clean parameter
if (empty($qty)) $qty=0;
if (empty($buyprice)) $buyprice=0;
if (empty($charges)) $charges=0;
if (empty($availability)) $availability=0;
if (empty($remise_percent)) $remise_percent=0;
if ($price_base_type == 'TTC')
{
//$ttx = get_default_tva($fourn,$mysoc,$this->id); // We must use the VAT rate defined by user and not calculate it
$ttx = $tva_tx;
$buyprice = $buyprice/(1+($ttx/100));
}
$buyprice=price2num($buyprice,'MU');
$charges=price2num($charges,'MU');
$qty=price2num($qty);
$error=0;
$unitBuyPrice = price2num($buyprice/$qty,'MU');
$unitCharges = price2num($charges/$qty,'MU');
$now=dol_now();
$this->db->begin();
if ($this->product_fourn_price_id)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql.= " SET fk_user = " . $user->id." ,";
$sql.= " ref_fourn = '" . $this->db->escape($ref_fourn) . "',";
$sql.= " price = ".price2num($buyprice).",";
$sql.= " quantity = ".$qty.",";
$sql.= " remise_percent = ".$remise_percent.",";
$sql.= " remise = ".$remise.",";
$sql.= " unitprice = ".$unitBuyPrice.",";
$sql.= " unitcharges = ".$unitCharges.",";
$sql.= " tva_tx = ".$tva_tx.",";
$sql.= " fk_availability = ".$availability.",";
$sql.= " entity = ".$conf->entity.",";
$sql.= " info_bits = ".$newnpr.",";
$sql.= " charges = ".$charges;
$sql.= " WHERE rowid = ".$this->product_fourn_price_id;
// TODO Add price_base_type and price_ttc
dol_syslog(get_class($this).'::update_buyprice', LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
// Call trigger
$result=$this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE',$user);
if ($result < 0) $error++;
// End call triggers
if (empty($error))
{
$this->db->commit();
return 0;
}
else
{
$this->db->rollback();
return 1;
}
}
else
{
$this->error=$this->db->error()." sql=".$sql;
$this->db->rollback();
return -2;
}
}
else
{
// Delete price for this quantity
$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql.= " WHERE fk_soc = ".$fourn->id." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".$qty." AND entity = ".$conf->entity;
dol_syslog(get_class($this).'::update_buyprice', LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
// Add price for this quantity to supplier
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price(";
$sql.= "datec, fk_product, fk_soc, ref_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, unitcharges, fk_availability, info_bits, entity)";
$sql.= " values('".$this->db->idate($now)."',";
$sql.= " ".$this->id.",";
$sql.= " ".$fourn->id.",";
$sql.= " '".$this->db->escape($ref_fourn)."',";
$sql.= " ".$user->id.",";
$sql.= " ".$buyprice.",";
$sql.= " ".$qty.",";
$sql.= " ".$remise_percent.",";
$sql.= " ".$remise.",";
$sql.= " ".$unitBuyPrice.",";
$sql.= " ".$tva_tx.",";
$sql.= " ".$charges.",";
$sql.= " ".$unitCharges.",";
$sql.= " ".$availability.",";
$sql.= " ".$newnpr.",";
$sql.= $conf->entity;
$sql.=")";
dol_syslog(get_class($this)."::update_buyprice", LOG_DEBUG);
if (! $this->db->query($sql))
{
$error++;
}
if (! $error && !empty($cong->global->PRODUCT_PRICE_SUPPLIER_NO_LOG))
{
// Add record into log table
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log(";
$sql.= "datec, fk_product_fournisseur,fk_user,price,quantity)";
$sql.= "values('".$this->db->idate($now)."',";
$sql.= " ".$this->product_fourn_id.",";
$sql.= " ".$user->id.",";
$sql.= " ".price2num($buyprice).",";
$sql.= " ".$qty;
$sql.=")";
$resql=$this->db->query($sql);
if (! $resql)
{
$error++;
}
}
if (! $error)
{
// Call trigger
$result=$this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE',$user);
if ($result < 0) $error++;
// End call triggers
if (empty($error))
{
$this->db->commit();
return 0;
}
else
{
$this->db->rollback();
return 1;
}
}
else
{
$this->error=$this->db->error()." sql=".$sql;
$this->db->rollback();
return -2;
}
}
else
{
$this->error=$this->db->error()." sql=".$sql;
$this->db->rollback();
return -1;
}
}
}
/**
* Loads the price information of a provider
*
* @param int $rowid Line id
* @param int $ignore_expression Ignores the math expression for calculating price and uses the db value instead
* @return int < 0 if KO, 0 if OK but not found, > 0 if OK
*/
function fetch_product_fournisseur_price($rowid, $ignore_expression = 0)
{
$sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability,";
$sql.= " pfp.fk_soc, pfp.ref_fourn, pfp.fk_product, pfp.charges, pfp.unitcharges, pfp.fk_supplier_price_expression"; // , pfp.recuperableonly as fourn_tva_npr"; FIXME this field not exist in llx_product_fournisseur_price
$sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
$sql.= " WHERE pfp.rowid = ".$rowid;
dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$obj = $this->db->fetch_object($resql);
if ($obj)
{
$this->product_fourn_price_id = $rowid;
$this->fourn_ref = $obj->ref_fourn;
$this->fourn_price = $obj->price;
$this->fourn_charges = $obj->charges;
$this->fourn_qty = $obj->quantity;
$this->fourn_remise_percent = $obj->remise_percent;
$this->fourn_remise = $obj->remise;
$this->fourn_unitprice = $obj->unitprice;
$this->fourn_unitcharges = $obj->unitcharges;
$this->fourn_tva_tx = $obj->tva_tx;
$this->product_id = $obj->fk_product; // deprecated
$this->fk_product = $obj->fk_product;
$this->fk_availability = $obj->fk_availability;
//$this->fourn_tva_npr = $obj->fourn_tva_npr; // FIXME this field not exist in llx_product_fournisseur_price
$this->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) {
$priceparser = new PriceParser($this->db);
$price_result = $priceparser->parseProductSupplier($this->fk_product, $this->fk_supplier_price_expression, $this->fourn_qty, $this->fourn_tva_tx);
if ($price_result >= 0) {
$this->fourn_price = $price_result;
//recalculation of unitprice, as probably the price changed...
if ($this->fourn_qty!=0)
{
$this->fourn_unitprice = price2num($this->fourn_price/$this->fourn_qty,'MU');
}
else
{
$this->fourn_unitprice="";
}
}
}
return 1;
}
else
{
return 0;
}
}
else
{
$this->error=$this->db->error();
return -1;
}
}
/**
* List all supplier prices of a product
*
* @param int $prodid Id of product
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @return array Array of Products with new properties to define supplier price
*/
function list_product_fournisseur_price($prodid, $sortfield='', $sortorder='')
{
global $conf;
$sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
$sql.= " pfp.rowid as product_fourn_pri_id, pfp.ref_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,";
$sql.= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.unitcharges, pfp.info_bits";
$sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
$sql.= ", ".MAIN_DB_PREFIX."societe as s";
$sql.= " WHERE pfp.entity IN (".getEntity('product', 1).")";
$sql.= " AND pfp.fk_soc = s.rowid";
$sql.= " AND pfp.fk_product = ".$prodid;
if (empty($sortfield)) $sql.= " ORDER BY s.nom, pfp.quantity, pfp.price";
else $sql.= $this->db->order($sortfield,$sortorder);
dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$retarray = array();
while ($record = $this->db->fetch_array($resql))
{
//define base attribute
$prodfourn = new ProductFournisseur($this->db);
$prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"];
$prodfourn->product_fourn_id = $record["product_fourn_id"];
$prodfourn->fourn_ref = $record["ref_fourn"];
$prodfourn->fourn_price = $record["price"];
$prodfourn->fourn_qty = $record["quantity"];
$prodfourn->fourn_remise_percent = $record["remise_percent"];
$prodfourn->fourn_remise = $record["remise"];
$prodfourn->fourn_unitprice = $record["unitprice"];
$prodfourn->fourn_charges = $record["charges"];
$prodfourn->fourn_unitcharges = $record["unitcharges"];
$prodfourn->fourn_tva_tx = $record["tva_tx"];
$prodfourn->fourn_id = $record["fourn_id"];
$prodfourn->fourn_name = $record["supplier_name"];
$prodfourn->fk_availability = $record["fk_availability"];
$prodfourn->id = $prodid;
$prodfourn->fourn_tva_npr = $record["info_bits"];
$prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
if (!empty($prodfourn->fk_supplier_price_expression)) {
$priceparser = new PriceParser($this->db);
$price_result = $priceparser->parseProductSupplier($prodid, $prodfourn->fk_supplier_price_expression, $prodfourn->fourn_qty, $prodfourn->fourn_tva_tx);
if ($price_result >= 0) {
$prodfourn->fourn_price = $price_result;
$prodfourn->fourn_unitprice = null; //force recalculation of unitprice, as probably the price changed...
}
}
if (!isset($prodfourn->fourn_unitprice))
{
if ($prodfourn->fourn_qty!=0)
{
$prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price/$prodfourn->fourn_qty,'MU');
}
else
{
$prodfourn->fourn_unitprice="";
}
}
$retarray[]=$prodfourn;
}
$this->db->free($resql);
return $retarray;
}
else
{
$this->error=$this->db->error();
return -1;
}
}
/**
* Load properties for minimum price
*
* @param int $prodid Product id
* @param int $qty Minimum quantity
* @return int <0 if KO, >0 if OK
*/
function find_min_price_product_fournisseur($prodid, $qty=0)
{
global $conf;
$this->product_fourn_price_id = '';
$this->product_fourn_id = '';
$this->fourn_ref = '';
$this->fourn_price = '';
$this->fourn_qty = '';
$this->fourn_remise_percent = '';
$this->fourn_remise = '';
$this->fourn_unitprice = '';
$this->fourn_id = '';
$this->fourn_name = '';
$this->id = '';
$sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
$sql.= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,";
$sql.= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges, pfp.unitcharges, ";
$sql.= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
$sql.= " WHERE s.entity IN (".getEntity('societe', 1).")";
$sql.= " AND pfp.fk_product = ".$prodid;
$sql.= " AND pfp.fk_soc = s.rowid";
if ($qty > 0) $sql.= " AND pfp.quantity <= ".$qty;
dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$record_array = array();
//Store each record to array for later search of min
while ($record = $this->db->fetch_array($resql))
{
$record_array[]=$record;
}
if (count($record_array) == 0)
{
$this->db->free($resql);
return 0;
}
else
{
$min = -1;
foreach($record_array as $record)
{
$fourn_price = $record["price"];
$fourn_unitprice = $record["unitprice"];
if (!empty($record["fk_supplier_price_expression"])) {
$priceparser = new PriceParser($this->db);
$price_result = $priceparser->parseProductSupplier($prodid, $record["fk_supplier_price_expression"], $record["quantity"], $record["tva_tx"]);
if ($price_result >= 0) {
$fourn_price = price2num($price_result,'MU');
if ($record["quantity"] != 0)
{
$fourn_unitprice = price2num($fourn_price/$record["quantity"],'MU');
}
else
{
$fourn_unitprice = $fourn_price;
}
}
}
if ($fourn_unitprice < $min || $min == -1)
{
$this->product_fourn_price_id = $record["product_fourn_price_id"];
$this->fourn_ref = $record["ref_fourn"];
$this->fourn_price = $fourn_price;
$this->fourn_qty = $record["quantity"];
$this->fourn_remise_percent = $record["remise_percent"];
$this->fourn_remise = $record["remise"];
$this->fourn_unitprice = $fourn_unitprice;
$this->fourn_charges = $record["charges"];
$this->fourn_unitcharges = $record["unitcharges"];
$this->fourn_tva_tx = $record["tva_tx"];
$this->fourn_id = $record["fourn_id"];
$this->fourn_name = $record["supplier_name"];
$this->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
$this->id = $prodid;
$min = $this->fourn_unitprice;
}
}
}
$this->db->free($resql);
return 1;
}
else
{
$this->error=$this->db->error();
return -1;
}
}
/**
* Sets the supplier price expression
*
* @param int $expression_id Expression
* @return int <0 if KO, >0 if OK
*/
function setSupplierPriceExpression($expression_id)
{
global $conf;
// Clean parameters
$this->db->begin();
$expression_id = $expression_id != 0 ? $expression_id : 'NULL';
$sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql.= " SET fk_supplier_price_expression = ".$expression_id;
$sql.= " WHERE rowid = ".$this->product_fourn_price_id;
dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$this->db->commit();
return 1;
}
else
{
$this->error=$this->db->error()." sql=".$sql;
$this->db->rollback();
return -1;
}
}
/**
* Display supplier of product
*
* @param int $withpicto Add picto
* @param string $option Target of link ('', 'customer', 'prospect', 'supplier')
* @return string String with supplier price
* TODO Remove this method. Use getNomUrl directly.
*/
function getSocNomUrl($withpicto=0,$option='supplier')
{
$thirdparty = new Fournisseur($this->db);
$thirdparty->fetch($this->fourn_id);
return $thirdparty->getNomUrl($withpicto,$option);
}
/**
* Display price of product
*
* @param int $showunitprice Show "Unit price" into output string
* @param int $showsuptitle Show "Supplier" into output string
* @return string String with supplier price
*/
function display_price_product_fournisseur($showunitprice=1,$showsuptitle=1)
{
global $langs;
$langs->load("suppliers");
$out=($showunitprice?price($this->fourn_unitprice).' '.$langs->trans("HT").' (':'').($showsuptitle?$langs->trans("Supplier").': ':'').$this->getSocNomUrl(1, 'supplier').' / '.$langs->trans("SupplierRef").': '.$this->fourn_ref.($showunitprice?')':'');
return $out;
}
}
| gpl-3.0 |
talperetz/deep_bb | bb-client/src/app/chat/chat.component.ts | 1180 | import {Component, OnInit} from '@angular/core';
import {ChatService} from "./chat.service";
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
public messages: any[] = [];
constructor(private chatService: ChatService) {
//
}
ngOnInit() {
}
public post(event) {
let text;
if (event.target)
text = event.target.value;
else
text = event;
if (!text || text.trim().length === 0) {
return;
}
this.messages.push({text: text, color: '#000'});
this.chatService.getAnswer(text).subscribe((answer: any) => {
let response = JSON.parse(answer._body).response;
this.messages.push({text: response, color: '#0863bb'});
// responsiveVoice.speak(response, "UK English Male", {pitch: .7, range: 1});
event.target.value = '';
event.target.disabled = '';
});
event.target.disabled = 'disabled';
event.target.value = 'Typing...';
}
public getMessages() {
return this.messages.slice(Math.max(this.messages.length - 10, 0))
}
public ngAfterViewChecked() {
}
}
| gpl-3.0 |
icgc-dcc/dcc-portal | dcc-portal-server/src/main/java/org/icgc/dcc/portal/server/service/SessionService.java | 4491 | /*
* Copyright (c) 2014 The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0.
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.icgc.dcc.portal.server.service;
import com.google.common.base.Optional;
import lombok.NonNull;
import lombok.val;
import org.icgc.dcc.portal.server.model.User;
import org.openid4java.discovery.DiscoveryInformation;
import java.util.Map;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Maps.newHashMap;
public class SessionService {
public static final String USERS_CACHE_NAME = "users";
public static final String DISCOVERY_INFO_CACHE_NAME = "openId_auth";
// Stores DiscoveryInformation received from OpenID Provider for further verification requests
private final Map<UUID, DiscoveryInformation> discoveryInfoCache;
// Stores session information about logged in users
private final Map<UUID, User> usersCache;
public SessionService() {
this.usersCache = newHashMap();
this.discoveryInfoCache = newHashMap();
}
public SessionService(Map<UUID, User> usersCache, Map<UUID, DiscoveryInformation> discoveryInfoCache) {
this.usersCache = usersCache;
this.discoveryInfoCache = discoveryInfoCache;
}
public void putUser(@NonNull UUID sessionToken, @NonNull User user) {
usersCache.put(sessionToken, user);
}
public void removeUser(@NonNull User user) {
checkNotNull(user.getSessionToken());
usersCache.remove(user.getSessionToken());
}
public java.util.Optional<User> getUserBySessionToken(@NonNull UUID sessionToken) {
return java.util.Optional.ofNullable(usersCache.get(sessionToken));
}
public Optional<User> getUserByOpenidIdentifier(String openIDIdentifier) {
checkArgument(!isNullOrEmpty(openIDIdentifier));
for (val user : usersCache.values()) {
if (user.getOpenIDIdentifier().equals(openIDIdentifier)) {
return Optional.of(user);
}
}
return Optional.absent();
}
public java.util.Optional<User> getUserByEmail(String emailAddress) {
if (emailAddress == null) return java.util.Optional.empty();
for (val user : usersCache.values()) {
if (user.getEmailAddress().equals(emailAddress)) {
return java.util.Optional.of(user);
}
}
return java.util.Optional.empty();
}
public void putDiscoveryInfo(@NonNull UUID sessionToken, @NonNull DiscoveryInformation discoveryInfo) {
discoveryInfoCache.put(sessionToken, discoveryInfo);
}
public Optional<DiscoveryInformation> getDiscoveryInfo(@NonNull UUID sessionToken) {
return Optional.fromNullable(discoveryInfoCache.get(sessionToken));
}
public void removeDiscoveryInfo(@NonNull UUID sessionToken) {
discoveryInfoCache.remove(sessionToken);
}
}
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qt3d/src/core/changes/qnodecreatedchange.cpp | 4269 | /****************************************************************************
**
** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** 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 http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnodecreatedchange.h"
#include "qnodecreatedchange_p.h"
#include <Qt3DCore/qnode.h>
#include <Qt3DCore/private/qnode_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
QNodeCreatedChangeBasePrivate::QNodeCreatedChangeBasePrivate(const QNode *node)
: QSceneChangePrivate()
, m_parentId(node->parentNode() ? node->parentNode()->id() : QNodeId())
, m_metaObject(QNodePrivate::findStaticMetaObject(node->metaObject()))
, m_nodeEnabled(node->isEnabled())
{
}
/*!
* \class Qt3DCore::QNodeCreatedChangeBase
* \inheaderfile Qt3DCore/QNodeCreatedChangeBase
* \inherits Qt3DCore::QSceneChange
* \inmodule Qt3DCore
* \brief The QNodeCreatedChangeBase class is the base class for all NodeCreated QSceneChange events
*
* The QNodeCreatedChangeBase class is the base class for all QSceneChange events that
* have the changeType() NodeCreated. You should not need to instantiate this class.
* Usually you should be using one of its subclasses such as QNodeCreatedChange.
*
* You can subclass this to create your own node update types for communication between
* your QNode and QBackendNode subclasses when writing your own aspects.
*/
/*!
* \typedef Qt3DCore::QNodeCreatedChangeBasePtr
* \relates Qt3DCore::QNodeCreatedChangeBase
*
* A shared pointer for QNodeCreatedChangeBase.
*/
/*!
* Constructs a new QNodeCreatedChangeBase with \a node.
*/
QNodeCreatedChangeBase::QNodeCreatedChangeBase(const QNode *node)
: QSceneChange(*new QNodeCreatedChangeBasePrivate(node), NodeCreated, node->id())
{
}
QNodeCreatedChangeBase::QNodeCreatedChangeBase(QNodeCreatedChangeBasePrivate &dd, const QNode *node)
: QSceneChange(dd, NodeCreated, node->id())
{
}
QNodeCreatedChangeBase::~QNodeCreatedChangeBase()
{
}
/*!
* \return parent id.
*/
QNodeId QNodeCreatedChangeBase::parentId() const Q_DECL_NOTHROW
{
Q_D(const QNodeCreatedChangeBase);
return d->m_parentId;
}
/*!
* \return metaobject.
*/
const QMetaObject *QNodeCreatedChangeBase::metaObject() const Q_DECL_NOTHROW
{
Q_D(const QNodeCreatedChangeBase);
return d->m_metaObject;
}
/*!
* \return node enabled.
*/
bool QNodeCreatedChangeBase::isNodeEnabled() const Q_DECL_NOTHROW
{
Q_D(const QNodeCreatedChangeBase);
return d->m_nodeEnabled;
}
} // namespace Qt3DCore
/*!
* \class Qt3DCore::QNodeCreatedChange
* \inheaderfile Qt3DCore/QNodeCreatedChange
* \inherits Qt3DCore::QNodeCreatedChangeBase
* \since 5.7
* \inmodule Qt3DCore
* \brief Used to notify when a node is created.
*/
QT_END_NAMESPACE
| gpl-3.0 |
AADProductions/FRONTIERS | Assets/Scripts/GameWorld/WIScripts/Creatures/BodyAnimator.cs | 9965 | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Frontiers;
public class BodyAnimator : MonoBehaviour
{
public Animator animator;
//send messages about our state to the sounds object
public float MovementMultiplier = 25f;
public float RunVerticalAxisCutoff = 15f;
public bool SupportsWalking = false;
public bool ForceWalk = false;
//these are the base names for the animation controller
//they're arbitrarily based on the wolf creature animation
public static string gAnimWalkName = "walk";
public static string gAnimSprintName = "run";
public static string gAnimIdle1Name = "idleNormal";
public static string gAnimIdle2Name = "idleLookAround";
public static string gAnimAttack1Name = "standBite";
public static string gAnimAttack2Name = "runBite";
public static string gAnimWarnName = "howl";
public static string gAnimTakeDamageName = "getHit";
public static string gAnimDyingName = "death";
public static string gAnimDeadName = "dead";
public static string gAnimJumpName = "run";
//TODO new clip here
//animations used for basic states
public AnimationClip AnimWalk;
public AnimationClip AnimSprint;
public AnimationClip AnimIdle1;
public AnimationClip AnimIdle2;
public AnimationClip AnimAttack1;
public AnimationClip AnimAttack2;
public AnimationClip AnimWarn;
public AnimationClip AnimTakeDamage;
public AnimationClip AnimDying;
public AnimationClip AnimDead;
public AnimationClip AnimJump;
public bool UseOverrideController = true;
//replaces previous enum movement modes
//this will be defined by motile scripts
public static FlagSet IdleAnimationFlags = null;
public List <string> ActiveMovementModes = new List <string> ();
public List <string> AvailableMovementModes = new List <string> ();
[NObjectSync]
public int BaseMovementMode {
get {
return mBaseMovementMode;
}
set {
mBaseMovementMode = value;
}
}
[NObjectSync]
public int IdleAnimation {
get {
return mIdleAnimation;
}
set {
if (value != mIdleAnimation) {
ApplyIdleAnimation (value);
}
}
}
[NObjectSync]
public float VerticalAxisMovement {
get {
return mVerticalAxisMovement;
}
set {
mVerticalAxisMovement = value;
}
}
public float YRotation {
get {
return mYRotation;
}
set {
mYRotation = value;
}
}
[NObjectSync]
public float HorizontalAxisMovement {
get {
return mHorizontalAxisMovement;
}
set {
mHorizontalAxisMovement = value;
}
}
[NObjectSync]
public bool TakingDamage {
get {
return mTakingDamage;
}
set {
mTakingDamage = value;
}
}
[NObjectSync]
public virtual bool Dead {
get {
return mDead;
}
set {
mDead = value;
}
}
[NObjectSync]
public bool Warn {
get {
return mWarn;
}
set {
mWarn = value;
}
}
[NObjectSync]
public bool Attack1 {
get {
return mAttack1;
}
set {
mAttack1 = value;
}
}
[NObjectSync]
public bool Attack2 {
get {
return mAttack2;
}
set {
mAttack2 = value;
}
}
[NObjectSync]
public bool Grounded {
get {
return mGrounded;
}
set {
mGrounded = value;
}
}
[NObjectSync]
public bool Jump {
get {
return mJump;
}
set {
mJump = value;
}
}
[NObjectSync]
public bool Paused {
get {
return mPaused;
}
set {
if (value != mPaused) {
SetPaused (value);
}
}
}
[NObjectSync]
public bool Idling {
get {
return mIdling;
}
set {
mIdling = value;
}
}
public virtual void Start ()
{
if (animator.avatar == null) {
mPaused = true;
}
animator.applyRootMotion = false;
animator.updateMode = AnimatorUpdateMode.Normal;
animator.cullingMode = AnimatorCullingMode.CullUpdateTransforms;
if (UseOverrideController) {
//override clips with this creature's animation clips
RuntimeAnimatorController controller = animator.runtimeAnimatorController;
AnimatorOverrideController overrideController = new AnimatorOverrideController ();
overrideController.runtimeAnimatorController = controller;
overrideController [gAnimWarnName] = AnimWarn;
overrideController [gAnimWalkName] = AnimWalk;
overrideController [gAnimSprintName] = AnimSprint;
overrideController [gAnimIdle1Name] = AnimIdle1;
overrideController [gAnimIdle2Name] = AnimIdle2;
overrideController [gAnimAttack1Name] = AnimAttack1;
overrideController [gAnimAttack2Name] = AnimAttack2;
overrideController [gAnimTakeDamageName] = AnimTakeDamage;
overrideController [gAnimDyingName] = AnimDying;
overrideController [gAnimDeadName] = AnimDead;
overrideController [gAnimJumpName] = AnimJump;
animator.runtimeAnimatorController = overrideController;
}
mSmoothVerticalAxisMovement = 0f;
mSmoothHorizontalAxisMovement = 0f;
VerticalAxisMovement = 0f;
HorizontalAxisMovement = 0f;
animator.SetFloat ("HorizontalAxisMovement", 0f);
animator.SetFloat ("VerticalAxisMovement", 0f);
animator.SetFloat ("MouseX", 0f);
animator.SetBool ("Falling", false);
animator.SetBool ("Grounded", true);
animator.SetBool ("Jump", false);
if (IdleAnimationFlags == null) {
GameWorld.Get.FlagSetByName ("IdleAnimation", out IdleAnimationFlags);
}
}
protected void SetPaused (bool Paused)
{
mPaused = Paused;
}
public virtual void FixedUpdate ()
{
if (mPaused) {
//animator.SetFloat ("AxisY", 0.0f);
//animator.SetFloat ("AxisX", 0.0f);
//animator.SetFloat ("MouseX", 0.0f);
//we're done
return;
}
if (mDead) {
animator.SetBool ("Dead", mDead);
if (mDead) {
animator.SetFloat ("HorizontalAxisMovement", 0f);
animator.SetFloat ("VerticalAxisMovement", 0f);
animator.SetFloat ("MouseX", 0f);
animator.SetBool ("Grounded", true);
animator.SetBool ("Jump", false);
animator.SetBool ("Walking", false);
}
return;
}
if (mToggle) {
mToggle = false;
mSmoothVerticalAxisMovement = Mathf.Lerp (mSmoothVerticalAxisMovement, VerticalAxisMovement, Time.deltaTime * 15f);
mSmoothHorizontalAxisMovement = Mathf.Lerp (mSmoothHorizontalAxisMovement, HorizontalAxisMovement, Time.deltaTime * 15f);
bool setWalking = true;
//animator.SetBool ("Idling", Idling);
if (Attack1) {
animator.SetBool ("Attack1", true);
setWalking = false;
} else if (Attack2) {
animator.SetBool ("Attack2", true);
setWalking = false;
} else if (Warn) {
animator.SetBool ("Warn", true);
setWalking = false;
}
if (TakingDamage) {
animator.SetBool ("TakingDamage", true);
setWalking = false;
}
float verticalAxisMovement = mSmoothVerticalAxisMovement * MovementMultiplier;
animator.SetFloat ("VerticalAxisMovement", verticalAxisMovement);
if (setWalking) {
if (SupportsWalking) {
if (ForceWalk) {
animator.SetBool ("Walking", true);
} else {
animator.SetBool ("Walking", (verticalAxisMovement < RunVerticalAxisCutoff));
}
}
} else {
animator.SetBool ("Walking", false);
}
//animator.SetFloat ("HorizontalAxisMovement", mSmoothHorizontalAxisMovement * MovementMultiplier);
mYRotationDifference = mYRotationDifference * 0.5f;
mYRotationDifference += ((mYRotationLastFrame - mYRotation) * MovementMultiplier);
if (Mathf.Abs (mYRotationDifference) < 0.001f) {
mYRotationDifference = 0f;
}
mYRotationLastFrame = mYRotation;
animator.SetFloat ("MouseX", mYRotationDifference);
} else {
mToggle = true;
if (Jump) {
animator.SetBool ("Grounded", false);
if (Grounded) {
animator.SetBool ("Jump", false);
Jump = false;
}
} else {
animator.SetBool ("Grounded", Grounded);
}
if (Attack1) {
animator.SetBool ("Attack1", false);
Attack1 = false;
}
if (Attack2) {
animator.SetBool ("Attack2", false);
Attack2 = false;
}
if (Warn) {
animator.SetBool ("Warn", false);
Warn = false;
}
if (TakingDamage) {
animator.SetBool ("TakingDamage", false);
TakingDamage = false;
}
}
}
protected bool mToggle = false;
protected virtual void ApplyIdleAnimation (int idleAnimation)
{
mIdleAnimation = idleAnimation;
if (idleAnimation == 0) {
//set everything to zero
//Debug.Log ("Setting idle animation to zero / default");
ActiveMovementModes.Clear ();
} else {
ActiveMovementModes.Clear ();
int[] flags = FlagSet.GetFlagValues (idleAnimation);
//Debug.Log ("Setting idle animation to " + idleAnimation.ToString ());
for (int i = 0; i < flags.Length; i++) {
string flagValue = IdleAnimationFlags.GetFlagName (1 << flags [i]);
if (!string.IsNullOrEmpty (flagValue)) {
//Debug.Log ("Got flag value " + flagValue + " for flag " + (1 << flags [i]).ToString ());
ActiveMovementModes.Add (flagValue);
}
}
}
for (int i = 0; i < AvailableMovementModes.Count; i++) {
if (ActiveMovementModes.Contains (AvailableMovementModes [i])) {
//Debug.Log ("Setting animation " + AvailableMovementModes [i] + " to true");
animator.SetBool (AvailableMovementModes [i], true);
} else {
//Debug.Log ("Setting animation " + AvailableMovementModes [i] + " to false");
animator.SetBool (AvailableMovementModes [i], false);
}
}
}
protected int mBaseMovementMode;
protected int mIdleAnimation;
protected string mPreviousMovementMode;
protected float mVerticalAxisMovement = 0f;
protected float mHorizontalAxisMovement = 0f;
protected bool mAttack1 = false;
protected bool mAttack2 = false;
protected bool mWarn = false;
protected bool mGrounded = true;
protected bool mJump = false;
protected float mSmoothVerticalAxisMovement = 0.0f;
protected float mSmoothHorizontalAxisMovement = 0.0f;
protected float mYRotationDifference = 0.0f;
protected float mYRotation;
protected float mYRotationLastFrame;
protected bool mPaused = false;
protected bool mDead = false;
protected bool mTakingDamage = false;
protected bool mIdling = false;
protected float mIdleBlend = 0f;
protected float mIdleTarget = 0f;
}
| gpl-3.0 |
Lyrositor/Omnibot | Utils.cpp | 2571 | /*
Copyright (C) 2012 Lyrositor
This file is part of Omnibot.
Omnibot 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.
Omnibot 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 Omnibot. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include "Utils.h"
static const char reverse_table[128] = {
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64
};
// Base64 decoding to plain text.
// Source: http://stackoverflow.com/questions/5288076/doing-base64-encoding-and-decoding-in-openssl-c
string DecodeBase64(const string &ascdata) {
string retVal;
const string::const_iterator last = ascdata.end();
int bits_collected = 0;
unsigned int accumulator = 0;
for (string::const_iterator i = ascdata.begin(); i != last; ++i) {
const int c = *i;
if (isspace(c) || c == '=') {
// Skip whitespace and padding. Be liberal in what you accept.
continue;
}
if ((c > 127) || (c < 0) || (reverse_table[c] > 63)) {
throw invalid_argument("This contains characters not legal in a base64 encoded string.");
}
accumulator = (accumulator << 6) | reverse_table[c];
bits_collected += 6;
if (bits_collected >= 8) {
bits_collected -= 8;
retVal += (char)((accumulator >> bits_collected) & 0xffu);
}
}
return retVal;
}
// Copies a string in reverse.
void ReverseCopy(string src, unsigned char* dst, int size) {
for (int i = 0; i < size; i++)
dst[i] = src[size - i - 1];
}
| gpl-3.0 |
cSploit/android.MSF | lib/msf/http/wordpress/version.rb | 8081 | # -*- coding: binary -*-
module Msf::HTTP::Wordpress::Version
# Used to check if the version is correct: must contain at least one dot
WORDPRESS_VERSION_PATTERN = '([^\r\n"\']+\.[^\r\n"\']+)'
# Extracts the Wordpress version information from various sources
#
# @return [String,nil] Wordpress version if found, nil otherwise
def wordpress_version
# detect version from generator
version = wordpress_version_helper(normalize_uri(target_uri.path), /<meta name="generator" content="WordPress #{WORDPRESS_VERSION_PATTERN}" \/>/i)
return version if version
# detect version from readme
version = wordpress_version_helper(wordpress_url_readme, /<br \/>\sversion #{WORDPRESS_VERSION_PATTERN}/i)
return version if version
# detect version from rss
version = wordpress_version_helper(wordpress_url_rss, /<generator>http:\/\/wordpress.org\/\?v=#{WORDPRESS_VERSION_PATTERN}<\/generator>/i)
return version if version
# detect version from rdf
version = wordpress_version_helper(wordpress_url_rdf, /<admin:generatorAgent rdf:resource="http:\/\/wordpress.org\/\?v=#{WORDPRESS_VERSION_PATTERN}" \/>/i)
return version if version
# detect version from atom
version = wordpress_version_helper(wordpress_url_atom, /<generator uri="http:\/\/wordpress.org\/" version="#{WORDPRESS_VERSION_PATTERN}">WordPress<\/generator>/i)
return version if version
# detect version from sitemap
version = wordpress_version_helper(wordpress_url_sitemap, /generator="wordpress\/#{WORDPRESS_VERSION_PATTERN}"/i)
return version if version
# detect version from opml
version = wordpress_version_helper(wordpress_url_opml, /generator="wordpress\/#{WORDPRESS_VERSION_PATTERN}"/i)
return version if version
nil
end
# Checks a readme for a vulnerable version
#
# @param [String] plugin_name The name of the plugin
# @param [String] fixed_version Optional, the version the vulnerability was fixed in
# @param [String] vuln_introduced_version Optional, the version the vulnerability was introduced
#
# @return [ Msf::Exploit::CheckCode ]
def check_plugin_version_from_readme(plugin_name, fixed_version = nil, vuln_introduced_version = nil)
check_version_from_readme(:plugin, plugin_name, fixed_version, vuln_introduced_version)
end
# Checks the style.css file for a vulnerable version
#
# @param [String] theme_name The name of the theme
# @param [String] fixed_version Optional, the version the vulnerability was fixed in
# @param [String] vuln_introduced_version Optional, the version the vulnerability was introduced
#
# @return [ Msf::Exploit::CheckCode ]
def check_theme_version_from_style(theme_name, fixed_version = nil, vuln_introduced_version = nil)
style_uri = normalize_uri(wordpress_url_themes, theme_name, 'style.css')
res = send_request_cgi(
'uri' => style_uri,
'method' => 'GET'
)
# No style.css file present
return Msf::Exploit::CheckCode::Unknown if res.nil? || res.code != 200
return extract_and_check_version(res.body.to_s, :style, :theme, fixed_version, vuln_introduced_version)
end
# Checks a readme for a vulnerable version
#
# @param [String] theme_name The name of the theme
# @param [String] fixed_version Optional, the version the vulnerability was fixed in
# @param [String] vuln_introduced_version Optional, the version the vulnerability was introduced
#
# @return [ Msf::Exploit::CheckCode ]
def check_theme_version_from_readme(theme_name, fixed_version = nil, vuln_introduced_version = nil)
check_version_from_readme(:theme, theme_name, fixed_version, vuln_introduced_version)
end
# Checks a custom file for a vulnerable version
#
# @param [String] uripath The relative path of the file
# @param [Regexp] regex The regular expression to extract the version. The first captured group must contain the version.
# @param [String] fixed_version Optional, the version the vulnerability was fixed in
# @param [String] vuln_introduced_version Optional, the version the vulnerability was introduced
#
# @return [ Msf::Exploit::CheckCode ]
def check_version_from_custom_file(uripath, regex, fixed_version = nil, vuln_introduced_version = nil)
res = send_request_cgi(
'uri' => uripath,
'method' => 'GET'
)
# file not found
unless res && res.code == 200
return Msf::Exploit::CheckCode::Unknown
end
extract_and_check_version(res.body.to_s, :custom, 'custom file', fixed_version, vuln_introduced_version, regex)
end
private
def wordpress_version_helper(url, regex)
res = send_request_cgi(
'method' => 'GET',
'uri' => url
)
if res
match = res.body.match(regex)
return match[1] if match
end
nil
end
def check_version_from_readme(type, name, fixed_version = nil, vuln_introduced_version = nil)
case type
when :plugin
folder = 'plugins'
when :theme
folder = 'themes'
else
fail("Unknown readme type #{type}")
end
readmes = ['readme.txt', 'Readme.txt', 'README.txt']
res = nil
readmes.each do |readme_name|
readme_url = normalize_uri(target_uri.path, wp_content_dir, folder, name, readme_name)
vprint_status("#{peer} - Checking #{readme_url}")
res = send_request_cgi(
'uri' => readme_url,
'method' => 'GET'
)
break if res && res.code == 200
end
if res.nil? || res.code != 200
# No readme.txt or Readme.txt present for plugin
return Msf::Exploit::CheckCode::Unknown if type == :plugin
# Try again using the style.css file
return check_theme_version_from_style(name, fixed_version, vuln_introduced_version) if type == :theme
end
version_res = extract_and_check_version(res.body.to_s, :readme, type, fixed_version, vuln_introduced_version)
if version_res == Msf::Exploit::CheckCode::Detected && type == :theme
# If no version could be found in readme.txt for a theme, try style.css
return check_theme_version_from_style(name, fixed_version, vuln_introduced_version)
else
return version_res
end
end
def extract_and_check_version(body, type, item_type, fixed_version = nil, vuln_introduced_version = nil, regex = nil)
case type
when :readme
# Try to extract version from readme
# Example line:
# Stable tag: 2.6.6
version = body[/(?:stable tag|version):\s*(?!trunk)([0-9a-z.-]+)/i, 1]
when :style
# Try to extract version from style.css
# Example line:
# Version: 1.5.2
version = body[/(?:Version):\s*([0-9a-z.-]+)/i, 1]
when :custom
version = body[regex, 1]
else
fail("Unknown file type #{type}")
end
# Could not identify version number
return Msf::Exploit::CheckCode::Detected if version.nil?
vprint_status("#{peer} - Found version #{version} of the #{item_type}")
if fixed_version.nil?
if vuln_introduced_version.nil?
# All versions are vulnerable
return Msf::Exploit::CheckCode::Appears
elsif Gem::Version.new(version) >= Gem::Version.new(vuln_introduced_version)
# Newer or equal to the version it was introduced
return Msf::Exploit::CheckCode::Appears
else
return Msf::Exploit::CheckCode::Safe
end
else
# Version older than fixed version
if Gem::Version.new(version) < Gem::Version.new(fixed_version)
if vuln_introduced_version.nil?
# Older than fixed version, no vuln introduction date, flag as vuln
return Msf::Exploit::CheckCode::Appears
# vuln_introduced_version provided, check if version is newer
elsif Gem::Version.new(version) >= Gem::Version.new(vuln_introduced_version)
return Msf::Exploit::CheckCode::Appears
else
# Not in range, nut vulnerable
return Msf::Exploit::CheckCode::Safe
end
# version newer than fixed version
else
return Msf::Exploit::CheckCode::Safe
end
end
end
end
| gpl-3.0 |
formtools/module-data_visualization | activity_charts/page_appearance.php | 1759 | <?php
use FormTools\Submissions;
$num_submissions = Submissions::getSubmissionCount($vis_info["form_id"], $vis_info["view_id"]);
$page_vars["has_submissions_in_view"] = ($num_submissions > 0) ? "yes" : "no";
$page_vars["js_messages"] = array(
"phrase_please_select", "phrase_please_select_form", "word_edit", "word_delete",
"word_yes", "word_no"
);
$page_vars["module_js_messages"] = array("phrase_delete_visualization", "confirm_delete_visualization");
$page_vars["head_js"] =<<< END
if (typeof google != "undefined") {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(vis_ns.update_activity_chart_data);
}
$(function() {
if (typeof google == "undefined") {
$("#no_internet_connection").show();
}
if ($("#has_submissions_in_view").val() == "no") {
$("#no_data_message").show();
}
if ($("input[name=chart_type]:checked").val() == "column_chart") {
$("#line_width").attr("disabled", "disabled");
}
$("#delete_visualization").bind("click", function() {
vis_ns.delete_visualization($vis_id);
});
$("#date_range, input[name=submission_count_group]").bind("change", vis_ns.update_activity_chart_data);
$("input[name=chart_type], #colour, #line_width").bind("change keyup", vis_ns.redraw_activity_chart);
$("#vis_name").bind("blur", vis_ns.redraw_activity_chart);
$("input[name=chart_type]").bind("change", function() {
if (this.value == "column_chart") {
$("#line_width").attr("disabled", "disabled");
} else {
$("#line_width").attr("disabled", "");
}
});
});
$js
var rules = [];
END;
$module->displayPage("templates/activity_charts/edit.tpl", $page_vars);
| gpl-3.0 |
crs4/vispa | galaxy/tools/multiplex.py | 800 | # BEGIN_COPYRIGHT
#
# Copyright (C) 2013-2014 CRS4.
#
# This file is part of vispa.
#
# vispa 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.
#
# vispa 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
# vispa. If not, see <http://www.gnu.org/licenses/>.
#
# END_COPYRIGHT
import sys
from bl.tiget.pipeline.multiplex import main
main(sys.argv[1:])
| gpl-3.0 |
autentia/TNTConcept | tntconcept-core/src/main/java/com/autentia/tnt/dao/search/DepartmentSearch.java | 14144 | /**
* TNTConcept Easy Enterprise Management by Autentia Real Bussiness Solution S.L.
* Copyright (C) 2007 Autentia Real Bussiness Solution S.L.
*
* 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.
*
* 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.autentia.tnt.dao.search;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import com.autentia.tnt.businessobject.Department;
import com.autentia.tnt.businessobject.Organization;
import com.autentia.tnt.dao.ITransferObject;
import com.autentia.tnt.dao.SearchCriteria;
/**
* Class to search for Department objects
* @author stajanov code generator
*/
public class DepartmentSearch extends SearchCriteria
{
/* Department - generated by stajanov (do not edit/delete) */
@Override
public String getHQL() {
StringBuilder ret = new StringBuilder();
int iArgNum = 0;
if( isNameSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( getName()==null ){
ret.append( "name is NULL" );
} else {
ret.append( "name like :arg"+(iArgNum++) );
}
}
if( isDescriptionSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( getDescription()==null ){
ret.append( "description is NULL" );
} else {
ret.append( "description = :arg"+(iArgNum++) );
}
}
if( isOwnerIdSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( getOwnerId()==null ){
ret.append( "ownerId is NULL" );
} else {
ret.append( "ownerId = :arg"+(iArgNum++) );
}
}
if( isDepartmentIdSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( getDepartmentId()==null ){
ret.append( "departmentId is NULL" );
} else {
ret.append( "departmentId = :arg"+(iArgNum++) );
}
}
if( isStartInsertDateSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( startInsertDate == null ){
ret.append( "insertDate=:arg"+(iArgNum++) );
} else {
ret.append( "insertDate>=:arg"+(iArgNum++) );
}
}
if( isEndInsertDateSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( endInsertDate == null ){
ret.append( "insertDate=:arg"+(iArgNum++) );
} else {
ret.append( "insertDate<=:arg"+(iArgNum++) );
}
}
if( isStartUpdateDateSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( startUpdateDate == null ){
ret.append( "updateDate=:arg"+(iArgNum++) );
} else {
ret.append( "updateDate>=:arg"+(iArgNum++) );
}
}
if( isEndUpdateDateSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( endUpdateDate == null ){
ret.append( "updateDate=:arg"+(iArgNum++) );
} else {
ret.append( "updateDate<=:arg"+(iArgNum++) );
}
}
if( isParentSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
if( getParent()==null ){
ret.append( "parent is NULL" );
} else {
ret.append( "parent = :arg"+(iArgNum++) );
}
}
if( isOrganizationSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
ret.append( "organizations.id IN (:arg"+(iArgNum++)+")" );
}
customGetHQL(ret,iArgNum);
return ret.toString();
}
@Override
public Object[] getArguments(){
ArrayList<Object> ret = new ArrayList<Object>();
if( isNameSet() && getName()!=null ){
ret.add( name );
}
if( isDescriptionSet() && getDescription()!=null ){
ret.add( description );
}
if( isOwnerIdSet() && getOwnerId()!=null ){
ret.add( ownerId );
}
if( isDepartmentIdSet() && getDepartmentId()!=null ){
ret.add( departmentId );
}
if( isStartInsertDateSet() ){
ret.add( startInsertDate );
}
if( isEndInsertDateSet() ){
ret.add( endInsertDate );
}
if( isStartUpdateDateSet() ){
ret.add( startUpdateDate );
}
if( isEndUpdateDateSet() ){
ret.add( endUpdateDate );
}
if( isParentSet() && getParent()!=null ){
ret.add( parent );
}
if( isOrganizationSet() && getOrganization()!=null ){
ret.add( organization.getId() );
}
customGetArguments(ret);
return ret.toArray();
}
@Override
public void reset(){
unsetName();
unsetDescription();
unsetOwnerId();
unsetDepartmentId();
unsetStartInsertDate();
unsetEndInsertDate();
unsetStartUpdateDate();
unsetEndUpdateDate();
unsetParent();
customReset();
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("DepartmentSearch{");
if( isNameSet() ){
ret.append( "(name" );
ret.append( "="+name );
ret.append( ")" );
}
if( isDescriptionSet() ){
ret.append( "(description" );
ret.append( "="+description );
ret.append( ")" );
}
if( isOwnerIdSet() ){
ret.append( "(ownerId" );
ret.append( "="+ownerId );
ret.append( ")" );
}
if( isDepartmentIdSet() ){
ret.append( "(departmentId" );
ret.append( "="+departmentId );
ret.append( ")" );
}
if( isStartInsertDateSet() ){
ret.append( "(startInsertDate" );
ret.append( "="+startInsertDate );
ret.append( ")" );
}
if( isEndInsertDateSet() ){
ret.append( "(endInsertDate" );
ret.append( "="+endInsertDate );
ret.append( ")" );
}
if( isStartUpdateDateSet() ){
ret.append( "(startUpdateDate" );
ret.append( "="+startUpdateDate );
ret.append( ")" );
}
if( isEndUpdateDateSet() ){
ret.append( "(endUpdateDate" );
ret.append( "="+endUpdateDate );
ret.append( ")" );
}
if( isParentSet() ){
ret.append( "(parent" );
ret.append( "="+parent );
ret.append( ")" );
}
customToString(ret);
ret.append("}");
return ret.toString();
}
// Getters and setters
public boolean isNameSet(){
return nameSet;
}
public String getName(){
return name;
}
public void setName( String name ){
this.name = name;
this.nameSet = true;
}
public void unsetName(){
this.nameSet = false;
}
public boolean isDescriptionSet(){
return descriptionSet;
}
public String getDescription(){
return description;
}
public void setDescription( String description ){
this.description = description;
this.descriptionSet = true;
}
public void unsetDescription(){
this.descriptionSet = false;
}
public boolean isOwnerIdSet(){
return ownerIdSet;
}
public Integer getOwnerId(){
return ownerId;
}
public void setOwnerId( Integer ownerId ){
this.ownerId = ownerId;
this.ownerIdSet = true;
}
public void unsetOwnerId(){
this.ownerIdSet = false;
}
public boolean isDepartmentIdSet(){
return departmentIdSet;
}
public Integer getDepartmentId(){
return departmentId;
}
public void setDepartmentId( Integer departmentId ){
this.departmentId = departmentId;
this.departmentIdSet = true;
}
public void unsetDepartmentId(){
this.departmentIdSet = false;
}
public boolean isOrganizationSet(){
return organizationSet;
}
public Organization getOrganization(){
return organization;
}
public void setOrganization( Organization organization ){
this.organization = organization;
this.organizationSet = true;
}
public void unsetOrganization(){
this.organizationSet = false;
}
public boolean isStartInsertDateSet(){
return startInsertDateSet;
}
public Date getStartInsertDate(){
return startInsertDate;
}
public void setStartInsertDate( Date startInsertDate ){
this.startInsertDate = startInsertDate;
this.startInsertDateSet = true;
}
public void unsetStartInsertDate(){
this.startInsertDateSet = false;
}
public boolean isEndInsertDateSet(){
return endInsertDateSet;
}
public Date getEndInsertDate(){
return endInsertDate;
}
public void setEndInsertDate( Date endInsertDate ){
this.endInsertDate = endInsertDate;
this.endInsertDateSet = true;
}
public void unsetEndInsertDate(){
this.endInsertDateSet = false;
}
public boolean isStartUpdateDateSet(){
return startUpdateDateSet;
}
public Date getStartUpdateDate(){
return startUpdateDate;
}
public void setStartUpdateDate( Date startUpdateDate ){
this.startUpdateDate = startUpdateDate;
this.startUpdateDateSet = true;
}
public void unsetStartUpdateDate(){
this.startUpdateDateSet = false;
}
public boolean isEndUpdateDateSet(){
return endUpdateDateSet;
}
public Date getEndUpdateDate(){
return endUpdateDate;
}
public void setEndUpdateDate( Date endUpdateDate ){
this.endUpdateDate = endUpdateDate;
this.endUpdateDateSet = true;
}
public void unsetEndUpdateDate(){
this.endUpdateDateSet = false;
}
public boolean isParentSet(){
return parentSet;
}
public Department getParent(){
return parent;
}
public void setParent( Department parent ){
this.parent = parent;
this.parentSet = true;
}
public void unsetParent(){
this.parentSet = false;
}
// Fields
private boolean nameSet;
private String name;
private boolean descriptionSet;
private String description;
private boolean ownerIdSet;
private Integer ownerId;
private boolean departmentIdSet;
private Integer departmentId;
private boolean startInsertDateSet;
private Date startInsertDate;
private boolean endInsertDateSet;
private Date endInsertDate;
private boolean startUpdateDateSet;
private Date startUpdateDate;
private boolean endUpdateDateSet;
private Date endUpdateDate;
private boolean organizationSet;
private Organization organization;
private boolean parentSet;
private Department parent;
// Returns if there are a search condition active
public boolean isSearchActive() {
return customIsSearchActive()||nameSet||descriptionSet||ownerIdSet||departmentIdSet||startInsertDateSet||endInsertDateSet||startUpdateDateSet||endUpdateDateSet||parentSet;
}
/* Department - generated by stajanov (do not edit/delete) */
/*
@Override
public String getHQL() {
StringBuilder ret = new StringBuilder();
int iArgNum = 0;
if( isNameSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
ret.append( "name like :arg"+(iArgNum++) );
}
if( isDescriptionSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
ret.append( "description = :arg"+(iArgNum++) );
}
if( isParentSet() ){
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
ret.append( "parent = :arg"+(iArgNum++) );
}
return ret.toString();
}
*/
private Integer idDifferentFrom;
private boolean idDifferentFromSet;
public Integer getIdDifferentFrom()
{
return idDifferentFrom;
}
public void setIdDifferentFrom(Integer id)
{
this.idDifferentFrom = id;
this.idDifferentFromSet = true;
}
public boolean isIdDifferentFromSet()
{
return idDifferentFromSet;
}
public void unsetIdDifferentFrom()
{
this.idDifferentFromSet = false;
}
private void customGetHQL(StringBuilder ret, int iArgNum)
{
if(isIdDifferentFromSet())
{
ret.append( (ret.length()==0) ? "WHERE " : " AND " );
ret.append( "id != :arg"+iArgNum );
}
}
private void customGetArguments(ArrayList ret)
{
if(isIdDifferentFromSet())
{
ret.add( idDifferentFrom );
}
}
private void customReset()
{
unsetIdDifferentFrom();
}
private void customToString(StringBuilder ret)
{
if( isIdDifferentFromSet() )
{
ret.append( "(idDifferentFrom" );
ret.append( "="+idDifferentFrom );
ret.append( ")" );
}
}
private boolean customIsSearchActive()
{
return idDifferentFromSet;
}
}
| gpl-3.0 |
fauconnier/LaToe | src/org/melodi/analyser/talismane_client/service/Sentence.java | 1972 | ///////////////////////////////////////////////////////////////////////////////
//Copyright (C) 2012 Jean-Philippe Fauconnier
//
//This file is part of TalismaneClient.
//
//TalismaneClient is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Talismane 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 Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with Talismane. If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////////////////
package org.melodi.analyser.talismane_client.service;
import java.io.Serializable;
import java.util.ArrayList;
public class Sentence extends ArrayList<Token> implements Serializable{
private int id_sentence;
/**
* A simple data structure to represent a sentence in CoNLL Format.
* This format is based on the CoNLL format.
*
* @see <a href="http://nextens.uvt.nl/depparse-wiki/DataFormat">CoNLL format</a>
* @author Jean-Philippe Fauconnier
*/
public Sentence(int id_sentence) {
this.id_sentence = id_sentence;
}
public Sentence(){
}
public void print(){
System.out.println(this.stringDump());
}
public String stringDump(){
/* to get a string dump of a CoNLL_Sentence*/
String all_token = "-------"+ this.getId_sentence()+"-------\n";
for(Token currToken : this){
all_token += currToken.stringDump() + "\n";
}
return all_token;
}
/*
* Getters and Setters
*/
public int getId_sentence() {
return id_sentence;
}
public void setId_sentence(int id_sentence) {
this.id_sentence = id_sentence;
}
}
| gpl-3.0 |
jvail/cutefarm | src/reportviewwidget.cpp | 18769 | /* CuteFarm
Copyright (C) 2008-2011 Jan Vaillant
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 License 3.
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 <QDomElement>
#include <QToolButton>
#include <QSqlError>
#include <QSqlRecord>
#include <QSqlField>
#include <QHeaderView>
#include <QFileDialog>
#include <QSqlQuery>
#include <QProgressDialog>
#include <QSortFilterProxyModel>
#include <QFileDialog>
#include <QColorDialog>
#include <QMenu>
#include <QMessageBox>
#include <QProgressDialog>
#include <QInputDialog>
#include "reportviewwidget.h"
#include "reportfiledialog.h"
#include "settingsdialog.h"
#include "highlighter.h"
#include "cutefarm.h"
ReportViewWidget::ReportViewWidget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
setupQry();
}
void ReportViewWidget::onDatabaseChanged()
{
disconnect(ui.cBTables, SIGNAL(currentIndexChanged(QString)),
this, SLOT(onCbTablesCurrentIndexChanged(QString)));
ui.cBTables->clear();
QSqlQuery q;
q.exec("SELECT tbl_name FROM sqlite_master WHERE type='table' AND tbl_name NOT LIKE '%sqlite%' ORDER BY tbl_name");
while (q.next())
ui.cBTables->addItem(q.value(0).toString());
onCbTablesCurrentIndexChanged(ui.cBTables->currentText());
connect(ui.cBTables, SIGNAL(currentIndexChanged(QString)),
this, SLOT(onCbTablesCurrentIndexChanged(QString)));
}
void ReportViewWidget::onCbTablesCurrentIndexChanged(const QString &table)
{
if (table.isEmpty())
return;
QSqlQuery q;
q.exec(QString("SELECT sql FROM sqlite_master WHERE type='table' AND tbl_name='%1'").arg(table));
while (q.next())
ui.textEditSchema->setText(q.value(0).toString());
}
void ReportViewWidget::setupQry()
{
m_currentQry = QString();
QWidget *cornerWidget = new QWidget(this);
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0, 0, 0, 1);
layout->setSpacing(1);
cornerWidget->setLayout(layout);
m_actnQryButton = new QToolButton(this);
m_actnQryButton->setMinimumSize(20, 20);
m_actnQryButton->setIcon(QIcon(":/pic/kchart_chrt.png"));
m_actnQryButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
m_actnQryButton->setPopupMode(QToolButton::InstantPopup);
layout->addWidget(m_actnQryButton);
QMenu *menu = new QMenu(this);
menu->addAction(ui.actionRunQryFromText);
menu->addAction(ui.actionSaveQry);
menu->addAction(ui.actionCloseQry);
menu->addSeparator();
menu->addAction(ui.actionCSV);
m_actnQryButton->setMenu(menu);
ui.tabWidget->setCornerWidget(cornerWidget, Qt::TopRightCorner);
m_qryModel = new SqlQueryModel(this);
QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this);
proxy->setSourceModel(m_qryModel);
ui.resultView->setModel(proxy);
m_dirModel = new QDirModel(QStringList() /*<< "*.qry"*/, QDir::AllDirs | QDir::AllEntries | QDir::NoDotAndDotDot,
QDir::Name, this);
m_dirModel->setReadOnly(false);
FileIconProvider *fIp= new FileIconProvider;
m_dirModel->setIconProvider(fIp);
// if (!QDir(QDir::home().path() + "/CuteFarm/Reports").exists()) {
// QDir(QDir::home().path()).mkdir("CuteFarm");
// QDir(QDir::home().path() + "/CuteFarm").mkdir("Reports");
// }
//
// qDebug() << QDir::home().path();
ui.dirView->setModel(m_dirModel);
ui.dirView->setRootIndex(m_dirModel->index(CuteFarm::reportsDirPath()));
ui.dirView->setAcceptDrops(true);
ui.dirView->hideColumn(1);
ui.dirView->hideColumn(2);
ui.dirView->hideColumn(3);
m_treeWidgetQryStrgFileActns << ui.actionEditQry << ui.actionDeleteQry << ui.actionRunQryFromFile << ui.actionNewFolder;
m_treeWidgetQryStrgDirActns << ui.actionNewFolder << ui.actionDeleteFolder;
ui.dirView->resizeColumnToContents(0);
ui.dirView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
ui.resultView->setAlternatingRowColors(SettingsDialog::alternatingRowColors());
ui.resultView->horizontalHeader()->setResizeMode(SettingsDialog::resizeMode());
ui.resultView->setShowGrid(SettingsDialog::showGrid());
// resultView->horizontalHeader()->setStretchLastSection(true);
Highlighter *highlighter = new Highlighter(0, true);
highlighter->setDocument(ui.textEditSql->document());
Highlighter *schemaHighlighter = new Highlighter(0, false);
schemaHighlighter->setDocument(ui.textEditSchema->document());
}
void ReportViewWidget::on_dirView_customContextMenuRequested(const QPoint &pos)
{
QString path = m_dirModel->data(ui.dirView->indexAt(pos), QDirModel::FilePathRole).toString();
if (QFileInfo(path).isDir()) {
if (QDir(path).exists()) {
qDebug() << QDir(path).entryList();
if (!QDir(path).entryList(QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::AllDirs).isEmpty())
ui.actionDeleteFolder->setEnabled(false);
else
ui.actionDeleteFolder->setEnabled(true);
m_menuTreeWidgetQryStrg.exec(m_treeWidgetQryStrgDirActns, QCursor::pos());
}
else
return;
}
else if (QFileInfo(path).isFile()) {
if (QFile(path).exists()) {
qDebug() << "file";
m_menuTreeWidgetQryStrg.exec(m_treeWidgetQryStrgFileActns, QCursor::pos());
}
else
return;
}
else if (!ui.dirView->indexAt(pos).isValid()) {
m_menuTreeWidgetQryStrg.exec(m_treeWidgetQryStrgDirActns, QCursor::pos());
}
}
void ReportViewWidget::on_actionCSV_triggered()
{
if (m_qryModel->rowCount() < 1)
return;
QString fileName = QFileDialog::getSaveFileName(
this, tr("Save csv file"), QDir::homePath(), "*.csv");
if (fileName.isEmpty())
return;
QFile file(fileName);
if (file.open(QFile::WriteOnly | QFile::Truncate)) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
QTextStream out(&file);
out.setCodec("UTF-8");
for (int col = 0; col < m_qryModel->columnCount(); ++col) {
out << m_qryModel->headerData(col, Qt::Horizontal, Qt::DisplayRole).toString();
out << "|";
}
out << endl;
for (int i = 0; i < m_qryModel->rowCount(); ++i) {
for (int j = 0; j < m_qryModel->columnCount(); ++j) {
out << m_qryModel->record(i).field(j).value().toString();
out << "|";
}
out << endl;
}
emit statusMsg(tr("Saved"), 5000);
file.close();
QApplication::restoreOverrideCursor();
}
else
emit statusMsg(tr("Error: %1").arg(file.errorString()), 5000);
}
void ReportViewWidget::on_actionEditQry_triggered()
{
m_currentQry.clear();
ui.textEditSql->clear();
ui.textEditComt->clear();
m_actnQryButton->setText("");
QString path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
if (!QFileInfo(path).isFile() || !QFile(path).exists())
return;
QString errorStr;
int errorLine;
int errorColumn;
QFile file(path);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, "CuteFarm",
tr("Can not read file %1\nError: %2")
.arg(QFile(path).fileName())
.arg(file.errorString()));
return;
}
if (!m_domDocument.setContent(&file, true, &errorStr, &errorLine,
&errorColumn)) {
QMessageBox::information(this, "CuteFarm",
tr("Error in line %1, column %2\nError: %3")
.arg(errorLine)
.arg(errorColumn)
.arg(errorStr));
return;
}
QDomElement root = m_domDocument.documentElement();
if (root.tagName() != "qry") {
QMessageBox::information(this, "CuteFarm",
tr("This file is not a query file."));
return;
} else if (root.hasAttribute("version")
&& root.attribute("version") != "1.0") {
QMessageBox::information(this, "CuteFarm",
tr("The file is not an query version 1.0 "
"file."));
return;
}
QString desc = root.firstChildElement("description").text();
QString sql = root.firstChildElement("sql").text();
ui.textEditSql->setText(sql);
ui.textEditComt->setText(desc);
m_actnQryButton->setText(QFileInfo(path).fileName());
file.close();
m_currentQry = path;
}
void ReportViewWidget::on_actionDeleteQry_triggered()
{
QString path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
if (QFileInfo(path).isFile() && QFile(path).exists()) {
QModelIndex parent = ui.dirView->currentIndex().parent();
if (QMessageBox::question(this, "CuteFarm", tr("Delete file '%1'").arg(path), QMessageBox::Yes|QMessageBox::No)
== QMessageBox::Yes) {
if(QFile(path).remove())
m_dirModel->refresh(parent);
}
return;
}
}
void ReportViewWidget::on_actionSaveQry_triggered()
{
if (m_currentQry.isEmpty()) {
ReportFileDialog fD(m_dirModel, this);
start:
if (fD.exec() != QDialog::Accepted)
return;
if (fD.fileName().isEmpty())
return;
m_currentQry = fD.path() + "/" + fD.fileName();
if (QFile(m_currentQry).exists()) {
if (QMessageBox::question(this, "CuteFarm",
tr("File %1 exists.\nReplace?")
.arg(m_currentQry), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
goto start;
}
QFile file(m_currentQry);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, "CuteFarm",
tr("Can not save file %1\n%2.")
.arg(file.fileName())
.arg(file.errorString()));
return;
}
QTextStream out(&file);
out << "<?xml version='1.0' encoding='UTF-8'?>\n"
"<!DOCTYPE qry>\n"
"<qry version=\"1.0\">\n"
" <description>"+ Qt::escape(ui.textEditComt->toPlainText()) +"</description>\n"
" <sql>"+ Qt::escape(ui.textEditSql->toPlainText()) +"</sql>\n"
"</qry>\n";
QModelIndex parent = ui.dirView->currentIndex().parent();
m_dirModel->refresh(parent);
file.close();
m_actnQryButton->setText(QFileInfo(file.fileName()).fileName());
return;
}
QFile file(m_currentQry);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, "CuteFarm",
tr("Can not save file %1\n%2.")
.arg(QFile(m_currentQry).fileName())
.arg(file.errorString()));
return;
}
QDomElement root = m_domDocument.documentElement();
QDomElement oldDesc = root.firstChildElement("description");
QDomElement newDesc = m_domDocument.createElement("description");
QDomText newDescText = m_domDocument.createTextNode(ui.textEditComt->toPlainText());
newDesc.appendChild(newDescText);
root.replaceChild(newDesc, oldDesc);
QDomElement oldSql = root.firstChildElement("sql");
QDomElement newSql = m_domDocument.createElement("sql");
QDomText newSqlText = m_domDocument.createTextNode(ui.textEditSql->toPlainText());
newSql.appendChild(newSqlText);
root.replaceChild(newSql, oldSql);
const int IndentSize = 4;
QTextStream out(&file);
m_domDocument.save(out, IndentSize);
file.close();
QModelIndex parent = ui.dirView->currentIndex().parent();
m_dirModel->refresh(parent);
emit statusMsg(tr("Saved: %1").arg(m_currentQry), 5000);
}
void ReportViewWidget::on_actionCloseQry_triggered()
{
m_currentQry.clear();
m_actnQryButton->setText(QString());
ui.textEditComt->clear();
ui.textEditError->clear();
ui.textEditSql->clear();
}
void ReportViewWidget::on_dirView_doubleClicked(const QModelIndex &index)
{
if (!index.isValid())
return;
if (QFileInfo(m_dirModel->data(index, QDirModel::FilePathRole).toString()).isDir())
return;
ui.dirView->setCurrentIndex(index);
on_actionRunQryFromFile_triggered();
}
void ReportViewWidget::on_actionRunQryFromFile_triggered()
{
QString path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
if (!QFileInfo(path).isFile() || !QFile(path).exists())
return;
QString errorStr;
int errorLine;
int errorColumn;
QFile file(path);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, "CuteFarm",
tr("Can not read file %1\nError: %2")
.arg(QFile(path).fileName())
.arg(file.errorString()));
return;
}
if (!m_domDocument.setContent(&file, true, &errorStr, &errorLine,
&errorColumn)) {
QMessageBox::information(this, "CuteFarm",
tr("Error in line %1, column %2\nError: %3")
.arg(errorLine)
.arg(errorColumn)
.arg(errorStr));
return;
}
QDomElement root = m_domDocument.documentElement();
if (root.tagName() != "qry") {
QMessageBox::information(this, "CuteFarm",
tr("This file is not a query file."));
return;
} else if (root.hasAttribute("version")
&& root.attribute("version") != "1.0") {
QMessageBox::information(this, "CuteFarm",
tr("The file is not an query version 1.0 "
"file."));
return;
}
QString sql = root.firstChildElement("sql").text();
file.close();
if (sql.contains("INSERT", Qt::CaseInsensitive) ||
sql.contains("UPDATE", Qt::CaseInsensitive) ||
sql.contains("CREATE", Qt::CaseInsensitive) ||
sql.contains("DELETE", Qt::CaseInsensitive))
return;
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
m_qryModel->setQuery(sql);
ui.resultView->resizeColumnsToContents();
ui.resultView->horizontalHeader()->setStretchLastSection(true);
QApplication::restoreOverrideCursor();
if (m_qryModel->lastError().type() != QSqlError::NoError)
emit statusMsg(tr("Error"), 2500);
else
emit statusMsg("Ok", 2500);
ui.textEditError->setText(m_qryModel->lastError().text());
}
void ReportViewWidget::on_actionNewQry_triggered()
{
QString path;
if (QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).isDir())
path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
else if (QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).isFile())
path = QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).absolutePath();
else if (!ui.dirView->currentIndex().isValid()) {
path = m_dirModel->data(ui.dirView->rootIndex(), QDirModel::FilePathRole).toString();
qDebug() << path;
}
else
return;
if (QFile(path + QDir::separator() + tr("New Query")).exists()) {
if (QMessageBox::question(this, "CuteFarm",
tr("File %1 exists.\nReplace?")
.arg(path + QDir::separator() + tr("New Query")), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
return;
}
qDebug() << path;
QFile file(path + QDir::separator() + tr("New Query"));
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, "CuteFarm",
tr("Can not save file %1\nError: %2")
.arg(file.fileName())
.arg(file.errorString()));
return;
}
QTextStream out(&file);
out << "<?xml version='1.0' encoding='UTF-8'?>\n"
"<!DOCTYPE qry>\n"
"<qry version=\"1.0\">\n"
" <description></description>\n"
" <sql></sql>\n"
"</qry>\n";
m_dirModel->refresh(m_dirModel->index(path, 0));
file.close();
}
void ReportViewWidget::on_actionNewFolder_triggered()
{
QString path;
if (QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).isDir())
path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
else if (QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).isFile())
path = QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).absolutePath();
else if (!ui.dirView->currentIndex().isValid()) {
path = m_dirModel->data(ui.dirView->rootIndex(), QDirModel::FilePathRole).toString();
}
bool ok;
QString name = QInputDialog::getText(this, tr("New Folder"), tr("Folder Name:"), QLineEdit::Normal, QString(), &ok);
if (!ok || name.trimmed().isEmpty())
return;
m_dirModel->mkdir(m_dirModel->index(path, 0), name);
}
void ReportViewWidget::on_actionDeleteFolder_triggered()
{
QString path;
if (QFileInfo(m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString()).isDir())
path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
if (path.isEmpty())
return;
QModelIndex parent = ui.dirView->currentIndex().parent();
// QDir::rmdir(path);
if (QMessageBox::question(this, "CuteFarm", tr("Delete folder '%1'").arg(path), QMessageBox::Yes|QMessageBox::No)
== QMessageBox::Yes)
QDir(path).rmpath(path);
m_dirModel->refresh(parent);
}
void ReportViewWidget::on_actionRunQryFromText_triggered()
{
QString query = ui.textEditSql->toPlainText();
if (query.isEmpty())
return;
if (query.contains("INSERT", Qt::CaseInsensitive) ||
query.contains("UPDATE", Qt::CaseInsensitive) ||
query.contains("CREATE", Qt::CaseInsensitive) ||
query.contains("DELETE", Qt::CaseInsensitive) ||
query.contains("PRAGMA", Qt::CaseInsensitive))
return;
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
m_qryModel->setQuery(query);
ui.resultView->resizeColumnsToContents();
ui.resultView->horizontalHeader()->setStretchLastSection(true);
QApplication::restoreOverrideCursor();
if (m_qryModel->lastError().type() != QSqlError::NoError)
emit statusMsg(tr("Error"), 2500);
else
emit statusMsg("Ok", 2500);
ui.textEditError->setText(m_qryModel->lastError().text());
}
ReportViewWidget::~ReportViewWidget()
{
}
| gpl-3.0 |
tylert/wall-calendar-core | holiday_canada.py | 11460 | #!/usr/bin/env python
from datetime import date, timedelta
import click
from paper_cal import *
@click.command()
@click.option(
'--year',
'-y',
default=date.today().year,
help='Year to show',
)
def main(year):
''' '''
# https://www.canada.ca/en/revenue-agency/services/tax/public-holidays.html
# https://www.canada.ca/fr/agence-revenu/services/impot/jours-feries.html
# https://en.wikipedia.org/wiki/Public_holidays_in_Canada
# https://fr.wikipedia.org/wiki/F%C3%AAtes_et_jours_f%C3%A9ri%C3%A9s_au_Canada
# https://en.wikipedia.org/wiki/New_Year's_Eve
# https://fr.wikipedia.org/wiki/R%C3%A9veillon_de_la_Saint-Sylvestre
# https://en.wikipedia.org/wiki/New_Year's_Day
# https://fr.wikipedia.org/wiki/Jour_de_l%27an
print(f'{date(year, DECEMBER, 31)} New Year\'s Eve') # Veille du Nouvel An
print(f'{date(year, JANUARY, 1)} New Year\'s Day') # Jour de l'an
if SATURDAY == date.weekday(date(year, JANUARY, 1)) or SUNDAY == date.weekday(
date(year, JANUARY, 1)
):
print(
f'{closest_date(MONDAY, date(year, JANUARY, 1))} New Year\'s Day Observed'
) # Jour de l'an observé
# https://en.wikipedia.org/wiki/National_Flag_of_Canada_Day
# https://fr.wikipedia.org/wiki/Jour_du_drapeau_national_du_Canada
print(f'{date(year, FEBRUARY, 15)} Flag Day (CA)')
# Jour du drapeau national du Canada
# The 3rd Monday in February is observed in 8 provinces and 0
# territories...
# CA-AB: Family Day; statutory
# CA-BC: Family Day; statutory
# CA-MB: Louis Riel Day; statutory
# CA-NB: Family Day; statutory
# CA-NL: not observed
# CA-NS: Heritage Day; statutory
# CA-NT: not observed
# CA-NU: not observed
# CA-ON: Family Day; statutory
# CA-PE: Islander Day; statutory
# CA-QC: not observed
# CA-SK: Family Day; statutory
# CA-YT: not observed
# https://en.wikipedia.org/wiki/Family_Day
# https://en.wikipedia.org/wiki/Family_Day_%28Canada%29
print(
f'{closest_date(MONDAY, date(year, FEBRUARY, WEEK3))} Family Day (CA-AB, CA-BC, CA-NB, CA-ON, CA-SK)'
) # Fête de la famille (CA-AB, CA-BC, CA-NB, CA-ON, CA-SK)
print(f'{closest_date(MONDAY, date(year, FEBRUARY, WEEK3))} Louis Riel Day (CA-MB)')
print(f'{closest_date(MONDAY, date(year, FEBRUARY, WEEK3))} Islander Day (CA-PE)')
print(f'{closest_date(MONDAY, date(year, FEBRUARY, WEEK3))} Heritage Day (CA-NS)')
# Journée Louis Riel (CA-MB)
# Fête des insulaires (CA-PE)
# Jour de patrimoine / Fête du patrimoine (CA-NS)
# Heritage Day (CA-YT) is the Friday before the last Sunday in February
# https://en.wikipedia.org/wiki/Family_Day_%28Canada%29
print(
f'{closest_date(SUNDAY, date(year, FEBRUARY, WEEK4), last=True) - timedelta(days=2)} Heritage Day (CA-YT))'
) # Jour de patrimoine / Fête du patrimoine (CA-YT)
# https://en.wikipedia.org/wiki/Commonwealth_Day
# https://fr.wikipedia.org/wiki/Journ%C3%A9e_du_Commonwealth
print(f'{closest_date(MONDAY, date(year, MARCH, WEEK2))} Commonwealth Day')
# Journée du Commonwealth
# March Break
# Congé de mars
# https://en.wikipedia.org/wiki/Spring_break
# Spring Break
# Congé de printemps
print(
f'{spring(year).date()} {spring(year).time().strftime("%H:%M")} First day of Spring'
) # Premier jour de printemps
print(
f'{summer(year).date()} {summer(year).time().strftime("%H:%M")} First day of Summer'
) # Premier jour d'été
print(
f'{autumn(year).date()} {autumn(year).time().strftime("%H:%M")} First day of Fall'
) # Premier jour d'automne
print(
f'{winter(year).date()} {winter(year).time().strftime("%H:%M")} First day of Winter'
) # Premier jour d'hiver
print(
f'{perihelion(year).date()} {perihelion(year).time().strftime("%H:%M")} Perihelion'
) # Périhélie
print(f'{aphelion(year).date()} {aphelion(year).time().strftime("%H:%M")} Aphelion')
# Aphélie
# Victoria Day is the Monday before May 25th
# https://en.wikipedia.org/wiki/Victoria_Day
# https://en.wikipedia.org/wiki/National_Patriots%27_Day
# https://fr.wikipedia.org/wiki/F%C3%AAte_de_la_Reine_(Canada)
print(f'{closest_date(MONDAY, date(year, MAY, 21))} Victoria Day (CA)')
# National Patriot's Day (CA-QC)
# Fête de la Reine / Fête de Victoria
# Journée nationale des patriotes (CA-QC)
# https://en.wikipedia.org/wiki/National_Aboriginal_Day
# https://en.wikipedia.org/wiki/National_Indigenous_Peoples_Day
# https://fr.wikipedia.org/wiki/Journ%C3%A9e_nationale_des_peuples_autochtones
# https://www.canada.ca/en/canadian-heritage/campaigns/indigenous-peoples-day.html
# https://www.canada.ca/fr/patrimoine-canadien/campagnes/journee-peuples-autochtones.html
print(f'{date(year, JUNE, 21)} National Indigenous Peoples Day (CA)')
# Journée nationale des peuples autochtones (CA)
# https://en.wikipedia.org/wiki/Discovery_Day
print(f'{closest_date(MONDAY, date(year, JUNE, 24))} June Day (CA-NL)')
# https://en.wikipedia.org/wiki/Multiculturalism_in_Canada
# https://www.canada.ca/en/canadian-heritage/campaigns/multiculturalism-day.html
# https://www.canada.ca/fr/patrimoine-canadien/campagnes/journee-multiculturalisme.html
print(f'{date(year, JUNE, 27)} Canadian Multiculturalism Day')
# Journée canadienne du multiculturalisme
# https://en.wikipedia.org/wiki/Canada_Day
# https://fr.wikipedia.org/wiki/F%C3%AAte_du_Canada
print(f'{date(year, JULY, 1)} Canada Day') # Fête du Canada
if SATURDAY == date.weekday(date(year, JULY, 1)) or SUNDAY == date.weekday(
date(year, JULY, 1)
):
print(f'{closest_date(MONDAY, date(year, JULY, 1))} Canada Day Observed')
# Fête du Canada observé
# https://en.wikipedia.org/wiki/Memorial_Day_(Newfoundland_and_Labrador)
print(f'{date(year, JULY, 1)} Memorial Day (CA-NL)')
# https://en.wikipedia.org/wiki/Nunavut_Day
print(f'{date(year, JULY, 9)} Nunavut Day ᓄᓇᕗᑦ ᐅᓪᓗᖓ (CA-NU)')
# Fête du Nunavut (CA-NU)
# The Quebec Construction Holiday begins on the 2nd last Sunday of July and
# lasts for 2 weeks
# https://en.wikipedia.org/wiki/Construction_Holiday_%28Quebec%29
# https://fr.wikipedia.org/wiki/Vacances_de_la_construction
# https://www.ccq.org/en/avantages-sociaux/dates-conges-vacances
# https://www.ccq.org/fr-CA/avantages-sociaux/dates-conges-vacances
print(
f'{closest_date(SUNDAY, date(year, JULY, WEEK4), last=True) - timedelta(days=7)} Construction Holiday Begins (CA-QC)'
) # Début des vacances de la construction (CA-QC)
print(
f'{closest_date(SUNDAY, date(year, JULY, WEEK4), last=True) + timedelta(days=6)} Construction Holiday Ends (CA-QC)'
) # Fin des vacances de la construction (CA-QC)
# The 1st Monday in August is a quasi-semi-poly-un-statutory holiday,
# kinda...
# CA-AB: Heritage Day; optional, formerly statutory
# CA-BC: British Columbia Day; statutory
# CA-MB: Terry Fox Day; non-statutory
# CA-NB: New Brunswick Day; statutory
# CA-NL: not observed
# CA-NS: Natal Day; non-statutory
# CA-NT: Civic Holiday; statutory
# CA-NU: Civic Holiday; statutory
# CA-ON: Civic Holiday and Simcoe Day; non-statutory
# CA-PE: Civic Holiday; statutory or non-statutory
# CA-QC: not observed
# CA-SK: Saskatchewan Day; statutory
# CA-YT: not observed
# https://en.wikipedia.org/wiki/Civic_Holiday
# https://en.wikipedia.org/wiki/Public_holidays_in_Canada
# https://fr.wikipedia.org/wiki/F%C3%AAtes_et_jours_f%C3%A9ri%C3%A9s_au_Canada
print(
f'{closest_date(MONDAY, date(year, AUGUST, WEEK1))} Civic Holiday (except CA-NL, CA-QC, CA-YT)'
) # Jour férié
# Congé civique (sauf CA-NL, CA-QC, CA-YT)
# Premier lundi d'août
# https://en.wikipedia.org/wiki/International_Day_of_the_World's_Indigenous_Peoples
# https://fr.wikipedia.org/wiki/Journ%C3%A9e_internationale_des_populations_autochtones
print(
f'{date(year, AUGUST, 9)} International Day of the World\'s Indigenous Peoples'
) # Journée internationale des populations autochtones du monde
# https://en.wikipedia.org/wiki/Discovery_Day
print(f'{closest_date(MONDAY, date(year, AUGUST, WEEK3))} Discovery Day (CA-YT)')
# Journée découverte (CA-YT)
# https://en.wikipedia.org/wiki/Remembrance_Day
# https://fr.wikipedia.org/wiki/Jour_du_Souvenir
# https://en.wikipedia.org/wiki/Merchant_Navy_(United_Kingdom)
print(f'{date(year, SEPTEMBER, 3)} Merchant Navy Day')
# Merchant Navy Rememberance Day
# Jour de la marine marchande
# https://en.wikipedia.org/wiki/Labour_Day
# https://fr.wikipedia.org/wiki/F%C3%AAte_du_Travail
print(f'{closest_date(MONDAY, date(year, SEPTEMBER, WEEK1))} Labour Day')
# Fête du Travail
# https://en.wikipedia.org/wiki/Orange_Shirt_Day
# https://fr.wikipedia.org/wiki/Journ%C3%A9e_nationale_de_la_v%C3%A9rit%C3%A9_et_de_la_r%C3%A9conciliation
# https://www.orangeshirtday.org/
print(f'{date(year, SEPTEMBER, 30)} Orange Shirt Day (CA)')
# Jour du chandail orange (CA)
# National Day for Truth and Reconciliation (CA)
# Journée nationale de la vérité et de la réconciliation (CA)
# https://en.wikipedia.org/wiki/Thanksgiving#Canada
# https://fr.wikipedia.org/wiki/Action_de_gr%C3%A2ce_(Canada)
# https://en.wikipedia.org/wiki/Oktoberfest
# https://fr.wikipedia.org/wiki/Oktoberfest
# Oktoberfest (CA-ON) starts the Friday before Thanksgiving and ends the
# Saturday after
print(
f'{closest_date(MONDAY, date(year, OCTOBER, WEEK2))} Thanksgiving Day (CA)'
) # Action de grâce (CA)
print(
f'{closest_date(MONDAY, date(year, OCTOBER, WEEK2)) - timedelta(days=3)} Oktoberfest Begins (CA-ON)'
) # Début de l'Oktoberfest (CA-ON)
print(
f'{closest_date(MONDAY, date(year, OCTOBER, WEEK2)) + timedelta(days=8)} Oktoberfest Ends (CA-ON)'
) # Fin de l'Oktoberfest (CA-ON)
# https://en.wikipedia.org/wiki/Remembrance_Day
# https://fr.wikipedia.org/wiki/Jour_du_Souvenir
# https://en.wikipedia.org/wiki/Armistice_Day
print(f'{date(year, NOVEMBER, 11)} Rememberance Day') # Jour du Souvenir
print(f'{date(year, NOVEMBER, 11)} Armistice Day (CA-NL)')
# Jour de l'Armistice (CA-NL)
# https://en.wikipedia.org/wiki/Statute_of_Westminster_1931
# https://fr.wikipedia.org/wiki/Statut_de_Westminster_de_1931
# https://www.canada.ca/en/canadian-heritage/services/important-commemorative-days/anniversary-statute-westminster.html
# https://www.canada.ca/fr/patrimoine-canadien/services/journees-importantes-commemoratives/anniversaire-statut-westminster.html
# The Statute of Westminster was enacted on December 11th, 1931
print(
f'{date(year, DECEMBER, 11)} {ordinal(year - 1931)} Anniversary of the Statute of Westminster'
)
# Anniversaire du Statut de Westminster
if __name__ == '__main__':
main()
| gpl-3.0 |
geronimp/enrichM | enrichm/databases.py | 8098 | #!/usr/bin/env python3
# Imports
import os
import logging
import pickle
# Local
from enrichm.data import Data
###############################################################################
class Databases:
def __init__(self):
if os.path.isfile(os.path.join(Data.DATABASE_DIR, 'VERSION')):
with open(os.path.join(Data.DATABASE_DIR, 'VERSION')) as out_io:
self.DB_VERSION = out_io.readline().strip().replace('.tar.gz', '')
self.CUR_DATABASE_DIR = os.path.join(Data.DATABASE_DIR, self.DB_VERSION)
with open(os.path.join(self.CUR_DATABASE_DIR, 'VERSION')) as out_io:
self.PICKLE_VERSION = out_io.readline().strip()
self.IDS_DIR = os.path.join(self.CUR_DATABASE_DIR, 'ids')
self.REF_DIR = os.path.join(self.CUR_DATABASE_DIR, 'databases')
self.KO_HMM_CUTOFFS = os.path.join(self.CUR_DATABASE_DIR, 'ko_cutoffs.tsv')
self.PICKLE = 'pickle'
self.HMM_SUFFIX = '.hmm'
self.DMND_SUFFIX = '.dmnd'
self.KO_DB_NAME = 'uniref100.KO'
self.EC_DB_NAME = 'uniref100.EC'
self.PFAM_DB_NAME = 'pfam'
self.KO_HMM_DB_NAME = 'ko'
self.TIGRFAM_DB_NAME = 'tigrfam'
self.CAZY_DB_NAME = 'cazy'
self.M2DEF = os.path.join(self.CUR_DATABASE_DIR, 'module_to_definition')
self.M = os.path.join(self.CUR_DATABASE_DIR, 'module_descriptions')
self.COMPOUND_DESC = os.path.join(self.CUR_DATABASE_DIR, 'br08001')
self.R2K = os.path.join(self.CUR_DATABASE_DIR, 'reaction_to_orthology')
self.R2C = os.path.join(self.CUR_DATABASE_DIR, 'reaction_to_compound')
self.R2M = os.path.join(self.CUR_DATABASE_DIR, 'reaction_to_module')
self.M2R = os.path.join(self.CUR_DATABASE_DIR, 'module_to_reaction')
self.M2C = os.path.join(self.CUR_DATABASE_DIR, 'module_to_cpd')
self.R2P = os.path.join(self.CUR_DATABASE_DIR, 'reaction_to_pathway')
self.P2R = os.path.join(self.CUR_DATABASE_DIR, 'pathway_to_reaction')
self.C2R = os.path.join(self.CUR_DATABASE_DIR, 'compound_to_reaction')
self.C = os.path.join(self.CUR_DATABASE_DIR, 'compound_descriptions')
self.R = os.path.join(self.CUR_DATABASE_DIR, 'reaction_descriptions')
self.P = os.path.join(self.CUR_DATABASE_DIR, 'pathway_descriptions')
self.K = os.path.join(self.CUR_DATABASE_DIR, 'ko_descriptions')
self.PFAM2CLAN = os.path.join(self.CUR_DATABASE_DIR, 'pfam_to_clan')
self.PFAM2NAME = os.path.join(self.CUR_DATABASE_DIR, 'pfam_to_name')
self.PFAM2DESCRIPTION = os.path.join(self.CUR_DATABASE_DIR, 'pfam_to_description')
self.EC2DESCRIPTION = os.path.join(self.CUR_DATABASE_DIR, 'ec_to_description')
self.TIGRFAM2DESCRIPTION = os.path.join(self.CUR_DATABASE_DIR, 'tigrfam_descriptions')
else:
raise Exception(f"\nNo database version file found. Have you: \n\
- Installed the EnrichM database using the 'enrichm data' command?\n\
- Specified the location of the EnrichM database by exporting a \
bash variable called ENRICHM_DB? (Currently I'm looking here: {Data.DATABASE_DIR})")
self.signature_modules = set(['M00611', 'M00612', 'M00613', 'M00614',
'M00617', 'M00618', 'M00615', 'M00616',
'M00363', 'M00542', 'M00574', 'M00575',
'M00564', 'M00660', 'M00664', 'M00625',
'M00627', 'M00745', 'M00651', 'M00652',
'M00704', 'M00725', 'M00726', 'M00730',
'M00744', 'M00718', 'M00639', 'M00641',
'M00642', 'M00643', 'M00769', 'M00649',
'M00696', 'M00697', 'M00698', 'M00700',
'M00702', 'M00714', 'M00705', 'M00746'])
self.KO_DB = os.path.join(self.REF_DIR, self.KO_DB_NAME + self.DMND_SUFFIX)
self.EC_DB = os.path.join(self.REF_DIR, self.EC_DB_NAME + self.DMND_SUFFIX)
self.PFAM_DB = os.path.join(self.REF_DIR, self.PFAM_DB_NAME + self.HMM_SUFFIX)
self.KO_HMM_DB = os.path.join(self.REF_DIR, self.KO_HMM_DB_NAME + self.HMM_SUFFIX)
self.TIGRFAM_DB = os.path.join(self.REF_DIR, self.TIGRFAM_DB_NAME + self.HMM_SUFFIX)
self.CAZY_DB = os.path.join(self.REF_DIR, self.CAZY_DB_NAME + self.HMM_SUFFIX)
self.PFAM_CLAN_DB = os.path.join(self.IDS_DIR, 'PFAM_CLANS.txt')
def m2def(self):
logging.debug("Loading module descriptions")
return self.load_pickle(self.M2DEF)
def m(self):
logging.debug("Loading reaction to pathway information")
return self.load_pickle(self.M)
def r2p(self):
logging.debug("Loading pathway to reaction information")
return self.load_pickle(self.R2P)
def p2r(self):
logging.debug("Loading reaction to orthology information")
return self.load_pickle(self.P2R)
def r2k(self):
logging.debug("Loading reaction to module information")
return self.load_pickle(self.R2K)
def r2m(self):
logging.debug("Loading module to reaction information")
return self.load_pickle(self.R2M)
def m2r(self):
logging.debug("Loading module to compound information")
return self.load_pickle(self.M2R)
def r2c(self):
logging.debug("Loading compound to reaction information")
return self.load_pickle(self.R2C)
def c2r(self):
logging.debug("Loading compound descriptions")
return self.load_pickle(self.C2R)
def c(self):
logging.debug("Loading pathway descriptions")
return self.load_pickle(self.C)
def p(self):
logging.debug("Loading reaction descriptions")
return self.load_pickle(self.P)
def r(self):
logging.debug("Loading ko descriptions")
return self.load_pickle(self.R)
def k(self):
logging.debug("Loading compound classifications")
return self.load_pickle(self.K)
def compound_desc_dict(self):
logging.debug("Loading pfam to clan information")
return self.load_pickle(self.COMPOUND_DESC)
def pfam2clan(self):
logging.debug("Loading clan descriptions")
return self.load_pickle(self.PFAM2CLAN)
def pfam2description(self):
logging.debug("Loading ec descriptions")
return self.load_pickle(self.PFAM2DESCRIPTION)
def ec2description(self):
logging.debug("Loading pfam hierarchy")
return self.load_pickle(self.EC2DESCRIPTION)
def tigrfamdescription(self):
logging.debug("Loading reference db paths")
return self.load_pickle(self.TIGRFAM2DESCRIPTION)
def k2r(self):
k2r = dict()
for reaction, kos in self.r2k().items():
for ko in kos:
if ko not in k2r:
k2r[ko] = list()
k2r[ko].append(reaction)
return k2r
def c2m(self):
c2m = dict()
for module, compounds in self.m2c().items():
substrates = compounds[0]
for substrate in substrates:
if substrate in c2m:
c2m[substrate].append(module)
else:
c2m[substrate] = [module]
return c2m
def load_pickle(self, file):
with open('.'.join([file, self.PICKLE_VERSION, self.PICKLE]), 'rb') as file_io:
loaded_pickle = pickle.load(file_io)
return loaded_pickle
def parse_ko_cutoffs(self):
cut_ko = dict()
out_io = open(self.KO_HMM_CUTOFFS)
_ = out_io.readline()
for line in out_io:
sline = line.strip().split('\t')
if sline[1] == '-':
cut_ko[sline[0]] = [0.0, "NA"]
else:
cut_ko[sline[0]] = [float(sline[1]), sline[2]]
return cut_ko
| gpl-3.0 |
jcenteno1973/sicafam | resources/views/plantillas/plantilla_inicio.blade.php | 2186 | <!doctype html>
<!--
* Nombre del archivo: plantilla_inicio.blade.php
* Descripción:
* Fecha de creación:11/11/2016
* Creado por: Juan Carlos Centeno Borja
-->
<html lang="es" xml:lang="es"></html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="905; URL=/sicafam/public/">
<title>@yield('title')</title>
@section('head')
<link rel="stylesheet" type=text/css href="{{asset('assets/css/bootstrap.css')}}" />
<link rel="stylesheet" type=text/css href="{{asset('assets/css/bootstrap.min.css')}}" />
<script src="{{asset('assets/js/jquery.min.js')}}"></script>
<script src="{{asset('assets/js/bootstrap.min.js')}}"></script>
<script src="{{asset('assets/js/scripts.js')}}"></script>
@show
</head>
<body>
<div class="container-fluid">
<div class="row"><!--Encabezado -->
<div class="col-md-12">
<img alt="Bootstrap Image Preview" src="{{asset('images/encabezado.png')}}" width="100%">
</div>
</div>
<div class="row"><!--fecha -->
<div class="col-md-12">
@yield('fecha_sistema')
</div>
</div>
<div class="row"><!--nombre de la pantalla -->
<div class="col-md-12">
@yield('nombre_pantalla')
</div>
</div>
<div class="row">
<div class="col-md-12"><!--area de trabajo -->
<div class="row"><!--filtros -->
<div class="col-md-12">
@yield('filtros_consulta')
</div>
</div>
<div class="row"><!--contenido -->
<div class="col-md-12">
@yield('contenido')
</div>
</div>
<div class="row"><!--botones -->
<div class="col-md-12">
@yield('botones')
</div>
</div>
</div>
</div>
<div class="row"><!--pie de pagina -->
<div class="col-md-12">
@yield('pie_pagina')
</div>
</div>
</div>
</body>
| gpl-3.0 |
jan-klos/dmn_python | dmn_python/DMNImport.py | 15551 | from xml.dom import minidom
from dmn_python.definitions.Elements import *
from dmn_python.definitions.Model import Model
from dmn_python.definitions.ItemDefinition import ItemDefinition
from dmn_python.definitions.Requirements import *
from dmn_python.definitions.Logic import *
class DMNImport:
@staticmethod
def load_model_from_xml(file_path):
DMNImport.xml_doc = minidom.parse(file_path)
DMNImport.model = Model()
DMNImport.import_header()
DMNImport.import_item_definition()
DMNImport.import_input_data_elem()
DMNImport.import_knowledge_source_elem()
DMNImport.import_business_knowledge_model_elem()
DMNImport.import_decision_elem()
DMNImport.import_requirement()
return DMNImport.model
##############################################################
@staticmethod
def import_header():
header = DMNImport.get_first_element_by_tag(DMNImport.xml_doc, 'definitions')
DMNImport.get_name_id(header, DMNImport.model)
DMNImport.model.namespace = DMNImport.get_attribute_value(header, 'namespace')
DMNImport.model.xmlns = DMNImport.get_attribute_value(header, 'xmlns')
DMNImport.model.xmlns_ex = DMNImport.get_attribute_value(header, 'xmlns:ex')
DMNImport.model.description = DMNImport.get_value_by_tag(DMNImport.xml_doc, 'description')
##############################################################
@staticmethod
def import_item_definition():
for item in DMNImport.get_list_by_tag(DMNImport.xml_doc, 'itemDefinition'):
item_def = DMNImport.get_name_id(item, ItemDefinition())
if DMNImport.get_list_by_tag(item, 'itemComponent'):
item_def.item_component_list = DMNImport.import_item_component(item)
else:
item_def = DMNImport.import_item_component_type_ref_allowed_values(item, item_def)
DMNImport.model.add_definition(item_def)
@staticmethod
def import_item_component(xml_node):
item_component_list = []
for item in DMNImport.get_list_by_tag(xml_node, 'itemComponent'):
if item.parentNode != xml_node:
continue
item_component = DMNImport.get_name_id(item, ItemDefinition())
if not DMNImport.at_least_one_element_by_tag(item, 'itemComponent'):
DMNImport.import_item_component_type_ref_allowed_values(item, item_component)
else:
item_component.item_component_list = DMNImport.import_item_component(item)
item_component_list.append(item_component)
return item_component_list
@staticmethod
def import_item_component_type_ref_allowed_values(xml_node, item_component):
type_ref_item = DMNImport.get_first_element_by_tag(xml_node, 'typeRef')
type_ref_xmlns = DMNImport.get_attribute_value(type_ref_item, 'xmlns:ns2')
type_ref = type_ref_item.childNodes[0].toxml()
try:
allowed_values = DMNImport.get_value_by_two_tags(xml_node, 'allowedValues', 'text')
except IndexError:
allowed_values = None
item_component.type_ref_xmlns = type_ref_xmlns
item_component.type_ref = type_ref
item_component.allowed_values = allowed_values
return item_component
############################################################
@staticmethod
def import_input_data_elem():
for item in DMNImport.get_list_by_tag(DMNImport.xml_doc, 'inputData'):
input_data_elem = DMNImport.get_name_id(item, InputDataElement(item))
input_data_elem.variable = DMNImport.import_input_element_variable(item)
DMNImport.model.add_element(input_data_elem)
@staticmethod
def import_input_element_variable(xml_node):
variable_item = DMNImport.get_first_element_by_tag(xml_node, 'variable')
variable = DMNImport.get_name_id(variable_item, InputElementVariable())
variable.type_ref_value = DMNImport.get_attribute_value(variable_item, 'typeRef')
variable.type_ref = DMNImport.model.get_definition_by_name(variable.name)
return variable
############################################################
@staticmethod
def import_knowledge_source_elem():
for item in DMNImport.get_list_by_tag(DMNImport.xml_doc, 'knowledgeSource'):
knowledge_source_elem = DMNImport.get_name_id(item, KnowledgeSourceElement(item))
DMNImport.model.add_element(knowledge_source_elem)
############################################################
@staticmethod
def import_business_knowledge_model_elem():
for item in DMNImport.get_list_by_tag(DMNImport.xml_doc, 'businessKnowledgeModel'):
business_knowledge_elem = DMNImport.get_name_id(item, BusinessKnowledgeModelElement(item))
business_knowledge_elem = DMNImport.import_logic(item, business_knowledge_elem)
DMNImport.model.add_element(business_knowledge_elem)
@staticmethod
def import_logic(xml_node, business_knowledge_elem):
business_knowledge_elem.formal_parameter_list = DMNImport.import_formal_parameter_list(xml_node, business_knowledge_elem)
try:
business_knowledge_elem.decision_table = DMNImport.import_decision_table(xml_node)
return business_knowledge_elem
except IndexError:
business_knowledge_elem.context = DMNImport.import_context(DMNImport.get_first_element_by_tag(xml_node, 'context'))
return business_knowledge_elem
@staticmethod
def import_formal_parameter_list(xml_node, business_knowledge_elem):
formal_parameter_list = []
for item in DMNImport.get_list_by_tag(xml_node, 'formalParameter'):
formal_parameter_list.append(FormalParameter(DMNImport.get_attribute_value(item, 'name'), DMNImport.get_attribute_value(item, 'id'),
DMNImport.get_attribute_value(item, 'typeRef'), DMNImport.get_attribute_value(item, 'xmlns:ns2')))
return formal_parameter_list
@staticmethod
def import_context(xml_node):
context = Context()
context.context_entry_list = DMNImport.import_context_entry_list(xml_node)
return context
@staticmethod
def import_context_entry_list(xml_node):
context_entry_list = []
for item in DMNImport.get_list_by_tag(xml_node, 'contextEntry'):
context_entry = ContextEntry()
try:
context_entry.name = DMNImport.get_attribute_value(DMNImport.get_first_element_by_tag(item, 'variable'), 'name')
except IndexError:
pass
if len(DMNImport.get_list_by_tag(item, 'invocation')):
context_entry.invocation = DMNImport.import_invocation(item)
else:
context_entry.literal_expression = DMNImport.get_literal_expression(item)
context_entry_list.append(context_entry)
return context_entry_list
############################################################
@staticmethod
def import_decision_elem():
for item in DMNImport.get_list_by_tag(DMNImport.xml_doc, 'decision'):
decision_elem = DMNImport.get_name_id(item, DecisionElement(item))
decision_elem.variable = DMNImport.import_decision_element_variable(item)
decision_elem = DMNImport.import_descr_quest_answ(item, decision_elem)
try:
decision_elem.invocation = DMNImport.import_invocation(item)
except IndexError:
pass
try:
decision_elem.decision_table = DMNImport.import_decision_table(item)
except IndexError:
pass
DMNImport.model.add_element(decision_elem)
@staticmethod
def import_decision_element_variable(xml_node):
try:
variable_item = DMNImport.get_first_element_by_tag(xml_node, 'variable')
variable = DMNImport.get_name_id(variable_item, DecisionElementVariable())
variable.type_ref = DMNImport.get_attribute_value(variable_item, 'typeRef')
variable.xmlns = DMNImport.get_attribute_value(variable_item, 'xmlns:ns2')
return variable
except IndexError:
pass
@staticmethod
def import_descr_quest_answ(xml_node, decision_elem):
try:
decision_elem.description = DMNImport.get_value_by_tag(xml_node, 'description')
decision_elem.question = DMNImport.get_value_by_tag(xml_node, 'question')
decision_elem.allowed_answers = DMNImport.get_value_by_tag(xml_node, 'allowedAnswers')
except IndexError:
pass
return decision_elem
#############################################################
@staticmethod
def import_invocation(xml_node):
xml_node = DMNImport.get_first_element_by_tag(xml_node, 'invocation')
invocation = Invocation(DMNImport.get_literal_expression(xml_node))
for item in DMNImport.get_list_by_tag(xml_node, 'binding'):
invocation.binding_list.append(Binding(DMNImport.get_attribute_value(DMNImport.get_first_element_by_tag(item, 'parameter'), 'name'), DMNImport.get_literal_expression(item)))
return invocation
@staticmethod
def import_decision_table(xml_node):
xml_node = DMNImport.get_first_element_by_tag(xml_node, 'decisionTable')
decision_table = DecisionTable(DMNImport.get_attribute_value(xml_node, 'id'), DMNImport.get_attribute_value(xml_node, 'hitPolicy'),
DMNImport.get_attribute_value(xml_node, 'preferredOrientation'), DMNImport.get_attribute_value(xml_node, 'aggregation'))
decision_table.input_list = DMNImport.import_decision_table_inputs(xml_node)
output_item = DMNImport.get_first_element_by_tag(xml_node, 'output')
decision_table.output = DecisionTableOutput(DMNImport.get_attribute_value(output_item, 'name'), DMNImport.get_value_by_tag(output_item, 'text'))
decision_table.rule_list = DMNImport.import_rules(xml_node, decision_table.input_list)
return decision_table
@staticmethod
def import_decision_table_inputs(xml_node):
input_list = []
for item in DMNImport.get_list_by_tag(xml_node, 'input'):
input = DecisionTableInput(DMNImport.get_attribute_value(item, 'label'), DMNImport.get_value_by_tag(item, 'text'), DMNImport.get_second_value_by_tag(item, 'text'))
input_list.append(input)
return input_list
@staticmethod
def import_rules(xml_node, decision_table_input_list):
rule_list = []
for item in DMNImport.get_list_by_tag(xml_node, 'rule'):
rule = Rule()
rule_input_list = []
for item1 in DMNImport.get_list_by_tag(item, 'inputEntry'):
rule_input = DMNImport.get_value_by_tag(item1, 'text')
rule_input_list.append(rule_input)
rule.output = DMNImport.get_value_by_two_tags(item, 'outputEntry', 'text')
rule.input_list = rule_input_list
rule_list.append(rule)
return rule_list
#############################################################
@staticmethod
def import_requirement():
for elem in DMNImport.model.element_list:
DMNImport.import_requirement_of_elem(elem)
@staticmethod
def import_requirement_of_elem(elem):
try:
elem.authority_requirement_list = DMNImport.import_requirement_list(elem.xml_node, 'authority')
except:
pass
try:
elem.knowledge_requirement_list = DMNImport.import_requirement_list(elem.xml_node, 'knowledge')
except:
pass
try:
elem.information_requirement_list = DMNImport.import_requirement_list(elem.xml_node, 'information')
except:
pass
DMNImport.add_requirements_to_model(elem)
@staticmethod
def import_requirement_list(xml_node, requirement_type):
requirement_list = []
for item in DMNImport.get_list_by_tag(xml_node, requirement_type + 'Requirement'):
try:
if DMNImport.at_least_one_element_by_tag(item, 'requiredDecision'):
requir = DMNImport.get_first_element_by_tag(item, 'requiredDecision')
elif DMNImport.at_least_one_element_by_tag(item, 'requiredInput'):
requir = DMNImport.get_first_element_by_tag(item, 'requiredInput')
elif DMNImport.at_least_one_element_by_tag(item, 'requiredKnowledge'):
requir = DMNImport.get_first_element_by_tag(item, 'requiredKnowledge')
elif DMNImport.at_least_one_element_by_tag(item, 'requiredAuthority'):
requir = DMNImport.get_first_element_by_tag(item, 'requiredAuthority')
requirement_list.append(DMNImport.model.get_element_by_id(requir.attributes['href'].value[1:]))
except:
raise Exception('Can\'t find needed ' + requirement_type + ' requirement')
return requirement_list
@staticmethod
def add_requirements_to_model(elem):
try:
for requirement in elem.authority_requirement_list:
DMNImport.model.add_requirement(AuthorityRequirement(requirement, elem))
except:
pass
try:
for requirement in elem.knowledge_requirement_list:
DMNImport.model.add_requirement(KnowledgeRequirement(requirement, elem))
except:
pass
try:
for requirement in elem.information_requirement_list:
DMNImport.model.add_requirement(InformationRequirement(requirement, elem))
except:
pass
#################################################################################################
@staticmethod
def at_least_one_element_by_tag(xml_node, tag):
return False if len(DMNImport.get_list_by_tag(xml_node, tag)) < 1 else True
@staticmethod
def get_value_by_two_tags(xml_node, tag1, tag2):
return xml_node.getElementsByTagName(tag1)[0].getElementsByTagName(tag2)[0].childNodes[0].toxml()
@staticmethod
def get_value_by_tag(xml_node, tag):
try:
return xml_node.getElementsByTagName(tag)[0].childNodes[0].toxml()
except IndexError:
return None
@staticmethod
def get_second_value_by_tag(xml_node, tag):
try:
return xml_node.getElementsByTagName(tag)[1].childNodes[0].toxml()
except IndexError:
return None
@staticmethod
def get_list_by_tag(xml_node, tag):
return xml_node.getElementsByTagName(tag)
@staticmethod
def get_first_element_by_tag(xml_node, tag):
return xml_node.getElementsByTagName(tag)[0]
@staticmethod
def get_name_id(xml_node, object):
object.id = DMNImport.get_attribute_value(xml_node, 'id')
object.name = DMNImport.get_attribute_value(xml_node, 'name')
return object
@staticmethod
def get_attribute_value(xml_node, value_name):
try:
return xml_node.attributes[value_name].value
except KeyError:
return None
@staticmethod
def get_literal_expression(xml_node):
try:
return DMNImport.get_value_by_two_tags(xml_node, 'literalExpression', 'text')
except KeyError:
return None
| gpl-3.0 |
parogers/demoquest | src/browser.js | 916 | /* demoquest - An adventure game demo with parallax scrolling
* Copyright (C) 2017 Peter Rogers
*
* 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/>.
*/
module.exports = {};
/* Checks if the browser is on a mobile device */
module.exports.isMobileDevice = function()
{
return /Mobi/.test(navigator.userAgent);
}
| gpl-3.0 |
felipetavares/flow | src/gen/index.js | 453 | var map;
module.exports.map = function (_map) {
map = _map;
}
function point (O, pos) {
if (map) {
var o = new O();
o.pos(pos);
map.insert(o);
return o;
}
}
module.exports.line = function (O, start, delta) {
if (map) {
var pos = Util.generatePositions(start, delta);
pos.splice(0, 0, start);
for (var p in pos) {
point(O, pos[p]);
}
}
}
module.exports.point = point;
var Util = require('../util');
| gpl-3.0 |
bes422/JDI | Java/Tests/jdi-uitest-webtests/src/test/java/com/epam/jdi/uitests/testing/unittests/tests/composite/SearchTests.java | 910 | package com.epam.jdi.uitests.testing.unittests.tests.composite;
import com.epam.jdi.uitests.testing.unittests.InitTests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import static com.epam.jdi.uitests.core.preconditions.PreconditionsState.isInState;
import static com.epam.jdi.uitests.testing.unittests.enums.Preconditions.HOME_PAGE;
import static com.epam.jdi.uitests.testing.unittests.pageobjects.EpamJDISite.header;
import static com.epam.jdi.uitests.testing.unittests.pageobjects.EpamJDISite.supportPage;
/**
* Created by Dmitry_Lebedev1 on 10/15/2015.
*/
public class SearchTests extends InitTests {
@BeforeMethod
public void before(final Method method) {
isInState(HOME_PAGE, method);
}
@Test
public void fillTest() {
header.search.find("something");
supportPage.checkOpened();
}
} | gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-9.js | 645 | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-9.js
* @description Object.isExtensible returns true for all built-in objects (Date)
*/
function testcase() {
var e = Object.isExtensible(Date);
if (e === true) {
return true;
}
}
runTestCase(testcase);
| gpl-3.0 |
Droon99-Developer/AGHF-APCS | src/AGHF/CreditsPnl.java | 1042 | package AGHF;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CreditsPnl extends JPanel {
private Font font = new Font("Dialog", Font.BOLD | Font.HANGING_BASELINE, 100);
private Font font2 = new Font("Dialog", Font.PLAIN | Font.ROMAN_BASELINE, 20);
public void show(){
JLabel title = new JLabel("CREDITS");
title.setFont(font);
title.setBounds(65, 20, this.getWidth(), 140);
title.setVisible(true);
add(title);
String[] names = {
"Project Manager: Connor Black",
"Lead Programmer: Andrew Burford",
"Programmer: Tim Frieden",
"Programmer: Julie Fleischman",
"Programmer: Sam Zhang",
"Programmer: Alex Abriola",
"Programmer: Andy Yu",
"Assets: James Horbury",
"Assets: Ray Tian"
};
JLabel[] labels = new JLabel[names.length];
for(int i = 0; i < names.length; i++){
labels[i] = new JLabel(names[i]);
labels[i].setFont(font2);
labels[i].setBounds(200, i*50 + 200, 400, 40);
labels[i].setVisible(true);
add(labels[i]);
}
}
}
| gpl-3.0 |
robbyn/minica | src/main/java/org/tastefuljava/minica/Filters.java | 2935 | /*
Minica, a very simple certificate authority
Copyright (C) 2011 Maurice Perry <maurice@perry.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/>.
*/
package org.tastefuljava.minica;
import java.io.File;
import javax.swing.filechooser.FileFilter;
class Filters {
static final FileFilter PEM_FILEFILTER;
static final FileFilter PKCS12_FILEFILTER;
static final FileFilter JKS_FILEFILTER;
static final FileFilter CERT_FILEFILTER;
static {
PEM_FILEFILTER = new FileFilter() {
@Override
public String getDescription() {
return "OpenSSL/OpenSSH files (*.pem)";
}
@Override
public boolean accept(File file) {
return file.isDirectory() || file.isFile()
&& file.getName().toLowerCase().endsWith(".pem");
}
};
PKCS12_FILEFILTER = new FileFilter() {
@Override
public String getDescription() {
return "PKCS12 files (*.p12)";
}
@Override
public boolean accept(File file) {
return file.isDirectory() || file.isFile()
&& file.getName().toLowerCase().endsWith(".p12");
}
};
JKS_FILEFILTER = new FileFilter() {
@Override
public String getDescription() {
return "JKS files (*.jks)";
}
@Override
public boolean accept(File file) {
return file.isDirectory() || file.isFile()
&& file.getName().toLowerCase().endsWith(".jks");
}
};
CERT_FILEFILTER = new FileFilter() {
@Override
public String getDescription() {
return "X509 certificate files (*.crt,*.cer,*.der)";
}
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (!file.isFile()) {
return false;
}
String name = file.getName().toLowerCase();
return name.endsWith(".crt") || name.endsWith(".cer")
|| name.endsWith(".der");
}
};
}
}
| gpl-3.0 |
MazZzinatus/storm | resources/3rdparty/eigen-3.3-beta1/unsupported/test/polynomialutils.cpp | 3584 | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/StormEigen/Polynomials>
#include <iostream>
using namespace std;
namespace StormEigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
enum {
ret = (Size == Dynamic) ? Dynamic : Size+1
};
};
}
}
template<typename _Scalar, int _Deg>
void realRoots_to_monicPolynomial_test(int deg)
{
typedef internal::increment_if_fixed_size<_Deg> Dim;
typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;
typedef Matrix<_Scalar,_Deg,1> EvalRootsType;
PolynomialType pols(deg+1);
EvalRootsType roots = EvalRootsType::Random(deg);
roots_to_monicPolynomial( roots, pols );
EvalRootsType evr( deg );
for( int i=0; i<roots.size(); ++i ){
evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }
bool evalToZero = evr.isZero( test_precision<_Scalar>() );
if( !evalToZero ){
cerr << evr.transpose() << endl; }
VERIFY( evalToZero );
}
template<typename _Scalar> void realRoots_to_monicPolynomial_scalar()
{
CALL_SUBTEST_2( (realRoots_to_monicPolynomial_test<_Scalar,2>(2)) );
CALL_SUBTEST_3( (realRoots_to_monicPolynomial_test<_Scalar,3>(3)) );
CALL_SUBTEST_4( (realRoots_to_monicPolynomial_test<_Scalar,4>(4)) );
CALL_SUBTEST_5( (realRoots_to_monicPolynomial_test<_Scalar,5>(5)) );
CALL_SUBTEST_6( (realRoots_to_monicPolynomial_test<_Scalar,6>(6)) );
CALL_SUBTEST_7( (realRoots_to_monicPolynomial_test<_Scalar,7>(7)) );
CALL_SUBTEST_8( (realRoots_to_monicPolynomial_test<_Scalar,17>(17)) );
CALL_SUBTEST_9( (realRoots_to_monicPolynomial_test<_Scalar,Dynamic>(
internal::random<int>(18,26) )) );
}
template<typename _Scalar, int _Deg>
void CauchyBounds(int deg)
{
typedef internal::increment_if_fixed_size<_Deg> Dim;
typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;
typedef Matrix<_Scalar,_Deg,1> EvalRootsType;
PolynomialType pols(deg+1);
EvalRootsType roots = EvalRootsType::Random(deg);
roots_to_monicPolynomial( roots, pols );
_Scalar M = cauchy_max_bound( pols );
_Scalar m = cauchy_min_bound( pols );
_Scalar Max = roots.array().abs().maxCoeff();
_Scalar min = roots.array().abs().minCoeff();
bool eval = (M >= Max) && (m <= min);
if( !eval )
{
cerr << "Roots: " << roots << endl;
cerr << "Bounds: (" << m << ", " << M << ")" << endl;
cerr << "Min,Max: (" << min << ", " << Max << ")" << endl;
}
VERIFY( eval );
}
template<typename _Scalar> void CauchyBounds_scalar()
{
CALL_SUBTEST_2( (CauchyBounds<_Scalar,2>(2)) );
CALL_SUBTEST_3( (CauchyBounds<_Scalar,3>(3)) );
CALL_SUBTEST_4( (CauchyBounds<_Scalar,4>(4)) );
CALL_SUBTEST_5( (CauchyBounds<_Scalar,5>(5)) );
CALL_SUBTEST_6( (CauchyBounds<_Scalar,6>(6)) );
CALL_SUBTEST_7( (CauchyBounds<_Scalar,7>(7)) );
CALL_SUBTEST_8( (CauchyBounds<_Scalar,17>(17)) );
CALL_SUBTEST_9( (CauchyBounds<_Scalar,Dynamic>(
internal::random<int>(18,26) )) );
}
void test_polynomialutils()
{
for(int i = 0; i < g_repeat; i++)
{
realRoots_to_monicPolynomial_scalar<double>();
realRoots_to_monicPolynomial_scalar<float>();
CauchyBounds_scalar<double>();
CauchyBounds_scalar<float>();
}
}
| gpl-3.0 |
davidfsmith/API-OAuth-Analytics | app/google/__init__.py | 4863 | from flask import Flask, Blueprint, render_template, redirect, url_for, session, request, flash
from flask_oauthlib.client import OAuth, OAuthException
from flask_debugtoolbar import DebugToolbarExtension
from flask import json
import os
import urllib2
mod = Blueprint('google', __name__, template_folder='templates', url_prefix='/google')
app = Flask(__name__)
app.config.from_object('app.config')
for k, v in os.environ.iteritems():
if k.startswith('GOOGLE_'):
try:
v = int(v)
except ValueError:
pass
app.config[k[6:]] = v
oauth = OAuth(app)
google = oauth.remote_app(
'google',
base_url='https://www.googleapis.com/analytics/v3',
consumer_key=app.config['GOOGLE_CLIENT_ID'],
consumer_secret=app.config['GOOGLE_CLIENT_SECRET'],
request_token_params={
'scope': 'https://www.googleapis.com/auth/analytics.readonly'
},
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth'
)
@google.tokengetter
def get_access_token(token=None):
return session.get('google')
media_types = (
'application/json'
)
@mod.route('/', methods=['GET'])
def index():
return redirect(url_for('index'))
@mod.route('/accounts', methods=['GET'])
def accounts():
google_access_token = session.get('google')
if google_access_token is None:
return redirect(url_for('google_login'))
try:
r = google.get('https://www.googleapis.com/analytics/v3/management/accounts',
headers={'Accept': ', '.join(media_types)}
)
if r.status == 200:
app.logger.debug('Account: %s' % r.data)
return render_template('accounts.html', data=r.data['items'])
else:
return render_template('error.html', message='Unable to get accounts info: %s' % accounts.status)
except OAuthException:
return render_template('error.html', message='OAuthException')
@mod.route('/account/<account_id>/view', methods=['GET'])
def analytics_account_view(account_id):
google_access_token = session.get('google')
if google_access_token is None:
return redirect(url_for('google_login'))
try:
r = google.get('https://www.googleapis.com/analytics/v3/management/accounts/{0}/webproperties'.format(account_id),
headers={'Accept': ', '.join(media_types)}
)
if r.status == 200:
app.logger.debug('r: %s' % r.data['items'])
# ga_data = ga_data.data['rows'][0]
return render_template('web_properties.html', data=r.data['items'])
else:
return render_template('error.html', message='Unable to get accounts info: %s' % accounts.status)
except OAuthException:
return render_template('error.html', message='OAuthException')
@mod.route('/account/<account_id>/view/<property_id>/view', methods=['GET'])
def analytics_property_view(account_id, property_id):
google_access_token = session.get('google')
if google_access_token is None:
return redirect(url_for('.login'))
try:
r = google.get('https://www.googleapis.com/analytics/v3/management/accounts/{0}/webproperties/{1}/profiles'.format(account_id, property_id),
headers={'Accept': ', '.join(media_types)}
)
if r.status == 200:
app.logger.debug('r: %s' % r.data['items'])
# ga_data = ga_data.data['rows'][0]
return render_template('web_profile.html', data=r.data['items'], account_id=account_id, property_id=property_id)
else:
return render_template('error.html', message='Unable to get accounts info: %s' % accounts.status)
except OAuthException:
return render_template('error.html', message='OAuthException')
@mod.route('/login', methods=['GET'])
def login():
callback=url_for('.authorized', _external=True)
return google.authorize(callback=callback)
@mod.route('/logout', methods=['GET'])
def logout():
session.pop('google', None)
flash('You were signed out of Google', category='success')
return redirect(url_for('index'))
@mod.route('/authorized', methods=['GET', 'POST'])
@google.authorized_handler
def authorized(resp):
# TODO capture OAuthException's
if resp is None:
flash('Access denied: reason : %s errror : %s' % (
request.args['error_reason'],
request.args['error_description']), category='danger'
)
return redirect(url_for('index'))
session['google'] = (resp['access_token'], '')
app.logger.debug('GA response: %s' % resp)
flash('You were signed in to Google', category='success')
return redirect(url_for('index'))
def main():
app.run()
if __name__ == '__main__':
main()
| gpl-3.0 |
Porobu/Al-kaboom | Al-kaboom/src/si/alkaboom/frontend/ranking/RankingInternalFrame.java | 813 | package si.alkaboom.frontend.ranking;
import java.awt.BorderLayout;
import javax.swing.JInternalFrame;
import si.alkaboom.backend.AlKaboom;
import si.alkaboom.frontend.TaulaPanela;
public class RankingInternalFrame extends JInternalFrame {
private static final long serialVersionUID = 6481265986429597754L;
private final int offset = 40;
public RankingInternalFrame(String izenburua) {
super(izenburua, true, false, true, true);
this.setLayout(new BorderLayout());
TaulaPanela taula = new TaulaPanela(izenburua, "");
this.add(taula, BorderLayout.CENTER);
this.pack();
setLocation(offset * AlKaboom.getAlKaboom().getUI().getRanking().getIrekitakoLeihoKop(),
offset * AlKaboom.getAlKaboom().getUI().getRanking().getIrekitakoLeihoKop());
this.setVisible(true);
}
}
| gpl-3.0 |
zetaops/ulakbus | ulakbus/views/bap/bap_satin_alma_islemleri.py | 30775 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
from pyoko import ListNode
from ulakbus.models import BAPTeklif, BAPButcePlani, BAPTeklifFiyatIsleme
from zengine.views.crud import CrudView, obj_filter, list_query
from zengine.forms import JsonForm, fields
from zengine.lib.translation import gettext as _, gettext_lazy as __
from ulakbus.lib.s3_file_manager import S3FileManager
from datetime import datetime, time
from ulakbus.settings import DATETIME_DEFAULT_FORMAT
import ulakbus.lib.doc_render as render
from pyoko.exceptions import ObjectDoesNotExist
class KazananFirmalarForm(JsonForm):
"""
Bütçe kalemleri için kazanan firmaların belirlenmesi formunu oluşturur.
"""
class Meta:
inline_edit = ['firma']
title = __(u"{} İçin Kazanan Firmaların Belirlenmesi")
help_text = __(u"Lütfen listelenmiş bütçe kalemleri için kazanan firmayı seçiniz. "
u"Kazanan bir firma bulunmuyor ise boş bırakınız.")
always_blank = False
class KazananFirmalar(ListNode):
class Meta:
title = __(u"Kazanan Firmalar")
kalem = fields.String(__(u"Bütçe Kalemi Adı"))
adet = fields.Integer(__(u"Adet"))
firma = fields.String(__(u"Kazanan Firma"))
key = fields.String('Key', hidden=True)
ilerle = fields.Button(__(u"İlerle"), cmd='ilerle')
geri = fields.Button(__(u"Teklif Görüntüleme Ekranına Geri Dön"), cmd='geri_don')
class KazananFirmalarGosterForm(KazananFirmalarForm):
"""
KazananFirmalarForm un read only olarak gösterilmesi için kalıtım formu.
"""
class Meta:
inline_edit = []
always_blank = False
KazananFirmalar = KazananFirmalarForm.KazananFirmalar
ilerle = fields.Button(__(u"Onayla"), cmd='onayla')
geri = fields.Button(__(u"Kazanan Belirleme Ekranına Geri Dön"), cmd='geri_don')
class TeklifGorForm(JsonForm):
"""
Seçilen satın alma duyurusuna yapılmış tekliflerin gösterildiği form.
"""
class Meta:
title = __(u"{} Satın Alma Duyurusu Teklifleri")
degerlendir = fields.Button(__(u"Teklifleri Değerlendir"), cmd='degerlendir')
indir = fields.Button(__(u"Bütün Teklif Dosyalarını İndir"), cmd='indir')
geri = fields.Button(__(u"Geri Dön"), cmd='geri_don')
class KararVerForm(JsonForm):
"""
Karar verme ekranına gitmek için kullanılan form.
"""
class Meta:
title = __(u"{} Satın Alma Duyurusuna Verilen Teklifler")
belirle = fields.Button(__(u"Kazanan Firmaları Belirle"), cmd='belirle')
geri = fields.Button(__(u"Geri Dön"), cmd='geri_don')
class TeklifIsleForm(JsonForm):
"""
Tekliflerin işlenmesi için kullanılan form.
"""
class Meta:
inline_edit = ['birim_fiyat']
title = __(u"{} Firması {} Satın Alma Duyurusu Fiyat İşlemeleri")
help_text = __(u"Firmanın teklifte bulunduğu bütçe kalemleri için gereken yerleri "
u"doldurunuz. Teklif verilmeyen kalemlerin alanlarını boş bırakınız.")
class TeklifIsle(ListNode):
class Meta:
title = __(u"Teklif Fiyat İşlemeleri")
kalem = fields.String(__(u"Bütçe Kalemi Adı"))
adet = fields.Integer(__(u"Adet"))
birim_fiyat = fields.Float(__(u" Birim Fiyat"))
key = fields.String('Key', hidden=True)
kaydet = fields.Button(__(u"Kaydet"), cmd='kaydet')
geri = fields.Button(__(u"Geri Dön"), cmd='geri_don')
class SatinAlmaBilgileriDuzenleForm(JsonForm):
"""
Seçilen satın alma duyurusuna ait teklife kapanma tarihi ve isim bilgilerini düzenleme
işlemini içerir.
"""
class Meta:
include = ['ad', 'teklife_acilma_tarihi', 'teklife_kapanma_tarihi', 'aciklama']
title = _(u'Duyuru Bilgileri Düzenle')
kaydet = fields.Button(__(u"Kaydet"), cmd="kaydet")
geri_don = fields.Button(__(u"Geri Dön"), cmd="geri_don")
class ButceKalemiBilgileriForm(JsonForm):
class Meta:
inline_edit = ['satin_alma_durum']
class KalemBilgileri(ListNode):
class Meta:
title = __(u"Bütçe Kalemi Bilgileri")
ad = fields.String(__(u"Ad"))
adet = fields.Integer(__(u"Adet"))
satin_alma_durum = fields.Integer(__(u"Satın Alma Durumu"),
choices='bap_butce_plani_satin_alma_durumu', default=None)
key = fields.String('Key', hidden=True)
guncelle = fields.Button(__(u"Güncelle"), cmd="satin_alma_islemler")
geri_don = fields.Button(__(u"Geri Dön"), cmd="geri_don")
class ButceKalemiSec(JsonForm):
class Meta:
title = _(u"Bütçe Kalemi Seç")
fields.Button(__(u"Go"))
class TemplateSecForm(JsonForm):
class Meta:
title = _(u"Belge İndir")
belge = fields.String(__(u"Belge Adı"),
choices=[('piyasa_fiyat_arastirmasi_tutanagi', 'Piyasa Fiyat Araştırması Tutanağı'),
('siparis_formu', 'Sipariş Formu'),
('muayene_gorevlendirmesi', 'Muayene Görevlendirmesi'),
('bap_muayene_ve_kabul_komisyon_tutanagi', 'BAP Muayene ve Kabul Komisyon Tutanağı')])
geri_don = fields.Button(__(u"Geri Dön"), cmd="geri_don")
indir = fields.Button(__(u"İndir"), cmd="template_indir")
class TeklifDegerlendirme(CrudView):
"""
Seçilen satın alma duyurusuna yapılmış tekliflerin değerlendirildiği view.
"""
class Meta:
model = 'BAPSatinAlma'
def _list(self):
"""
Koordinasyon birimi görevlisinin kendi üstünde bulunan satın alma duyurularını listeler.
"""
form = JsonForm(title=__(u"Satın Alma Duyurularının Listesi"))
self.list(custom_form=form)
def teklifleri_gor(self):
"""
Seçilen satın alma duyurusuna teklif yapmış firmalar listelenir.
"""
self.output['objects'] = [[_(u'Firma Adı')]]
for teklif in BAPTeklif.objects.filter(satin_alma=self.object).order_by():
name, cmd = (_(u'Teklif Fiyatları Düzenle'), 'duzenle') if teklif.fiyat_islemesi else (
_(u'Teklif Fiyatları İşle'), 'isle')
list_item = {
"fields": [teklif.firma.ad],
"actions": [
{'name': name, 'cmd': cmd, 'show_as': 'button', 'object_key': 'data_key'}
],
'key': teklif.key}
self.output['objects'].append(list_item)
form = TeklifGorForm(current=self.current)
form.title = form.title.format(self.object.ad)
self.form_out(form)
def belge_indir(self):
"""
Duyuruya teklif vermiş bütün firmaların teklifleri topluca bir zip dosyası halinde
indirilir.
"""
teklifler = BAPTeklif.objects.filter(satin_alma=self.object)
keys = [belge.belge for teklif in teklifler for belge in teklif.Belgeler]
s3 = S3FileManager()
zip_url = s3.download_files_as_zip(keys, "{}FirmaTeklifBelgeleri".format(self.object.ad))
self.set_client_cmd('download')
self.current.output['download_url'] = zip_url
def teklifleri_isle_duzenle(self):
"""
Firmaların verdiği teklifler birim fiyatolarak işlenir. Adet ve birim fiyat kullanılarak
toplam fiyat hesaplanir. Eğer önceden işlenmiş ise düzenlenebilir.
"""
self.current.output["meta"]["allow_add_listnode"] = False
self.current.output["meta"]["allow_actions"] = False
firma = BAPTeklif.objects.get(self.input['data_key']).firma
self.current.task_data['teklif_id'] = self.input['data_key']
form = TeklifIsleForm(current=self.current)
form.title = form.title.format(firma.ad, self.object.ad)
for kalem in self.object.ButceKalemleri:
kalem = kalem.butce
kwargs = {'kalem': kalem.ad,
'adet': kalem.adet,
'key': kalem.key,
'birim_fiyat': None,
}
if self.cmd == 'duzenle':
fiyat = BAPTeklifFiyatIsleme.objects.get_or_none(**{'kalem': kalem, 'firma': firma})
if fiyat:
kwargs.update({'birim_fiyat': fiyat.birim_fiyat})
form.TeklifIsle(**kwargs)
self.form_out(form)
def teklif_islemeleri_kaydet(self):
"""
Yeni girilen teklif işlemeleri ya da düzenlenen teklif işlemeleri kaydedilir. Teklife ilk
defa işleme yapılıyor ise fiyat işlemesi fieldı True yapılır.
"""
teklif = BAPTeklif.objects.get(self.current.task_data['teklif_id'])
self.current.task_data['firma_ad'] = teklif.firma.ad
for obj in self.input['form']['TeklifIsle']:
teklif_bilgileri = {'firma_id': teklif.firma.key,
'kalem_id': obj['key'],
'satin_alma_id': self.object.key}
if not obj['birim_fiyat']:
BAPTeklifFiyatIsleme.objects.delete_if_exists(**teklif_bilgileri)
continue
isleme, new = BAPTeklifFiyatIsleme.objects.get_or_create(**teklif_bilgileri)
teklif.fiyat_islemesi = True
isleme(birim_fiyat=float(obj['birim_fiyat']),
toplam_fiyat=float(obj['birim_fiyat']) * obj['adet']).save()
teklif.save()
def islem_mesaji_olustur(self):
"""
Teklif işleme kaydetme ya da düzenleme işleminden sonra başarılı işlem mesajı gösterilir.
"""
islem_mesaji = _(u"{} firmasının teklif işleme işlemi başarıyla gerçekleştirilmiştir. "
u"Düzenleme butonuna basarak girmiş olduğunuz bilgileri "
u"düzenleyebilirsiniz.".format(self.current.task_data['firma_ad']))
self.current.output['msgbox'] = {'type': 'info',
"title": _(u"İşlem Mesajı"),
"msg": islem_mesaji}
def degerlendirme_kontrol(self):
"""
Tekliflerin değerlendirilebilmesi için duyuruya yapılmış bütün tekliflerin işlemelerinin
yapılmış olması gerekmektedir. Bu durum kontrol edilir.
"""
teklifler = BAPTeklif.objects.filter(satin_alma=self.object, fiyat_islemesi=False)
self.current.task_data['degerlendirme_kontrol'] = False if teklifler else True
def degerlendirme_hata_mesaji_olustur(self):
"""
Eğer işlemesi yapılmayan teklifler varken değerlendirme yapılması denenirse önce
işlemelerin yapılması gerektiği hakkında uyarı mesajı oluşturulur.
"""
hata_mesaji = _(u"'{}' adlı satın almaya ait teklif fiyatları işlemediğiniz firmalar "
u"bulunmaktadır. Karar vermeden önce lütfen teklif veren tüm firmaların "
u"tekliflerini işleyiniz.".format(self.object.ad))
self.current.output['msgbox'] = {'type': 'warning',
"title": _(u"Hata Mesajı"),
"msg": hata_mesaji}
def teklifleri_degerlendir(self):
"""
Bütçe kalemlerine firmaların verdiği teklifler toplam fiyat olarak gösterilir.
"""
self.current.output["meta"]["allow_actions"] = False
form = KararVerForm(current=self.current)
form.title = form.title.format(self.object.ad)
self.output['objects'] = [[_(u'Kalem Adı'), _(u'Adet')]]
firmalar = [teklif.firma for teklif in
BAPTeklif.objects.filter(satin_alma=self.object).order_by()]
self.current.task_data['firma_adlari'] = [(firma.key, firma.ad) for firma in firmalar]
self.output['objects'][0].extend([firma.ad for firma in firmalar])
for kalem in self.object.ButceKalemleri:
kalem = kalem.butce
list_item = {
"fields": [kalem.ad,
str(kalem.adet)],
"actions": '',
}
for firma in firmalar:
fiyat = BAPTeklifFiyatIsleme.objects.get_or_none(**{'kalem': kalem, 'firma': firma})
list_item['fields'].append(str(fiyat.toplam_fiyat) if fiyat else '-')
self.output['objects'].append(list_item)
self.form_out(form)
def kazanan_firmalari_belirle(self):
"""
Seçilen satın alma duyurusunda bulunan her bir bütçe kalemi için kazanan firma belirlenir.
"""
self.current.output["meta"]["allow_add_listnode"] = False
self.current.output["meta"]["allow_actions"] = False
form = KazananFirmalarForm(current=self.current)
form.title = form.title.format(self.object.ad)
form.KazananFirmalar._fields['firma'].choices = self.current.task_data['firma_adlari']
for kalem in self.object.ButceKalemleri:
kalem = kalem.butce
form.KazananFirmalar(kalem=kalem.ad,
adet=kalem.adet,
key=kalem.key)
self.form_out(form)
def onaylama_ekrani_goster(self):
"""
Seçimlerin onaylanmadan önce son kontrol için bütçe kalemleri için seçilen kazanan firma
gösterilir.
"""
self.current.output["meta"]["allow_add_listnode"] = False
self.current.output["meta"]["allow_actions"] = False
help_text = __(u"{} satın alma duyurusunda bulunan bütçe kalemleri için belirlediğiniz "
u"kazanan firmalar aşağıda listelenmiştir. Değişiklik yapmak için bir "
u"önceki ekrana dönebilir, kaydetmek için Onayla butonuna basarak "
u"ilerleyebilirsiniz.").format(self.object.ad)
self.current.task_data['KazananFirmalarGosterForm'] = self.current.task_data[
'KazananFirmalarForm']
form = KazananFirmalarGosterForm(current=self.current,
title=__(u'Kazanan Firmaların Onayı'))
form.help_text = help_text
self.form_out(form)
def kazanan_firma_kaydet(self):
"""
Onaylanırsa, her bir bütçe kalemi için seçilmiş kazanan firma kaydedilir.
"""
self.object.teklif_durum = 3
self.object.blocking_save({'teklif_durum': 3})
for obj in self.input['form']['KazananFirmalar']:
if obj['firma']:
kalem = BAPButcePlani.objects.get(obj['key'])
teklif = BAPTeklif.objects.get(firma_id=str(obj['firma']), satin_alma=self.object)
kalem.kazanan_firma_id = str(obj['firma'])
teklif.durum = 3
teklif.save()
kalem.save()
def islem_mesaji_goster(self):
"""
Kaydedilme işleminden sonra, başarılı işlem mesajı gösterilir.
"""
self.current.output['msgbox'] = {
'type': 'info', "title": _(u'İşlem Bilgilendirme'),
"msg": _(u'{} adlı satın alma duyurusu için teklifler değerlendirildi ve kazanan '
u'firma/firmalar belirlendi.'.format(self.object.ad))}
def teklife_kapat(self):
"""
Durumu Teklife Açık olan satın alma duyurusunun durumunu Teklife Kapalı olarak
değiştirir.
"""
self.object.teklif_durum = 2
self.object.blocking_save({'teklif_durum': 2})
self.current.output['msgbox'] = {
'type': 'info', "title": _(u'İşlem Bilgilendirme'),
"msg": _(
u'{} adlı satın alma duyurusu teklife kapatıldı. Teklifleri Değerlendir butonuna '
u'tıklayarak duyuruya ait teklifleri değerlendirebilirsiniz.'.format(
self.object.ad))}
def satin_alma(self):
"""
Seçili olan satın alma duyurusuna ait bütçe kalemlerinin bilgilerini listeler.
"""
self.current.output["meta"]["allow_actions"] = False
self.current.output["meta"]["allow_add_listnode"] = False
form = ButceKalemiBilgileriForm(title="{} Bütçe Kalemlerinin Bilgileri".format(self.object.ad))
for kalem in self.object.ButceKalemleri:
form.KalemBilgileri(ad=kalem.butce.ad, adet=kalem.butce.adet,
satin_alma_durum=kalem.butce.satin_alma_durum, key=kalem.butce.key)
self.form_out(form)
def satin_alma_islemler(self):
"""
Seçili olan satın alma duyurusunun satın alma durumunun belirlenmesi işlemini içerir.
"""
for obj in self.input["form"]["KalemBilgileri"]:
kalem = BAPButcePlani.objects.get(obj["key"])
if obj["satin_alma_durum"] == 4:
try:
BAPTeklifFiyatIsleme.objects.get(kalem=kalem, firma=kalem.kazanan_firma)
kalem.satin_alma_durum = obj["satin_alma_durum"]
except ObjectDoesNotExist:
pass
else:
kalem.satin_alma_durum = obj["satin_alma_durum"]
kalem.save()
def satin_alma_bilgilerini_duzenle(self):
"""
Seçili olan satın alma duyurusunun bilgilerini düzenleme işlemini içerir.
"""
form = SatinAlmaBilgileriDuzenleForm(self.object, current=self.current)
self.form_out(form)
def degisiklikleri_kaydet(self):
"""
Seçilen satın alma duyurusunda yapılan değişiklikleri kaydetme işlemini içerir.
"""
tat = "{} {}".format(self.input["form"]["teklife_acilma_tarihi"], time(17))
tkt = "{} {}".format(self.input["form"]["teklife_kapanma_tarihi"], time(17))
self.object.teklife_acilma_tarihi = datetime.strptime(tat, DATETIME_DEFAULT_FORMAT)
self.object.teklife_kapanma_tarihi = datetime.strptime(tkt, DATETIME_DEFAULT_FORMAT)
self.object.ad = self.input["form"]["ad"]
self.object.aciklama = self.input['form']['aciklama']
self.object.save()
def butce_kalemi_sec(self):
"""
Something.
Returns:
"""
satin_alma_object = self.model_class.objects.get(self.current.task_data['object_id'])
butce_kalemleri = satin_alma_object.ButceKalemleri
self.output['objects'] = [[_(u'Bütçe Kalemi'),
_(u'Adet'),
_(u'Birim Fiyat'),
_(u'Toplam Fiyat'),
_(u'Gerekçe'),
_(u'Kazanan Firma')]]
for butce_kalemi in butce_kalemleri:
name, cmd = (_(u'Seç'), 'sec')
list_item = {
"fields": [butce_kalemi.butce.ad,
str(butce_kalemi.butce.adet),
str(butce_kalemi.butce.birim_fiyat),
str(butce_kalemi.butce.toplam_fiyat),
butce_kalemi.butce.gerekce,
butce_kalemi.butce.kazanan_firma.ad],
"actions": [
{'name': name, 'cmd': cmd, 'show_as': 'button', 'object_key': 'data_key'}
],
'key': butce_kalemi.butce.key}
self.output['objects'].append(list_item)
"""form = TeklifGorForm(current=self.current)
form.title = form.title.format(self.object.ad)
self.form_out(form)"""
form = ButceKalemiSec(current=self.current)
self.form_out(form)
def template_sec(self):
"""
DocumentRender servisine gönderilecek belgenin seçilmesi ve belgenin oluşturulup, indirilmesi.
"""
form = TemplateSecForm()
self.form_out(form)
def template_indir(self):
"""
Template seçimine göre, `render_function_map` dict'inden `render` ve `context` fonksiyonları elde edilir.
Sonuç olarak bunları çalıştırdığımızda elimizde render edilmiş bir template'in URL'i olur.
"""
template_name = self.current.task_data.get('TemplateSecForm').get('belge')
render_function_map = {'piyasa_fiyat_arastirmasi_tutanagi':
[render.piyasa_fiyat_arastirmasi_tutanagi_uret,
self.piyasa_fiyat_arastirmasi_tutanagi_context,
False],
'siparis_formu':
[render.siparis_formu_uret,
self.siparis_formu_context,
False],
'muayene_gorevlendirmesi':
[render.muayene_gorevlendirmesi_uret,
self.muayene_gorevlendirmesi_context,
False],
'bap_muayene_ve_kabul_komisyon_tutanagi':
[render.bap_muayene_ve_kabul_komisyonu_tutanagi_uret,
self.bap_muayene_ve_kabul_komisyon_tutanagi,
False]}
render_function, context_function, wants_pdf = render_function_map[template_name]
self.set_client_cmd('download')
self.current.output['download_url'] = render_function(context_data=context_function(),
wants_pdf=True)
def piyasa_fiyat_arastirmasi_tutanagi_context(self):
"""
Piyasa fiyat araştırması tutanagı için gerekli verileri veritabanından okuyarak, context datası oluşturur.
Returns:
dict: Context data for template file.
"""
rightnow = datetime.now()
formatted_date = datetime.strftime(rightnow, '%d.%m.%Y')
satin_alma_object = self.model_class.objects.get(self.current.task_data['object_id'])
malzemeler = satin_alma_object.ButceKalemleri
kazanan_firma = malzemeler[0].butce.kazanan_firma
firma2, firma3 = BAPTeklifFiyatIsleme.en_iyi_teklif_veren_ikinci_ve_ucuncu_firmayi_getir(
malzemeler[0].butce)
context = {
"idare_adi": "YILDIRIM BEYAZIT ÜNİVERSİTESİ REKTÖRLÜĞÜ BİLİMSEL ARAŞTIRMA PROJELERİ KOORDİNASYON BİRİMİ",
"yapilan_isin_adi": "Mal Alımı, Malzeme Alımı",
"alim_yapan_gorevlilere_iliskin": "",
"ihale_onay_belgesi_tarih_sayi": satin_alma_object.onay_tarih_sayi,
"malzemeler": [],
"firmalar": [kazanan_firma.ad,
firma2.ad,
firma3.ad],
"f1_genel_toplam": 0,
"f2_genel_toplam": 0,
"f3_genel_toplam": 0,
"malzeme_sayisi": 0,
"uygun_gorulen_firma_adi_adresi": kazanan_firma.adres,
"uygun_gorulen_teklif_tutari": 0,
"gorevli": [
{"ad": str(satin_alma_object.sorumlu.user), "unvan": "Proje Yürütücüsü"},
{"ad": "", "unvan": ""},
{"ad": "", "unvan": ""}
],
"harcama_yetkilisi": {"ad": "", "unvan": ""},
"belge_imza_tarihi": formatted_date
}
i = 0
for malzeme in malzemeler:
i += 1
teklifler = []
kazanan_firma = malzeme.butce.kazanan_firma
firma2, firma3 = BAPTeklifFiyatIsleme.en_iyi_teklif_veren_ikinci_ve_ucuncu_firmayi_getir(
malzeme.butce)
for firm in [kazanan_firma, firma2, firma3]:
teklifler.append(BAPTeklifFiyatIsleme.objects.get(firma=firm,
kalem=malzeme.butce))
# Firmaların verdiği teklifler ve malzemeler liste olarak context'e ekleniyor.
context['malzemeler'].append({"sira_no": i,
"adi": malzeme.butce.ad,
"miktar": malzeme.butce.adet,
"birim": "Adet",
"f1_birim": teklifler[0].birim_fiyat,
"f1_toplam": teklifler[0].toplam_fiyat,
"f2_birim": teklifler[1].birim_fiyat,
"f2_toplam": teklifler[1].toplam_fiyat,
"f3_birim": teklifler[2].birim_fiyat,
"f3_toplam": teklifler[2].toplam_fiyat
})
# Firmaların verdiği tekliflerin toplam tutuarı bulunuyor.
context['f1_genel_toplam'] += teklifler[0].toplam_fiyat
context['f2_genel_toplam'] += teklifler[1].toplam_fiyat
context['f3_genel_toplam'] += teklifler[2].toplam_fiyat
context['malzeme_sayisi'] = i
context['uygun_gorulen_teklif_tutari'] = context['f1_genel_toplam']
return context
def siparis_formu_context(self):
"""
Context data for siparis_formu template file.
Returns:
dict: Context data.
"""
satin_alma_object = self.model_class.objects.get(self.current.task_data['object_id'])
selected_butce_kalemi = self.input.get('data_key')
selected_butce_kalemi = BAPButcePlani.objects.get(selected_butce_kalemi)
context = {
"isin_niteligi": selected_butce_kalemi.kod_adi,
"butce_tertibi": "2.20.00.00.00 1",
"isin_adi_veya_miktari": "",
"malzemeler": [
{
"sira_no": 1,
"adi": selected_butce_kalemi.ad,
"miktar": selected_butce_kalemi.adet,
"birim": "Kalem"
}
],
"yuklenici_firma_adi": selected_butce_kalemi.kazanan_firma.ad,
"tebligata_esas_adresi": selected_butce_kalemi.kazanan_firma.adres,
"siparis_bedeli": selected_butce_kalemi.toplam_fiyat,
"odeme_saymanligi": "Strateji Geliştirme Dairesi Başkanlığı",
"vergi_resim_ve_harclar": "Yükleniciye Aittir",
"garanti_suresi_ve_sartlar": "",
"yedek_parca_montaj_sartlari": "",
"teslim_suresi": "",
"gerceklestirme_gorevlisi": {"ad": str(satin_alma_object.sorumlu.user), "unvan": "Proje Yürütücüsü"},
"harcama_yetkilisi": {"ad": "", "unvan": ""},
"belge_yili": datetime.now().year
}
return context
def muayene_gorevlendirmesi_context(self):
"""
Context variables for muayene_gorevlendirmesi file.
Returns:
dict: Context data.
"""
satin_alma_object = self.model_class.objects.get(self.current.task_data['object_id'])
rightnow = datetime.now()
context = {
"dilekce_sayisi": "",
"dilekce_tarihi": datetime.strftime(rightnow,'%d.%m.%Y'),
"gerceklestirme_gorevlisi": {"ad": str(satin_alma_object.sorumlu.user), "unvan": "Proje Yürütücüsü"},
"harcama_yetkilisi": {"ad": "", "unvan": ""},
"muayene_komisyonu_idari_uzman": "",
"muayene_komisyonu_teknik_uzman": "",
"muayene_komisyonu_ambar_gorevlisi": ""
}
return context
def bap_muayene_ve_kabul_komisyon_tutanagi(self):
"""
Prepare context data.
Returns:
dict:
"""
satin_alma_object = self.model_class.objects.get(self.current.task_data['object_id'])
malzemeler = satin_alma_object.ButceKalemleri
kazanan_firma = malzemeler[0].butce.kazanan_firma
context = {
"i_f_no": "",
"nereden_geldigi": kazanan_firma.ad,
"dayandigi_belge_sayisi": "",
"dayandigi_belge_tarihi": "",
"muayene_kabul_komisyonu_tutanagi_tarihi": "",
"tasinirlar": [],
"tasinir_sayisi": len(malzemeler),
"baskan": {"adi": str(satin_alma_object.sorumlu.user), "unvan": "Proje Yürütücüsü"},
"uye1": {"adi": "", "unvan": ""},
"uye2": {"adi": "", "unvan": ""}
}
for malz in malzemeler:
context['tasinirlar'].append({
"miktari": malz.butce.adet,
"birimi": "Adet",
"adi_ve_ozellikleri": "{} {}".format(malz.butce.ad, malz.butce.ozellik)
})
return context
@obj_filter
def satin_alma_duyurulari_actions(self, obj, result):
"""
Satın Alma Duyurularının butonları 4 duruma göre eklenir.
1) Düzenle: Durumu Teklife açık olan ve teklife kapanma tarihi sonlanmayan duyurular için.
2) Teklife Kapat: Durumu Teklife açık olan ve teklife kapanma tarihi sonlanan duyurular için.
3) Teklifleri Değerlendir: Durumu Teklife Kapalı olan duyurular için.
4) Satın Alma Gerçekleştir: Durumu Değerlendirildi olan duyurular için.
data(dict): Buton ismi ve cmd değerlerini içerir. Gelen nesnenin teklif durumuna göre
datadaki veriler kullanılır.
"""
data = {1: {"name": "Teklife Kapat", "cmd": "teklife_kapat"},
2: {"name": "Teklifleri Değerlendir", "cmd": "degerlendir"}}
if obj.teklif_durum == 1 and obj.teklife_kapanma_tarihi < datetime.now():
result['actions'] = [{'name': "Düzenle", 'cmd': "duzenle", "mode": "normal",
"show_as": "button"}]
elif obj.teklif_durum == 3:
result['actions'] = [{"name": "Satın Alma Bilgilerini Güncelle", "cmd": "satin_alma", "mode": "normal",
"show_as": "button"},
{"name": "Belgeleri İndir", "cmd": "template_sec", "mode": "normal",
"show_as": "button"}]
else:
result['actions'] = [{"name": data[obj.teklif_durum]["name"],
"cmd": data[obj.teklif_durum]["cmd"], "mode": "normal",
"show_as": "button"}]
@list_query
def satin_alma_duyurularini_listele(self, queryset):
"""
Sorumluya gösterilecek satın alma duyuruları listelenir.
"""
return queryset.filter(sorumlu=self.current.role).order_by()
| gpl-3.0 |
abrandao/lab | phpunit-with-code-coverage/vendor/composer/autoload_static.php | 65126 | <?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit148e3ff598796c30c73a1c9a3acfccd8
{
public static $files = array (
'6124b4c8570aa390c21fafd04a26c69f' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
);
public static $prefixLengthsPsr4 = array (
'p' =>
array (
'phpDocumentor\\Reflection\\' => 25,
),
'W' =>
array (
'Webmozart\\Assert\\' => 17,
),
'D' =>
array (
'Doctrine\\Instantiator\\' => 22,
'DeepCopy\\' => 9,
),
'A' =>
array (
'Apteles\\Acme\\' => 13,
),
);
public static $prefixDirsPsr4 = array (
'phpDocumentor\\Reflection\\' =>
array (
0 => __DIR__ . '/..' . '/phpdocumentor/reflection-common/src',
1 => __DIR__ . '/..' . '/phpdocumentor/type-resolver/src',
2 => __DIR__ . '/..' . '/phpdocumentor/reflection-docblock/src',
),
'Webmozart\\Assert\\' =>
array (
0 => __DIR__ . '/..' . '/webmozart/assert/src',
),
'Doctrine\\Instantiator\\' =>
array (
0 => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator',
),
'DeepCopy\\' =>
array (
0 => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy',
),
'Apteles\\Acme\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $prefixesPsr0 = array (
'P' =>
array (
'Prophecy\\' =>
array (
0 => __DIR__ . '/..' . '/phpspec/prophecy/src',
),
),
);
public static $classMap = array (
'File_Iterator' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Iterator.php',
'File_Iterator_Facade' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Facade.php',
'File_Iterator_Factory' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Factory.php',
'PHPUnit\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Exception.php',
'PHPUnit\\Framework\\Assert' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Assert.php',
'PHPUnit\\Framework\\AssertionFailedError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/AssertionFailedError.php',
'PHPUnit\\Framework\\BaseTestListener' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/BaseTestListener.php',
'PHPUnit\\Framework\\CodeCoverageException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/CodeCoverageException.php',
'PHPUnit\\Framework\\Constraint\\ArrayHasKey' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ArrayHasKey.php',
'PHPUnit\\Framework\\Constraint\\ArraySubset' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ArraySubset.php',
'PHPUnit\\Framework\\Constraint\\Attribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Attribute.php',
'PHPUnit\\Framework\\Constraint\\Callback' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Callback.php',
'PHPUnit\\Framework\\Constraint\\ClassHasAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ClassHasAttribute.php',
'PHPUnit\\Framework\\Constraint\\ClassHasStaticAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ClassHasStaticAttribute.php',
'PHPUnit\\Framework\\Constraint\\Composite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Composite.php',
'PHPUnit\\Framework\\Constraint\\Constraint' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Constraint.php',
'PHPUnit\\Framework\\Constraint\\Count' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Count.php',
'PHPUnit\\Framework\\Constraint\\DirectoryExists' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/DirectoryExists.php',
'PHPUnit\\Framework\\Constraint\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Exception.php',
'PHPUnit\\Framework\\Constraint\\ExceptionCode' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionCode.php',
'PHPUnit\\Framework\\Constraint\\ExceptionMessage' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessage.php',
'PHPUnit\\Framework\\Constraint\\ExceptionMessageRegularExpression' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegularExpression.php',
'PHPUnit\\Framework\\Constraint\\FileExists' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/FileExists.php',
'PHPUnit\\Framework\\Constraint\\GreaterThan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/GreaterThan.php',
'PHPUnit\\Framework\\Constraint\\IsAnything' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsAnything.php',
'PHPUnit\\Framework\\Constraint\\IsEmpty' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsEmpty.php',
'PHPUnit\\Framework\\Constraint\\IsEqual' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsEqual.php',
'PHPUnit\\Framework\\Constraint\\IsFalse' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsFalse.php',
'PHPUnit\\Framework\\Constraint\\IsFinite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsFinite.php',
'PHPUnit\\Framework\\Constraint\\IsIdentical' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsIdentical.php',
'PHPUnit\\Framework\\Constraint\\IsInfinite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsInfinite.php',
'PHPUnit\\Framework\\Constraint\\IsInstanceOf' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsInstanceOf.php',
'PHPUnit\\Framework\\Constraint\\IsJson' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsJson.php',
'PHPUnit\\Framework\\Constraint\\IsNan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsNan.php',
'PHPUnit\\Framework\\Constraint\\IsNull' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsNull.php',
'PHPUnit\\Framework\\Constraint\\IsReadable' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsReadable.php',
'PHPUnit\\Framework\\Constraint\\IsTrue' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsTrue.php',
'PHPUnit\\Framework\\Constraint\\IsType' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsType.php',
'PHPUnit\\Framework\\Constraint\\IsWritable' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsWritable.php',
'PHPUnit\\Framework\\Constraint\\JsonMatches' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php',
'PHPUnit\\Framework\\Constraint\\JsonMatchesErrorMessageProvider' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php',
'PHPUnit\\Framework\\Constraint\\LessThan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LessThan.php',
'PHPUnit\\Framework\\Constraint\\LogicalAnd' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalAnd.php',
'PHPUnit\\Framework\\Constraint\\LogicalNot' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalNot.php',
'PHPUnit\\Framework\\Constraint\\LogicalOr' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalOr.php',
'PHPUnit\\Framework\\Constraint\\LogicalXor' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalXor.php',
'PHPUnit\\Framework\\Constraint\\ObjectHasAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php',
'PHPUnit\\Framework\\Constraint\\RegularExpression' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/RegularExpression.php',
'PHPUnit\\Framework\\Constraint\\SameSize' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/SameSize.php',
'PHPUnit\\Framework\\Constraint\\StringContains' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringContains.php',
'PHPUnit\\Framework\\Constraint\\StringEndsWith' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.php',
'PHPUnit\\Framework\\Constraint\\StringMatchesFormatDescription' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringMatchesFormatDescription.php',
'PHPUnit\\Framework\\Constraint\\StringStartsWith' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringStartsWith.php',
'PHPUnit\\Framework\\Constraint\\TraversableContains' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContains.php',
'PHPUnit\\Framework\\Constraint\\TraversableContainsOnly' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php',
'PHPUnit\\Framework\\CoveredCodeNotExecutedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/CoveredCodeNotExecutedException.php',
'PHPUnit\\Framework\\DataProviderTestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/DataProviderTestSuite.php',
'PHPUnit\\Framework\\Error\\Deprecated' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Deprecated.php',
'PHPUnit\\Framework\\Error\\Error' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Error.php',
'PHPUnit\\Framework\\Error\\Notice' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Notice.php',
'PHPUnit\\Framework\\Error\\Warning' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Warning.php',
'PHPUnit\\Framework\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception.php',
'PHPUnit\\Framework\\ExceptionWrapper' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/ExceptionWrapper.php',
'PHPUnit\\Framework\\ExpectationFailedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/ExpectationFailedException.php',
'PHPUnit\\Framework\\IncompleteTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/IncompleteTest.php',
'PHPUnit\\Framework\\IncompleteTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/IncompleteTestCase.php',
'PHPUnit\\Framework\\IncompleteTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/IncompleteTestError.php',
'PHPUnit\\Framework\\InvalidCoversTargetException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/InvalidCoversTargetException.php',
'PHPUnit\\Framework\\MissingCoversAnnotationException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MissingCoversAnnotationException.php',
'PHPUnit\\Framework\\MockObject\\BadMethodCallException' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Exception/BadMethodCallException.php',
'PHPUnit\\Framework\\MockObject\\Builder\\Identity' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/Identity.php',
'PHPUnit\\Framework\\MockObject\\Builder\\InvocationMocker' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/InvocationMocker.php',
'PHPUnit\\Framework\\MockObject\\Builder\\Match' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/Match.php',
'PHPUnit\\Framework\\MockObject\\Builder\\MethodNameMatch' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/MethodNameMatch.php',
'PHPUnit\\Framework\\MockObject\\Builder\\NamespaceMatch' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/NamespaceMatch.php',
'PHPUnit\\Framework\\MockObject\\Builder\\ParametersMatch' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/ParametersMatch.php',
'PHPUnit\\Framework\\MockObject\\Builder\\Stub' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Builder/Stub.php',
'PHPUnit\\Framework\\MockObject\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Exception/Exception.php',
'PHPUnit\\Framework\\MockObject\\Generator' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Generator.php',
'PHPUnit\\Framework\\MockObject\\Invocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Invocation/Invocation.php',
'PHPUnit\\Framework\\MockObject\\InvocationMocker' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/InvocationMocker.php',
'PHPUnit\\Framework\\MockObject\\Invocation\\ObjectInvocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Invocation/ObjectInvocation.php',
'PHPUnit\\Framework\\MockObject\\Invocation\\StaticInvocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Invocation/StaticInvocation.php',
'PHPUnit\\Framework\\MockObject\\Invokable' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Invokable.php',
'PHPUnit\\Framework\\MockObject\\Matcher' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\AnyInvokedCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/AnyInvokedCount.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\AnyParameters' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/AnyParameters.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\ConsecutiveParameters' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/ConsecutiveParameters.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\Invocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/Invocation.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\InvokedAtIndex' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/InvokedAtIndex.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\InvokedAtLeastCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/InvokedAtLeastCount.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\InvokedAtLeastOnce' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/InvokedAtLeastOnce.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\InvokedAtMostCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/InvokedAtMostCount.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\InvokedCount' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/InvokedCount.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\InvokedRecorder' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/InvokedRecorder.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\MethodName' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/MethodName.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\Parameters' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/Parameters.php',
'PHPUnit\\Framework\\MockObject\\Matcher\\StatelessInvocation' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Matcher/StatelessInvocation.php',
'PHPUnit\\Framework\\MockObject\\MockBuilder' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/MockBuilder.php',
'PHPUnit\\Framework\\MockObject\\MockObject' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/ForwardCompatibility/MockObject.php',
'PHPUnit\\Framework\\MockObject\\RuntimeException' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Exception/RuntimeException.php',
'PHPUnit\\Framework\\MockObject\\Stub' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ConsecutiveCalls' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ConsecutiveCalls.php',
'PHPUnit\\Framework\\MockObject\\Stub\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/Exception.php',
'PHPUnit\\Framework\\MockObject\\Stub\\MatcherCollection' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/MatcherCollection.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ReturnArgument' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ReturnArgument.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ReturnCallback' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ReturnCallback.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ReturnReference' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ReturnReference.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ReturnSelf' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ReturnSelf.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ReturnStub' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ReturnStub.php',
'PHPUnit\\Framework\\MockObject\\Stub\\ReturnValueMap' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Stub/ReturnValueMap.php',
'PHPUnit\\Framework\\MockObject\\Verifiable' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/Verifiable.php',
'PHPUnit\\Framework\\OutputError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/OutputError.php',
'PHPUnit\\Framework\\RiskyTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/RiskyTest.php',
'PHPUnit\\Framework\\RiskyTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/RiskyTestError.php',
'PHPUnit\\Framework\\SelfDescribing' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SelfDescribing.php',
'PHPUnit\\Framework\\SkippedTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTest.php',
'PHPUnit\\Framework\\SkippedTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTestCase.php',
'PHPUnit\\Framework\\SkippedTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTestError.php',
'PHPUnit\\Framework\\SkippedTestSuiteError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTestSuiteError.php',
'PHPUnit\\Framework\\SyntheticError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SyntheticError.php',
'PHPUnit\\Framework\\Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Test.php',
'PHPUnit\\Framework\\TestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestCase.php',
'PHPUnit\\Framework\\TestFailure' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestFailure.php',
'PHPUnit\\Framework\\TestListener' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestListener.php',
'PHPUnit\\Framework\\TestListenerDefaultImplementation' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestListenerDefaultImplementation.php',
'PHPUnit\\Framework\\TestResult' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestResult.php',
'PHPUnit\\Framework\\TestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestSuite.php',
'PHPUnit\\Framework\\TestSuiteIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestSuiteIterator.php',
'PHPUnit\\Framework\\UnintentionallyCoveredCodeError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/UnintentionallyCoveredCodeError.php',
'PHPUnit\\Framework\\Warning' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Warning.php',
'PHPUnit\\Framework\\WarningTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/WarningTestCase.php',
'PHPUnit\\Runner\\BaseTestRunner' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/BaseTestRunner.php',
'PHPUnit\\Runner\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Exception.php',
'PHPUnit\\Runner\\Filter\\ExcludeGroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/ExcludeGroupFilterIterator.php',
'PHPUnit\\Runner\\Filter\\Factory' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Factory.php',
'PHPUnit\\Runner\\Filter\\GroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/GroupFilterIterator.php',
'PHPUnit\\Runner\\Filter\\IncludeGroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/IncludeGroupFilterIterator.php',
'PHPUnit\\Runner\\Filter\\NameFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/NameFilterIterator.php',
'PHPUnit\\Runner\\PhptTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/PhptTestCase.php',
'PHPUnit\\Runner\\StandardTestSuiteLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php',
'PHPUnit\\Runner\\TestSuiteLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/TestSuiteLoader.php',
'PHPUnit\\Runner\\Version' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Version.php',
'PHPUnit\\TextUI\\Command' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/Command.php',
'PHPUnit\\TextUI\\ResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/ResultPrinter.php',
'PHPUnit\\TextUI\\TestRunner' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/TestRunner.php',
'PHPUnit\\Util\\Blacklist' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Blacklist.php',
'PHPUnit\\Util\\Configuration' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Configuration.php',
'PHPUnit\\Util\\ConfigurationGenerator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/ConfigurationGenerator.php',
'PHPUnit\\Util\\ErrorHandler' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/ErrorHandler.php',
'PHPUnit\\Util\\Fileloader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Fileloader.php',
'PHPUnit\\Util\\Filesystem' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Filesystem.php',
'PHPUnit\\Util\\Filter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Filter.php',
'PHPUnit\\Util\\Getopt' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Getopt.php',
'PHPUnit\\Util\\GlobalState' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/GlobalState.php',
'PHPUnit\\Util\\InvalidArgumentHelper' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/InvalidArgumentHelper.php',
'PHPUnit\\Util\\Json' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Json.php',
'PHPUnit\\Util\\Log\\JUnit' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/JUnit.php',
'PHPUnit\\Util\\Log\\TeamCity' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/TeamCity.php',
'PHPUnit\\Util\\PHP\\AbstractPhpProcess' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/AbstractPhpProcess.php',
'PHPUnit\\Util\\PHP\\DefaultPhpProcess' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/DefaultPhpProcess.php',
'PHPUnit\\Util\\PHP\\WindowsPhpProcess' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/WindowsPhpProcess.php',
'PHPUnit\\Util\\Printer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Printer.php',
'PHPUnit\\Util\\RegularExpression' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/RegularExpression.php',
'PHPUnit\\Util\\Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Test.php',
'PHPUnit\\Util\\TestDox\\HtmlResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/HtmlResultPrinter.php',
'PHPUnit\\Util\\TestDox\\NamePrettifier' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/NamePrettifier.php',
'PHPUnit\\Util\\TestDox\\ResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter.php',
'PHPUnit\\Util\\TestDox\\TextResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/TextResultPrinter.php',
'PHPUnit\\Util\\TestDox\\XmlResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/XmlResultPrinter.php',
'PHPUnit\\Util\\TextTestListRenderer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TextTestListRenderer.php',
'PHPUnit\\Util\\Type' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Type.php',
'PHPUnit\\Util\\Xml' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Xml.php',
'PHPUnit\\Util\\XmlTestListRenderer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/XmlTestListRenderer.php',
'PHPUnit_Framework_MockObject_MockObject' => __DIR__ . '/..' . '/phpunit/phpunit-mock-objects/src/MockObject.php',
'PHP_Timer' => __DIR__ . '/..' . '/phpunit/php-timer/src/Timer.php',
'PHP_Token' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_TokenWithScope' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_TokenWithScopeAndVisibility' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ABSTRACT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AMPERSAND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AND_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ARRAY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ARRAY_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ASYNC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_AWAIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BACKTICK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BAD_CHARACTER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOLEAN_AND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOLEAN_OR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BOOL_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_BREAK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CALLABLE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CARET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CASE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CATCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CHARACTER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLASS_NAME_CONSTANT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLONE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_BRACKET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_CURLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_SQUARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CLOSE_TAG' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COALESCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMMA' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMMENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_COMPILER_HALT_OFFSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONCAT_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONSTANT_ENCAPSED_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CONTINUE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_CURLY_OPEN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DEC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DECLARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DEFAULT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIV' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DIV_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DNUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOC_COMMENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOLLAR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_ARROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_COLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_DOUBLE_QUOTES' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ECHO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELLIPSIS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELSE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ELSEIF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EMPTY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENCAPSED_AND_WHITESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDDECLARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDFOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDFOREACH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDIF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDSWITCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENDWHILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_END_HEREDOC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ENUM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EQUALS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EVAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXCLAMATION_MARK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_EXTENDS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FINAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FINALLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FOREACH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FUNCTION' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_FUNC_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GLOBAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GOTO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_HALT_COMPILER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IMPLEMENTS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INCLUDE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INCLUDE_ONCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INLINE_HTML' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INSTANCEOF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INSTEADOF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INTERFACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_INT_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ISSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_GREATER_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_IDENTICAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_NOT_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_NOT_IDENTICAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_IS_SMALLER_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_Includes' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_JOIN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_ARROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_CP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LAMBDA_OP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LINE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LIST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LNUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_AND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_OR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LOGICAL_XOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_METHOD_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MINUS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MINUS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MOD_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MULT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_MUL_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NAMESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NEW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NS_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NS_SEPARATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NULLSAFE_OBJECT_OPERATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_NUM_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OBJECT_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OBJECT_OPERATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_ONUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_BRACKET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_CURLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_SQUARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_TAG' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OPEN_TAG_WITH_ECHO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PERCENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PIPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PLUS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PLUS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_POW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_POW_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PRINT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PRIVATE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PROTECTED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_PUBLIC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_QUESTION_MARK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_REQUIRE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_REQUIRE_ONCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_RETURN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SEMICOLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SHAPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SL_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SPACESHIP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_START_HEREDOC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STATIC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_STRING_VARNAME' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SUPER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_SWITCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_Stream' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token/Stream.php',
'PHP_Token_Stream_CachingFactory' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token/Stream/CachingFactory.php',
'PHP_Token_THROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TILDE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRAIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRAIT_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TRY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPELIST_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_TYPELIST_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_UNSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_UNSET_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_USE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_USE_FUNCTION' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_VAR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_VARIABLE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHERE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_WHITESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_ATTRIBUTE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CATEGORY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CATEGORY_LABEL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_CHILDREN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_LABEL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_REQUIRED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TAG_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TAG_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XHP_TEXT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_XOR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_YIELD' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PHP_Token_YIELD_FROM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
'PharIo\\Manifest\\Application' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Application.php',
'PharIo\\Manifest\\ApplicationName' => __DIR__ . '/..' . '/phar-io/manifest/src/values/ApplicationName.php',
'PharIo\\Manifest\\Author' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Author.php',
'PharIo\\Manifest\\AuthorCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/values/AuthorCollection.php',
'PharIo\\Manifest\\AuthorCollectionIterator' => __DIR__ . '/..' . '/phar-io/manifest/src/values/AuthorCollectionIterator.php',
'PharIo\\Manifest\\AuthorElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/AuthorElement.php',
'PharIo\\Manifest\\AuthorElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/AuthorElementCollection.php',
'PharIo\\Manifest\\BundledComponent' => __DIR__ . '/..' . '/phar-io/manifest/src/values/BundledComponent.php',
'PharIo\\Manifest\\BundledComponentCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/values/BundledComponentCollection.php',
'PharIo\\Manifest\\BundledComponentCollectionIterator' => __DIR__ . '/..' . '/phar-io/manifest/src/values/BundledComponentCollectionIterator.php',
'PharIo\\Manifest\\BundlesElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/BundlesElement.php',
'PharIo\\Manifest\\ComponentElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ComponentElement.php',
'PharIo\\Manifest\\ComponentElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ComponentElementCollection.php',
'PharIo\\Manifest\\ContainsElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ContainsElement.php',
'PharIo\\Manifest\\CopyrightElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/CopyrightElement.php',
'PharIo\\Manifest\\CopyrightInformation' => __DIR__ . '/..' . '/phar-io/manifest/src/values/CopyrightInformation.php',
'PharIo\\Manifest\\ElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ElementCollection.php',
'PharIo\\Manifest\\Email' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Email.php',
'PharIo\\Manifest\\Exception' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/Exception.php',
'PharIo\\Manifest\\ExtElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ExtElement.php',
'PharIo\\Manifest\\ExtElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ExtElementCollection.php',
'PharIo\\Manifest\\Extension' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Extension.php',
'PharIo\\Manifest\\ExtensionElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ExtensionElement.php',
'PharIo\\Manifest\\InvalidApplicationNameException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/InvalidApplicationNameException.php',
'PharIo\\Manifest\\InvalidEmailException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/InvalidEmailException.php',
'PharIo\\Manifest\\InvalidUrlException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/InvalidUrlException.php',
'PharIo\\Manifest\\Library' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Library.php',
'PharIo\\Manifest\\License' => __DIR__ . '/..' . '/phar-io/manifest/src/values/License.php',
'PharIo\\Manifest\\LicenseElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/LicenseElement.php',
'PharIo\\Manifest\\Manifest' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Manifest.php',
'PharIo\\Manifest\\ManifestDocument' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ManifestDocument.php',
'PharIo\\Manifest\\ManifestDocumentException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestDocumentException.php',
'PharIo\\Manifest\\ManifestDocumentLoadingException' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ManifestDocumentLoadingException.php',
'PharIo\\Manifest\\ManifestDocumentMapper' => __DIR__ . '/..' . '/phar-io/manifest/src/ManifestDocumentMapper.php',
'PharIo\\Manifest\\ManifestDocumentMapperException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestDocumentMapperException.php',
'PharIo\\Manifest\\ManifestElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ManifestElement.php',
'PharIo\\Manifest\\ManifestElementException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestElementException.php',
'PharIo\\Manifest\\ManifestLoader' => __DIR__ . '/..' . '/phar-io/manifest/src/ManifestLoader.php',
'PharIo\\Manifest\\ManifestLoaderException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestLoaderException.php',
'PharIo\\Manifest\\ManifestSerializer' => __DIR__ . '/..' . '/phar-io/manifest/src/ManifestSerializer.php',
'PharIo\\Manifest\\PhpElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/PhpElement.php',
'PharIo\\Manifest\\PhpExtensionRequirement' => __DIR__ . '/..' . '/phar-io/manifest/src/values/PhpExtensionRequirement.php',
'PharIo\\Manifest\\PhpVersionRequirement' => __DIR__ . '/..' . '/phar-io/manifest/src/values/PhpVersionRequirement.php',
'PharIo\\Manifest\\Requirement' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Requirement.php',
'PharIo\\Manifest\\RequirementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/values/RequirementCollection.php',
'PharIo\\Manifest\\RequirementCollectionIterator' => __DIR__ . '/..' . '/phar-io/manifest/src/values/RequirementCollectionIterator.php',
'PharIo\\Manifest\\RequiresElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/RequiresElement.php',
'PharIo\\Manifest\\Type' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Type.php',
'PharIo\\Manifest\\Url' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Url.php',
'PharIo\\Version\\AbstractVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/AbstractVersionConstraint.php',
'PharIo\\Version\\AndVersionConstraintGroup' => __DIR__ . '/..' . '/phar-io/version/src/AndVersionConstraintGroup.php',
'PharIo\\Version\\AnyVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/AnyVersionConstraint.php',
'PharIo\\Version\\ExactVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/ExactVersionConstraint.php',
'PharIo\\Version\\Exception' => __DIR__ . '/..' . '/phar-io/version/src/Exception.php',
'PharIo\\Version\\GreaterThanOrEqualToVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/GreaterThanOrEqualToVersionConstraint.php',
'PharIo\\Version\\InvalidVersionException' => __DIR__ . '/..' . '/phar-io/version/src/InvalidVersionException.php',
'PharIo\\Version\\OrVersionConstraintGroup' => __DIR__ . '/..' . '/phar-io/version/src/OrVersionConstraintGroup.php',
'PharIo\\Version\\PreReleaseSuffix' => __DIR__ . '/..' . '/phar-io/version/src/PreReleaseSuffix.php',
'PharIo\\Version\\SpecificMajorAndMinorVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/SpecificMajorAndMinorVersionConstraint.php',
'PharIo\\Version\\SpecificMajorVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/SpecificMajorVersionConstraint.php',
'PharIo\\Version\\UnsupportedVersionConstraintException' => __DIR__ . '/..' . '/phar-io/version/src/UnsupportedVersionConstraintException.php',
'PharIo\\Version\\Version' => __DIR__ . '/..' . '/phar-io/version/src/Version.php',
'PharIo\\Version\\VersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/VersionConstraint.php',
'PharIo\\Version\\VersionConstraintParser' => __DIR__ . '/..' . '/phar-io/version/src/VersionConstraintParser.php',
'PharIo\\Version\\VersionConstraintValue' => __DIR__ . '/..' . '/phar-io/version/src/VersionConstraintValue.php',
'PharIo\\Version\\VersionNumber' => __DIR__ . '/..' . '/phar-io/version/src/VersionNumber.php',
'SebastianBergmann\\CodeCoverage\\CodeCoverage' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/CodeCoverage.php',
'SebastianBergmann\\CodeCoverage\\CoveredCodeNotExecutedException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/CoveredCodeNotExecutedException.php',
'SebastianBergmann\\CodeCoverage\\Driver\\Driver' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/Driver.php',
'SebastianBergmann\\CodeCoverage\\Driver\\HHVM' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/HHVM.php',
'SebastianBergmann\\CodeCoverage\\Driver\\PHPDBG' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/PHPDBG.php',
'SebastianBergmann\\CodeCoverage\\Driver\\Xdebug' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/Xdebug.php',
'SebastianBergmann\\CodeCoverage\\Exception' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/Exception.php',
'SebastianBergmann\\CodeCoverage\\Filter' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Filter.php',
'SebastianBergmann\\CodeCoverage\\InvalidArgumentException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/InvalidArgumentException.php',
'SebastianBergmann\\CodeCoverage\\MissingCoversAnnotationException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/MissingCoversAnnotationException.php',
'SebastianBergmann\\CodeCoverage\\Node\\AbstractNode' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/AbstractNode.php',
'SebastianBergmann\\CodeCoverage\\Node\\Builder' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/Builder.php',
'SebastianBergmann\\CodeCoverage\\Node\\Directory' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/Directory.php',
'SebastianBergmann\\CodeCoverage\\Node\\File' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/File.php',
'SebastianBergmann\\CodeCoverage\\Node\\Iterator' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/Iterator.php',
'SebastianBergmann\\CodeCoverage\\Report\\Clover' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Clover.php',
'SebastianBergmann\\CodeCoverage\\Report\\Crap4j' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Crap4j.php',
'SebastianBergmann\\CodeCoverage\\Report\\Html\\Dashboard' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer/Dashboard.php',
'SebastianBergmann\\CodeCoverage\\Report\\Html\\Directory' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer/Directory.php',
'SebastianBergmann\\CodeCoverage\\Report\\Html\\Facade' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Facade.php',
'SebastianBergmann\\CodeCoverage\\Report\\Html\\File' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer/File.php',
'SebastianBergmann\\CodeCoverage\\Report\\Html\\Renderer' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer.php',
'SebastianBergmann\\CodeCoverage\\Report\\PHP' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/PHP.php',
'SebastianBergmann\\CodeCoverage\\Report\\Text' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Text.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\BuildInformation' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/BuildInformation.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Coverage' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Coverage.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Directory' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Directory.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Facade' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Facade.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\File' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/File.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Method' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Method.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Node' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Node.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Project' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Project.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Report' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Report.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Source' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Source.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Tests' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Tests.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Totals' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Totals.php',
'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Unit' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Unit.php',
'SebastianBergmann\\CodeCoverage\\RuntimeException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/RuntimeException.php',
'SebastianBergmann\\CodeCoverage\\UnintentionallyCoveredCodeException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/UnintentionallyCoveredCodeException.php',
'SebastianBergmann\\CodeCoverage\\Util' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Util.php',
'SebastianBergmann\\CodeCoverage\\Version' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Version.php',
'SebastianBergmann\\CodeUnitReverseLookup\\Wizard' => __DIR__ . '/..' . '/sebastian/code-unit-reverse-lookup/src/Wizard.php',
'SebastianBergmann\\Comparator\\ArrayComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ArrayComparator.php',
'SebastianBergmann\\Comparator\\Comparator' => __DIR__ . '/..' . '/sebastian/comparator/src/Comparator.php',
'SebastianBergmann\\Comparator\\ComparisonFailure' => __DIR__ . '/..' . '/sebastian/comparator/src/ComparisonFailure.php',
'SebastianBergmann\\Comparator\\DOMNodeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DOMNodeComparator.php',
'SebastianBergmann\\Comparator\\DateTimeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DateTimeComparator.php',
'SebastianBergmann\\Comparator\\DoubleComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DoubleComparator.php',
'SebastianBergmann\\Comparator\\ExceptionComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ExceptionComparator.php',
'SebastianBergmann\\Comparator\\Factory' => __DIR__ . '/..' . '/sebastian/comparator/src/Factory.php',
'SebastianBergmann\\Comparator\\MockObjectComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/MockObjectComparator.php',
'SebastianBergmann\\Comparator\\NumericComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/NumericComparator.php',
'SebastianBergmann\\Comparator\\ObjectComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ObjectComparator.php',
'SebastianBergmann\\Comparator\\ResourceComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ResourceComparator.php',
'SebastianBergmann\\Comparator\\ScalarComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ScalarComparator.php',
'SebastianBergmann\\Comparator\\SplObjectStorageComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/SplObjectStorageComparator.php',
'SebastianBergmann\\Comparator\\TypeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/TypeComparator.php',
'SebastianBergmann\\Diff\\Chunk' => __DIR__ . '/..' . '/sebastian/diff/src/Chunk.php',
'SebastianBergmann\\Diff\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php',
'SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php',
'SebastianBergmann\\Diff\\Exception' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/Exception.php',
'SebastianBergmann\\Diff\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/InvalidArgumentException.php',
'SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php',
'SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php',
'SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php',
'SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php',
'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php',
'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php',
'SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php',
'SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php',
'SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php',
'SebastianBergmann\\Environment\\Console' => __DIR__ . '/..' . '/sebastian/environment/src/Console.php',
'SebastianBergmann\\Environment\\OperatingSystem' => __DIR__ . '/..' . '/sebastian/environment/src/OperatingSystem.php',
'SebastianBergmann\\Environment\\Runtime' => __DIR__ . '/..' . '/sebastian/environment/src/Runtime.php',
'SebastianBergmann\\Exporter\\Exporter' => __DIR__ . '/..' . '/sebastian/exporter/src/Exporter.php',
'SebastianBergmann\\GlobalState\\Blacklist' => __DIR__ . '/..' . '/sebastian/global-state/src/Blacklist.php',
'SebastianBergmann\\GlobalState\\CodeExporter' => __DIR__ . '/..' . '/sebastian/global-state/src/CodeExporter.php',
'SebastianBergmann\\GlobalState\\Exception' => __DIR__ . '/..' . '/sebastian/global-state/src/exceptions/Exception.php',
'SebastianBergmann\\GlobalState\\Restorer' => __DIR__ . '/..' . '/sebastian/global-state/src/Restorer.php',
'SebastianBergmann\\GlobalState\\RuntimeException' => __DIR__ . '/..' . '/sebastian/global-state/src/exceptions/RuntimeException.php',
'SebastianBergmann\\GlobalState\\Snapshot' => __DIR__ . '/..' . '/sebastian/global-state/src/Snapshot.php',
'SebastianBergmann\\ObjectEnumerator\\Enumerator' => __DIR__ . '/..' . '/sebastian/object-enumerator/src/Enumerator.php',
'SebastianBergmann\\ObjectEnumerator\\Exception' => __DIR__ . '/..' . '/sebastian/object-enumerator/src/Exception.php',
'SebastianBergmann\\ObjectEnumerator\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/object-enumerator/src/InvalidArgumentException.php',
'SebastianBergmann\\ObjectReflector\\Exception' => __DIR__ . '/..' . '/sebastian/object-reflector/src/Exception.php',
'SebastianBergmann\\ObjectReflector\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/object-reflector/src/InvalidArgumentException.php',
'SebastianBergmann\\ObjectReflector\\ObjectReflector' => __DIR__ . '/..' . '/sebastian/object-reflector/src/ObjectReflector.php',
'SebastianBergmann\\RecursionContext\\Context' => __DIR__ . '/..' . '/sebastian/recursion-context/src/Context.php',
'SebastianBergmann\\RecursionContext\\Exception' => __DIR__ . '/..' . '/sebastian/recursion-context/src/Exception.php',
'SebastianBergmann\\RecursionContext\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/recursion-context/src/InvalidArgumentException.php',
'SebastianBergmann\\ResourceOperations\\ResourceOperations' => __DIR__ . '/..' . '/sebastian/resource-operations/src/ResourceOperations.php',
'SebastianBergmann\\Version' => __DIR__ . '/..' . '/sebastian/version/src/Version.php',
'Text_Template' => __DIR__ . '/..' . '/phpunit/php-text-template/src/Template.php',
'TheSeer\\Tokenizer\\Exception' => __DIR__ . '/..' . '/theseer/tokenizer/src/Exception.php',
'TheSeer\\Tokenizer\\NamespaceUri' => __DIR__ . '/..' . '/theseer/tokenizer/src/NamespaceUri.php',
'TheSeer\\Tokenizer\\NamespaceUriException' => __DIR__ . '/..' . '/theseer/tokenizer/src/NamespaceUriException.php',
'TheSeer\\Tokenizer\\Token' => __DIR__ . '/..' . '/theseer/tokenizer/src/Token.php',
'TheSeer\\Tokenizer\\TokenCollection' => __DIR__ . '/..' . '/theseer/tokenizer/src/TokenCollection.php',
'TheSeer\\Tokenizer\\TokenCollectionException' => __DIR__ . '/..' . '/theseer/tokenizer/src/TokenCollectionException.php',
'TheSeer\\Tokenizer\\Tokenizer' => __DIR__ . '/..' . '/theseer/tokenizer/src/Tokenizer.php',
'TheSeer\\Tokenizer\\XMLSerializer' => __DIR__ . '/..' . '/theseer/tokenizer/src/XMLSerializer.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit148e3ff598796c30c73a1c9a3acfccd8::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit148e3ff598796c30c73a1c9a3acfccd8::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit148e3ff598796c30c73a1c9a3acfccd8::$prefixesPsr0;
$loader->classMap = ComposerStaticInit148e3ff598796c30c73a1c9a3acfccd8::$classMap;
}, null, ClassLoader::class);
}
}
| gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/org/codehaus/jackson/impl/JsonParserBase.java | 161 | // INTERNAL ERROR //
/* Location: classes_dex2jar.jar
* Qualified Name: org.codehaus.jackson.impl.JsonParserBase
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
danielbonetto/twig_MVC | lang/th/filters.php | 4537 | <?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/>.
/**
* Strings for component 'filters', language 'th', branch 'MOODLE_22_STABLE'
*
* @package filters
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['actfilterhdr'] = 'ตัวกรองที่ใช้งานอยู่';
$string['addfilter'] = 'เพิ่มกรอง';
$string['anycategory'] = 'หมวดหมู่ใด ๆ';
$string['anycourse'] = 'หลักสูตรใดก็ได้';
$string['anyfield'] = 'สาขาใดสาขาหนึ่ง';
$string['anyrole'] = 'บทบาทใด ๆ';
$string['anyvalue'] = 'ค่าใด ๆ';
$string['categoryrole'] = 'บทบาทหมวดหมู่';
$string['contains'] = 'ประกอบด้วย';
$string['courserole'] = 'บทบาทของรายวิชา';
$string['courserolelabel'] = '{$a->label} {$a->rolename} ใน {$a->coursename} จาก {$a->categoryname}';
$string['courserolelabelerror'] = '{$a->label} ข้อผิดพ: สนาม {$a->coursename} ไม่อยู่';
$string['customlabel'] = '{$a->label}: {$a->custom} {$a->operator} {$a->value}';
$string['customlabelnovalue'] = '{$a->label}: {$a->profile} {$a->operator}';
$string['datelabelisafter'] = '{$a->label} คือหลังจก {$a->after}';
$string['datelabelisbefore'] = '{$a->label} is before {$a->before}';
$string['datelabelisbetween'] = '{$a->label} is between {$a->after} and {$a->before}';
$string['doesnotcontain'] = 'ไม่ได้มี';
$string['endswith'] = 'จบลงด้วย';
$string['firstaccess'] = 'เข้าถึงครั้งแรก';
$string['globalrolelabel'] = '{$a->label} is {$a->value}';
$string['includenever'] = 'ไม่รวม';
$string['includesubcategories'] = 'รวมทั้งหมวดย่อย?';
$string['isafter'] = 'คือหลังจากที่';
$string['isanyvalue'] = 'คือค่าใด ๆ';
$string['isbefore'] = 'คือก่อนที่';
$string['isdefined'] = 'ถูกกำหนดไว้';
$string['isempty'] = 'เป็นที่ว่างเปล่า';
$string['isequalto'] = 'มีค่าเท่ากับ';
$string['isgreaterorequalto'] = 'มีค่ามากกว่าหรือเท่ากับ';
$string['isgreaterthan'] = 'มีค่ามากกว่า';
$string['islessthan'] = 'มีค่าน้อยกว่า';
$string['islessthanorequalto'] = 'มีค่าน้อยกว่าหรือเท่ากับ';
$string['isnotdefined'] = 'ไม่ได้กำหนด';
$string['isnotequalto'] = 'ไม่เท่ากับ';
$string['matchesallselected'] = 'ตรงกับที่เลือกไว้ทั้งหมด';
$string['matchesanyselected'] = 'ตรงกับที่เลือกใด ๆ';
$string['newfilter'] = 'ตัวกรองใหม่';
$string['profilelabel'] = '{$a->label}: {$a->profile} {$a->operator} {$a->value}';
$string['profilelabelnovalue'] = '{$a->label}: {$a->profile} {$a->operator}';
$string['removeall'] = 'ลบตัวกรองทั้งหมด';
$string['removeselected'] = 'ลบออกเลือก';
$string['selectlabel'] = '{$a->label} {$a->operator} {$a->value}';
$string['selectlabelnoop'] = '{$a->label} {$a->value}';
$string['startswith'] = 'เริ่มต้นด้วย';
$string['tablenosave'] = 'การเปลี่ยนแปลงในด้านบนของตารางจะถูกบันทึกไว้โดยอัตโนมัติ';
$string['textlabel'] = '{$a->label} {$a->operator} {$a->value}';
$string['textlabelnovalue'] = '{$a->label} {$a->operator}';
| gpl-3.0 |
bieberg0n/bjdns | gfwlistcheck.py | 1277 | import base64
import urllib.parse
from utils import (
dict_deep_set
)
class GfwList:
def __init__(self):
self.data = dict()
self.read_line()
def add_host(self, host):
parts = [part for part in reversed(host.split('.')) if part]
dict_deep_set(self.data, parts)
def read_line(self):
with open('gfwlist.txt') as f:
txt = f.read()
txt = base64.b64decode(txt).decode()
lines = txt.split('\n')
for line in lines:
if line == '' or line[0] in ('[', '!', '@'):
continue
elif line.startswith('|http'):
url = urllib.parse.urlsplit(line[1:])
host = url.netloc
self.add_host(host)
elif line.startswith('||'):
self.add_host(line[2:])
elif '/' not in line:
self.add_host(line)
def check(self, host):
d = self.data
parts = [part for part in reversed(host.split('.')) if part]
for part in parts[:-1]:
if d.get(part):
d = d[part]
else:
return False
else:
return d.get(parts[-1]) is not None
if __name__ == '__main__':
gfwlist = GfwList()
| gpl-3.0 |
njdart/markings-template-example | root.syntaxes.js | 2455 |
/**
* module - export a function that will modify any existing syntaxes
*
* @param {type} taskDefs description
* @return {type} description
*/
module.exports.default = function(taskDefs) {
let taskOrder = taskDefs.taskOrder;
let tasks = taskDefs.tasks;
tasks['fillertexts'] = {
runTasksBefore: [],
runTasksAfter: [],
runBeforesIfDependency: false,
runAftersIfDependency: false,
disabled: false,
syntaxes: [
{
name: 'Samuel Lipsum',
disabled: false,
do: function(text) {
return text.replace(/\n[ \t]{0,3}\[\[lorem\s+ipsum\]\][ \t]*\n/gi, `
> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
> eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
> voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
> clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
> amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
> nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
> sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
> rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
> ipsum dolor sit amet.\n`.replace(/[ \t]{2,}/, ' '));
}
},
{
name: 'Samuel Lipsum',
disabled: false,
do: function(text) {
return text.replace(/\n[ \t]{0,3}\[\[samuel\s+l\.?\s*ipsum\]\][ \t]*\n/gi, `
> The path of the righteous man is beset on all sides by the iniquities of
> the selfish and the tyranny of evil men. Blessed is he who, in the name of
> charity and good will, shepherds the weak through the valley of darkness,
> for he is truly his brother\'s keeper and the finder of lost children. And
> I will strike down upon thee with great vengeance and furious anger those
> who would attempt to poison and destroy My brothers. And you will know My
> name is the Lord when I lay My vengeance upon thee.\n`.replace(/[ \t]{2,}/, ' '));
}
}
]
};
// the fillertexts needs to be inserted after the 'preParseCleanup' and before 'formParahraphs'
taskOrder.splice(taskOrder.indexOf('preParseCleanup') + 1, 0, 'fillertexts');
return {
taskOrder,
tasks
};
};
| gpl-3.0 |
HexHive/datashield | compiler/llvm/lib/Target/X86/X86MCInstLower.cpp | 67998 | //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code to lower X86 MachineInstrs to their corresponding
// MCInst records.
//
//===----------------------------------------------------------------------===//
#include "X86AsmPrinter.h"
#include "X86RegisterInfo.h"
#include "X86ShuffleDecodeConstantPool.h"
#include "InstPrinter/X86ATTInstPrinter.h"
#include "MCTargetDesc/X86BaseInfo.h"
#include "Utils/X86ShuffleDecode.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Mangler.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
static cl::opt<bool>
DataShieldUsePrefix("datashield-use-prefix",
cl::desc("enable address override bounds enforcement"),
cl::init(false));
static cl::opt<bool>
DataShieldUseLateMPX("datashield-use-late-mpx",
cl::desc("enable mpx bounds enforcement at code emission"),
cl::init(false));
namespace {
/// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
class X86MCInstLower {
MCContext &Ctx;
const MachineFunction &MF;
const TargetMachine &TM;
const MCAsmInfo &MAI;
X86AsmPrinter &AsmPrinter;
public:
X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
const MachineOperand &MO) const;
void Lower(const MachineInstr *MI, MCInst &OutMI) const;
MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
private:
MachineModuleInfoMachO &getMachOMMI() const;
Mangler *getMang() const {
return AsmPrinter.Mang;
}
};
} // end anonymous namespace
// Emit a minimal sequence of nops spanning NumBytes bytes.
static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
const MCSubtargetInfo &STI);
namespace llvm {
X86AsmPrinter::StackMapShadowTracker::StackMapShadowTracker(TargetMachine &TM)
: TM(TM), InShadow(false), RequiredShadowSize(0), CurrentShadowSize(0) {}
X86AsmPrinter::StackMapShadowTracker::~StackMapShadowTracker() {}
void
X86AsmPrinter::StackMapShadowTracker::startFunction(MachineFunction &F) {
MF = &F;
CodeEmitter.reset(TM.getTarget().createMCCodeEmitter(
*MF->getSubtarget().getInstrInfo(),
*MF->getSubtarget().getRegisterInfo(), MF->getContext()));
}
void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
const MCSubtargetInfo &STI) {
if (InShadow) {
SmallString<256> Code;
SmallVector<MCFixup, 4> Fixups;
raw_svector_ostream VecOS(Code);
CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
CurrentShadowSize += Code.size();
if (CurrentShadowSize >= RequiredShadowSize)
InShadow = false; // The shadow is big enough. Stop counting.
}
}
void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
if (InShadow && CurrentShadowSize < RequiredShadowSize) {
InShadow = false;
EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
}
}
void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
OutStreamer->EmitInstruction(Inst, getSubtargetInfo());
SMShadowTracker.count(Inst, getSubtargetInfo());
}
} // end llvm namespace
X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
X86AsmPrinter &asmprinter)
: Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
AsmPrinter(asmprinter) {}
MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
}
/// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
/// operand to an MCSymbol.
MCSymbol *X86MCInstLower::
GetSymbolFromOperand(const MachineOperand &MO) const {
const DataLayout &DL = MF.getDataLayout();
assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) && "Isn't a symbol reference");
MCSymbol *Sym = nullptr;
SmallString<128> Name;
StringRef Suffix;
switch (MO.getTargetFlags()) {
case X86II::MO_DLLIMPORT:
// Handle dllimport linkage.
Name += "__imp_";
break;
case X86II::MO_DARWIN_STUB:
Suffix = "$stub";
break;
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
Suffix = "$non_lazy_ptr";
break;
}
if (!Suffix.empty())
Name += DL.getPrivateGlobalPrefix();
unsigned PrefixLen = Name.size();
if (MO.isGlobal()) {
const GlobalValue *GV = MO.getGlobal();
AsmPrinter.getNameWithPrefix(Name, GV);
} else if (MO.isSymbol()) {
Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
} else if (MO.isMBB()) {
assert(Suffix.empty());
Sym = MO.getMBB()->getSymbol();
}
unsigned OrigLen = Name.size() - PrefixLen;
Name += Suffix;
if (!Sym)
Sym = Ctx.getOrCreateSymbol(Name);
StringRef OrigName = StringRef(Name).substr(PrefixLen, OrigLen);
// If the target flags on the operand changes the name of the symbol, do that
// before we return the symbol.
switch (MO.getTargetFlags()) {
default: break;
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
MachineModuleInfoImpl::StubValueTy &StubSym =
getMachOMMI().getGVStubEntry(Sym);
if (!StubSym.getPointer()) {
assert(MO.isGlobal() && "Extern symbol not handled yet");
StubSym =
MachineModuleInfoImpl::
StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
!MO.getGlobal()->hasInternalLinkage());
}
break;
}
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE: {
MachineModuleInfoImpl::StubValueTy &StubSym =
getMachOMMI().getHiddenGVStubEntry(Sym);
if (!StubSym.getPointer()) {
assert(MO.isGlobal() && "Extern symbol not handled yet");
StubSym =
MachineModuleInfoImpl::
StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
!MO.getGlobal()->hasInternalLinkage());
}
break;
}
case X86II::MO_DARWIN_STUB: {
MachineModuleInfoImpl::StubValueTy &StubSym =
getMachOMMI().getFnStubEntry(Sym);
if (StubSym.getPointer())
return Sym;
if (MO.isGlobal()) {
StubSym =
MachineModuleInfoImpl::
StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
!MO.getGlobal()->hasInternalLinkage());
} else {
StubSym =
MachineModuleInfoImpl::
StubValueTy(Ctx.getOrCreateSymbol(OrigName), false);
}
break;
}
}
return Sym;
}
MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
MCSymbol *Sym) const {
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
const MCExpr *Expr = nullptr;
MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
// These affect the name of the symbol, not any suffix.
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DLLIMPORT:
case X86II::MO_DARWIN_STUB:
break;
case X86II::MO_TLVP: RefKind = MCSymbolRefExpr::VK_TLVP; break;
case X86II::MO_TLVP_PIC_BASE:
Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
// Subtract the pic base.
Expr = MCBinaryExpr::createSub(Expr,
MCSymbolRefExpr::create(MF.getPICBaseSymbol(),
Ctx),
Ctx);
break;
case X86II::MO_SECREL: RefKind = MCSymbolRefExpr::VK_SECREL; break;
case X86II::MO_TLSGD: RefKind = MCSymbolRefExpr::VK_TLSGD; break;
case X86II::MO_TLSLD: RefKind = MCSymbolRefExpr::VK_TLSLD; break;
case X86II::MO_TLSLDM: RefKind = MCSymbolRefExpr::VK_TLSLDM; break;
case X86II::MO_GOTTPOFF: RefKind = MCSymbolRefExpr::VK_GOTTPOFF; break;
case X86II::MO_INDNTPOFF: RefKind = MCSymbolRefExpr::VK_INDNTPOFF; break;
case X86II::MO_TPOFF: RefKind = MCSymbolRefExpr::VK_TPOFF; break;
case X86II::MO_DTPOFF: RefKind = MCSymbolRefExpr::VK_DTPOFF; break;
case X86II::MO_NTPOFF: RefKind = MCSymbolRefExpr::VK_NTPOFF; break;
case X86II::MO_GOTNTPOFF: RefKind = MCSymbolRefExpr::VK_GOTNTPOFF; break;
case X86II::MO_GOTPCREL: RefKind = MCSymbolRefExpr::VK_GOTPCREL; break;
case X86II::MO_GOT: RefKind = MCSymbolRefExpr::VK_GOT; break;
case X86II::MO_GOTOFF: RefKind = MCSymbolRefExpr::VK_GOTOFF; break;
case X86II::MO_PLT: RefKind = MCSymbolRefExpr::VK_PLT; break;
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
Expr = MCSymbolRefExpr::create(Sym, Ctx);
// Subtract the pic base.
Expr = MCBinaryExpr::createSub(Expr,
MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx),
Ctx);
if (MO.isJTI()) {
assert(MAI.doesSetDirectiveSuppressesReloc());
// If .set directive is supported, use it to reduce the number of
// relocations the assembler will generate for differences between
// local labels. This is only safe when the symbols are in the same
// section so we are restricting it to jumptable references.
MCSymbol *Label = Ctx.createTempSymbol();
AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
Expr = MCSymbolRefExpr::create(Label, Ctx);
}
break;
}
if (!Expr)
Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
Expr = MCBinaryExpr::createAdd(Expr,
MCConstantExpr::create(MO.getOffset(), Ctx),
Ctx);
return MCOperand::createExpr(Expr);
}
/// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
/// a short fixed-register form.
static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
unsigned ImmOp = Inst.getNumOperands() - 1;
assert(Inst.getOperand(0).isReg() &&
(Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
Inst.getNumOperands() == 2) && "Unexpected instruction!");
// Check whether the destination register can be fixed.
unsigned Reg = Inst.getOperand(0).getReg();
if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
return;
// If so, rewrite the instruction.
MCOperand Saved = Inst.getOperand(ImmOp);
Inst = MCInst();
Inst.setOpcode(Opcode);
Inst.addOperand(Saved);
}
/// \brief If a movsx instruction has a shorter encoding for the used register
/// simplify the instruction to use it instead.
static void SimplifyMOVSX(MCInst &Inst) {
unsigned NewOpcode = 0;
unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
switch (Inst.getOpcode()) {
default:
llvm_unreachable("Unexpected instruction!");
case X86::MOVSX16rr8: // movsbw %al, %ax --> cbtw
if (Op0 == X86::AX && Op1 == X86::AL)
NewOpcode = X86::CBW;
break;
case X86::MOVSX32rr16: // movswl %ax, %eax --> cwtl
if (Op0 == X86::EAX && Op1 == X86::AX)
NewOpcode = X86::CWDE;
break;
case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
if (Op0 == X86::RAX && Op1 == X86::EAX)
NewOpcode = X86::CDQE;
break;
}
if (NewOpcode != 0) {
Inst = MCInst();
Inst.setOpcode(NewOpcode);
}
}
/// \brief Simplify things like MOV32rm to MOV32o32a.
static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
unsigned Opcode) {
// Don't make these simplifications in 64-bit mode; other assemblers don't
// perform them because they make the code larger.
if (Printer.getSubtarget().is64Bit())
return;
bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
unsigned AddrBase = IsStore;
unsigned RegOp = IsStore ? 0 : 5;
unsigned AddrOp = AddrBase + 3;
assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
(Inst.getOperand(AddrOp).isExpr() ||
Inst.getOperand(AddrOp).isImm()) &&
"Unexpected instruction!");
// Check whether the destination register can be fixed.
unsigned Reg = Inst.getOperand(RegOp).getReg();
if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
return;
// Check whether this is an absolute address.
// FIXME: We know TLVP symbol refs aren't, but there should be a better way
// to do this here.
bool Absolute = true;
if (Inst.getOperand(AddrOp).isExpr()) {
const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
Absolute = false;
}
if (Absolute &&
(Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
return;
// If so, rewrite the instruction.
MCOperand Saved = Inst.getOperand(AddrOp);
MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
Inst = MCInst();
Inst.setOpcode(Opcode);
Inst.addOperand(Saved);
Inst.addOperand(Seg);
}
static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
}
Optional<MCOperand>
X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
const MachineOperand &MO) const {
switch (MO.getType()) {
default:
MI->dump();
llvm_unreachable("unknown operand type");
case MachineOperand::MO_Register:
// Ignore all implicit register operands.
if (MO.isImplicit())
return None;
return MCOperand::createReg(MO.getReg());
case MachineOperand::MO_Immediate:
return MCOperand::createImm(MO.getImm());
case MachineOperand::MO_MachineBasicBlock:
case MachineOperand::MO_GlobalAddress:
case MachineOperand::MO_ExternalSymbol:
return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
case MachineOperand::MO_MCSymbol:
return LowerSymbolOperand(MO, MO.getMCSymbol());
case MachineOperand::MO_JumpTableIndex:
return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
case MachineOperand::MO_ConstantPoolIndex:
return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
case MachineOperand::MO_BlockAddress:
return LowerSymbolOperand(
MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
case MachineOperand::MO_RegisterMask:
// Ignore call clobbers.
return None;
}
}
void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
OutMI.setOpcode(MI->getOpcode());
for (const MachineOperand &MO : MI->operands())
if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
OutMI.addOperand(MaybeMCOp.getValue());
// Handle a few special cases to eliminate operand modifiers.
ReSimplify:
switch (OutMI.getOpcode()) {
case X86::LEA64_32r:
case X86::LEA64r:
case X86::LEA16r:
case X86::LEA32r:
// LEA should have a segment register, but it must be empty.
assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
"Unexpected # of LEA operands");
assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
"LEA has segment specified!");
break;
// Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
// if one of the registers is extended, but other isn't.
case X86::VMOVZPQILo2PQIrr:
case X86::VMOVAPDrr:
case X86::VMOVAPDYrr:
case X86::VMOVAPSrr:
case X86::VMOVAPSYrr:
case X86::VMOVDQArr:
case X86::VMOVDQAYrr:
case X86::VMOVDQUrr:
case X86::VMOVDQUYrr:
case X86::VMOVUPDrr:
case X86::VMOVUPDYrr:
case X86::VMOVUPSrr:
case X86::VMOVUPSYrr: {
if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
unsigned NewOpc;
switch (OutMI.getOpcode()) {
default: llvm_unreachable("Invalid opcode");
case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr; break;
case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
}
OutMI.setOpcode(NewOpc);
}
break;
}
case X86::VMOVSDrr:
case X86::VMOVSSrr: {
if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
unsigned NewOpc;
switch (OutMI.getOpcode()) {
default: llvm_unreachable("Invalid opcode");
case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
}
OutMI.setOpcode(NewOpc);
}
break;
}
// TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
// inputs modeled as normal uses instead of implicit uses. As such, truncate
// off all but the first operand (the callee). FIXME: Change isel.
case X86::TAILJMPr64:
case X86::TAILJMPr64_REX:
case X86::CALL64r:
case X86::CALL64pcrel32: {
unsigned Opcode = OutMI.getOpcode();
MCOperand Saved = OutMI.getOperand(0);
OutMI = MCInst();
OutMI.setOpcode(Opcode);
OutMI.addOperand(Saved);
break;
}
case X86::EH_RETURN:
case X86::EH_RETURN64: {
OutMI = MCInst();
OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
break;
}
case X86::CLEANUPRET: {
// Replace CATCHRET with the appropriate RET.
OutMI = MCInst();
OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
break;
}
case X86::CATCHRET: {
// Replace CATCHRET with the appropriate RET.
const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
OutMI = MCInst();
OutMI.setOpcode(getRetOpcode(Subtarget));
OutMI.addOperand(MCOperand::createReg(ReturnReg));
break;
}
// TAILJMPd, TAILJMPd64 - Lower to the correct jump instructions.
case X86::TAILJMPr:
case X86::TAILJMPd:
case X86::TAILJMPd64: {
unsigned Opcode;
switch (OutMI.getOpcode()) {
default: llvm_unreachable("Invalid opcode");
case X86::TAILJMPr: Opcode = X86::JMP32r; break;
case X86::TAILJMPd:
case X86::TAILJMPd64: Opcode = X86::JMP_1; break;
}
MCOperand Saved = OutMI.getOperand(0);
OutMI = MCInst();
OutMI.setOpcode(Opcode);
OutMI.addOperand(Saved);
break;
}
case X86::DEC16r:
case X86::DEC32r:
case X86::INC16r:
case X86::INC32r:
// If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
if (!AsmPrinter.getSubtarget().is64Bit()) {
unsigned Opcode;
switch (OutMI.getOpcode()) {
default: llvm_unreachable("Invalid opcode");
case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
case X86::INC16r: Opcode = X86::INC16r_alt; break;
case X86::INC32r: Opcode = X86::INC32r_alt; break;
}
OutMI.setOpcode(Opcode);
}
break;
// These are pseudo-ops for OR to help with the OR->ADD transformation. We do
// this with an ugly goto in case the resultant OR uses EAX and needs the
// short form.
case X86::ADD16rr_DB: OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
case X86::ADD32rr_DB: OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
case X86::ADD64rr_DB: OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
case X86::ADD16ri_DB: OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
case X86::ADD32ri_DB: OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
case X86::ADD16ri8_DB: OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
case X86::ADD32ri8_DB: OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
case X86::ADD64ri8_DB: OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
// Atomic load and store require a separate pseudo-inst because Acquire
// implies mayStore and Release implies mayLoad; fix these to regular MOV
// instructions here
case X86::ACQUIRE_MOV8rm: OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
case X86::ACQUIRE_MOV16rm: OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
case X86::ACQUIRE_MOV32rm: OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
case X86::ACQUIRE_MOV64rm: OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
case X86::RELEASE_MOV8mr: OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
case X86::RELEASE_MOV16mr: OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
case X86::RELEASE_MOV32mr: OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
case X86::RELEASE_MOV64mr: OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
case X86::RELEASE_MOV8mi: OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
case X86::RELEASE_MOV16mi: OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
case X86::RELEASE_MOV32mi: OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
case X86::RELEASE_ADD8mi: OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
case X86::RELEASE_ADD8mr: OutMI.setOpcode(X86::ADD8mr); goto ReSimplify;
case X86::RELEASE_ADD32mi: OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
case X86::RELEASE_ADD32mr: OutMI.setOpcode(X86::ADD32mr); goto ReSimplify;
case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
case X86::RELEASE_ADD64mr: OutMI.setOpcode(X86::ADD64mr); goto ReSimplify;
case X86::RELEASE_AND8mi: OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
case X86::RELEASE_AND8mr: OutMI.setOpcode(X86::AND8mr); goto ReSimplify;
case X86::RELEASE_AND32mi: OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
case X86::RELEASE_AND32mr: OutMI.setOpcode(X86::AND32mr); goto ReSimplify;
case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
case X86::RELEASE_AND64mr: OutMI.setOpcode(X86::AND64mr); goto ReSimplify;
case X86::RELEASE_OR8mi: OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
case X86::RELEASE_OR8mr: OutMI.setOpcode(X86::OR8mr); goto ReSimplify;
case X86::RELEASE_OR32mi: OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
case X86::RELEASE_OR32mr: OutMI.setOpcode(X86::OR32mr); goto ReSimplify;
case X86::RELEASE_OR64mi32: OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
case X86::RELEASE_OR64mr: OutMI.setOpcode(X86::OR64mr); goto ReSimplify;
case X86::RELEASE_XOR8mi: OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
case X86::RELEASE_XOR8mr: OutMI.setOpcode(X86::XOR8mr); goto ReSimplify;
case X86::RELEASE_XOR32mi: OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
case X86::RELEASE_XOR32mr: OutMI.setOpcode(X86::XOR32mr); goto ReSimplify;
case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
case X86::RELEASE_XOR64mr: OutMI.setOpcode(X86::XOR64mr); goto ReSimplify;
case X86::RELEASE_INC8m: OutMI.setOpcode(X86::INC8m); goto ReSimplify;
case X86::RELEASE_INC16m: OutMI.setOpcode(X86::INC16m); goto ReSimplify;
case X86::RELEASE_INC32m: OutMI.setOpcode(X86::INC32m); goto ReSimplify;
case X86::RELEASE_INC64m: OutMI.setOpcode(X86::INC64m); goto ReSimplify;
case X86::RELEASE_DEC8m: OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
case X86::RELEASE_DEC16m: OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
case X86::RELEASE_DEC32m: OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
case X86::RELEASE_DEC64m: OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
// We don't currently select the correct instruction form for instructions
// which have a short %eax, etc. form. Handle this by custom lowering, for
// now.
//
// Note, we are currently not handling the following instructions:
// MOV64ao8, MOV64o8a
// XCHG16ar, XCHG32ar, XCHG64ar
case X86::MOV8mr_NOREX:
case X86::MOV8mr: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8o32a); break;
case X86::MOV8rm_NOREX:
case X86::MOV8rm: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8ao32); break;
case X86::MOV16mr: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16o32a); break;
case X86::MOV16rm: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16ao32); break;
case X86::MOV32mr: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32o32a); break;
case X86::MOV32rm: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32ao32); break;
case X86::ADC8ri: SimplifyShortImmForm(OutMI, X86::ADC8i8); break;
case X86::ADC16ri: SimplifyShortImmForm(OutMI, X86::ADC16i16); break;
case X86::ADC32ri: SimplifyShortImmForm(OutMI, X86::ADC32i32); break;
case X86::ADC64ri32: SimplifyShortImmForm(OutMI, X86::ADC64i32); break;
case X86::ADD8ri: SimplifyShortImmForm(OutMI, X86::ADD8i8); break;
case X86::ADD16ri: SimplifyShortImmForm(OutMI, X86::ADD16i16); break;
case X86::ADD32ri: SimplifyShortImmForm(OutMI, X86::ADD32i32); break;
case X86::ADD64ri32: SimplifyShortImmForm(OutMI, X86::ADD64i32); break;
case X86::AND8ri: SimplifyShortImmForm(OutMI, X86::AND8i8); break;
case X86::AND16ri: SimplifyShortImmForm(OutMI, X86::AND16i16); break;
case X86::AND32ri: SimplifyShortImmForm(OutMI, X86::AND32i32); break;
case X86::AND64ri32: SimplifyShortImmForm(OutMI, X86::AND64i32); break;
case X86::CMP8ri: SimplifyShortImmForm(OutMI, X86::CMP8i8); break;
case X86::CMP16ri: SimplifyShortImmForm(OutMI, X86::CMP16i16); break;
case X86::CMP32ri: SimplifyShortImmForm(OutMI, X86::CMP32i32); break;
case X86::CMP64ri32: SimplifyShortImmForm(OutMI, X86::CMP64i32); break;
case X86::OR8ri: SimplifyShortImmForm(OutMI, X86::OR8i8); break;
case X86::OR16ri: SimplifyShortImmForm(OutMI, X86::OR16i16); break;
case X86::OR32ri: SimplifyShortImmForm(OutMI, X86::OR32i32); break;
case X86::OR64ri32: SimplifyShortImmForm(OutMI, X86::OR64i32); break;
case X86::SBB8ri: SimplifyShortImmForm(OutMI, X86::SBB8i8); break;
case X86::SBB16ri: SimplifyShortImmForm(OutMI, X86::SBB16i16); break;
case X86::SBB32ri: SimplifyShortImmForm(OutMI, X86::SBB32i32); break;
case X86::SBB64ri32: SimplifyShortImmForm(OutMI, X86::SBB64i32); break;
case X86::SUB8ri: SimplifyShortImmForm(OutMI, X86::SUB8i8); break;
case X86::SUB16ri: SimplifyShortImmForm(OutMI, X86::SUB16i16); break;
case X86::SUB32ri: SimplifyShortImmForm(OutMI, X86::SUB32i32); break;
case X86::SUB64ri32: SimplifyShortImmForm(OutMI, X86::SUB64i32); break;
case X86::TEST8ri: SimplifyShortImmForm(OutMI, X86::TEST8i8); break;
case X86::TEST16ri: SimplifyShortImmForm(OutMI, X86::TEST16i16); break;
case X86::TEST32ri: SimplifyShortImmForm(OutMI, X86::TEST32i32); break;
case X86::TEST64ri32: SimplifyShortImmForm(OutMI, X86::TEST64i32); break;
case X86::XOR8ri: SimplifyShortImmForm(OutMI, X86::XOR8i8); break;
case X86::XOR16ri: SimplifyShortImmForm(OutMI, X86::XOR16i16); break;
case X86::XOR32ri: SimplifyShortImmForm(OutMI, X86::XOR32i32); break;
case X86::XOR64ri32: SimplifyShortImmForm(OutMI, X86::XOR64i32); break;
// Try to shrink some forms of movsx.
case X86::MOVSX16rr8:
case X86::MOVSX32rr16:
case X86::MOVSX64rr32:
SimplifyMOVSX(OutMI);
break;
}
}
void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
const MachineInstr &MI) {
bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
MI.getOpcode() == X86::TLS_base_addr64;
bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
MCContext &context = OutStreamer->getContext();
if (needsPadding)
EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
MCSymbolRefExpr::VariantKind SRVK;
switch (MI.getOpcode()) {
case X86::TLS_addr32:
case X86::TLS_addr64:
SRVK = MCSymbolRefExpr::VK_TLSGD;
break;
case X86::TLS_base_addr32:
SRVK = MCSymbolRefExpr::VK_TLSLDM;
break;
case X86::TLS_base_addr64:
SRVK = MCSymbolRefExpr::VK_TLSLD;
break;
default:
llvm_unreachable("unexpected opcode");
}
MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
const MCSymbolRefExpr *symRef = MCSymbolRefExpr::create(sym, SRVK, context);
MCInst LEA;
if (is64Bits) {
LEA.setOpcode(X86::LEA64r);
LEA.addOperand(MCOperand::createReg(X86::RDI)); // dest
LEA.addOperand(MCOperand::createReg(X86::RIP)); // base
LEA.addOperand(MCOperand::createImm(1)); // scale
LEA.addOperand(MCOperand::createReg(0)); // index
LEA.addOperand(MCOperand::createExpr(symRef)); // disp
LEA.addOperand(MCOperand::createReg(0)); // seg
} else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
LEA.setOpcode(X86::LEA32r);
LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
LEA.addOperand(MCOperand::createReg(X86::EBX)); // base
LEA.addOperand(MCOperand::createImm(1)); // scale
LEA.addOperand(MCOperand::createReg(0)); // index
LEA.addOperand(MCOperand::createExpr(symRef)); // disp
LEA.addOperand(MCOperand::createReg(0)); // seg
} else {
LEA.setOpcode(X86::LEA32r);
LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
LEA.addOperand(MCOperand::createReg(0)); // base
LEA.addOperand(MCOperand::createImm(1)); // scale
LEA.addOperand(MCOperand::createReg(X86::EBX)); // index
LEA.addOperand(MCOperand::createExpr(symRef)); // disp
LEA.addOperand(MCOperand::createReg(0)); // seg
}
EmitAndCountInstruction(LEA);
if (needsPadding) {
EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
}
StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name);
const MCSymbolRefExpr *tlsRef =
MCSymbolRefExpr::create(tlsGetAddr,
MCSymbolRefExpr::VK_PLT,
context);
EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
: X86::CALLpcrel32)
.addExpr(tlsRef));
}
/// \brief Emit the optimal amount of multi-byte nops on X86.
static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI) {
// This works only for 64bit. For 32bit we have to do additional checking if
// the CPU supports multi-byte nops.
assert(Is64Bit && "EmitNops only supports X86-64");
while (NumBytes) {
unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
Opc = IndexReg = Displacement = SegmentReg = 0;
BaseReg = X86::RAX; ScaleVal = 1;
switch (NumBytes) {
case 0: llvm_unreachable("Zero nops?"); break;
case 1: NumBytes -= 1; Opc = X86::NOOP; break;
case 2: NumBytes -= 2; Opc = X86::XCHG16ar; break;
case 3: NumBytes -= 3; Opc = X86::NOOPL; break;
case 4: NumBytes -= 4; Opc = X86::NOOPL; Displacement = 8; break;
case 5: NumBytes -= 5; Opc = X86::NOOPL; Displacement = 8;
IndexReg = X86::RAX; break;
case 6: NumBytes -= 6; Opc = X86::NOOPW; Displacement = 8;
IndexReg = X86::RAX; break;
case 7: NumBytes -= 7; Opc = X86::NOOPL; Displacement = 512; break;
case 8: NumBytes -= 8; Opc = X86::NOOPL; Displacement = 512;
IndexReg = X86::RAX; break;
case 9: NumBytes -= 9; Opc = X86::NOOPW; Displacement = 512;
IndexReg = X86::RAX; break;
default: NumBytes -= 10; Opc = X86::NOOPW; Displacement = 512;
IndexReg = X86::RAX; SegmentReg = X86::CS; break;
}
unsigned NumPrefixes = std::min(NumBytes, 5U);
NumBytes -= NumPrefixes;
for (unsigned i = 0; i != NumPrefixes; ++i)
OS.EmitBytes("\x66");
switch (Opc) {
default: llvm_unreachable("Unexpected opcode"); break;
case X86::NOOP:
OS.EmitInstruction(MCInstBuilder(Opc), STI);
break;
case X86::XCHG16ar:
OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
break;
case X86::NOOPL:
case X86::NOOPW:
OS.EmitInstruction(MCInstBuilder(Opc).addReg(BaseReg)
.addImm(ScaleVal).addReg(IndexReg)
.addImm(Displacement).addReg(SegmentReg), STI);
break;
}
} // while (NumBytes)
}
void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
X86MCInstLower &MCIL) {
assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
StatepointOpers SOpers(&MI);
if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
getSubtargetInfo());
} else {
// Lower call target and choose correct opcode
const MachineOperand &CallTarget = SOpers.getCallTarget();
MCOperand CallTargetMCOp;
unsigned CallOpcode;
switch (CallTarget.getType()) {
case MachineOperand::MO_GlobalAddress:
case MachineOperand::MO_ExternalSymbol:
CallTargetMCOp = MCIL.LowerSymbolOperand(
CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
CallOpcode = X86::CALL64pcrel32;
// Currently, we only support relative addressing with statepoints.
// Otherwise, we'll need a scratch register to hold the target
// address. You'll fail asserts during load & relocation if this
// symbol is to far away. (TODO: support non-relative addressing)
break;
case MachineOperand::MO_Immediate:
CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
CallOpcode = X86::CALL64pcrel32;
// Currently, we only support relative addressing with statepoints.
// Otherwise, we'll need a scratch register to hold the target
// immediate. You'll fail asserts during load & relocation if this
// address is to far away. (TODO: support non-relative addressing)
break;
case MachineOperand::MO_Register:
CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
CallOpcode = X86::CALL64r;
break;
default:
llvm_unreachable("Unsupported operand type in statepoint call target");
break;
}
// Emit call
MCInst CallInst;
CallInst.setOpcode(CallOpcode);
CallInst.addOperand(CallTargetMCOp);
OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
}
// Record our statepoint node in the same section used by STACKMAP
// and PATCHPOINT
SM.recordStatepoint(MI);
}
void X86AsmPrinter::LowerFAULTING_LOAD_OP(const MachineInstr &MI,
X86MCInstLower &MCIL) {
// FAULTING_LOAD_OP <def>, <handler label>, <load opcode>, <load operands>
unsigned LoadDefRegister = MI.getOperand(0).getReg();
MCSymbol *HandlerLabel = MI.getOperand(1).getMCSymbol();
unsigned LoadOpcode = MI.getOperand(2).getImm();
unsigned LoadOperandsBeginIdx = 3;
FM.recordFaultingOp(FaultMaps::FaultingLoad, HandlerLabel);
MCInst LoadMI;
LoadMI.setOpcode(LoadOpcode);
if (LoadDefRegister != X86::NoRegister)
LoadMI.addOperand(MCOperand::createReg(LoadDefRegister));
for (auto I = MI.operands_begin() + LoadOperandsBeginIdx,
E = MI.operands_end();
I != E; ++I)
if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, *I))
LoadMI.addOperand(MaybeOperand.getValue());
OutStreamer->EmitInstruction(LoadMI, getSubtargetInfo());
}
// Lower a stackmap of the form:
// <id>, <shadowBytes>, ...
void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
SM.recordStackMap(MI);
unsigned NumShadowBytes = MI.getOperand(1).getImm();
SMShadowTracker.reset(NumShadowBytes);
}
// Lower a patchpoint of the form:
// [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
X86MCInstLower &MCIL) {
assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
SM.recordPatchPoint(MI);
PatchPointOpers opers(&MI);
unsigned ScratchIdx = opers.getNextScratchIdx();
unsigned EncodedBytes = 0;
const MachineOperand &CalleeMO =
opers.getMetaOper(PatchPointOpers::TargetPos);
// Check for null target. If target is non-null (i.e. is non-zero or is
// symbolic) then emit a call.
if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
MCOperand CalleeMCOp;
switch (CalleeMO.getType()) {
default:
/// FIXME: Add a verifier check for bad callee types.
llvm_unreachable("Unrecognized callee operand type.");
case MachineOperand::MO_Immediate:
if (CalleeMO.getImm())
CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
break;
case MachineOperand::MO_ExternalSymbol:
case MachineOperand::MO_GlobalAddress:
CalleeMCOp =
MCIL.LowerSymbolOperand(CalleeMO,
MCIL.GetSymbolFromOperand(CalleeMO));
break;
}
// Emit MOV to materialize the target address and the CALL to target.
// This is encoded with 12-13 bytes, depending on which register is used.
unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
if (X86II::isX86_64ExtendedReg(ScratchReg))
EncodedBytes = 13;
else
EncodedBytes = 12;
EmitAndCountInstruction(
MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
}
// Emit padding.
unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
assert(NumBytes >= EncodedBytes &&
"Patchpoint can't request size less than the length of a call.");
EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
getSubtargetInfo());
}
// Returns instruction preceding MBBI in MachineFunction.
// If MBBI is the first instruction of the first basic block, returns null.
static MachineBasicBlock::const_iterator
PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
const MachineBasicBlock *MBB = MBBI->getParent();
while (MBBI == MBB->begin()) {
if (MBB == MBB->getParent()->begin())
return nullptr;
MBB = MBB->getPrevNode();
MBBI = MBB->end();
}
return --MBBI;
}
static const Constant *getConstantFromPool(const MachineInstr &MI,
const MachineOperand &Op) {
if (!Op.isCPI())
return nullptr;
ArrayRef<MachineConstantPoolEntry> Constants =
MI.getParent()->getParent()->getConstantPool()->getConstants();
const MachineConstantPoolEntry &ConstantEntry =
Constants[Op.getIndex()];
// Bail if this is a machine constant pool entry, we won't be able to dig out
// anything useful.
if (ConstantEntry.isMachineConstantPoolEntry())
return nullptr;
auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
assert((!C || ConstantEntry.getType() == C->getType()) &&
"Expected a constant of the same type!");
return C;
}
static std::string getShuffleComment(const MachineOperand &DstOp,
const MachineOperand &SrcOp,
ArrayRef<int> Mask) {
std::string Comment;
// Compute the name for a register. This is really goofy because we have
// multiple instruction printers that could (in theory) use different
// names. Fortunately most people use the ATT style (outside of Windows)
// and they actually agree on register naming here. Ultimately, this is
// a comment, and so its OK if it isn't perfect.
auto GetRegisterName = [](unsigned RegNum) -> StringRef {
return X86ATTInstPrinter::getRegisterName(RegNum);
};
StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
raw_string_ostream CS(Comment);
CS << DstName << " = ";
bool NeedComma = false;
bool InSrc = false;
for (int M : Mask) {
// Wrap up any prior entry...
if (M == SM_SentinelZero && InSrc) {
InSrc = false;
CS << "]";
}
if (NeedComma)
CS << ",";
else
NeedComma = true;
// Print this shuffle...
if (M == SM_SentinelZero) {
CS << "zero";
} else {
if (!InSrc) {
InSrc = true;
CS << SrcName << "[";
}
if (M == SM_SentinelUndef)
CS << "u";
else
CS << M;
}
}
if (InSrc)
CS << "]";
CS.flush();
return Comment;
}
void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
X86MCInstLower MCInstLowering(*MF, *this);
const X86RegisterInfo *RI = MF->getSubtarget<X86Subtarget>().getRegisterInfo();
switch (MI->getOpcode()) {
case TargetOpcode::DBG_VALUE:
llvm_unreachable("Should be handled target independently");
// Emit nothing here but a comment if we can.
case X86::Int_MemBarrier:
OutStreamer->emitRawComment("MEMBARRIER");
return;
case X86::EH_RETURN:
case X86::EH_RETURN64: {
// Lower these as normal, but add some comments.
unsigned Reg = MI->getOperand(0).getReg();
OutStreamer->AddComment(StringRef("eh_return, addr: %") +
X86ATTInstPrinter::getRegisterName(Reg));
break;
}
case X86::CLEANUPRET: {
// Lower these as normal, but add some comments.
OutStreamer->AddComment("CLEANUPRET");
break;
}
case X86::CATCHRET: {
// Lower these as normal, but add some comments.
OutStreamer->AddComment("CATCHRET");
break;
}
case X86::TAILJMPr:
case X86::TAILJMPm:
case X86::TAILJMPd:
case X86::TAILJMPr64:
case X86::TAILJMPm64:
case X86::TAILJMPd64:
case X86::TAILJMPr64_REX:
case X86::TAILJMPm64_REX:
case X86::TAILJMPd64_REX:
// Lower these as normal, but add some comments.
OutStreamer->AddComment("TAILCALL");
break;
case X86::TLS_addr32:
case X86::TLS_addr64:
case X86::TLS_base_addr32:
case X86::TLS_base_addr64:
return LowerTlsAddr(MCInstLowering, *MI);
case X86::MOVPC32r: {
// This is a pseudo op for a two instruction sequence with a label, which
// looks like:
// call "L1$pb"
// "L1$pb":
// popl %esi
// Emit the call.
MCSymbol *PICBase = MF->getPICBaseSymbol();
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
.addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
const X86FrameLowering* FrameLowering =
MF->getSubtarget<X86Subtarget>().getFrameLowering();
bool hasFP = FrameLowering->hasFP(*MF);
// TODO: This is needed only if we require precise CFA.
bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
!OutStreamer->getDwarfFrameInfos().back().End;
int stackGrowth = -RI->getSlotSize();
if (HasActiveDwarfFrame && !hasFP) {
OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
}
// Emit the label.
OutStreamer->EmitLabel(PICBase);
// popl $reg
EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
.addReg(MI->getOperand(0).getReg()));
if (HasActiveDwarfFrame && !hasFP) {
OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
}
return;
}
case X86::ADD32ri: {
// Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
break;
// Okay, we have something like:
// EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
// For this, we want to print something like:
// MYGLOBAL + (. - PICBASE)
// However, we can't generate a ".", so just emit a new label here and refer
// to it.
MCSymbol *DotSym = OutContext.createTempSymbol();
OutStreamer->EmitLabel(DotSym);
// Now that we have emitted the label, lower the complex operand expression.
MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
const MCExpr *PICBase =
MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
DotExpr = MCBinaryExpr::createAdd(MCSymbolRefExpr::create(OpSym,OutContext),
DotExpr, OutContext);
EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
.addReg(MI->getOperand(0).getReg())
.addReg(MI->getOperand(1).getReg())
.addExpr(DotExpr));
return;
}
case TargetOpcode::STATEPOINT:
return LowerSTATEPOINT(*MI, MCInstLowering);
case TargetOpcode::FAULTING_LOAD_OP:
return LowerFAULTING_LOAD_OP(*MI, MCInstLowering);
case TargetOpcode::STACKMAP:
return LowerSTACKMAP(*MI);
case TargetOpcode::PATCHPOINT:
return LowerPATCHPOINT(*MI, MCInstLowering);
case X86::MORESTACK_RET:
EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
return;
case X86::MORESTACK_RET_RESTORE_R10:
// Return, then restore R10.
EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
.addReg(X86::R10)
.addReg(X86::RAX));
return;
case X86::SEH_PushReg:
OutStreamer->EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
return;
case X86::SEH_SaveReg:
OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
MI->getOperand(1).getImm());
return;
case X86::SEH_SaveXMM:
OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
MI->getOperand(1).getImm());
return;
case X86::SEH_StackAlloc:
OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
return;
case X86::SEH_SetFrame:
OutStreamer->EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
MI->getOperand(1).getImm());
return;
case X86::SEH_PushFrame:
OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
return;
case X86::SEH_EndPrologue:
OutStreamer->EmitWinCFIEndProlog();
return;
case X86::SEH_Epilogue: {
MachineBasicBlock::const_iterator MBBI(MI);
// Check if preceded by a call and emit nop if so.
for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
// Conservatively assume that pseudo instructions don't emit code and keep
// looking for a call. We may emit an unnecessary nop in some cases.
if (!MBBI->isPseudo()) {
if (MBBI->isCall())
EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
break;
}
}
return;
}
// Lower PSHUFB and VPERMILP normally but add a comment if we can find
// a constant shuffle mask. We won't be able to do this at the MC layer
// because the mask isn't an immediate.
case X86::PSHUFBrm:
case X86::VPSHUFBrm:
case X86::VPSHUFBYrm:
case X86::VPSHUFBZ128rm:
case X86::VPSHUFBZ128rmk:
case X86::VPSHUFBZ128rmkz:
case X86::VPSHUFBZ256rm:
case X86::VPSHUFBZ256rmk:
case X86::VPSHUFBZ256rmkz:
case X86::VPSHUFBZrm:
case X86::VPSHUFBZrmk:
case X86::VPSHUFBZrmkz: {
if (!OutStreamer->isVerboseAsm())
break;
unsigned SrcIdx, MaskIdx;
switch (MI->getOpcode()) {
default: llvm_unreachable("Invalid opcode");
case X86::PSHUFBrm:
case X86::VPSHUFBrm:
case X86::VPSHUFBYrm:
case X86::VPSHUFBZ128rm:
case X86::VPSHUFBZ256rm:
case X86::VPSHUFBZrm:
SrcIdx = 1; MaskIdx = 5; break;
case X86::VPSHUFBZ128rmkz:
case X86::VPSHUFBZ256rmkz:
case X86::VPSHUFBZrmkz:
SrcIdx = 2; MaskIdx = 6; break;
case X86::VPSHUFBZ128rmk:
case X86::VPSHUFBZ256rmk:
case X86::VPSHUFBZrmk:
SrcIdx = 3; MaskIdx = 7; break;
}
assert(MI->getNumOperands() >= 6 &&
"We should always have at least 6 operands!");
const MachineOperand &DstOp = MI->getOperand(0);
const MachineOperand &SrcOp = MI->getOperand(SrcIdx);
const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
if (auto *C = getConstantFromPool(*MI, MaskOp)) {
SmallVector<int, 16> Mask;
DecodePSHUFBMask(C, Mask);
if (!Mask.empty())
OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, Mask));
}
break;
}
case X86::VPERMILPSrm:
case X86::VPERMILPDrm:
case X86::VPERMILPSYrm:
case X86::VPERMILPDYrm: {
if (!OutStreamer->isVerboseAsm())
break;
assert(MI->getNumOperands() > 5 &&
"We should always have at least 5 operands!");
const MachineOperand &DstOp = MI->getOperand(0);
const MachineOperand &SrcOp = MI->getOperand(1);
const MachineOperand &MaskOp = MI->getOperand(5);
unsigned ElSize;
switch (MI->getOpcode()) {
default: llvm_unreachable("Invalid opcode");
case X86::VPERMILPSrm: case X86::VPERMILPSYrm: ElSize = 32; break;
case X86::VPERMILPDrm: case X86::VPERMILPDYrm: ElSize = 64; break;
}
if (auto *C = getConstantFromPool(*MI, MaskOp)) {
SmallVector<int, 16> Mask;
DecodeVPERMILPMask(C, ElSize, Mask);
if (!Mask.empty())
OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, Mask));
}
break;
}
#define MOV_CASE(Prefix, Suffix) \
case X86::Prefix##MOVAPD##Suffix##rm: \
case X86::Prefix##MOVAPS##Suffix##rm: \
case X86::Prefix##MOVUPD##Suffix##rm: \
case X86::Prefix##MOVUPS##Suffix##rm: \
case X86::Prefix##MOVDQA##Suffix##rm: \
case X86::Prefix##MOVDQU##Suffix##rm:
#define MOV_AVX512_CASE(Suffix) \
case X86::VMOVDQA64##Suffix##rm: \
case X86::VMOVDQA32##Suffix##rm: \
case X86::VMOVDQU64##Suffix##rm: \
case X86::VMOVDQU32##Suffix##rm: \
case X86::VMOVDQU16##Suffix##rm: \
case X86::VMOVDQU8##Suffix##rm: \
case X86::VMOVAPS##Suffix##rm: \
case X86::VMOVAPD##Suffix##rm: \
case X86::VMOVUPS##Suffix##rm: \
case X86::VMOVUPD##Suffix##rm:
#define CASE_ALL_MOV_RM() \
MOV_CASE(, ) /* SSE */ \
MOV_CASE(V, ) /* AVX-128 */ \
MOV_CASE(V, Y) /* AVX-256 */ \
MOV_AVX512_CASE(Z) \
MOV_AVX512_CASE(Z256) \
MOV_AVX512_CASE(Z128)
// For loads from a constant pool to a vector register, print the constant
// loaded.
CASE_ALL_MOV_RM()
if (!OutStreamer->isVerboseAsm())
break;
if (MI->getNumOperands() > 4)
if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
std::string Comment;
raw_string_ostream CS(Comment);
const MachineOperand &DstOp = MI->getOperand(0);
CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
CS << "[";
for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
if (i != 0)
CS << ",";
if (CDS->getElementType()->isIntegerTy())
CS << CDS->getElementAsInteger(i);
else if (CDS->getElementType()->isFloatTy())
CS << CDS->getElementAsFloat(i);
else if (CDS->getElementType()->isDoubleTy())
CS << CDS->getElementAsDouble(i);
else
CS << "?";
}
CS << "]";
OutStreamer->AddComment(CS.str());
} else if (auto *CV = dyn_cast<ConstantVector>(C)) {
CS << "<";
for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
if (i != 0)
CS << ",";
Constant *COp = CV->getOperand(i);
if (isa<UndefValue>(COp)) {
CS << "u";
} else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
if (CI->getBitWidth() <= 64) {
CS << CI->getZExtValue();
} else {
// print multi-word constant as (w0,w1)
auto Val = CI->getValue();
CS << "(";
for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
if (i > 0)
CS << ",";
CS << Val.getRawData()[i];
}
CS << ")";
}
} else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
SmallString<32> Str;
CF->getValueAPF().toString(Str);
CS << Str;
} else {
CS << "?";
}
}
CS << ">";
OutStreamer->AddComment(CS.str());
}
}
break;
}
// memory sandboxing
// only prefix instructions inside functions that we marked during our DataShield pass
auto func = MI->getParent()->getParent()->getFunction();
if (DataShieldUsePrefix && MI->mayLoadOrStore() && func->getMetadata("mask") && !func->getName().startswith("__")) {
OutStreamer->EmitIntValue(0x67, 1);
}
MCInst TmpInst;
MCInstLowering.Lower(MI, TmpInst);
if (DataShieldUseLateMPX && MI->mayLoadOrStore() && func->getMetadata("mask") && !func->getName().startswith("__")) {
//TmpInst.dump();
//dbgs() << "num operands: " << TmpInst.getNumOperands() << "\n";
//MI->dump();
switch (TmpInst.getOpcode()) {
case X86::MOV8mi:
case X86::MOV16mi:
case X86::MOV32mi:
case X86::MOV8mr:
case X86::MOV16mr:
case X86::MOV32mr:
case X86::MOV64mr:
case X86::MOV64mi32:
case X86::CMP8mi8:
case X86::CMP8mi:
case X86::CMP16mi8:
case X86::CMP32mi8:
case X86::CMP32mi:
case X86::CMP32mr:
case X86::CMP64mi32:
case X86::CMP64mi8:
case X86::CMP64mr:
case X86::MOVSSmr:
case X86::MOVSDmr:
case X86::TEST32mi:
case X86::TEST16mi:
case X86::TEST8mi:
case X86::MOVAPDmr:
case X86::INC8m:
case X86::INC16m:
case X86::INC32m:
case X86::INC64m:
case X86::DEC8m:
case X86::DEC16m:
case X86::DEC32m:
case X86::DEC64m:
//case X86::JMP16m:
//case X86::JMP32m:
//case X86::JMP64m:
case X86::ADD64mi8:
case X86::ADD64mi32:
case X86::ADD64mr:
case X86::ADD32mi8:
case X86::ADD32mi:
case X86::ADD32mr:
case X86::ADD16mi8:
case X86::ADD16mi:
case X86::ADD16mr:
case X86::ADD8mi8:
case X86::ADD8mr:
case X86::MOVUPSmr:
case X86::MOVUPDmr:
case X86::MOVAPSmr:
case X86::MOVDQUmr:
case X86::MOVDQAmr:
case X86::MOVPQI2QImr:
case X86::MOVPDI2DImr:
case X86::IDIV64m:
case X86::IDIV32m:
case X86::IDIV16m:
case X86::IDIV8m:
case X86::DIV64m:
case X86::DIV32m:
case X86::DIV16m:
case X86::DIV8m:
case X86::OR8mi:
case X86::OR16mi:
case X86::OR32mi:
case X86::OR16mi8:
case X86::OR32mi8:
case X86::OR64mi32:
case X86::OR8mr:
case X86::OR16mr:
case X86::OR32mr:
case X86::OR64mr:
case X86::XOR8mi:
case X86::XOR16mi:
case X86::XOR32mi:
case X86::XOR16mi8:
case X86::XOR32mi8:
case X86::XOR8mr:
case X86::XOR16mr:
case X86::XOR32mr:
case X86::XOR64mr:
case X86::SETBEm:
case X86::SETEm:
case X86::SETGm:
case X86::SETGEm:
case X86::SETLm:
case X86::SETLEm:
case X86::SETNEm:
case X86::AND8mr:
case X86::AND16mr:
case X86::AND32mr:
case X86::AND64mr:
case X86::AND8mi:
case X86::AND16mi:
case X86::AND32mi:
case X86::AND8mi8:
case X86::AND16mi8:
case X86::AND32mi8:
case X86::AND64mi8:
case X86::AND64mi32:
case X86::SUB8mr:
case X86::SUB16mr:
case X86::SUB32mr:
case X86::SUB64mr:
//case X86::CALL64m:
//case X86::CALL32m:
case X86::ROL64mi:
case X86::ROL32mi:
case X86::ROL16mi:
case X86::ROR64mi:
case X86::ROR32mi:
case X86::ROR16mi:
case X86::SHR64mi:
case X86::SHR32mi:
case X86::SHR16mi:
case X86::SHL64mi:
case X86::SHL32mi:
case X86::SHL16mi:
case X86::SHR64m1:
case X86::SHR32m1:
case X86::SHR16m1:
case X86::SHL64m1:
case X86::SHL32m1:
case X86::SHL16m1:
case X86::ADC64mi8:
case X86::ADC32mi8:
case X86::ADC32mi:
case X86::ADC16mi:
case X86::ADC8mi:
case X86::SBB32mi:
case X86::SBB32mi8:
case X86::SBB16mi:
case X86::SBB16mi8:
case X86::MOV8mr_NOREX:
//case X86::TAILJMPm64:
case X86::SHLD64mri8:
case X86::SHLD32mri8:
case X86::SHLD16mri8:
case X86::NOT64m:
case X86::NOT32m:
case X86::NOT16m:
case X86::NOT8m:
case X86::NEG64m:
case X86::NEG32m:
case X86::NEG16m:
case X86::NEG8m:
case X86::OR64mi8:
case X86::OR8mi8:
case X86::MOVLPDmr:
case X86::MOVLPSmr:
case X86::ST_FP80m:
case X86::ST_FP64m:
case X86::ST_FP32m:
case X86::LD_F80m:
case X86::LD_F64m:
case X86::LD_F32m:
case X86::SAR64mi:
case X86::SAR32mi:
case X86::SAR32m1:
case X86::SHL64mCL:
case X86::SETAEm:
case X86::SETBm:
case X86::MOVHPDmr:
case X86::SETAm:
case X86::ILD_F64m:
case X86::MOVSDto64mr:
case X86::MOVSS2DImr:
case X86::MUL_F64m:
case X86::MUL_F32m:
{
//for (unsigned i = 0; i < TmpInst.getNumOperands(); ++i) {
// dbgs() << i << ": ";
// TmpInst.getOperand(i).dump();
//}
auto bndChk = MCInstBuilder(X86::BNDCU64rm);
bndChk.addReg(X86::BND0);
bndChk.addOperand(TmpInst.getOperand(0));
bndChk.addOperand(TmpInst.getOperand(1));
bndChk.addOperand(TmpInst.getOperand(2));
bndChk.addOperand(TmpInst.getOperand(3));
bndChk.addOperand(TmpInst.getOperand(4));
EmitAndCountInstruction(bndChk);
break;
}
case X86::MOV8rm:
case X86::MOV16rm:
case X86::MOV32rm:
case X86::MOV64rm:
case X86::CMP64rm:
case X86::CMP32rm:
case X86::MOVSSrm:
case X86::MOVSDrm:
case X86::MOVSX64rm8:
case X86::MOVSX64rm16:
case X86::MOVSX64rm32:
case X86::MOVSX32rm8:
case X86::MOVSX32rm16:
case X86::MOVZX32rm8:
case X86::MOVZX32rm16:
case X86::CVTSI2SD64rm:
case X86::CVTSI2SDrm:
case X86::CVTSI2SSrm:
case X86::CVTSS2SIrm:
case X86::CVTTSS2SI64rm:
case X86::CVTTSS2SIrm:
case X86::CVTPS2PDrm:
case X86::UCOMISSrm:
case X86::UCOMISDrm:
case X86::MOVAPDrm:
case X86::MOVAPSrm:
case X86::MOVUPSrm:
case X86::MOVUPDrm:
case X86::MOVDQUrm:
case X86::MOVDQArm:
case X86::MOVQI2PQIrm:
case X86::IMUL64rmi32:
case X86::IMUL64rmi8:
case X86::IMUL32rmi8:
case X86::IMUL16rmi8:
case X86::IMUL32rmi:
case X86::IMUL16rmi:
case X86::MOVDI2PDIrm:
case X86::TEST8rm:
case X86::TEST16rm:
case X86::TEST32rm:
case X86::TEST64rm:
case X86::PSHUFDmi:
case X86::CVTTSD2SIrm:
case X86::CVTTSD2SI64rm:
case X86::PSHUFLWmi:
case X86::MOVZQI2PQIrm:
case X86::CVTPD2PSrm:
case X86::MOVDI2SSrm:
case X86::MOV64toSDrm:
{
//for (unsigned i = 0; i < TmpInst.getNumOperands(); ++i) {
// dbgs() << i << ": ";
// TmpInst.getOperand(i).dump();
//}
auto bndChk = MCInstBuilder(X86::BNDCU64rm);
bndChk.addReg(X86::BND0);
bndChk.addOperand(TmpInst.getOperand(1));
bndChk.addOperand(TmpInst.getOperand(2));
bndChk.addOperand(TmpInst.getOperand(3));
bndChk.addOperand(TmpInst.getOperand(4));
bndChk.addOperand(TmpInst.getOperand(5));
EmitAndCountInstruction(bndChk);
break;
}
case X86::DIVSSrm:
case X86::DIVSDrm:
case X86::SUBSSrm:
case X86::SUBSDrm:
case X86::SUB64rm:
case X86::SUB32rm:
case X86::SUB16rm:
case X86::SUB8rm:
case X86::MULSSrm:
case X86::MULSDrm:
case X86::AND64rm:
case X86::AND32rm:
case X86::AND16rm:
case X86::AND8rm:
case X86::PADDQrm:
case X86::ADD64rm:
case X86::ADD32rm:
case X86::ADD16rm:
case X86::ADD8rm:
case X86::ADDSSrm:
case X86::ADDSDrm:
case X86::FvXORPDrm:
case X86::FvXORPSrm:
case X86::FvANDPSrm:
case X86::OR64rm:
case X86::OR32rm:
case X86::OR16rm:
case X86::OR8rm:
case X86::PANDrm:
case X86::PANDNrm:
case X86::PXORrm:
case X86::PORrm:
case X86::MINSSrm:
case X86::MINSDrm:
case X86::MAXSSrm:
case X86::MAXSDrm:
case X86::IMUL64rm:
case X86::IMUL32rm:
case X86::IMUL16rm:
case X86::UNPCKLPDrm:
case X86::CMOVS64rm:
case X86::CMOVS32rm:
case X86::CMOVS16rm:
case X86::CMOVE64rm:
case X86::CMOVE32rm:
case X86::CMOVE16rm:
case X86::CMOVNE64rm:
case X86::CMOVNE32rm:
case X86::CMOVNE16rm:
case X86::CMOVGE64rm:
case X86::CMOVGE32rm:
case X86::CMOVGE16rm:
case X86::CMOVG64rm:
case X86::CMOVG32rm:
case X86::CMOVG16rm:
case X86::CMOVLE64rm:
case X86::CMOVLE32rm:
case X86::CMOVLE16rm:
case X86::CMOVL64rm:
case X86::CMOVL32rm:
case X86::CMOVL16rm:
case X86::CMOVB64rm:
case X86::CMOVB32rm:
case X86::CMOVB16rm:
case X86::CMOVBE64rm:
case X86::CMOVBE32rm:
case X86::CMOVBE16rm:
case X86::XOR64rm:
case X86::XOR32rm:
case X86::XOR16rm:
case X86::XOR8rm:
case X86::PUNPCKLQDQrm:
case X86::PINSRWrmi:
case X86::ORPSrm:
case X86::PCMPEQDrm:
case X86::PCMPEQQrm:
case X86::PUNPCKLDQrm:
case X86::SUBPDrm:
case X86::CMOVAE64rm:
case X86::MOVHPDrm:
case X86::CMOVNS32rm:
case X86::CMPSDrm:
case X86::ANDPSrm:
case X86::ANDPDrm:
case X86::PMULUDQrm:
case X86::FvANDPDrm:
case X86::CMOVA64rm:
case X86::CMOVA32rm:
case X86::CMOVA16rm:
case X86::MULPDrm:
case X86::ADDPDrm:
case X86::PADDDrm:
case X86::CMPSSrm:
case X86::SHUFPDrmi:
case X86::DIVPDrm:
case X86::ADDPSrm:
case X86::ANDNPDrm:
case X86::MOVLPDrm:
case X86::UNPCKLPSrm:
case X86::UNPCKHPDrm:
case X86::XORPDrm:
case X86::CMPPDrmi:
case X86::MULPSrm:
{
//for (unsigned i = 0; i < TmpInst.getNumOperands(); ++i) {
// dbgs() << i << ": ";
// TmpInst.getOperand(i).dump();
//}
auto bndChk = MCInstBuilder(X86::BNDCU64rm);
bndChk.addReg(X86::BND0);
bndChk.addOperand(TmpInst.getOperand(2));
bndChk.addOperand(TmpInst.getOperand(3));
bndChk.addOperand(TmpInst.getOperand(4));
bndChk.addOperand(TmpInst.getOperand(5));
bndChk.addOperand(TmpInst.getOperand(6));
EmitAndCountInstruction(bndChk);
break;
}
//case X86::PUSH64r:
//case X86::POP64r:
// {
// // some value from the stack into a register
// // so we need to check that the stack pointer is in bounds?
// // if we just replaced with a PUSH32 we would need no bounds check at all
// //for (unsigned i = 0; i < TmpInst.getNumOperands(); ++i) {
// // dbgs() << i << ": ";
// // TmpInst.getOperand(i).dump();
// //}
// auto bndChk = MCInstBuilder(X86::BNDCU64rm);
// bndChk.addReg(X86::BND0);
// bndChk.addReg(X86::RSP);
// bndChk.addImm(1);
// bndChk.addReg(0);
// bndChk.addImm(0);
// bndChk.addReg(0);
// EmitAndCountInstruction(bndChk);
// break;
// }
case X86::PUSH64r:
case X86::PUSHF64:
case X86::POP64r:
case X86::POPF64:
case X86::CALL64m:
case X86::CALL32m:
case X86::JMP16m:
case X86::JMP32m:
case X86::JMP64m:
case X86::TAILJMPm64:
{
break; // we don't do CFI
}
default:
MI->dump();
for (unsigned i = 0; i < TmpInst.getNumOperands(); ++i) {
dbgs() << i << ": ";
TmpInst.getOperand(i).dump();
}
dbgs() << TmpInst.getOpcode() << "\n";
llvm_unreachable("unhandled opcode.");
//dbgs() << "unhandled opcode.\n";
break;
}
}
// Stackmap shadows cannot include branch targets, so we can count the bytes
// in a call towards the shadow, but must ensure that the no thread returns
// in to the stackmap shadow. The only way to achieve this is if the call
// is at the end of the shadow.
if (MI->isCall()) {
// Count then size of the call towards the shadow
SMShadowTracker.count(TmpInst, getSubtargetInfo());
// Then flush the shadow so that we fill with nops before the call, not
// after it.
SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
// Then emit the call
OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
return;
}
EmitAndCountInstruction(TmpInst);
}
| gpl-3.0 |
ImagoTrigger/sdrtrunk | src/main/java/io/github/dsheirer/source/wave/RealWaveSource.java | 8217 | /*******************************************************************************
* SDR Trunk
* Copyright (C) 2014,2015 Dennis Sheirer
*
* 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 io.github.dsheirer.source.wave;
import io.github.dsheirer.sample.ConversionUtils;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.buffer.ReusableBufferQueue;
import io.github.dsheirer.sample.buffer.ReusableFloatBuffer;
import io.github.dsheirer.source.IControllableFileSource;
import io.github.dsheirer.source.IFrameLocationListener;
import io.github.dsheirer.source.RealSource;
import io.github.dsheirer.source.SourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class RealWaveSource extends RealSource implements IControllableFileSource, AutoCloseable
{
private final static Logger mLog = LoggerFactory.getLogger(RealWaveSource.class);
private ReusableBufferQueue mReusableBufferQueue = new ReusableBufferQueue("RealWaveSource");
private IFrameLocationListener mFrameLocationListener;
private int mBytesPerFrame;
private int mFrameCounter = 0;
private long mFrequency = 0;
private Listener<ReusableFloatBuffer> mListener;
private AudioInputStream mInputStream;
private File mFile;
public RealWaveSource(File file) throws IOException
{
mFile = file;
}
@Override
public void setSourceEventListener(Listener<SourceEvent> listener)
{
//Not implemented
}
@Override
public void removeSourceEventListener()
{
//Not implemented
}
@Override
public Listener<SourceEvent> getSourceEventListener()
{
//Not implemented
return null;
}
@Override
public void reset()
{
stop();
start();
}
@Override
public void start()
{
try
{
open();
}
catch(IOException | UnsupportedAudioFileException e)
{
mLog.error("Error starting real wave source", e);
}
}
@Override
public void stop()
{
try
{
close();
}
catch(IOException e)
{
mLog.error("Error stopping real wave source", e);
}
}
@Override
public long getFrameCount() throws IOException
{
return 0;
}
@Override
public double getSampleRate()
{
if(mInputStream != null)
{
return mInputStream.getFormat().getSampleRate();
}
return 0;
}
/**
* Returns the frequency set for this file. Normally returns zero, but
* the value can be set with setFrequency() method.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Changes the value returned from getFrequency() for this source.
*/
public void setFrequency(long frequency)
{
mFrequency = frequency;
}
/**
* Closes the source file
*/
public void close() throws IOException
{
if(mInputStream != null)
{
mInputStream.close();
}
else
{
throw new IOException("Can't close wave source - was not opened");
}
mInputStream = null;
}
/**
* Opens the source file for reading
*/
public void open() throws IOException, UnsupportedAudioFileException
{
if(mInputStream == null)
{
mInputStream = AudioSystem.getAudioInputStream(mFile);
}
else
{
throw new IOException("Can't open wave source - is already opened");
}
AudioFormat format = mInputStream.getFormat();
mBytesPerFrame = format.getFrameSize();
if(format.getChannels() != 1 || format.getSampleSizeInBits() != 16)
{
throw new IOException("Unsupported Wave Format - EXPECTED: 1 " +
"channel 16-bit samples FOUND: " +
mInputStream.getFormat().getChannels() + " channels " +
mInputStream.getFormat().getSampleSizeInBits() + "-bit samples");
}
/* Broadcast that we're at frame location 0 */
broadcast(0);
}
/**
* Reads the number of frames and sends a buffer to the listener
*/
@Override
public void next(int frames) throws IOException
{
next(frames, true);
}
/**
* Reads the number of frames and optionally sends the buffer to the listener
*/
public void next(int frames, boolean broadcast) throws IOException
{
if(mInputStream != null)
{
byte[] buffer = new byte[mBytesPerFrame * frames];
/* Fill the buffer with samples from the file */
int samplesRead = mInputStream.read(buffer);
mFrameCounter += samplesRead;
broadcast(mFrameCounter);
if(broadcast && mListener != null)
{
if(samplesRead < buffer.length)
{
if(samplesRead == -1)
{
throw new IOException("End of recording");
}
buffer = Arrays.copyOf(buffer, samplesRead);
}
float[] samples = ConversionUtils.convertFromSigned16BitSamples(buffer);
ReusableFloatBuffer reusableFloatBuffer = mReusableBufferQueue.getBuffer(samples.length);
reusableFloatBuffer.reloadFrom(samples, System.currentTimeMillis());
mListener.receive(reusableFloatBuffer);
}
}
}
/**
* Registers the listener to receive sample buffers as they are read from the wave file
*/
@Override
public void setListener(Listener<ReusableFloatBuffer> listener)
{
mListener = listener;
}
/**
* Unregisters the listener from receiving sample buffers
*/
@Override
public void removeListener(Listener<ReusableFloatBuffer> listener)
{
mListener = null;
}
@Override
public void dispose()
{
mListener = null;
}
@Override
public File getFile()
{
return mFile;
}
private void broadcast(int byteLocation)
{
int frameLocation = (int)(byteLocation / mBytesPerFrame);
if(mFrameLocationListener != null)
{
mFrameLocationListener.frameLocationUpdated(frameLocation);
}
}
@Override
public void setListener(IFrameLocationListener listener)
{
mFrameLocationListener = listener;
}
@Override
public void removeListener(IFrameLocationListener listener)
{
mFrameLocationListener = null;
}
/**
* Indicates if the file is a supported audio file type
*/
public static boolean supports(File file)
{
try(AudioInputStream ais = AudioSystem.getAudioInputStream(file))
{
AudioFormat format = ais.getFormat();
if(format.getChannels() == 1 && format.getSampleSizeInBits() == 16)
{
return true;
}
}
catch(Exception e)
{
//Do nothing, we'll return a default of false
}
return false;
}
}
| gpl-3.0 |
craftercms/studio-ui | ui/app/src/components/NewContentDialog/styles.ts | 1494 | /*
* Copyright (C) 2007-2021 Crafter Software Corporation. All Rights Reserved.
*
* This program 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.
*
* 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/>.
*/
import createStyles from '@mui/styles/createStyles';
import makeStyles from '@mui/styles/makeStyles';
import palette from '../../styles/palette';
const useStyles = makeStyles(() =>
createStyles({
compact: {
marginRight: 'auto'
},
dialogContent: {
minHeight: 455
},
cardsContainer: {
marginTop: 14
},
searchBox: {
minWidth: '33%'
},
emptyStateImg: {
width: 250,
marginBottom: 17
}
})
);
export const useContentCardStyles = makeStyles(() => ({
defaultCard: {
maxWidth: 345,
cursor: 'pointer'
},
compactCard: {
display: 'flex',
cursor: 'pointer'
},
media: {
paddingTop: '75%'
},
compactMedia: {
width: 151
},
selected: {
border: `1px solid ${palette.blue.tint}`
}
}));
export default useStyles;
| gpl-3.0 |
MiniMarvin/studies | algorithms/insertion_sort_01.cpp | 1625 | #include <iostream>
#include <cstdlib>
#define MAX_SIZE 20
#define MAX_NUM 100
using namespace std;
int randArr(int *&arr);
void insertion_sort(int *arr, int size, int order);
int main(int argc, char** argv) {
srand(time(NULL));
int *arr;
int size;
int order = 1;
// if user input the order the system will use it as order
if(argc > 1) {
order = atoi(argv[1]);
}
size = randArr(arr);
insertion_sort(arr, size, order);
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return EXIT_SUCCESS;
}
/**
* @brief Generate a random size array with random numbers.
*
* @param arr The arr pointer where it's going to be allocated.
*
* @return The array size.
*/
int randArr(int *&arr) {
int size = rand()%MAX_SIZE;
cout << "size: " << size << endl;
// *arr = new int[size];
arr = new int[size];
for (int i = 0; i < size; ++i) {
// (*arr)[i] = rand();
arr[i] = rand()%MAX_NUM;
cout << arr[i] << " ";
}
cout << endl;
return size;
}
void insertion_sort(int *arr, int size, int order) {
// increase order
for(int i = 1; i < size; i++) {
int key = arr[i]; // make the actual value as comparison key
int j = i-1; // start analysing the value before the key one
for(;j >= 0 && (order >= 0 ? arr[j] < key : arr[j] > key); j--) {
arr[j+1] = arr[j]; // put the array elements one element to the front
arr[j] = key; // garant that the key is going to be placed in the correct positioin
}
}
} | gpl-3.0 |
jeffreyadams/atlasofliegroups-docs | atlas_static/doxygen/search/typedefs_5.js | 1108 | var searchData=
[
['f_5floop',['f_loop',['../namespaceatlas_1_1interpreter.html#afb5ad98db48bb2ba2643978703cfda0d',1,'atlas::interpreter']]],
['fiber_5forbit',['fiber_orbit',['../namespaceatlas_1_1cartanclass.html#a423f20840e390fe67c01c15d5f852668',1,'atlas::cartanclass']]],
['fiberelt',['FiberElt',['../namespaceatlas_1_1cartanclass.html#a41091637fc022a14ac514482fc2ffda9',1,'atlas::cartanclass']]],
['file_5fpos',['file_pos',['../coef-merge_8cpp.html#a8c79c1929e173b6c23ae58ba054fd57f',1,'coef-merge.cpp']]],
['form_5freps',['form_reps',['../structatlas_1_1innerclass_1_1InnerClass_1_1C__info.html#a8289e65ffc169dc8385206afbe3e2066',1,'atlas::innerclass::InnerClass::C_info']]],
['form_5fstack',['form_stack',['../namespaceatlas_1_1interpreter.html#a8c6b4cd1fce27cd9386e73a0ab9b9b5a',1,'atlas::interpreter']]],
['func_5ftype_5fp',['func_type_p',['../namespaceatlas_1_1interpreter.html#a5b10a9ef47b95fa1aac4e2158d3ce84c',1,'atlas::interpreter']]],
['func_5ftype_5fptr',['func_type_ptr',['../namespaceatlas_1_1interpreter.html#a6e43df650364e62767e0786a9d61a977',1,'atlas::interpreter']]]
];
| gpl-3.0 |
m3rlin87/darkstar | scripts/zones/Middle_Delkfutts_Tower/Zone.lua | 3141 | -----------------------------------
--
-- Zone: Middle_Delkfutts_Tower
--
-----------------------------------
local ID = require("scripts/zones/Middle_Delkfutts_Tower/IDs");
require("scripts/globals/conquest");
require("scripts/globals/npc_util");
require("scripts/globals/settings");
require("scripts/globals/treasure")
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -36, -50, 83, -30, -49, 89 ); -- Fourth Floor G-6 porter to Lower Delkfutt's Tower
zone:registerRegion(2, -49, -50, -50, -43, -49, -43 ); -- Fourth Floor G-6 porter to Lower Delkfutt's Tower "1"
zone:registerRegion(3, 103, -50, 10, 109, -49, 16 ); -- Fourth Floor J-6 porter to Lower Delkfutt's Tower "2"
zone:registerRegion(4, -49, -82, -48, -43, -81, -43 ); -- Sixth Floor F-10 porter to Seventh Floor "G"
zone:registerRegion(5, -489, -98, -48, -483, -97, -43 ); -- Seventh Floor F-10 porter to Sixth Floor "G"
zone:registerRegion(6, 83, -82, -48, 89, -81, -43 ); -- Sixth Floor J-10 porter to Seventh Floor "H"
zone:registerRegion(7, -356, -98, -48, -351, -97, -43 ); -- Seventh Floor J-10 porter to Sixth Floor "H"
zone:registerRegion(8, 84, -82, 83, 89, -81, 89 ); -- Sixth Floor J-6 porter to Seventh Floor "I"
zone:registerRegion(9, -356, -98, 84, -351, -97, 88 ); -- Seventh Floor J-6 porter to Sixth Floor "I"
zone:registerRegion(10, -415, -98, 104, -411, -97, 108 ); -- Seventh Floor H-6 porter to Sixth Floor "J"
zone:registerRegion(11, -489, -130, 84, -484,-129, 88 ); -- Ninth Floor F-6 porter to Upper Delkfutt's Tower
dsp.treasure.initZone(zone)
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-43.0914,-47.4255,77.5126,120);
end
return cs;
end;
function onRegionEnter(player,region)
local regionId = region:GetRegionID();
if (regionId == 8 and player:getQuestStatus(BASTOK,BLADE_OF_EVIL) == QUEST_ACCEPTED and player:getVar("bladeOfEvilCS") == 1) then
player:startEvent(14);
else
player:startEvent(regionId - 1);
end
end;
function onRegionLeave(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
-- teleporters
if (csid <= 11 and option == 1) then
if (csid == 0) then
player:setPos(412, -32, 80, 100, 184);
elseif (csid == 1) then
player:setPos(388, -32, -40, 231, 184);
elseif (csid == 2) then
player:setPos(540, -32, 20, 128, 184);
elseif (csid == 10) then
player:setPos(-355, -144, 91, 64, 158);
end
-- BLADE OF EVIL
elseif ( csid == 14 and option == 0 and npcUtil.completeQuest(player, BASTOK, BLADE_OF_EVIL, {item=12516, title=dsp.title.PARAGON_OF_DARK_KNIGHT_EXCELLENCE, fame=AF3_FAME}) ) then
player:setVar("bladeOfEvilCS",0);
end
end;
| gpl-3.0 |
immesys/bw2 | vendor/vuvuzela.io/crypto/rand/cpu_amd64.go | 32 | package rand
func cpu() uint64
| gpl-3.0 |
marcusmueller/gnuradio | gr-fec/lib/tagged_decoder_impl.cc | 3260 | /* -*- c++ -*- */
/*
* Copyright 2014 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "tagged_decoder_impl.h"
#include <gnuradio/io_signature.h>
#include <stdio.h>
namespace gr {
namespace fec {
tagged_decoder::sptr tagged_decoder::make(generic_decoder::sptr my_decoder,
size_t input_item_size,
size_t output_item_size,
const std::string& lengthtagname,
int mtu)
{
return gnuradio::get_initial_sptr(new tagged_decoder_impl(
my_decoder, input_item_size, output_item_size, lengthtagname, mtu));
}
tagged_decoder_impl::tagged_decoder_impl(generic_decoder::sptr my_decoder,
size_t input_item_size,
size_t output_item_size,
const std::string& lengthtagname,
int mtu)
: tagged_stream_block("fec_tagged_decoder",
io_signature::make(1, 1, input_item_size),
io_signature::make(1, 1, output_item_size),
lengthtagname),
d_mtu(mtu)
{
d_decoder = my_decoder;
d_decoder->set_frame_size(d_mtu * 8);
set_relative_rate(d_decoder->rate());
}
int tagged_decoder_impl::calculate_output_stream_length(const gr_vector_int& ninput_items)
{
if ((ninput_items[0] * d_decoder->rate()) > (d_mtu * 8)) {
throw std::runtime_error("tagged_encoder: received frame is larger than MTU.");
}
d_decoder->set_frame_size(round(ninput_items[0] * d_decoder->rate()));
return d_decoder->get_output_size();
}
tagged_decoder_impl::~tagged_decoder_impl() {}
int tagged_decoder_impl::work(int noutput_items,
gr_vector_int& ninput_items,
gr_vector_const_void_star& input_items,
gr_vector_void_star& output_items)
{
const unsigned char* in = (unsigned char*)input_items[0];
unsigned char* out = (unsigned char*)output_items[0];
GR_LOG_DEBUG(d_debug_logger,
boost::format("%1%, %2%, %3%") % noutput_items % ninput_items[0] %
d_decoder->get_output_size());
d_decoder->generic_work((void*)in, (void*)out);
return d_decoder->get_output_size();
}
} /* namespace fec */
} /* namespace gr */
| gpl-3.0 |
clovertrail/cloudinit-bis | cloudinit/config/cc_apt_configure.py | 33402 | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program 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.
#
# 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/>.
"""
Apt Configure
-------------
**Summary:** configure apt
This module handles both configuration of apt options and adding source lists.
There are configuration options such as ``apt_get_wrapper`` and
``apt_get_command`` that control how cloud-init invokes apt-get.
These configuration options are handled on a per-distro basis, so consult
documentation for cloud-init's distro support for instructions on using
these config options.
.. note::
To ensure that apt configuration is valid yaml, any strings containing
special characters, especially ``:`` should be quoted.
.. note::
For more information about apt configuration, see the
``Additional apt configuration`` example.
**Preserve sources.list:**
By default, cloud-init will generate a new sources list in
``/etc/apt/sources.list.d`` based on any changes specified in cloud config.
To disable this behavior and preserve the sources list from the pristine image,
set ``preserve_sources_list`` to ``true``.
.. note::
The ``preserve_sources_list`` option overrides all other config keys that
would alter ``sources.list`` or ``sources.list.d``, **except** for
additional sources to be added to ``sources.list.d``.
**Disable source suites:**
Entries in the sources list can be disabled using ``disable_suites``, which
takes a list of suites to be disabled. If the string ``$RELEASE`` is present in
a suite in the ``disable_suites`` list, it will be replaced with the release
name. If a suite specified in ``disable_suites`` is not present in
``sources.list`` it will be ignored. For convenience, several aliases are
provided for ``disable_suites``:
- ``updates`` => ``$RELEASE-updates``
- ``backports`` => ``$RELEASE-backports``
- ``security`` => ``$RELEASE-security``
- ``proposed`` => ``$RELEASE-proposed``
- ``release`` => ``$RELEASE``
.. note::
When a suite is disabled using ``disable_suites``, its entry in
``sources.list`` is not deleted; it is just commented out.
**Configure primary and security mirrors:**
The primary and security archive mirrors can be specified using the ``primary``
and ``security`` keys, respectively. Both the ``primary`` and ``security`` keys
take a list of configs, allowing mirrors to be specified on a per-architecture
basis. Each config is a dictionary which must have an entry for ``arches``,
specifying which architectures that config entry is for. The keyword
``default`` applies to any architecture not explicitly listed. The mirror url
can be specified with the ``url`` key, or a list of mirrors to check can be
provided in order, with the first mirror that can be resolved being selected.
This allows the same configuration to be used in different environment, with
different hosts used for a local apt mirror. If no mirror is provided by uri or
search, ``search_dns`` may be used to search for dns names in the format
``<distro>-mirror`` in each of the following:
- fqdn of this host per cloud metadata
- localdomain
- domains listed in ``/etc/resolv.conf``
If there is a dns entry for ``<distro>-mirror``, then it is assumed that there
is a distro mirror at ``http://<distro>-mirror.<domain>/<distro>``. If the
``primary`` key is defined, but not the ``security`` key, then then
configuration for ``primary`` is also used for ``security``. If ``search_dns``
is used for the ``security`` key, the search pattern will be.
``<distro>-security-mirror``.
If no mirrors are specified, or all lookups fail, then default mirrors defined
in the datasource are used. If none are present in the datasource either the
following defaults are used:
- primary: ``http://archive.ubuntu.com/ubuntu``
- security: ``http://security.ubuntu.com/ubuntu``
**Specify sources.list template:**
A custom template for rendering ``sources.list`` can be specefied with
``sources_list``. If no ``sources_list`` template is given, cloud-init will
use sane default. Within this template, the following strings will be replaced
with the appropriate values:
- ``$MIRROR``
- ``$RELEASE``
- ``$PRIMARY``
- ``$SECURITY``
**Pass configuration to apt:**
Apt configuration can be specified using ``conf``. Configuration is specified
as a string. For multiline apt configuration, make sure to follow yaml syntax.
**Configure apt proxy:**
Proxy configuration for apt can be specified using ``conf``, but proxy config
keys also exist for convenience. The proxy config keys, ``http_proxy``,
``ftp_proxy``, and ``https_proxy`` may be used to specify a proxy for http, ftp
and https protocols respectively. The ``proxy`` key also exists as an alias for
``http_proxy``. Proxy url is specified in the format
``<protocol>://[[user][:pass]@]host[:port]/``.
**Add apt repos by regex:**
All source entries in ``apt-sources`` that match regex in
``add_apt_repo_match`` will be added to the system using
``add-apt-repository``. If ``add_apt_repo_match`` is not specified, it defaults
to ``^[\w-]+:\w``
**Add source list entries:**
Source list entries can be specified as a dictionary under the ``sources``
config key, with key in the dict representing a different source file. The key
The key of each source entry will be used as an id that can be referenced in
other config entries, as well as the filename for the source's configuration
under ``/etc/apt/sources.list.d``. If the name does not end with ``.list``,
it will be appended. If there is no configuration for a key in ``sources``, no
file will be written, but the key may still be referred to as an id in other
``sources`` entries.
Each entry under ``sources`` is a dictionary which may contain any of the
following optional keys:
- ``source``: a sources.list entry (some variable replacements apply)
- ``keyid``: a key to import via shortid or fingerprint
- ``key``: a raw PGP key
- ``keyserver``: alternate keyserver to pull ``keyid`` key from
The ``source`` key supports variable replacements for the following strings:
- ``$MIRROR``
- ``$PRIMARY``
- ``$SECURITY``
- ``$RELEASE``
**Internal name:** ``cc_apt_configure``
**Module frequency:** per instance
**Supported distros:** ubuntu, debian
**Config keys**::
apt:
preserve_sources_list: <true/false>
disable_suites:
- $RELEASE-updates
- backports
- $RELEASE
- mysuite
primary:
- arches:
- amd64
- i386
- default
uri: "http://us.archive.ubuntu.com/ubuntu"
search:
- "http://cool.but-sometimes-unreachable.com/ubuntu"
- "http://us.archive.ubuntu.com/ubuntu"
search_dns: <true/false>
- arches:
- s390x
- arm64
uri: "http://archive-to-use-for-arm64.example.com/ubuntu"
security:
- arches:
- default
search_dns: true
sources_list: |
deb $MIRROR $RELEASE main restricted
deb-src $MIRROR $RELEASE main restricted
deb $PRIMARY $RELEASE universe restricted
deb $SECURITY $RELEASE-security multiverse
debconf_selections:
set1: the-package the-package/some-flag boolean true
conf: |
APT {
Get {
Assume-Yes "true";
Fix-Broken "true";
}
}
proxy: "http://[[user][:pass]@]host[:port]/"
http_proxy: "http://[[user][:pass]@]host[:port]/"
ftp_proxy: "ftp://[[user][:pass]@]host[:port]/"
https_proxy: "https://[[user][:pass]@]host[:port]/"
sources:
source1:
keyid: "keyid"
keyserver: "keyserverurl"
source: "deb http://<url>/ xenial main"
source2:
source: "ppa:<ppa-name>"
source3:
source: "deb $MIRROR $RELEASE multiverse"
key: |
------BEGIN PGP PUBLIC KEY BLOCK-------
<key data>
------END PGP PUBLIC KEY BLOCK-------
"""
import glob
import os
import re
from cloudinit import gpg
from cloudinit import log as logging
from cloudinit import templater
from cloudinit import util
LOG = logging.getLogger(__name__)
# this will match 'XXX:YYY' (ie, 'cloud-archive:foo' or 'ppa:bar')
ADD_APT_REPO_MATCH = r"^[\w-]+:\w"
# place where apt stores cached repository data
APT_LISTS = "/var/lib/apt/lists"
# Files to store proxy information
APT_CONFIG_FN = "/etc/apt/apt.conf.d/94cloud-init-config"
APT_PROXY_FN = "/etc/apt/apt.conf.d/90cloud-init-aptproxy"
# Default keyserver to use
DEFAULT_KEYSERVER = "keyserver.ubuntu.com"
# Default archive mirrors
PRIMARY_ARCH_MIRRORS = {"PRIMARY": "http://archive.ubuntu.com/ubuntu/",
"SECURITY": "http://security.ubuntu.com/ubuntu/"}
PORTS_MIRRORS = {"PRIMARY": "http://ports.ubuntu.com/ubuntu-ports",
"SECURITY": "http://ports.ubuntu.com/ubuntu-ports"}
PRIMARY_ARCHES = ['amd64', 'i386']
PORTS_ARCHES = ['s390x', 'arm64', 'armhf', 'powerpc', 'ppc64el']
def get_default_mirrors(arch=None, target=None):
"""returns the default mirrors for the target. These depend on the
architecture, for more see:
https://wiki.ubuntu.com/UbuntuDevelopment/PackageArchive#Ports"""
if arch is None:
arch = util.get_architecture(target)
if arch in PRIMARY_ARCHES:
return PRIMARY_ARCH_MIRRORS.copy()
if arch in PORTS_ARCHES:
return PORTS_MIRRORS.copy()
raise ValueError("No default mirror known for arch %s" % arch)
def handle(name, ocfg, cloud, log, _):
"""process the config for apt_config. This can be called from
curthooks if a global apt config was provided or via the "apt"
standalone command."""
# keeping code close to curtin codebase via entry handler
target = None
if log is not None:
global LOG
LOG = log
# feed back converted config, but only work on the subset under 'apt'
ocfg = convert_to_v3_apt_format(ocfg)
cfg = ocfg.get('apt', {})
if not isinstance(cfg, dict):
raise ValueError("Expected dictionary for 'apt' config, found %s",
type(cfg))
LOG.debug("handling apt (module %s) with apt config '%s'", name, cfg)
release = util.lsb_release(target=target)['codename']
arch = util.get_architecture(target)
mirrors = find_apt_mirror_info(cfg, cloud, arch=arch)
LOG.debug("Apt Mirror info: %s", mirrors)
apply_debconf_selections(cfg, target)
if util.is_false(cfg.get('preserve_sources_list', False)):
generate_sources_list(cfg, release, mirrors, cloud)
rename_apt_lists(mirrors, target)
try:
apply_apt_config(cfg, APT_PROXY_FN, APT_CONFIG_FN)
except (IOError, OSError):
LOG.exception("Failed to apply proxy or apt config info:")
# Process 'apt_source -> sources {dict}'
if 'sources' in cfg:
params = mirrors
params['RELEASE'] = release
params['MIRROR'] = mirrors["MIRROR"]
matcher = None
matchcfg = cfg.get('add_apt_repo_match', ADD_APT_REPO_MATCH)
if matchcfg:
matcher = re.compile(matchcfg).search
add_apt_sources(cfg['sources'], cloud, target=target,
template_params=params, aa_repo_match=matcher)
def debconf_set_selections(selections, target=None):
util.subp(['debconf-set-selections'], data=selections, target=target,
capture=True)
def dpkg_reconfigure(packages, target=None):
# For any packages that are already installed, but have preseed data
# we populate the debconf database, but the filesystem configuration
# would be preferred on a subsequent dpkg-reconfigure.
# so, what we have to do is "know" information about certain packages
# to unconfigure them.
unhandled = []
to_config = []
for pkg in packages:
if pkg in CONFIG_CLEANERS:
LOG.debug("unconfiguring %s", pkg)
CONFIG_CLEANERS[pkg](target)
to_config.append(pkg)
else:
unhandled.append(pkg)
if len(unhandled):
LOG.warn("The following packages were installed and preseeded, "
"but cannot be unconfigured: %s", unhandled)
if len(to_config):
util.subp(['dpkg-reconfigure', '--frontend=noninteractive'] +
list(to_config), data=None, target=target, capture=True)
def apply_debconf_selections(cfg, target=None):
"""apply_debconf_selections - push content to debconf"""
# debconf_selections:
# set1: |
# cloud-init cloud-init/datasources multiselect MAAS
# set2: pkg pkg/value string bar
selsets = cfg.get('debconf_selections')
if not selsets:
LOG.debug("debconf_selections was not set in config")
return
selections = '\n'.join(
[selsets[key] for key in sorted(selsets.keys())])
debconf_set_selections(selections.encode() + b"\n", target=target)
# get a complete list of packages listed in input
pkgs_cfgd = set()
for key, content in selsets.items():
for line in content.splitlines():
if line.startswith("#"):
continue
pkg = re.sub(r"[:\s].*", "", line)
pkgs_cfgd.add(pkg)
pkgs_installed = util.get_installed_packages(target)
LOG.debug("pkgs_cfgd: %s", pkgs_cfgd)
need_reconfig = pkgs_cfgd.intersection(pkgs_installed)
if len(need_reconfig) == 0:
LOG.debug("no need for reconfig")
return
dpkg_reconfigure(need_reconfig, target=target)
def clean_cloud_init(target):
"""clean out any local cloud-init config"""
flist = glob.glob(
util.target_path(target, "/etc/cloud/cloud.cfg.d/*dpkg*"))
LOG.debug("cleaning cloud-init config from: %s", flist)
for dpkg_cfg in flist:
os.unlink(dpkg_cfg)
def mirrorurl_to_apt_fileprefix(mirror):
"""mirrorurl_to_apt_fileprefix
Convert a mirror url to the file prefix used by apt on disk to
store cache information for that mirror.
To do so do:
- take off ???://
- drop tailing /
- convert in string / to _"""
string = mirror
if string.endswith("/"):
string = string[0:-1]
pos = string.find("://")
if pos >= 0:
string = string[pos + 3:]
string = string.replace("/", "_")
return string
def rename_apt_lists(new_mirrors, target=None):
"""rename_apt_lists - rename apt lists to preserve old cache data"""
default_mirrors = get_default_mirrors(util.get_architecture(target))
pre = util.target_path(target, APT_LISTS)
for (name, omirror) in default_mirrors.items():
nmirror = new_mirrors.get(name)
if not nmirror:
continue
oprefix = pre + os.path.sep + mirrorurl_to_apt_fileprefix(omirror)
nprefix = pre + os.path.sep + mirrorurl_to_apt_fileprefix(nmirror)
if oprefix == nprefix:
continue
olen = len(oprefix)
for filename in glob.glob("%s_*" % oprefix):
newname = "%s%s" % (nprefix, filename[olen:])
LOG.debug("Renaming apt list %s to %s", filename, newname)
try:
os.rename(filename, newname)
except OSError:
# since this is a best effort task, warn with but don't fail
LOG.warn("Failed to rename apt list:", exc_info=True)
def mirror_to_placeholder(tmpl, mirror, placeholder):
"""mirror_to_placeholder
replace the specified mirror in a template with a placeholder string
Checks for existance of the expected mirror and warns if not found"""
if mirror not in tmpl:
LOG.warn("Expected mirror '%s' not found in: %s", mirror, tmpl)
return tmpl.replace(mirror, placeholder)
def map_known_suites(suite):
"""there are a few default names which will be auto-extended.
This comes at the inability to use those names literally as suites,
but on the other hand increases readability of the cfg quite a lot"""
mapping = {'updates': '$RELEASE-updates',
'backports': '$RELEASE-backports',
'security': '$RELEASE-security',
'proposed': '$RELEASE-proposed',
'release': '$RELEASE'}
try:
retsuite = mapping[suite]
except KeyError:
retsuite = suite
return retsuite
def disable_suites(disabled, src, release):
"""reads the config for suites to be disabled and removes those
from the template"""
if not disabled:
return src
retsrc = src
for suite in disabled:
suite = map_known_suites(suite)
releasesuite = templater.render_string(suite, {'RELEASE': release})
LOG.debug("Disabling suite %s as %s", suite, releasesuite)
newsrc = ""
for line in retsrc.splitlines(True):
if line.startswith("#"):
newsrc += line
continue
# sources.list allow options in cols[1] which can have spaces
# so the actual suite can be [2] or later. example:
# deb [ arch=amd64,armel k=v ] http://example.com/debian
cols = line.split()
if len(cols) > 1:
pcol = 2
if cols[1].startswith("["):
for col in cols[1:]:
pcol += 1
if col.endswith("]"):
break
if cols[pcol] == releasesuite:
line = '# suite disabled by cloud-init: %s' % line
newsrc += line
retsrc = newsrc
return retsrc
def generate_sources_list(cfg, release, mirrors, cloud):
"""generate_sources_list
create a source.list file based on a custom or default template
by replacing mirrors and release in the template"""
aptsrc = "/etc/apt/sources.list"
params = {'RELEASE': release, 'codename': release}
for k in mirrors:
params[k] = mirrors[k]
params[k.lower()] = mirrors[k]
tmpl = cfg.get('sources_list', None)
if tmpl is None:
LOG.info("No custom template provided, fall back to builtin")
template_fn = cloud.get_template_filename('sources.list.%s' %
(cloud.distro.name))
if not template_fn:
template_fn = cloud.get_template_filename('sources.list')
if not template_fn:
LOG.warn("No template found, not rendering /etc/apt/sources.list")
return
tmpl = util.load_file(template_fn)
rendered = templater.render_string(tmpl, params)
disabled = disable_suites(cfg.get('disable_suites'), rendered, release)
util.write_file(aptsrc, disabled, mode=0o644)
def add_apt_key_raw(key, target=None):
"""
actual adding of a key as defined in key argument
to the system
"""
LOG.debug("Adding key:\n'%s'", key)
try:
util.subp(['apt-key', 'add', '-'], data=key.encode(), target=target)
except util.ProcessExecutionError:
LOG.exception("failed to add apt GPG Key to apt keyring")
raise
def add_apt_key(ent, target=None):
"""
Add key to the system as defined in ent (if any).
Supports raw keys or keyid's
The latter will as a first step fetched to get the raw key
"""
if 'keyid' in ent and 'key' not in ent:
keyserver = DEFAULT_KEYSERVER
if 'keyserver' in ent:
keyserver = ent['keyserver']
ent['key'] = gpg.getkeybyid(ent['keyid'], keyserver)
if 'key' in ent:
add_apt_key_raw(ent['key'], target)
def update_packages(cloud):
cloud.distro.update_package_sources()
def add_apt_sources(srcdict, cloud, target=None, template_params=None,
aa_repo_match=None):
"""
add entries in /etc/apt/sources.list.d for each abbreviated
sources.list entry in 'srcdict'. When rendering template, also
include the values in dictionary searchList
"""
if template_params is None:
template_params = {}
if aa_repo_match is None:
raise ValueError('did not get a valid repo matcher')
if not isinstance(srcdict, dict):
raise TypeError('unknown apt format: %s' % (srcdict))
for filename in srcdict:
ent = srcdict[filename]
LOG.debug("adding source/key '%s'", ent)
if 'filename' not in ent:
ent['filename'] = filename
add_apt_key(ent, target)
if 'source' not in ent:
continue
source = ent['source']
source = templater.render_string(source, template_params)
if not ent['filename'].startswith("/"):
ent['filename'] = os.path.join("/etc/apt/sources.list.d/",
ent['filename'])
if not ent['filename'].endswith(".list"):
ent['filename'] += ".list"
if aa_repo_match(source):
try:
util.subp(["add-apt-repository", source], target=target)
except util.ProcessExecutionError:
LOG.exception("add-apt-repository failed.")
raise
continue
sourcefn = util.target_path(target, ent['filename'])
try:
contents = "%s\n" % (source)
util.write_file(sourcefn, contents, omode="a")
except IOError as detail:
LOG.exception("failed write to file %s: %s", sourcefn, detail)
raise
update_packages(cloud)
return
def convert_v1_to_v2_apt_format(srclist):
"""convert v1 apt format to v2 (dict in apt_sources)"""
srcdict = {}
if isinstance(srclist, list):
LOG.debug("apt config: convert V1 to V2 format (source list to dict)")
for srcent in srclist:
if 'filename' not in srcent:
# file collides for multiple !filename cases for compatibility
# yet we need them all processed, so not same dictionary key
srcent['filename'] = "cloud_config_sources.list"
key = util.rand_dict_key(srcdict, "cloud_config_sources.list")
else:
# all with filename use that as key (matching new format)
key = srcent['filename']
srcdict[key] = srcent
elif isinstance(srclist, dict):
srcdict = srclist
else:
raise ValueError("unknown apt_sources format")
return srcdict
def convert_key(oldcfg, aptcfg, oldkey, newkey):
"""convert an old key to the new one if the old one exists
returns true if a key was found and converted"""
if oldcfg.get(oldkey, None) is not None:
aptcfg[newkey] = oldcfg.get(oldkey)
del oldcfg[oldkey]
return True
return False
def convert_mirror(oldcfg, aptcfg):
"""convert old apt_mirror keys into the new more advanced mirror spec"""
keymap = [('apt_mirror', 'uri'),
('apt_mirror_search', 'search'),
('apt_mirror_search_dns', 'search_dns')]
converted = False
newmcfg = {'arches': ['default']}
for oldkey, newkey in keymap:
if convert_key(oldcfg, newmcfg, oldkey, newkey):
converted = True
# only insert new style config if anything was converted
if converted:
aptcfg['primary'] = [newmcfg]
def convert_v2_to_v3_apt_format(oldcfg):
"""convert old to new keys and adapt restructured mirror spec"""
mapoldkeys = {'apt_sources': 'sources',
'apt_mirror': None,
'apt_mirror_search': None,
'apt_mirror_search_dns': None,
'apt_proxy': 'proxy',
'apt_http_proxy': 'http_proxy',
'apt_ftp_proxy': 'https_proxy',
'apt_https_proxy': 'ftp_proxy',
'apt_preserve_sources_list': 'preserve_sources_list',
'apt_custom_sources_list': 'sources_list',
'add_apt_repo_match': 'add_apt_repo_match'}
needtoconvert = []
for oldkey in mapoldkeys:
if oldkey in oldcfg:
if oldcfg[oldkey] in (None, ""):
del oldcfg[oldkey]
else:
needtoconvert.append(oldkey)
# no old config, so no new one to be created
if not needtoconvert:
return oldcfg
LOG.debug("apt config: convert V2 to V3 format for keys '%s'",
", ".join(needtoconvert))
# if old AND new config are provided, prefer the new one (LP #1616831)
newaptcfg = oldcfg.get('apt', None)
if newaptcfg is not None:
LOG.debug("apt config: V1/2 and V3 format specified, preferring V3")
for oldkey in needtoconvert:
newkey = mapoldkeys[oldkey]
verify = oldcfg[oldkey] # drop, but keep a ref for verification
del oldcfg[oldkey]
if newkey is None or newaptcfg.get(newkey, None) is None:
# no simple mapping or no collision on this particular key
continue
if verify != newaptcfg[newkey]:
raise ValueError("Old and New apt format defined with unequal "
"values %s vs %s @ %s" % (verify,
newaptcfg[newkey],
oldkey))
# return conf after clearing conflicting V1/2 keys
return oldcfg
# create new format from old keys
aptcfg = {}
# simple renames / moves under the apt key
for oldkey in mapoldkeys:
if mapoldkeys[oldkey] is not None:
convert_key(oldcfg, aptcfg, oldkey, mapoldkeys[oldkey])
# mirrors changed in a more complex way
convert_mirror(oldcfg, aptcfg)
for oldkey in mapoldkeys:
if oldcfg.get(oldkey, None) is not None:
raise ValueError("old apt key '%s' left after conversion" % oldkey)
# insert new format into config and return full cfg with only v3 content
oldcfg['apt'] = aptcfg
return oldcfg
def convert_to_v3_apt_format(cfg):
"""convert the old list based format to the new dict based one. After that
convert the old dict keys/format to v3 a.k.a 'new apt config'"""
# V1 -> V2, the apt_sources entry from list to dict
apt_sources = cfg.get('apt_sources', None)
if apt_sources is not None:
cfg['apt_sources'] = convert_v1_to_v2_apt_format(apt_sources)
# V2 -> V3, move all former globals under the "apt" key
# Restructure into new key names and mirror hierarchy
cfg = convert_v2_to_v3_apt_format(cfg)
return cfg
def search_for_mirror(candidates):
"""
Search through a list of mirror urls for one that works
This needs to return quickly.
"""
if candidates is None:
return None
LOG.debug("search for mirror in candidates: '%s'", candidates)
for cand in candidates:
try:
if util.is_resolvable_url(cand):
LOG.debug("found working mirror: '%s'", cand)
return cand
except Exception:
pass
return None
def search_for_mirror_dns(configured, mirrortype, cfg, cloud):
"""
Try to resolve a list of predefines DNS names to pick mirrors
"""
mirror = None
if configured:
mydom = ""
doms = []
if mirrortype == "primary":
mirrordns = "mirror"
elif mirrortype == "security":
mirrordns = "security-mirror"
else:
raise ValueError("unknown mirror type")
# if we have a fqdn, then search its domain portion first
(_, fqdn) = util.get_hostname_fqdn(cfg, cloud)
mydom = ".".join(fqdn.split(".")[1:])
if mydom:
doms.append(".%s" % mydom)
doms.extend((".localdomain", "",))
mirror_list = []
distro = cloud.distro.name
mirrorfmt = "http://%s-%s%s/%s" % (distro, mirrordns, "%s", distro)
for post in doms:
mirror_list.append(mirrorfmt % (post))
mirror = search_for_mirror(mirror_list)
return mirror
def update_mirror_info(pmirror, smirror, arch, cloud):
"""sets security mirror to primary if not defined.
returns defaults if no mirrors are defined"""
if pmirror is not None:
if smirror is None:
smirror = pmirror
return {'PRIMARY': pmirror,
'SECURITY': smirror}
# None specified at all, get default mirrors from cloud
mirror_info = cloud.datasource.get_package_mirror_info()
if mirror_info:
# get_package_mirror_info() returns a dictionary with
# arbitrary key/value pairs including 'primary' and 'security' keys.
# caller expects dict with PRIMARY and SECURITY.
m = mirror_info.copy()
m['PRIMARY'] = m['primary']
m['SECURITY'] = m['security']
return m
# if neither apt nor cloud configured mirrors fall back to
return get_default_mirrors(arch)
def get_arch_mirrorconfig(cfg, mirrortype, arch):
"""out of a list of potential mirror configurations select
and return the one matching the architecture (or default)"""
# select the mirror specification (if-any)
mirror_cfg_list = cfg.get(mirrortype, None)
if mirror_cfg_list is None:
return None
# select the specification matching the target arch
default = None
for mirror_cfg_elem in mirror_cfg_list:
arches = mirror_cfg_elem.get("arches")
if arch in arches:
return mirror_cfg_elem
if "default" in arches:
default = mirror_cfg_elem
return default
def get_mirror(cfg, mirrortype, arch, cloud):
"""pass the three potential stages of mirror specification
returns None is neither of them found anything otherwise the first
hit is returned"""
mcfg = get_arch_mirrorconfig(cfg, mirrortype, arch)
if mcfg is None:
return None
# directly specified
mirror = mcfg.get("uri", None)
# fallback to search if specified
if mirror is None:
# list of mirrors to try to resolve
mirror = search_for_mirror(mcfg.get("search", None))
# fallback to search_dns if specified
if mirror is None:
# list of mirrors to try to resolve
mirror = search_for_mirror_dns(mcfg.get("search_dns", None),
mirrortype, cfg, cloud)
return mirror
def find_apt_mirror_info(cfg, cloud, arch=None):
"""find_apt_mirror_info
find an apt_mirror given the cfg provided.
It can check for separate config of primary and security mirrors
If only primary is given security is assumed to be equal to primary
If the generic apt_mirror is given that is defining for both
"""
if arch is None:
arch = util.get_architecture()
LOG.debug("got arch for mirror selection: %s", arch)
pmirror = get_mirror(cfg, "primary", arch, cloud)
LOG.debug("got primary mirror: %s", pmirror)
smirror = get_mirror(cfg, "security", arch, cloud)
LOG.debug("got security mirror: %s", smirror)
mirror_info = update_mirror_info(pmirror, smirror, arch, cloud)
# less complex replacements use only MIRROR, derive from primary
mirror_info["MIRROR"] = mirror_info["PRIMARY"]
return mirror_info
def apply_apt_config(cfg, proxy_fname, config_fname):
"""apply_apt_config
Applies any apt*proxy config from if specified
"""
# Set up any apt proxy
cfgs = (('proxy', 'Acquire::http::Proxy "%s";'),
('http_proxy', 'Acquire::http::Proxy "%s";'),
('ftp_proxy', 'Acquire::ftp::Proxy "%s";'),
('https_proxy', 'Acquire::https::Proxy "%s";'))
proxies = [fmt % cfg.get(name) for (name, fmt) in cfgs if cfg.get(name)]
if len(proxies):
LOG.debug("write apt proxy info to %s", proxy_fname)
util.write_file(proxy_fname, '\n'.join(proxies) + '\n')
elif os.path.isfile(proxy_fname):
util.del_file(proxy_fname)
LOG.debug("no apt proxy configured, removed %s", proxy_fname)
if cfg.get('conf', None):
LOG.debug("write apt config info to %s", config_fname)
util.write_file(config_fname, cfg.get('conf'))
elif os.path.isfile(config_fname):
util.del_file(config_fname)
LOG.debug("no apt config configured, removed %s", config_fname)
CONFIG_CLEANERS = {
'cloud-init': clean_cloud_init,
}
# vi: ts=4 expandtab syntax=python
| gpl-3.0 |
SOWRON/SC | src/server/game/AI/CoreAI/PetAI.cpp | 15647 | /*
*
* Copyright (C) 2011-2012 ArkCORE2 <http://www.arkania.net/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.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/>.
*/
#include "PetAI.h"
#include "Errors.h"
#include "Pet.h"
#include "Player.h"
#include "DBCStores.h"
#include "Spell.h"
#include "ObjectAccessor.h"
#include "SpellMgr.h"
#include "Creature.h"
#include "World.h"
#include "Util.h"
#include "Group.h"
#include "SpellInfo.h"
int PetAI::Permissible(const Creature* creature)
{
if (creature->isPet())
return PERMIT_BASE_SPECIAL;
return PERMIT_BASE_NO;
}
PetAI::PetAI(Creature* c) : CreatureAI(c), i_tracker(TIME_INTERVAL_LOOK)
{
m_AllySet.clear();
UpdateAllies();
}
void PetAI::EnterEvadeMode()
{
}
bool PetAI::_needToStop()
{
// This is needed for charmed creatures, as once their target was reset other effects can trigger threat
if (me->isCharmed() && me->getVictim() == me->GetCharmer())
return true;
return !me->IsValidAttackTarget(me->getVictim());
}
void PetAI::_stopAttack()
{
if (!me->isAlive())
{
sLog->outStaticDebug("Creature stoped attacking cuz his dead [guid=%u]", me->GetGUIDLow());
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveIdle();
me->CombatStop();
me->getHostileRefManager().deleteReferences();
return;
}
me->AttackStop();
me->GetCharmInfo()->SetIsCommandAttack(false);
HandleReturnMovement();
}
void PetAI::UpdateAI(const uint32 diff)
{
if (!me->isAlive())
return;
Unit* owner = me->GetCharmerOrOwner();
if (m_updateAlliesTimer <= diff)
// UpdateAllies self set update timer
UpdateAllies();
else
m_updateAlliesTimer -= diff;
// me->getVictim() can't be used for check in case stop fighting, me->getVictim() clear at Unit death etc.
if (me->getVictim())
{
// is only necessary to stop casting, the pet must not exit combat
if (me->getVictim()->HasBreakableByDamageCrowdControlAura(me))
{
me->InterruptNonMeleeSpells(false);
return;
}
if (_needToStop())
{
sLog->outStaticDebug("Pet AI stopped attacking [guid=%u]", me->GetGUIDLow());
_stopAttack();
return;
}
DoMeleeAttackIfReady();
}
else if (owner && me->GetCharmInfo()) //no victim
{
Unit* nextTarget = SelectNextTarget();
if (me->HasReactState(REACT_PASSIVE))
_stopAttack();
else if (nextTarget)
AttackStart(nextTarget);
else
HandleReturnMovement();
}
else if (owner && !me->HasUnitState(UNIT_STATE_FOLLOW)) // no charm info and no victim
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle());
if (!me->GetCharmInfo())
return;
// Autocast (casted only in combat or persistent spells in any state)
if (!me->HasUnitState(UNIT_STATE_CASTING))
{
typedef std::vector<std::pair<Unit*, Spell*> > TargetSpellList;
TargetSpellList targetSpellStore;
for (uint8 i = 0; i < me->GetPetAutoSpellSize(); ++i)
{
uint32 spellID = me->GetPetAutoSpellOnPos(i);
if (!spellID)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellID);
if (!spellInfo)
continue;
// Check global cooldown
if (me->GetCharmInfo() && me->GetCharmInfo()->GetGlobalCooldownMgr().HasGlobalCooldown(spellInfo))
continue;
// Check spell cooldown
if (me->HasSpellCooldown(spellInfo->Id))
continue;
// Check if pet is in combat and if spell can be cast
if (me->isInCombat() && !spellInfo->CanBeUsedInCombat())
continue;
// Prevent spells like Furious Howl from constantly casting out of
// combat when the cooldown is up
if (!me->isInCombat() && !spellInfo->NeedsToBeTriggeredByCaster())
continue;
// We have a spell we can cast, let's pick a target
if (spellInfo->IsPositive())
{
// These would be buff spells like Furious Howl, Consume Shadows, etc.
Spell* spell = new Spell(me, spellInfo, TRIGGERED_NONE, 0);
bool spellUsed = false;
for (std::set<uint64>::const_iterator tar = m_AllySet.begin(); tar != m_AllySet.end(); ++tar)
{
Unit* target = ObjectAccessor::GetUnit(*me, *tar);
if (!target)
continue;
if (spell->CanAutoCast(target))
{
targetSpellStore.push_back(std::make_pair(target, spell));
spellUsed = true;
break;
}
}
if (!spellUsed)
delete spell;
}
else if (me->getVictim() && CanAttack(me->getVictim()))
{
// These would be offensive spells like Claw, Bite, Torment, Fireball, etc.
Spell* spell = new Spell(me, spellInfo, TRIGGERED_NONE, 0);
if (spell->CanAutoCast(me->getVictim()))
targetSpellStore.push_back(std::make_pair(me->getVictim(), spell));
else
delete spell;
}
}
//found units to cast on to
if (!targetSpellStore.empty())
{
uint32 index = urand(0, targetSpellStore.size() - 1);
Spell* spell = targetSpellStore[index].second;
Unit* target = targetSpellStore[index].first;
targetSpellStore.erase(targetSpellStore.begin() + index);
SpellCastTargets targets;
targets.SetUnitTarget(target);
if (!me->HasInArc(M_PI, target))
{
me->SetInFront(target);
if (target && target->GetTypeId() == TYPEID_PLAYER)
me->SendUpdateToPlayer(target->ToPlayer());
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
me->SendUpdateToPlayer(owner->ToPlayer());
}
me->AddCreatureSpellCooldown(spell->m_spellInfo->Id);
spell->prepare(&targets);
}
// deleted cached Spell objects
for (TargetSpellList::const_iterator itr = targetSpellStore.begin(); itr != targetSpellStore.end(); ++itr)
delete itr->second;
}
}
void PetAI::UpdateAllies()
{
Unit* owner = me->GetCharmerOrOwner();
Group* group = NULL;
m_updateAlliesTimer = 10*IN_MILLISECONDS; //update friendly targets every 10 seconds, lesser checks increase performance
if (!owner)
return;
else if (owner->GetTypeId() == TYPEID_PLAYER)
group = owner->ToPlayer()->GetGroup();
//only pet and owner/not in group->ok
if (m_AllySet.size() == 2 && !group)
return;
//owner is in group; group members filled in already (no raid ->subgroupcount = whole count)
if (group && !group->isRaidGroup() && m_AllySet.size() == (group->GetMembersCount() + 2))
return;
m_AllySet.clear();
m_AllySet.insert(me->GetGUID());
if (group) //add group
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
if (!Target || !group->SameSubGroup((Player*)owner, Target))
continue;
if (Target->GetGUID() == owner->GetGUID())
continue;
m_AllySet.insert(Target->GetGUID());
}
}
else //remove group
m_AllySet.insert(owner->GetGUID());
}
void PetAI::KilledUnit(Unit* victim)
{
// Called from Unit::Kill() in case where pet or owner kills something
// if owner killed this victim, pet may still be attacking something else
if (me->getVictim() && me->getVictim() != victim)
return;
// Clear target just in case. May help problem where health / focus / mana
// regen gets stuck. Also resets attack command.
// Can't use _stopAttack() because that activates movement handlers and ignores
// next target selection
me->AttackStop();
me->GetCharmInfo()->SetIsCommandAttack(false);
me->SendMeleeAttackStop(); // Stops the pet's 'Attack' button from flashing
Unit* nextTarget = SelectNextTarget();
if (nextTarget)
AttackStart(nextTarget);
else
HandleReturnMovement(); // Return
}
void PetAI::AttackStart(Unit* target)
{
// Overrides Unit::AttackStart to correctly evaluate Pet states
// Check all pet states to decide if we can attack this target
if (!CanAttack(target))
return;
if (Unit* owner = me->GetOwner())
owner->SetInCombatWith(target);
DoAttack(target, true);
}
Unit* PetAI::SelectNextTarget()
{
// Provides next target selection after current target death
// Passive pets don't do next target selection
if (me->HasReactState(REACT_PASSIVE))
return NULL;
Unit* target = me->getAttackerForHelper();
// Check pet's attackers first to prevent dragging mobs back to owner
if (target && !target->HasBreakableByDamageCrowdControlAura())
return target;
if (me->GetCharmerOrOwner())
{
// Check owner's attackers if pet didn't have any
target = me->GetCharmerOrOwner()->getAttackerForHelper();
if (target && !target->HasBreakableByDamageCrowdControlAura())
return target;
// 3.0.2 - Pets now start attacking their owners target in defensive mode as soon as the hunter does
target = me->GetCharmerOrOwner()->getVictim();
if (target && !target->HasBreakableByDamageCrowdControlAura())
return target;
}
// Default
return NULL;
}
void PetAI::HandleReturnMovement()
{
// Handles moving the pet back to stay or owner
if (me->GetCharmInfo()->HasCommandState(COMMAND_STAY))
{
if (!me->GetCharmInfo()->IsAtStay() && !me->GetCharmInfo()->IsReturning())
{
// Return to previous position where stay was clicked
if (!me->GetCharmInfo()->IsCommandAttack())
{
float x, y, z;
me->GetCharmInfo()->GetStayPosition(x, y, z);
me->GetCharmInfo()->SetIsReturning(true);
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MovePoint(me->GetGUIDLow(), x, y, z);
}
}
}
else // COMMAND_FOLLOW
{
if (!me->GetCharmInfo()->IsFollowing() && !me->GetCharmInfo()->IsReturning())
{
if (!me->GetCharmInfo()->IsCommandAttack())
{
me->GetCharmInfo()->SetIsReturning(true);
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveFollow(me->GetCharmerOrOwner(), PET_FOLLOW_DIST, me->GetFollowAngle());
}
}
}
}
void PetAI::DoAttack(Unit* target, bool chase)
{
// Handles attack with or without chase and also resets all
// PetAI flags for next update / creature kill
// me->GetCharmInfo()->SetIsCommandAttack(false);
// The following conditions are true if chase == true
// (Follow && (Aggressive || Defensive))
// ((Stay || Follow) && (Passive && player clicked attack))
if (chase)
{
if (me->Attack(target, true))
{
me->GetCharmInfo()->SetIsAtStay(false);
me->GetCharmInfo()->SetIsFollowing(false);
me->GetCharmInfo()->SetIsReturning(false);
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveChase(target);
}
}
else // (Stay && ((Aggressive || Defensive) && In Melee Range)))
{
me->GetCharmInfo()->SetIsAtStay(true);
me->GetCharmInfo()->SetIsFollowing(false);
me->GetCharmInfo()->SetIsReturning(false);
me->Attack(target, true);
}
}
void PetAI::MovementInform(uint32 moveType, uint32 data)
{
// Receives notification when pet reaches stay or follow owner
switch (moveType)
{
case POINT_MOTION_TYPE:
{
// Pet is returning to where stay was clicked. data should be
// pet's GUIDLow since we set that as the waypoint ID
if (data == me->GetGUIDLow() && me->GetCharmInfo()->IsReturning())
{
me->GetCharmInfo()->SetIsAtStay(true);
me->GetCharmInfo()->SetIsReturning(false);
me->GetCharmInfo()->SetIsFollowing(false);
me->GetCharmInfo()->SetIsCommandAttack(false);
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveIdle();
}
break;
}
case FOLLOW_MOTION_TYPE:
{
// If data is owner's GUIDLow then we've reached follow point,
// otherwise we're probably chasing a creature
if (me->GetCharmerOrOwner() && me->GetCharmInfo() && data == me->GetCharmerOrOwner()->GetGUIDLow() && me->GetCharmInfo()->IsReturning())
{
me->GetCharmInfo()->SetIsAtStay(false);
me->GetCharmInfo()->SetIsReturning(false);
me->GetCharmInfo()->SetIsFollowing(true);
me->GetCharmInfo()->SetIsCommandAttack(false);
}
break;
}
default:
break;
}
}
bool PetAI::CanAttack(Unit* target)
{
// Evaluates wether a pet can attack a specific
// target based on CommandState, ReactState and other flags
// Returning - check first since pets returning ignore attacks
if (me->GetCharmInfo()->IsReturning())
return false;
// Passive - check now so we don't have to worry about passive in later checks
if (me->HasReactState(REACT_PASSIVE))
return me->GetCharmInfo()->IsCommandAttack();
// Pets commanded to attack should not stop their approach if attacked by another creature
if (me->getVictim() && (me->getVictim() != target))
return !me->GetCharmInfo()->IsCommandAttack();
// From this point on, pet will always be either aggressive or defensive
// Stay - can attack if target is within range or commanded to
if (me->GetCharmInfo()->HasCommandState(COMMAND_STAY))
return (me->IsWithinMeleeRange(target, MIN_MELEE_REACH) || me->GetCharmInfo()->IsCommandAttack());
// Follow
if (me->GetCharmInfo()->HasCommandState(COMMAND_FOLLOW))
return true;
// default, though we shouldn't ever get here
return false;
}
| gpl-3.0 |
cammace/iGuide | app/src/main/java/team6/iguide/CampusIssueInfoWindow.java | 9058 | package team6.iguide;
/***
iGuide
Copyright (C) 2015 Cameron Mace
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/>.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.InfoWindow;
import com.mapbox.mapboxsdk.views.MapView;
import java.util.List;
import team6.iguide.IssueDataModel.IssueMarker;
public class CampusIssueInfoWindow extends InfoWindow {
// This class is used to handle what happens when an issue marker is clicked.
private Context mContext;
String title;
String ref;
String shortTitle;
String shortRef;
public CampusIssueInfoWindow(final Context context, final Activity activity, final MapView mv, final List<IssueMarker> issueInfo, final int position) {
super(R.layout.campus_issue_info_window, mv);
this.mContext = context;
// We clip the layout so it displays rounded corners. This however only works with API 21
// and higher.
if(Build.VERSION.SDK_INT >= 21) {
getView().findViewById(R.id.mainpanal).setClipToOutline(true);
mView.setElevation(24);
}
ImageButton routing = (ImageButton)mView.findViewById(R.id.routing_button);
routing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Build the alert dialog that displays when resolve issue is clicked
AlertDialog.Builder resolveIssueConfirmation = new AlertDialog.Builder(activity);
resolveIssueConfirmation.setTitle("Resolve Issue?");
resolveIssueConfirmation.setMessage("This issue will be marked as resolved and disappear from the map permanently. Only resolve if you personally fixed the issue or know someone who did.");
resolveIssueConfirmation.setPositiveButton("Resolve Issue",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Snackbar.make(MainActivity.mapContainer, "Issue resolved", Snackbar.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Snackbar.make(MainActivity.mapContainer, "Long press to add an issue at that location", Snackbar.LENGTH_INDEFINITE).setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
// Handle click here
}
}).show();
}
}, 5000);
resolveIssue(issueInfo.get(position).getPid());
close();
}
});
resolveIssueConfirmation.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do action when dialog is canceled, in our case, we don't have
// to do anything
}
});
// Show the alert dialog
resolveIssueConfirmation.show();
}
});
// Add own OnTouchListener to customize handling InfoWindow touch events
setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Bundle bundle = new Bundle();
bundle.putString("TITLE", title);
bundle.putString("DESCRIPTION", ref);
bundle.putString("TYPE", issueInfo.get(position).getType());
bundle.putString("STATUS", issueInfo.get(position).getStatus());
bundle.putString("ROOM", issueInfo.get(position).getRoom());
bundle.putString("CREATEDAT", issueInfo.get(position).getCreatedAt());
bundle.putString("UPDATEDAT", issueInfo.get(position).getUpdatedAt());
bundle.putInt("PID", issueInfo.get(position).getPid());
Intent intent = new Intent(mView.getContext(), CampusIssueDetailActivity.class);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
// Still close the InfoWindow though
close();
}
// Return true as we're done processing this event
return true;
}
});
}
@Override
public void onOpen(Marker overlayItem) {
title = overlayItem.getTitle();
ref = overlayItem.getDescription();
// Check string's length and if longer then 25 characters, we shorten
if(title.length() > 25){
shortTitle = title.substring(0,24)+"...";
((TextView) mView.findViewById(R.id.title)).setText(shortTitle);
}else ((TextView) mView.findViewById(R.id.title)).setText(title);
if(ref.length() > 25){
shortRef = ref.substring(0,24)+"...";
((TextView) mView.findViewById(R.id.ref)).setText(shortRef);
} else ((TextView) mView.findViewById(R.id.ref)).setText(ref);
}
public void resolveIssue(int pid){
RequestQueue mRequestQueue = Volley.newRequestQueue(mContext);
String Url = "http://iguide.heliohost.org/delete_marker.php?pid=" + pid;
StringRequest req = new StringRequest(Request.Method.POST, Url,new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v("issue.Volley", "Volley Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Snackbar.make(MainActivity.mapContainer, "Error occurred resolving issue", Snackbar.LENGTH_LONG).show();
Log.e("issue.Volley", "onErrorResponse: ", error);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Snackbar.make(MainActivity.mapContainer, "Long press to add an issue at that location", Snackbar.LENGTH_INDEFINITE).setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
// Handle click here
}
}).show();
}
}, 5000);
}
});
mRequestQueue.add(req);
// This allows volley to retry request if for some reason it times out the first time
// More info can be found in this question:
// http://stackoverflow.com/questions/17094718/android-volley-timeout
req.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}
| gpl-3.0 |
9thSenseRobotics/bosh_server | abhinavsingh-JAXL-f049d08/xep/jaxl.0050.php | 2739 | <?php
/* Jaxl (Jabber XMPP Library)
*
* Copyright (c) 2009-2010, Abhinav Singh <me@abhinavsingh.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Abhinav Singh nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* XEP-0050: Ad-Hoc Commands
*/
class JAXL0050 {
public static $ns = 'http://jabber.org/protocol/commands';
public static function init($jaxl) {
$jaxl->features[] = self::$ns;
}
public static function getCommandList($to, $from, $callback, $jaxl) {
$payload = '<query xmlns="http://jabber.org/protocol/disco#items" node="'.self::$ns.'"/>';
return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
}
public static function getCommandInfo($to, $from, $node, $callback, $jaxl) {
$payload = '<query xmlns="http://jabber.org/protocol/disco#info" node="'.$node.'"/>';
return XMPPSend::iq($jaxl, 'get', $payload, $to, $from, $callback);
}
public static function executeCommand($to, $from, $node, $callback, $jaxl) {
$payload = '<command xmlns="'.self::$ns.'" node="'.$node.'" action="execute"/>';
return XMPPSend::iq($jaxl, 'set', $payload, $to, $from, $callback);
}
}
?>
| gpl-3.0 |
JoseLoarca/jc-chat | JCChat/app/src/main/java/org/jcloarca/jcchat/entities/User.java | 1033 | package org.jcloarca.jcchat.entities;
import java.util.Map;
/**
* Created by JCLoarca on 6/9/2016.
*/
public class User {
String email;
boolean online;
Map<String, Boolean> contacts;
public final static boolean ONLINE = true;
public final static boolean OFFLINE = false;
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
public Map<String, Boolean> getContacts() {
return contacts;
}
public void setContacts(Map<String, Boolean> contacts) {
this.contacts = contacts;
}
@Override
public boolean equals(Object obj){
boolean equal = false;
if(obj instanceof User){
User user = (User)obj;
equal = this.email.equals(user.getEmail());
}
return equal;
}
}
| gpl-3.0 |
MHeasell/rwe | src/rwe/io/tnt/TntArchive.cpp | 3823 | #include "TntArchive.h"
#include <array>
#include <cassert>
#include <rwe/io_utils.h>
namespace rwe
{
TntException::TntException(const std::string& __arg) : runtime_error(__arg)
{
}
TntException::TntException(const char* string) : runtime_error(string)
{
}
TntArchive::TntArchive(std::istream* _stream) : stream(_stream)
{
header = readRaw<TntHeader>(*stream);
if (header.magicNumber != TntMagicNumber)
{
throw TntException("Invalid TNT version number");
}
}
void TntArchive::readTiles(std::function<void(const char*)> tileCallback)
{
stream->seekg(header.tileGraphicsOffset);
std::array<char, 32 * 32> buffer{};
for (unsigned int i = 0; i < header.numberOfTiles; ++i)
{
stream->read(buffer.data(), 32 * 32);
tileCallback(buffer.data());
}
}
void TntArchive::readFeatures(std::function<void(const std::string&)> featureCallback)
{
stream->seekg(header.featuresOffset);
std::string str;
str.reserve(128);
for (unsigned int i = 0; i < header.numberOfFeatures; ++i)
{
auto feature = readRaw<TntFeature>(*stream);
auto nullIt = std::find(feature.name, feature.name + 128, '\0');
str.erase();
str.append(feature.name, nullIt);
featureCallback(str);
}
}
const TntHeader& TntArchive::getHeader() const
{
return header;
}
void TntArchive::readMapData(uint16_t* outputBuffer)
{
stream->seekg(header.mapDataOffset);
stream->read(reinterpret_cast<char*>(outputBuffer), (header.width / 2) * (header.height / 2) * sizeof(uint16_t));
}
void TntArchive::readMapAttributes(TntTileAttributes* outputBuffer)
{
stream->seekg(header.mapAttributesOffset);
stream->read(reinterpret_cast<char*>(outputBuffer), header.width * header.height * sizeof(TntTileAttributes));
}
struct MinimapSize
{
unsigned int width;
unsigned int height;
};
MinimapSize getMinimapActualSize(const std::vector<char>& data, unsigned int width, unsigned int height)
{
unsigned int realWidth = width;
unsigned int realHeight = height;
while (realWidth > 0 && data[realWidth - 1] == TntMinimapVoidByte)
{
--realWidth;
}
while (realHeight > 0 && data[((realHeight - 1) * width)] == TntMinimapVoidByte)
{
--realHeight;
}
return MinimapSize{realWidth, realHeight};
}
std::vector<char> trimMinimapBytes(const std::vector<char>& data, unsigned int width, unsigned int height, unsigned int newWidth, unsigned int newHeight)
{
assert(newWidth <= width);
assert(newHeight <= height);
std::vector<char> newData(newWidth * newHeight);
for (unsigned int y = 0; y < newHeight; ++y)
{
for (unsigned int x = 0; x < newWidth; ++x)
{
newData[(y * newWidth) + x] = data[(y * width) + x];
}
}
return newData;
}
TntMinimapInfo TntArchive::readMinimap()
{
stream->seekg(header.minimapOffset);
auto minimapHeader = readRaw<TntMinimapHeader>(*stream);
std::vector<char> buffer(minimapHeader.width * minimapHeader.height);
stream->read(buffer.data(), minimapHeader.width * minimapHeader.height);
auto realSize = getMinimapActualSize(buffer, minimapHeader.width, minimapHeader.height);
auto resizedBuffer = trimMinimapBytes(buffer, minimapHeader.width, minimapHeader.height, realSize.width, realSize.height);
return TntMinimapInfo{realSize.width, realSize.height, std::move(resizedBuffer)};
}
}
| gpl-3.0 |
kremi151/MinaMod | src/main/java/lu/kremi151/minamod/util/FeatureList.java | 534 | package lu.kremi151.minamod.util;
public class FeatureList {
public static final boolean enable_ice_altar = false;
public static final boolean enable_redstone_crossroad = false;
public static final boolean enable_bees = false;
public static final boolean enable_jetpack = false;
public static final boolean enable_chairs = false;
public static final boolean enable_wookie_houses = false;
public static final boolean enable_casino = true;
//1.11:
public static final boolean enable_mixtures = true;
}
| gpl-3.0 |
Maxim-38RUS-Zabelin/sdk-release | sdk-android/src/com/mobileapptracker/MATPreloadData.java | 4058 | package com.mobileapptracker;
public class MATPreloadData {
public String publisherId;
public String offerId;
public String agencyId;
public String publisherReferenceId;
public String publisherSub1;
public String publisherSub2;
public String publisherSub3;
public String publisherSub4;
public String publisherSub5;
public String publisherSubAd;
public String publisherSubAdgroup;
public String publisherSubCampaign;
public String publisherSubKeyword;
public String publisherSubPublisher;
public String publisherSubSite;
public String advertiserSubAd;
public String advertiserSubAdgroup;
public String advertiserSubCampaign;
public String advertiserSubKeyword;
public String advertiserSubPublisher;
public String advertiserSubSite;
public MATPreloadData(String publisherId) {
this.publisherId = publisherId;
}
public MATPreloadData withOfferId(String offerId) {
this.offerId = offerId;
return this;
}
public MATPreloadData withAgencyId(String agencyId) {
this.agencyId = agencyId;
return this;
}
public MATPreloadData withPublisherReferenceId(String publisherReferenceId) {
this.publisherReferenceId = publisherReferenceId;
return this;
}
public MATPreloadData withPublisherSub1(String publisherSub1) {
this.publisherSub1 = publisherSub1;
return this;
}
public MATPreloadData withPublisherSub2(String publisherSub2) {
this.publisherSub2 = publisherSub2;
return this;
}
public MATPreloadData withPublisherSub3(String publisherSub3) {
this.publisherSub3 = publisherSub3;
return this;
}
public MATPreloadData withPublisherSub4(String publisherSub4) {
this.publisherSub4 = publisherSub4;
return this;
}
public MATPreloadData withPublisherSub5(String publisherSub5) {
this.publisherSub5 = publisherSub5;
return this;
}
public MATPreloadData withPublisherSubAd(String publisherSubAd) {
this.publisherSubAd = publisherSubAd;
return this;
}
public MATPreloadData withPublisherSubAdgroup(String publisherSubAdgroup) {
this.publisherSubAdgroup = publisherSubAdgroup;
return this;
}
public MATPreloadData withPublisherSubCampaign(String publisherSubCampaign) {
this.publisherSubCampaign = publisherSubCampaign;
return this;
}
public MATPreloadData withPublisherSubKeyword(String publisherSubKeyword) {
this.publisherSubKeyword = publisherSubKeyword;
return this;
}
public MATPreloadData withPublisherSubPublisher(String publisherSubPublisher) {
this.publisherSubPublisher = publisherSubPublisher;
return this;
}
public MATPreloadData withPublisherSubSite(String publisherSubSite) {
this.publisherSubSite = publisherSubSite;
return this;
}
public MATPreloadData withAdvertiserSubAd(String advertiserSubAd) {
this.advertiserSubAd = advertiserSubAd;
return this;
}
public MATPreloadData withAdvertiserSubAdgroup(String advertiserSubAdgroup) {
this.advertiserSubAdgroup = advertiserSubAdgroup;
return this;
}
public MATPreloadData withAdvertiserSubCampaign(String advertiserSubCampaign) {
this.advertiserSubCampaign = advertiserSubCampaign;
return this;
}
public MATPreloadData withAdvertiserSubKeyword(String advertiserSubKeyword) {
this.advertiserSubKeyword = advertiserSubKeyword;
return this;
}
public MATPreloadData withAdvertiserSubPublisher(String advertiserSubPublisher) {
this.advertiserSubPublisher = advertiserSubPublisher;
return this;
}
public MATPreloadData withAdvertiserSubSite(String advertiserSubSite) {
this.advertiserSubSite = advertiserSubSite;
return this;
}
}
| gpl-3.0 |
AkiraGTX/Erebus-Password-Manager | Erebus/Tests/Erebus.Core.Tests/AesCryptographerTests.cs | 7014 | using Erebus.Core.Contracts;
using Erebus.Core.Implementations;
using Moq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using Xunit;
namespace Erebus.Tests.Common
{
public class AesCryptographerTests : IDisposable
{
private SecureString Key;
private SecureString SecondKey;
private Mock<ISecureStringConverter> SecureStringConverterMock;
public AesCryptographerTests()
{
this.Key = new SecureString();
foreach (char c in "123456")
{
Key.AppendChar(c);
}
this.SecondKey = new SecureString();
foreach (char c in "654321")
{
SecondKey.AppendChar(c);
}
SecureStringConverterMock = new Mock<ISecureStringConverter>(MockBehavior.Strict);
SecureStringConverterMock.Setup(mock => mock.ToString(this.Key)).Returns("123456");
SecureStringConverterMock.Setup(mock => mock.ToString(this.SecondKey)).Returns("654321");
}
public void Dispose()
{
this.Key.Dispose();
this.SecondKey.Dispose();
}
private AesCryptographer CreateDefault()
{
var defaultInstance = new AesCryptographer(SecureStringConverterMock.Object);
return defaultInstance;
}
[Theory]
[MemberData(nameof(RoundtripCases))]
public void IsKeyValid_KeyIsValid_ReturnsTrue(byte[] input)
{
//Arrange
var sut = CreateDefault();
//Act
var encrypted = sut.Encrypt(input, this.Key);
bool isValid = sut.IsKeyValid(encrypted, this.Key);
//Assert
Assert.True(isValid);
}
[Theory]
[MemberData(nameof(RoundtripCases))]
public void IsKeyValid_KeyIsNotValid_ReturnsFalse(byte[] input)
{
//Arrange
var sut = CreateDefault();
//Act
var encrypted = sut.Encrypt(input, this.Key);
bool isValid = sut.IsKeyValid(encrypted, this.SecondKey);
//Assert
Assert.False(isValid);
}
[Fact]
public void Decrypt_InputIsNull_ThrowsArgumentNullException()
{
//Arrange
var sut = CreateDefault();
//Act
//Assert
Assert.Throws<ArgumentNullException>(() =>
{
var result = sut.Decrypt(null, this.Key);
});
}
[Fact]
public void Decrypt_KeyIsNull_ThrowsArgumentNullException()
{
//Arrange
var sut = CreateDefault();
//Act
//Assert
Assert.Throws<ArgumentNullException>(() =>
{
var result = sut.Decrypt(new byte[] { 0x34 }, null);
});
}
[Fact]
public void Encrypt_InputIsNull_ThrowsArgumentNullException()
{
//Arrange
var sut = CreateDefault();
//Act
//Assert
Assert.Throws<ArgumentNullException>(() =>
{
var result = sut.Encrypt(null, this.Key);
});
}
[Fact]
public void Encrypt_KeyIsNull_ThrowsArgumentNullException()
{
//Arrange
var sut = CreateDefault();
//Act
//Assert
Assert.Throws<ArgumentNullException>(() =>
{
var result = sut.Encrypt(new byte[] { 0x34 }, null);
});
}
[Theory]
[MemberData(nameof(RoundtripCases))]
public void Encrypt_Decrypt_Roundtrip_ResultIsSameAsSource(byte[] input)
{
//Arrange
var sut = CreateDefault();
//Act
var encrypted = sut.Encrypt(input, this.Key);
var result = sut.Decrypt(encrypted, this.Key);
//Assert
Assert.Equal(result, input);
Assert.NotEqual(encrypted, input);
}
public static IEnumerable<object[]> RoundtripCases
{
get
{
return new[]
{
new object[] { new byte[] { 0x43, 0x23, 0xef } },
new object[] { new byte[] { 0x43, 0x23, 0xef, 0x43, 0x23, 0xee , 0x43, 0x23, 0xe2, 0x4a,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23,
0x23, 0xee, 0x43, 0x23, 0xef, 0x43, 0x23, 0xee, 0x43, 0x23
}
}
};
}
}
}
}
| gpl-3.0 |
cool-runnings/CometVisu | src/designs/discreet_sand/design_setup.js | 1111 | /* design_setup.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
* Design setup for the discreet sand design
*
* @author Christian Mayer
* @since 2012
*/
templateEngine.messageBroker.subscribe("setup.dom.finished", function() {
$('#navbarLeft').data('columns', 6);
$('#main').data('columns', 12);
$('#navbarRight').data('columns', 6);
}); | gpl-3.0 |
PhoenixDevTeam/Phoenix-for-VK | app/src/main/java/biz/dealnote/messenger/model/selection/Sources.java | 2308 | package biz.dealnote.messenger.model.selection;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Ruslan Kolbasa on 16.08.2017.
* phoenix
*/
public class Sources implements Parcelable {
private final ArrayList<AbsSelectableSource> sources;
public Sources() {
this.sources = new ArrayList<>(2);
}
protected Sources(Parcel in) {
int size = in.readInt();
this.sources = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
@Types
int type = in.readInt();
switch (type) {
case Types.FILES:
this.sources.add(in.readParcelable(FileManagerSelectableSource.class.getClassLoader()));
break;
case Types.LOCAL_PHOTOS:
this.sources.add(in.readParcelable(LocalPhotosSelectableSource.class.getClassLoader()));
break;
case Types.VK_PHOTOS:
this.sources.add(in.readParcelable(VkPhotosSelectableSource.class.getClassLoader()));
break;
default:
throw new UnsupportedOperationException("Invalid type " + type);
}
}
}
public ArrayList<AbsSelectableSource> getSources() {
return sources;
}
public static final Creator<Sources> CREATOR = new Creator<Sources>() {
@Override
public Sources createFromParcel(Parcel in) {
return new Sources(in);
}
@Override
public Sources[] newArray(int size) {
return new Sources[size];
}
};
public Sources with(AbsSelectableSource source) {
this.sources.add(source);
return this;
}
@Override
public int describeContents() {
return 0;
}
public int count(){
return sources.size();
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(sources.size());
for (AbsSelectableSource source : sources) {
parcel.writeInt(source.getType());
parcel.writeParcelable(source, flags);
}
}
public AbsSelectableSource get(int position) {
return sources.get(position);
}
} | gpl-3.0 |
pascal-ballet/ChronoCell | src/chronocell/Phase.java | 956 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chronocell;
import java.util.Hashtable;
/**
*
* @author goby
*/
public class Phase {
String name=null;
Hashtable<String,FunctionStructure> density = new Hashtable<String,FunctionStructure>();
Hashtable<String,FunctionStructure> cumul = new Hashtable<String,FunctionStructure>();
Hashtable<String,FunctionStructure> oneMinCumul = new Hashtable<String,FunctionStructure>();
Hashtable<String,FunctionStructure> alpha = new Hashtable<String,FunctionStructure>();
FunctionStructure solutionFilter = new FunctionStructure();
FunctionStructure thetaConvolution = new FunctionStructure();
FunctionStructure timeToNextPhaseDensity = new FunctionStructure();
FunctionStructure timeToNextPhaseOneMinCumul = new FunctionStructure();
} | gpl-3.0 |