code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* TempAtoms.java
*
* Copyright (C) 2005 Aalborg University
*
* contact:
* jaeger@cs.aau.dk http://www.cs.aau.dk/~jaeger/Primula.html
*
* 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 2
* 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.
*/
package RBNgui;
import RBNpackage.*;
import java.util.*;
class TempAtoms{
private Rel rel;
private int [] args;
public TempAtoms(Rel rel, int[] args){
this.rel = rel;
this.args = args;
}
public Rel getRel(){
return rel;
}
public int[] getArgs(){
return args;
}
}
|
csimons/primula-vulgaris
|
src/main/java/RBNgui/TempAtoms.java
|
Java
|
gpl-3.0
| 1,156
|
package me.mrCookieSlime.Slimefun.ancient_altar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.mrCookieSlime.Slimefun.SlimefunPlugin;
import me.mrCookieSlime.Slimefun.Lists.SlimefunItems;
import me.mrCookieSlime.Slimefun.Setup.SlimefunManager;
import me.mrCookieSlime.Slimefun.api.BlockStorage;
public final class Pedestals {
private Pedestals() {}
public static List<Block> getPedestals(Block altar) {
String pedestal = "ANCIENT_PEDESTAL";
List<Block> list = new ArrayList<>();
if (BlockStorage.check(altar.getRelative(2, 0, -2), pedestal)) {
list.add(altar.getRelative(2, 0, -2));
}
if (BlockStorage.check(altar.getRelative(3, 0, 0), pedestal)) {
list.add(altar.getRelative(3, 0, 0));
}
if (BlockStorage.check(altar.getRelative(2, 0, 2), pedestal)) {
list.add(altar.getRelative(2, 0, 2));
}
if (BlockStorage.check(altar.getRelative(0, 0, 3), pedestal)) {
list.add(altar.getRelative(0, 0, 3));
}
if (BlockStorage.check(altar.getRelative(-2, 0, 2), pedestal)) {
list.add(altar.getRelative(-2, 0, 2));
}
if (BlockStorage.check(altar.getRelative(-3, 0, 0), pedestal)) {
list.add(altar.getRelative(-3, 0, 0));
}
if (BlockStorage.check(altar.getRelative(-2, 0, -2), pedestal)) {
list.add(altar.getRelative(-2, 0, -2));
}
if (BlockStorage.check(altar.getRelative(0, 0, -3), pedestal)) {
list.add(altar.getRelative(0, 0, -3));
}
return list;
}
public static ItemStack getRecipeOutput(ItemStack catalyst, List<ItemStack> input) {
if (input.size() != 8) return null;
if (SlimefunManager.isItemSimilar(catalyst, SlimefunItems.BROKEN_SPAWNER, false)) {
if (checkRecipe(SlimefunItems.BROKEN_SPAWNER, input) == null) return null;
ItemStack spawner = SlimefunItems.REPAIRED_SPAWNER.clone();
ItemMeta im = spawner.getItemMeta();
im.setLore(Arrays.asList(catalyst.getItemMeta().getLore().get(0)));
spawner.setItemMeta(im);
return spawner;
}
return checkRecipe(catalyst, input);
}
private static ItemStack checkRecipe(ItemStack catalyst, List<ItemStack> items) {
for (AltarRecipe recipe : SlimefunPlugin.getUtilities().altarRecipes) {
if (SlimefunManager.isItemSimilar(catalyst, recipe.getCatalyst(), true)) {
for (int i = 0; i < 8; i++) {
if (SlimefunManager.isItemSimilar(items.get(i), recipe.getInput().get(0), true)) {
for (int j = 1; j < 8; j++) {
if (!SlimefunManager.isItemSimilar(items.get((i + j) % items.size()), recipe.getInput().get(j), true)) {
break;
}
else if (j == 7) {
return recipe.getOutput();
}
}
}
}
}
}
return null;
}
}
|
AlexLander123/Slimefun4
|
src/main/java/me/mrCookieSlime/Slimefun/ancient_altar/Pedestals.java
|
Java
|
gpl-3.0
| 2,914
|
<?php
include_once("header.php");
$action = $_GET['action'];
$feedid = $_GET['feedid'];
$catid = $_GET['catid'];
$feedid = mysql_real_escape_string($feedid);
$catid = mysql_real_escape_string($catid);
if (checkCookie()) {
if ( preg_match("/^markread$/",$action) ) {
markFeedRead($feedid);
} else if ( preg_match("/^markcatread$/",$action) ) {
markCatRead($catid);
}
showFeedsFrontPage();
}
include_once("footer.php");
?>
|
ultramookie/sour-reader
|
index.php
|
PHP
|
gpl-3.0
| 450
|
<?php
/**
* SiteEditor Postmeta Option Class
*
* Implements Create Postmeta option in the SiteEditor Application.
*
* @package SiteEditor
* @subpackage Options
*/
/**
* Class SiteEditorPostmetaOption
*/
final class SiteEditorPostmetaOption {
/**
* Meta key.
*
* @var string
*/
public $meta_key;
/**
* Theme supports.
*
* @var string
*/
public $theme_supports;
/**
* Post types for which the meta should be registered.
*
* This will be intersected with the post types matching post_type_supports.
*
* @var array
*/
public $post_types = array();
/**
* Post type support for the postmeta.
*
* @var string
*/
public $post_type_supports;
/**
* Setting sanitize callback.
*
* @var callable
*/
public $sanitize_callback;
/**
* Sanitize JS setting value callback (aka JSON export).
*
* @var callable
*/
public $sanitize_js_callback;
/**
* Setting validate callback.
*
* @var callable
*/
public $validate_callback;
/**
* Setting transport.
*
* @var string
*/
public $setting_transport = 'postMessage';
/**
* Setting default value.
*
* @var string
*/
public $default = '';
public $unique = false;
/**
* SiteEditorPostmetaController constructor.
*
* @throws Exception If meta_key is missing.
*
* @param array $args Args.
*/
public function __construct( $args = array() ) {
$keys = array_keys( get_object_vars( $this ) );
foreach ( $keys as $key ) {
if ( isset( $args[ $key ] ) ) {
$this->$key = $args[ $key ];
}
}
if ( empty( $this->meta_key ) ) {
throw new Exception( 'Missing meta_key' );
}
if ( ! isset( $this->sanitize_callback ) ) {
$this->sanitize_callback = array( $this, 'sanitize_setting' );
}
if ( ! isset( $this->sanitize_js_callback ) ) {
$this->sanitize_js_callback = array( $this, 'js_value' );
}
if ( ! isset( $this->validate_callback ) ) {
$this->validate_callback = array( $this, 'validate_setting' );
}
add_action( 'sed_app_posts_register_meta' , array( $this, 'register_meta' ) );
add_action( 'sed_enqueue_scripts' , array( $this, 'enqueue_editor_scripts' ) );
add_action( 'sed_app_preview_init' , array( $this, 'sed_app_preview_init' ) );
}
/**
* Register meta.
*
* @param SiteEditorCustomizePosts $posts_component Component.
* @return int The number of post types for which the meta was registered.
*/
public function register_meta( SiteEditorCustomizePosts $posts_component ) {
// Short-circuit if theme support is not present.
if ( $this->theme_supports && ! current_theme_supports( $this->theme_supports ) && ! sed_current_theme_supports( $this->theme_supports ) ) {
return 0;
}
$count = 0;
register_meta( 'post', $this->meta_key, array( $this, 'sanitize_value' ) );
if ( ! empty( $this->post_types ) && ! empty( $this->post_type_supports ) ) {
$post_types = array_intersect( $this->post_types, get_post_types_by_support( $this->post_type_supports ) );
} elseif ( ! empty( $this->post_type_supports ) ) {
$post_types = get_post_types_by_support( $this->post_type_supports );
} else {
$post_types = $this->post_types;
}
foreach ( $post_types as $post_type ) {
$setting_args = array(
'sanitize_callback' => $this->sanitize_callback,
'sanitize_js_callback' => $this->sanitize_js_callback,
'validate_callback' => $this->validate_callback,
'transport' => $this->setting_transport,
'theme_supports' => $this->theme_supports,
'default' => $this->default,
);
$posts_component->register_post_type_meta( $post_type, $this->meta_key, $setting_args );
$count += 1;
}
return $count;
}
/**
* Enqueue scripts for Customizer pane (controls).
*
* This would be the scripts for the postmeta Customizer control.
*/
public function enqueue_editor_scripts(){}
/**
* Initialize Customizer preview.
*/
public function sed_app_preview_init() {
add_action( 'wp_enqueue_scripts' , array( $this, 'enqueue_preview_scripts' ) );
//add_filter( 'the_posts' , array( $this, 'add_post_meta' ) , 1000 );
}
/*function add_post_meta( array $posts ){
foreach ( $posts as &$post ) {
if ( !in_array( $this->meta_key , get_post_custom_keys( $post->ID ) ) ) {
add_post_meta( $post->ID , $this->meta_key , $this->default , $this->unique );
}
}
return $posts;
}*/
/**
* Enqueue scripts for the Customizer preview.
*
* This would enqueue the script for any custom partials.
*/
public function enqueue_preview_scripts() {}
/**
* Sanitize a meta value.
*
* Callback for `sanitize_post_meta_{$meta_key}` filter when `sanitize_meta()` is called.
*
* @see sanitize_meta()
*
* @param mixed $meta_value Meta value.
* @return mixed Sanitized value.
*/
public function sanitize_value( $meta_value ) {
return $meta_value;
}
/**
* Sanitize an input.
*
* Callback for `sed_app_sanitize_post_meta_{$meta_key}` filter.
*
* @see update_metadata()
*
* @param string $meta_value The value to sanitize.
* @param SiteEditorPostmetaSetting $setting Setting.
* @return mixed|null Sanitized value or `null` if invalid.
*/
public function sanitize_setting( $meta_value, SiteEditorPostmetaSetting $setting ) {
unset( $setting );
return $meta_value;
}
/**
* Validate an input.
*
* Callback for `sed_app_validate_post_meta_{$meta_key}` filter.
*
* @see update_metadata()
*
* @param WP_Error $validity Validity.
* @param string $meta_value The value to sanitize.
* @param SiteEditorPostmetaSetting $setting Setting.
* @return WP_Error Validity.
*/
public function validate_setting( $validity, $meta_value, SiteEditorPostmetaSetting $setting ) {
unset( $setting, $meta_value );
return $validity;
}
/**
* Callback to format a Customize setting value for use in JavaScript.
*
* Callback for `sed_app_sanitize_js_post_meta_{$meta_key}` filter.
*
* @param mixed $meta_value The setting value.
* @param SiteEditorPostmetaSetting $setting Setting instance.
* @return mixed Formatted value.
*/
public function js_value( $meta_value, SiteEditorPostmetaSetting $setting ) {
unset( $setting );
return $meta_value;
}
}
|
SiteEditor/editor
|
editor/extensions/options-engine/includes/site-editor-postmeta-option.class.php
|
PHP
|
gpl-3.0
| 7,513
|
/*
BattleNetApi - A .NET battle.net API library.
Copyright (C) 2016 Sebastian Grunow <sebastian@grunow-it.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Threading.Tasks;
using BattleNetApi.Client.Models.WoW;
// ReSharper disable once CheckNamespace
namespace BattleNetApi.Client
{
public partial class WowApiClient
{
public static string GetBossUrl(int id)
{
return $"/wow/boss/{id}";
}
public static string GetBossListUrl()
{
return "/wow/boss/";
}
public Boss GetBoss(int id)
{
return GetApiResponse(ForgeApiRequest<Boss>(GetBossUrl(id)));
}
public async Task<Boss> GetBossAsync(int id)
{
return await GetApiResponseAsync(ForgeApiRequest<Boss>(GetBossUrl(id)));
}
public BossList GetBossList()
{
return GetApiResponse(ForgeApiRequest<BossList>(GetBossListUrl()));
}
public async Task<BossList> GetBossListAsync()
{
return await GetApiResponseAsync(ForgeApiRequest<BossList>(GetBossListUrl()));
}
}
}
|
GrunowIT/BattleNetApi
|
BattleNetApi.Client/Endpoints/WoW/Boss.cs
|
C#
|
gpl-3.0
| 1,778
|
{% extends "ner/base_site.html" %}
{% comment %}
Vacancy list page of the portal.
{% endcomment %}
{% block title %}
Vacancy list
{% endblock %}
{% block coltype %}colMS{% endblock %}
{% block content %}
{{ block.super }}
{% include 'ner/vacancy_list_snippet.html' %}
{% endblock %}
|
datakid/ner
|
ner/templates/ner/vacancy_list.html
|
HTML
|
gpl-3.0
| 286
|
/*
* Copyright (C) 2015-2021 Marco Bortolin
*
* This file is part of IBMulator.
*
* IBMulator 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.
*
* IBMulator 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 IBMulator. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef IBMULATOR_GUI_INTERFACE_H
#define IBMULATOR_GUI_INTERFACE_H
#include "gui/window.h"
#include "gui/guifx.h"
#include "screen_renderer.h"
#include "fileselect.h"
#include "state_save.h"
#include "state_save_info.h"
#include "state_load.h"
#include "hardware/devices/vga.h"
#include "hardware/devices/floppy.h"
#include <RmlUi/Core/EventListener.h>
class Machine;
class GUI;
class Mixer;
class FloppyCtrl;
class StorageCtrl;
class InterfaceFX : public GUIFX
{
private:
enum SampleType {
FLOPPY_INSERT,
FLOPPY_EJECT
};
std::vector<AudioBuffer> m_buffers;
const static SoundFX::samples_t ms_samples;
std::atomic<int> m_event;
public:
InterfaceFX() : GUIFX() {}
void init(Mixer *);
void use_floppy(bool _insert);
bool create_sound_samples(uint64_t _time_span_us, bool, bool);
};
class InterfaceScreen
{
protected:
std::unique_ptr<ScreenRenderer> m_renderer;
GUI *m_gui;
public:
struct {
VGADisplay display; // GUI-Machine interface
vec2i size; // size in pixels of the vga image inside the interface
mat4f mvmat; // position and size of the vga image inside the interface
mat4f pmat; // projection matrix
float brightness;
float contrast;
float saturation;
} vga;
public:
InterfaceScreen(GUI *_gui);
virtual ~InterfaceScreen();
ScreenRenderer * renderer() { return m_renderer.get(); }
virtual void render();
protected:
void sync_with_device();
};
class Interface : public Window
{
protected:
std::unique_ptr<InterfaceScreen> m_screen;
vec2i m_size = 0; // current size of the interface
struct {
Rml::Element *power;
Rml::Element *fdd_select;
} m_buttons;
struct {
Rml::Element *fdd_led, *hdd_led;
Rml::Element *fdd_disk;
} m_status;
struct {
bool power, fdd, hdd;
} m_leds;
Rml::Element *m_speed = nullptr, *m_speed_value = nullptr;
Rml::Element *m_message = nullptr;
uint m_curr_drive = 0;
bool m_floppy_present = false;
bool m_floppy_changed = false;
Machine *m_machine;
Mixer *m_mixer;
std::unique_ptr<FileSelect> m_fs;
std::unique_ptr<StateSave> m_state_save;
std::unique_ptr<StateSaveInfo> m_state_save_info;
std::unique_ptr<StateLoad> m_state_load;
FloppyCtrl *m_floppy = nullptr;
StorageCtrl *m_hdd = nullptr;
bool m_audio_enabled = false;
InterfaceFX m_audio;
public:
Interface(Machine *_machine, GUI * _gui, Mixer *_mixer, const char *_rml);
virtual ~Interface();
virtual void create();
virtual void update();
virtual void close();
virtual void config_changed();
virtual void container_size_changed(int /*_width*/, int /*_height*/) {}
vec2i get_size() { return m_size; }
void show_message(const char* _mex);
void save_state(StateRecord::Info _info);
void on_power(Rml::Event &);
void on_fdd_select(Rml::Event &);
void on_fdd_eject(Rml::Event &);
void on_fdd_mount(Rml::Event &);
void on_floppy_mount(std::string _img_path, bool _write_protect);
void on_save_state(Rml::Event &);
void on_load_state(Rml::Event &);
void on_dblclick(Rml::Event &);
VGADisplay * vga_display() { return & m_screen->vga.display; }
void render_screen();
virtual void action(int) {}
virtual void switch_power();
virtual void set_audio_volume(float);
virtual void set_video_brightness(float);
virtual void set_video_contrast(float);
virtual void set_video_saturation(float);
virtual bool is_system_visible() const { return true; }
void save_framebuffer(std::string _screenfile, std::string _palfile);
SDL_Surface * copy_framebuffer();
virtual void sig_state_restored() {}
protected:
virtual void set_hdd_active(bool _active);
virtual void set_floppy_string(std::string _filename);
virtual void set_floppy_config(bool _b_present);
virtual void set_floppy_active(bool _active);
std::vector<uint64_t> get_floppy_sizes(unsigned _floppy_drive);
void show_state_dialog(bool _save);
void show_state_info_dialog(StateRecord::Info _info);
static std::string get_filesel_info(std::string);
std::string create_new_floppy_image(std::string _dir, std::string _file,
FloppyDiskType _type, bool _formatted);
void reset_savestate_dialogs(std::string _dir);
};
#endif
|
barotto/IBMulator
|
src/gui/windows/interface.h
|
C
|
gpl-3.0
| 4,854
|
Joomla 3.3.3 = 1a3c7fd1a0cc1c7b97c2ca3eaeaaba64
Joomla 3.6.4 = e8a47ed0b2e209bc4e59dc3e52ff7e4c
Joomla 3.2.1 = 24e9a44a67bf53c256065e088c21b749
Joomla 3.4.8 = e9215879b0bfc6ddfad1ecbcfdec855d
Joomla 3.7.0 = 70c678ef63cb1e7e6a64e90c2e6e0edb
Joomla 3.0.2 = ff32f85f370d05d2c58fa04cf477066f
Joomla 3.1.1 = 5e78de2b317cc8fe095d695032fb4c58
|
gohdan/DFC
|
known_files/hashes/administrator/templates/hathor/html/com_config/application/default_cookie.php
|
PHP
|
gpl-3.0
| 336
|
package com.warehouse.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.warehouse.entity.FinanceAccountReconciliation;
public interface FinanceAccountReconciliationMapper {
// 新增
int insertSelective(FinanceAccountReconciliation record);
// 根据ID查询
FinanceAccountReconciliation selectByPrimaryKey(Integer id);
// 修改
int updateByPrimaryKeySelective(FinanceAccountReconciliation record);
// 分页查询
int getCountByPrimaryKey(FinanceAccountReconciliation record);
List<FinanceAccountReconciliation> selectByPrimaryKeyPage(FinanceAccountReconciliation record);
// 导入
int insertSelectiveByExcle(@Param(value = "sql") String sql);
}
|
iceblow/beilaile
|
src/main/java/com/warehouse/dao/FinanceAccountReconciliationMapper.java
|
Java
|
gpl-3.0
| 703
|
# -*- coding: utf-8 -*-
__author__ = 'ogaidukov'
import os.path
import argparse
import tornado.ioloop
import tornado.httpserver
import tornado.web
from commonlib import configparser, logmaker
from rotabanner.lib import route
import redis
import pygeoip
config = None
logger = None
args = None
redisdb = None
geoip = None
def init_application():
# TODO refactor these global variables
global config, logger, args, redisdb, geoip
arg_parser = argparse.ArgumentParser(description="Ad Serving daemon which built on top of Tornado")
arg_parser.add_argument('config', help="Daemon's config file")
arg_parser.add_argument('-D', '--debug', help="Debug mode", action='store_true')
arg_parser.add_argument('-A', '--listen_addr', help="Listen address or '0.0.0.0'")
arg_parser.add_argument('-L', '--listen_port', help="Listen TCP port")
args = arg_parser.parse_args()
config = configparser.parse_config(args.config)
# TODO make use of standard Tornado logging streams 'tornado.access', 'tornado.application' and 'tornado.general'
logger = logmaker.logger_from_config(config)
redis_config = configparser.config_section_obj(config, 'redis')
redisdb = redis.StrictRedis(host=redis_config.host, port=int(redis_config.port),
db=redis_config.db, password=redis_config.password)
geoip = pygeoip.GeoIP('../me-advert/rotabanner/data/GeoIPCity.dat', pygeoip.MEMORY_CACHE)
import handlers # Important! Initialize url handler classes by importing
def run_application():
init_application()
listen_port = int(args.listen_port)
listen_addr = args.listen_addr
template_path=os.path.join(os.path.dirname(__file__), "templates")
application = TornadoApp(debug=args.debug, template_path=template_path)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(listen_port, address=listen_addr)
tornado.ioloop.IOLoop.instance().start()
class TornadoApp(tornado.web.Application):
def __init__(self, **settings):
logger.info("Starting Tornado application instance")
tornado.web.Application.__init__(self, route.url_handlers, **settings)
|
olegvg/me-advert
|
me-advert/rotabanner/application.py
|
Python
|
gpl-3.0
| 2,183
|
/*
* Copyright (C) 1993,1994 Bernd Feige
* This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING).
*/
/*
* complex.c routines for handling of complex numbers
* -- Bernd Feige 4.05.1993
*/
#include <math.h>
#include "transform.h"
#include "bf.h"
GLOBAL double
c_phase(complex cmpl) {
return atan2(cmpl.Im, cmpl.Re);
}
GLOBAL double
c_power(complex cmpl) {
return cmpl.Re*cmpl.Re+cmpl.Im*cmpl.Im;
}
GLOBAL double
c_abs(complex cmpl) {
return sqrt(c_power(cmpl));
}
GLOBAL complex
c_add(complex cmpl1, complex cmpl2) {
complex result;
result.Re=cmpl1.Re+cmpl2.Re;
result.Im=cmpl1.Im+cmpl2.Im;
return result;
}
GLOBAL complex
c_mult(complex cmpl1, complex cmpl2) {
complex result;
result.Re=cmpl1.Re*cmpl2.Re-cmpl1.Im*cmpl2.Im;
result.Im=cmpl1.Re*cmpl2.Im+cmpl1.Im*cmpl2.Re;
return result;
}
GLOBAL complex
c_smult(complex cmpl, DATATYPE factor) {
complex result;
result.Re=cmpl.Re*factor;
result.Im=cmpl.Im*factor;
return result;
}
GLOBAL complex
c_konj(complex cmpl) {
complex result;
result.Re= cmpl.Re;
result.Im= -cmpl.Im;
return result;
}
GLOBAL complex
c_inv(complex cmpl) {
return c_smult(c_konj(cmpl), 1.0/c_power(cmpl));
}
|
berndf/avg_q
|
bf/complex.c
|
C
|
gpl-3.0
| 1,194
|
@interface SBUIControlCenterVisualEffect : UIVisualEffect {
NSInteger _style;
}
+(id)effectWithStyle:(NSInteger)arg1 ;
-(id)copyWithZone:(NSZone*)arg1 ;
-(id)effectConfig;
@end
|
andrewwiik/Tweaks
|
ogygia/headers/SpringBoard/SBUIControlCenterVisualEffect.h
|
C
|
gpl-3.0
| 179
|
<?php
echo '<p>Testing SiteLink...</p>';
define( 'SITELINK_URL', "https://api.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define( 'SITELINK_CORP_CODE', "CCTST" );
define( 'SITELINK_LOC_CODE', "Demo" );
define( 'SITELINK_CORP_LOGIN', "Administrator" );
define( 'SITELINK_CORP_PASS', "Demo" );
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
try
{
$units = $client->SiteInformation( $params );
$result = $units->SiteInformationResult;
}
catch (Exception $e )
{
die( 'Error: '.$e->getMessage().'<br>'.$e );
}
echo htmlentities( $result->any );
?>
|
bojo1498/Sitelink-API-PHP-Interface
|
index.php
|
PHP
|
gpl-3.0
| 722
|
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
/**
* @var FW_Option_Type_Typography_v2 $typography_v2
* @var string $id
* @var array $option
* @var array $data
* @var array $defaults
*/
{
$wrapper_attr = $option['attr'];
unset(
$wrapper_attr['value'],
$wrapper_attr['name']
);
}
{
$option['value'] = array_merge( $defaults['value'], (array) $option['value'] );
$data['value'] = array_merge( $option['value'], is_array($data['value']) ? $data['value'] : array() );
$google_font = $typography_v2->get_google_font( $data['value']['family'] );
}
$components = (isset($option['components']) && is_array($option['components']))
? array_merge($defaults['components'], $option['components'])
: $defaults['components'];
?>
<div <?php echo fw_attr_to_html( $wrapper_attr ) ?>>
<?php if ( $components['family'] ) : ?>
<div class="fw-option-typography-v2-option fw-option-typography-v2-option-family fw-border-box-sizing fw-col-sm-5">
<select data-type="family" data-value="<?php echo esc_attr($data['value']['family']); ?>"
name="<?php echo esc_attr( $option['attr']['name'] ) ?>[family]"
class="fw-option-typography-v2-option-family-input">
</select>
<div class="fw-inner"><?php _e('Font face', 'fw'); ?></div>
</div>
<?php if ( $components['style'] ) : ?>
<div class="fw-option-typography-v2-option fw-option-typography-v2-option-style fw-border-box-sizing fw-col-sm-3"
style="display: <?php echo ( $google_font ) ? 'none' : 'inline-block'; ?>;">
<select data-type="style" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[style]"
class="fw-option-typography-v2-option-style-input">
<?php foreach (
array(
'normal' => __('Normal', 'fw'),
'italic' => __('Italic', 'fw'),
'oblique' => __('Oblique', 'fw')
)
as $key => $style
): ?>
<option value="<?php echo esc_attr( $key ) ?>"
<?php if ($data['value']['style'] === $key): ?>selected="selected"<?php endif; ?>><?php echo fw_htmlspecialchars( $style ) ?></option>
<?php endforeach; ?>
</select>
<div class="fw-inner"><?php _e( 'Style', 'fw' ); ?></div>
</div>
<?php endif; ?>
<?php if ( $components['weight'] ) : ?>
<div class="fw-option-typography-v2-option fw-option-typography-v2-option-weight fw-border-box-sizing fw-col-sm-3"
style="display: <?php echo ( $google_font ) ? 'none' : 'inline-block'; ?>;">
<select data-type="weight" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[weight]"
class="fw-option-typography-v2-option-weight-input">
<?php foreach (
array(
100 => 100,
200 => 200,
300 => 300,
400 => 400,
500 => 500,
600 => 600,
700 => 700,
800 => 800,
900 => 900
)
as $key => $style
): ?>
<option value="<?php echo esc_attr( $key ) ?>"
<?php if ($data['value']['weight'] == $key): ?>selected="selected"<?php endif; ?>><?php echo fw_htmlspecialchars( $style ) ?></option>
<?php endforeach; ?>
</select>
<div class="fw-inner"><?php _e( 'Weight', 'fw' ); ?></div>
</div>
<?php endif; ?>
<div class="fw-option-typography-v2-option fw-option-typography-v2-option-subset fw-border-box-sizing fw-col-sm-2"
style="display: <?php echo ( $google_font ) ? 'inline-block' : 'none'; ?>;">
<select data-type="subset" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[subset]"
class="fw-option-typography-v2-option-subset">
<?php if ( $google_font ) {
foreach ( $google_font['subsets'] as $subset ) { ?>
<option value="<?php echo esc_attr( $subset ) ?>"
<?php if ($data['value']['subset'] === $subset): ?>selected="selected"<?php endif; ?>><?php echo fw_htmlspecialchars( $subset ); ?></option>
<?php }
}
?>
</select>
<div class="fw-inner"><?php _e( 'Script', 'fw' ); ?></div>
</div>
<?php if ( $components['variation'] ) : ?>
<div
class="fw-option-typography-v2-option fw-option-typography-v2-option-variation fw-border-box-sizing fw-col-sm-2"
style="display: <?php echo ( $google_font ) ? 'inline-block' : 'none'; ?>;">
<select data-type="variation" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[variation]"
class="fw-option-typography-v2-option-variation">
<?php if ( $google_font ) {
foreach ( $google_font['variants'] as $variant ) { ?>
<option value="<?php echo esc_attr( $variant ) ?>"
<?php if ($data['value']['variation'] == $variant): ?>selected="selected"<?php endif; ?>><?php echo fw_htmlspecialchars( $variant ); ?></option>
<?php }
}
?>
</select>
<div class="fw-inner"><?php esc_html_e( 'Style', 'fw' ); ?></div>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if ( $components['size'] ) : ?>
<div class="fw-option-typography-v2-option fw-option-typography-v2-option-size fw-border-box-sizing fw-col-sm-2">
<input data-type="size" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[size]"
class="fw-option-typography-v2-option-size-input" type="text"
value="<?php echo esc_attr($data['value']['size']); ?>">
<div class="fw-inner"><?php esc_html_e( 'Size', 'fw' ); ?></div>
</div>
<?php endif; ?>
<?php if ( $components['line-height'] ) : ?>
<div
class="fw-option-typography-v2-option fw-option-typography-v2-option-line-height fw-border-box-sizing fw-col-sm-2">
<input data-type="line-height" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[line-height]"
value="<?php echo esc_attr($data['value']['line-height']); ?>"
class="fw-option-typography-v2-option-line-height-input" type="text">
<div class="fw-inner"><?php esc_html_e( 'Line height', 'fw' ); ?></div>
</div>
<?php endif; ?>
<?php if ( $components['letter-spacing'] ) : ?>
<div
class="fw-option-typography-v2-option fw-option-typography-v2-option-letter-spacing fw-border-box-sizing fw-col-sm-2">
<input data-type="letter-spacing" name="<?php echo esc_attr( $option['attr']['name'] ) ?>[letter-spacing]"
value="<?php echo esc_attr($data['value']['letter-spacing']); ?>"
class="fw-option-typography-v2-option-letter-spacing-input" type="text">
<div class="fw-inner"><?php esc_html_e( 'Spacing', 'fw' ); ?></div>
</div>
<?php endif; ?>
<?php if ( $components['color'] ) : ?>
<div class="fw-option-typography-v2-option fw-option-typography-v2-option-color fw-border-box-sizing fw-col-sm-2"
data-type="color">
<?php
echo fw()->backend->option_type( 'color-picker' )->render(
'color',
array(
'label' => false,
'desc' => false,
'type' => 'color-picker',
'value' => $option['value']['color']
),
array(
'value' => $data['value']['color'],
'id_prefix' => 'fw-option-' . $id . '-typography-v2-option-',
'name_prefix' => $data['name_prefix'] . '[' . $id . ']',
)
)
?>
<div class="fw-inner"><?php esc_html_e( 'Color', 'fw' ); ?></div>
</div>
<?php endif; ?>
</div>
|
andreiglingeanu/Unyson
|
framework/includes/option-types/typography-v2/view.php
|
PHP
|
gpl-3.0
| 7,075
|
/* Licence: GPL version 3, Wikus Coetser, 2013, http://www.gnu.org/licenses/gpl-3.0.html */
/*
Function from MDN: This makes use requestAnimationFrame is availible.
*/
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
/*
Function for converting a RGBA encoded byte array to a bitmap image
*/
function RGBAImageToDataUrl(bmpData, width, height) {
if (!(bmpData instanceof Uint8Array)) throw "RGBAImageToDataUrl: Expected a Uint8Array data array as input";
if (bmpData.length != width * height * 4) throw "Invalid image data, length must be " + (width * height * 4);
}
|
WCoetser/RandomUsefulCode
|
WebGLPicking/WebGL_06/Scripts/Utils.js
|
JavaScript
|
gpl-3.0
| 807
|
/*
** Anitomy
** Copyright (C) 2014-2015, Eren Okka
**
** 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 <algorithm>
#include <regex>
#include "keyword.h"
#include "parser.h"
#include "astring.h"
namespace anitomy {
const string_t kDashes = L"-\u2010\u2011\u2012\u2013\u2014\u2015";
const string_t kDashesWithSpace = L" -\u2010\u2011\u2012\u2013\u2014\u2015";
size_t Parser::FindNumberInString(const string_t& str) {
auto it = std::find_if(str.begin(), str.end(), IsNumericChar);
return it == str.end() ? str.npos : (it - str.begin());
}
string_t Parser::GetNumberFromOrdinal(const string_t& word) {
static const std::map<string_t, string_t> ordinals{
{L"1st", L"1"}, {L"First", L"1"},
{L"2nd", L"2"}, {L"Second", L"2"},
{L"3rd", L"3"}, {L"Third", L"3"},
{L"4th", L"4"}, {L"Fourth", L"4"},
{L"5th", L"5"}, {L"Fifth", L"5"},
{L"6th", L"6"}, {L"Sixth", L"6"},
{L"7th", L"7"}, {L"Seventh", L"7"},
{L"8th", L"8"}, {L"Eighth", L"8"},
{L"9th", L"9"}, {L"Ninth", L"9"},
};
auto it = ordinals.find(word);
return it != ordinals.end() ? it->second : string_t();
}
bool Parser::IsCrc32(const string_t& str) {
return str.size() == 8 && IsHexadecimalString(str);
}
bool Parser::IsDashCharacter(const string_t& str) {
if (str.size() != 1)
return false;
auto result = std::find(kDashes.begin(), kDashes.end(), str.front());
return result != kDashes.end();
}
bool Parser::IsResolution(const string_t& str) {
// Using a regex such as "\\d{3,4}(p|(x\\d{3,4}))$" would be more elegant,
// but it's much slower (e.g. 2.4ms -> 24.9ms).
const size_t min_width_size = 3;
const size_t min_height_size = 3;
// *###x###*
if (str.size() >= min_width_size + 1 + min_height_size) {
size_t pos = str.find_first_of(L"xX\u00D7"); // multiplication sign
if (pos != str.npos &&
pos >= min_width_size &&
pos <= str.size() - (min_height_size + 1)) {
for (size_t i = 0; i < str.size(); i++)
if (i != pos && !IsNumericChar(str.at(i)))
return false;
return true;
}
// *###p
} else if (str.size() >= min_height_size + 1) {
if (str.back() == L'p' || str.back() == L'P') {
for (size_t i = 0; i < str.size() - 1; i++)
if (!IsNumericChar(str.at(i)))
return false;
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Parser::CheckAnimeSeasonKeyword(const token_iterator_t token) {
auto set_anime_season = [&](token_iterator_t first, token_iterator_t second,
const string_t& content) {
elements_.insert(kElementAnimeSeason, content);
first->category = kIdentifier;
second->category = kIdentifier;
};
auto previous_token = FindPreviousToken(tokens_, token, kFlagNotDelimiter);
if (previous_token != tokens_.end()) {
auto number = GetNumberFromOrdinal(previous_token->content);
if (!number.empty()) {
set_anime_season(previous_token, token, number);
return true;
}
}
auto next_token = FindNextToken(tokens_, token, kFlagNotDelimiter);
if (next_token != tokens_.end() &&
IsNumericString(next_token->content)) {
set_anime_season(token, next_token, next_token->content);
return true;
}
return false;
}
bool Parser::CheckEpisodeKeyword(const token_iterator_t token) {
auto next_token = FindNextToken(tokens_, token, kFlagNotDelimiter);
if (next_token != tokens_.end() &&
next_token->category == kUnknown) {
if (FindNumberInString(next_token->content) == 0) {
if (!MatchEpisodePatterns(next_token->content, *next_token))
SetEpisodeNumber(next_token->content, *next_token, false);
token->category = kIdentifier;
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Parser::IsElementCategorySearchable(ElementCategory category) {
switch (category) {
case kElementAnimeSeasonPrefix:
case kElementAnimeType:
case kElementAudioTerm:
case kElementDeviceCompatibility:
case kElementEpisodePrefix:
case kElementFileChecksum:
case kElementLanguage:
case kElementOther:
case kElementReleaseGroup:
case kElementReleaseInformation:
case kElementReleaseVersion:
case kElementSource:
case kElementSubtitles:
case kElementVideoResolution:
case kElementVideoTerm:
return true;
}
return false;
}
bool Parser::IsElementCategorySingular(ElementCategory category) {
switch (category) {
case kElementAnimeSeason:
case kElementAnimeType:
case kElementAudioTerm:
case kElementDeviceCompatibility:
case kElementEpisodeNumber:
case kElementLanguage:
case kElementOther:
case kElementReleaseInformation:
case kElementSource:
case kElementVideoTerm:
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void Parser::BuildElement(ElementCategory category, bool keep_delimiters,
const token_iterator_t token_begin,
const token_iterator_t token_end) const {
string_t element;
for (auto token = token_begin; token != token_end; ++token) {
switch (token->category) {
case kUnknown:
element += token->content;
token->category = kIdentifier;
break;
case kBracket:
element += token->content;
break;
case kDelimiter: {
auto delimiter = token->content.front();
if (keep_delimiters) {
element.push_back(delimiter);
} else if (token != token_begin && token != token_end) {
switch (delimiter) {
case L',':
case L'&':
element.push_back(delimiter);
break;
default:
element.push_back(L' ');
break;
}
}
break;
}
}
}
if (!keep_delimiters)
TrimString(element, kDashesWithSpace.c_str());
if (!element.empty())
elements_.insert(category, element);
}
////////////////////////////////////////////////////////////////////////////////
bool Parser::IsTokenIsolated(const token_iterator_t token) const {
auto previous_token = FindPreviousToken(tokens_, token, kFlagNotDelimiter);
if (previous_token == tokens_.end() || previous_token->category != kBracket)
return false;
auto next_token = FindNextToken(tokens_, token, kFlagNotDelimiter);
if (next_token == tokens_.end() || next_token->category != kBracket)
return false;
return true;
}
} // namespace anitomy
|
Ippytraxx/anitomy
|
anitomy/parser_helper.cpp
|
C++
|
gpl-3.0
| 7,282
|
require_dependency 'project'
module RedmineSearch
module Patches
module ProjectPatch
def self.included(base)
base.class_eval do
unloadable
Searchkick.search_method_name = :elastic_search
# searchkick language: RedmineSearch.elastic_search_language unless Project.respond_to?(:searchkick_index)
unless Project.respond_to?(:searchkick_index)
searchkick language: RedmineSearch.elastic_search_language,
# index_name: 'redmine_project',
callbacks: :async,
highlight: [:name, :description]
end
def search_data
attributes
end
end
end
end
end
end
unless Project.included_modules.include?(RedmineSearch::Patches::ProjectPatch)
Project.send(:include, RedmineSearch::Patches::ProjectPatch)
end
|
efigence/redmine_search
|
lib/redmine_search/patches/project_patch.rb
|
Ruby
|
gpl-3.0
| 867
|
const initialState = {
config: {},
isSuccess: false,
isFailure: false,
isFetching: false,
useManual: false,
}
export default function automaticSetup(state = initialState, {type, payload}) {
switch (type) {
case 'AUTOMATIC_SETUP_BEGIN':
return {
...initialState,
isFetching: true,
}
case 'AUTOMATIC_SETUP_SUCCESS':
return {
config: payload,
isSuccess: true,
isFailure: false,
isFetching: false,
}
case 'AUTOMATIC_SETUP_FAILURE':
return {
...initialState,
isFailure: true,
}
case 'MANUAL_SETUP_USE':
return {
...initialState,
useManual: true,
}
default:
return state
}
}
|
JodusNodus/syncthing-tray
|
app/client/reducers/automatic-setup.js
|
JavaScript
|
gpl-3.0
| 700
|
/*
* Copyright (C) 2013
*
* This file is part of Messic.
*
* 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.messic.android.smartphone.activities.main.fragments.explore;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.messic.android.R;
import org.messic.android.databinding.FragmentExploreBinding;
import org.messic.android.messiccore.MessicCoreApp;
import org.messic.android.messiccore.datamodel.MDMAlbum;
import org.messic.android.messiccore.datamodel.MDMAuthor;
import org.messic.android.smartphone.MessicSmartphoneApp;
import org.messic.android.smartphone.activities.albuminfo.AlbumInfoActivity;
import org.messic.android.smartphone.rxevents.RxAction;
import org.messic.android.smartphone.rxevents.RxDispatcher;
import org.messic.android.smartphone.utils.WrapContentStaggeredGridLayoutManager;
import org.messic.android.smartphone.views.fastscroller.FastScroller;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import timber.log.Timber;
public class ExploreFragment extends Fragment implements ExploreAuthorsAdapter.EventListener {
@Inject
ExplorePresenter presenter;
@Inject
ExploreAuthorsAdapter mAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private Subscription subscription;
private RecyclerView mRecycler;
private ProgressBar mProgressBar;
private FragmentExploreBinding binding;
private StaggeredGridLayoutManager gaggeredGridLayoutManager;
private FastScroller fastScroller;
private Action1<Throwable> exploreAuthorOnError = new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Timber.e(throwable.getMessage(), throwable);
mProgressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), "Server Error", Toast.LENGTH_SHORT).show();
}
};
private Action0 exploreAuthorOnCompleted = new Action0() {
@Override
public void call() {
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
mProgressBar.setVisibility(View.GONE);
}
};
private Action1<MDMAuthor> exploreAuthorOnNext = new Action1<MDMAuthor>() {
@Override
public void call(MDMAuthor author) {
mAdapter.addAuthor(author);
}
};
@Override
public void onStart() {
super.onStart();
if (this.mAdapter.getItemCount() == 0) {
updateAuthors();
} else {
mProgressBar.setVisibility(View.GONE);
}
}
private void updateAuthors() {
android.app.Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setVisibility(View.VISIBLE);
Observable<MDMAuthor> observable = presenter.getAuthors();
mAdapter.clear();
observable.subscribeOn(Schedulers.io()).onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread()).subscribe(exploreAuthorOnNext, exploreAuthorOnError, exploreAuthorOnCompleted);
}
});
}
}
@Override
public void onResume() {
super.onResume();
this.presenter.resume();
if (this.subscription != null)
RxDispatcher.get().unsubscribe(this.subscription);
this.subscription = subscribe();
}
@Override
public void onPause() {
super.onPause();
this.presenter.pause();
RxDispatcher.get().unsubscribe(this.subscription);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Perform injection so that when this call returns all dependencies will be available for use.
((MessicSmartphoneApp) MessicCoreApp.getInstance()).getSmartphoneComponent().inject(this);
View view = bindData(inflater, container, savedInstanceState);
setupLayout();
this.presenter.initialize();
return view;
}
private Subscription subscribe() {
return RxDispatcher.get().subscribe(new RxDispatcher.RxSubscriber() {
public void call(RxAction event) {
// if (event.isType(RandomEvents.EVENT_SONG_ADDED)) {
// MDMSong song = (MDMSong) event.getSimpleData();
// Toast.makeText(getActivity(), getResources().getText(R.string.player_added) + song.getName(),
// Toast.LENGTH_SHORT).show();
// }
}
});
}
/**
* Binding information form the layout to objects
*/
private View bindData(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_explore, container, false);
View view = inflater.inflate(R.layout.fragment_explore, container, false);
this.mAdapter.setContext(this.getActivity());
this.mAdapter.setListener(this);
mRecycler = (RecyclerView) view.findViewById(R.id.explore_recyclerview);
mRecycler.setHasFixedSize(true);
gaggeredGridLayoutManager = new WrapContentStaggeredGridLayoutManager(3, 1);
mRecycler.setLayoutManager(gaggeredGridLayoutManager);
mRecycler.setAdapter(this.mAdapter);
fastScroller = (FastScroller) view.findViewById(R.id.explore_fastscroller);
fastScroller.setRecyclerView(mRecycler);
mProgressBar = (ProgressBar) view.findViewById(R.id.explore_progress);
this.swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.explore_swipe);
this.swipeRefreshLayout.setColorSchemeColors(Color.GREEN);
this.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
public void onRefresh() {
updateAuthors();
}
});
// LoginActivityBindingImpl user;
// if (savedInstanceState == null) {
// user = new LoginActivityBindingImpl("", "", true, "ccc", "dddd");
// } else {
// user = Parcels.unwrap(savedInstanceState.getParcelable(BINDING_PARCEL));
// }
this.binding.setEvents(this);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putParcelable(BINDING_PARCEL, Parcels.wrap(this.binding.getUser()));
}
/**
* setting up the layout of the activity.
* Here you must put elements, remove elements, manage events, ...
*/
private void setupLayout() {
}
@Override
public void coverTouch(MDMAlbum album) {
presenter.playAction(album);
Toast.makeText(getActivity(), getResources().getText(R.string.player_added) + album.getName(),
Toast.LENGTH_SHORT).show();
}
@Override
public void coverLongTouch(MDMAlbum album) {
presenter.longPlayAction(album);
Toast.makeText(getActivity(), getResources().getText(R.string.player_added) + album.getName(),
Toast.LENGTH_SHORT).show();
}
@Override
public void textTouch(MDMAlbum album, ImageView cover) {
showAlbumInfo(cover, album);
}
@Override
public void moreTouch(final MDMAlbum album, View anchor, int index) {
// Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ExploreFragment.this.getActivity(), anchor);
// Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.activity_explore_menu_album, popup.getMenu());
// registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_album_item_play:
presenter.playAction(album);
break;
case R.id.menu_album_item_playnow:
presenter.longPlayAction(album);
break;
case R.id.menu_album_item_download:
presenter.downloadAlbum(album);
break;
}
return true;
}
});
popup.show();// showing popup menu
}
/**
* Show the AlbumInfo Activity
*
* @param cover
* @param album
*/
private void showAlbumInfo(ImageView cover, MDMAlbum album) {
//lets show the albuminfoactivity
Intent ssa = new Intent(getActivity(), AlbumInfoActivity.class);
ssa.putExtra(AlbumInfoActivity.EXTRA_ALBUM_SID, album);
BitmapDrawable d = ((BitmapDrawable) cover.getDrawable());
if (d != null) {
Bitmap bitmap = d.getBitmap();
AlbumInfoActivity.defaultArt = bitmap;
//ssa.putExtra(AlbumInfoActivity.EXTRA_ALBUM_ART, bitmap);
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(this.getActivity(), cover, "cover");
getActivity().startActivity(ssa, options.toBundle());
}
}
}
|
spheras/messic-android
|
messic-smartphone/src/main/java/org/messic/android/smartphone/activities/main/fragments/explore/ExploreFragment.java
|
Java
|
gpl-3.0
| 10,975
|
from collections import defaultdict
from math import log2 as log
from gui.transcriptions import STANDARD_SYMBOLS
from imports import (QDialog, QHBoxLayout, QVBoxLayout, QGroupBox, QRadioButton, QButtonGroup, QPushButton,
QStackedWidget, QWidget, QComboBox, QMessageBox, QLabel, QLineEdit, QTableWidget, QTableWidgetItem)
class FunctionalLoadDialog(QDialog):
def __init__(self, corpus):
super().__init__()
self.corpus = corpus
self.results = list()
self.setWindowTitle('Functional Load')
layout = QVBoxLayout()
#Set up top row of radio button options
contrastBox = QGroupBox('Contrast')
contrastLayout = QHBoxLayout()
self.contrastGroup = QButtonGroup()
flexionOption = QRadioButton('Degrees of flexion')
flexionOption.click()
ductionOption = QRadioButton('Degree of duction')
oppositionOption = QRadioButton('Thumb opposition')
contactOption = QRadioButton('Thumb/finger contact')
customOption = QRadioButton('Custom options')
self.contrastGroup.addButton(flexionOption, id=0)
self.contrastGroup.addButton(ductionOption, id=1)
self.contrastGroup.addButton(oppositionOption, id=2)
self.contrastGroup.addButton(contactOption, id=3)
self.contrastGroup.addButton(customOption, id=4)
contrastLayout.addWidget(flexionOption)
contrastLayout.addWidget(ductionOption)
contrastLayout.addWidget(oppositionOption)
contrastLayout.addWidget(contactOption)
contrastLayout.addWidget(customOption)
contrastBox.setLayout(contrastLayout)
#set up stacked widgets
self.middleWidget = QStackedWidget()
#Collapse degress of flexion
flexionWidget = QWidget()
flexionLayout = QHBoxLayout()
self.flexionFingerSelection = QComboBox()
self.flexionFingerSelection.addItems(['Thumb', 'Index', 'Middle', 'Pinky', 'Ring', 'All'])
self.flexionJointSelection = QComboBox()
self.flexionJointSelection.addItems(['Proximal', 'Medial', 'Distal', 'All'])
#note: Thumb+Proximal not possible, and there's an alert window that will pop up if this combination is chosen
flexionLayout.addWidget(self.flexionFingerSelection)
flexionLayout.addWidget(self.flexionJointSelection)
flexionWidget.setLayout(flexionLayout)
#Collapse degrees of duction
ductionWidget = QWidget()
ductionLayout = QHBoxLayout()
self.ductionFingerSelection = QComboBox()
self.ductionFingerSelection.addItems(['Thumb/Finger', 'Index/Middle', 'Middle/Ring', 'Ring/Pinky', 'All'])
ductionLayout.addWidget(self.ductionFingerSelection)
ductionWidget.setLayout(ductionLayout)
#Collapse thumb opposition
oppositionWidget = QWidget()
oppositionLayout = QHBoxLayout()
oppositionWidget.setLayout(oppositionLayout)
#Collapse thumb/finger contact
contactWidget = QWidget()
contactLayout = QHBoxLayout()
contactWidget.setLayout(contactLayout)
#Collapse custom slots
customWidget = QWidget()
customLayout = QHBoxLayout()
customLayout.addWidget(QLabel('Merge this symbol: '))
self.customSymbo1A = QComboBox()
self.customSymbo1A.addItem('')
self.customSymbo1A.addItems(STANDARD_SYMBOLS)
self.customSymbo1A.setEditable(True)
customLayout.addWidget(self.customSymbo1A)
customLayout.addWidget(QLabel('with this symbol: '))
self.customSymbolB = QComboBox()
self.customSymbolB.addItem('')
self.customSymbolB.addItems(STANDARD_SYMBOLS)
self.customSymbolB.setEditable(True)
customLayout.addWidget(self.customSymbolB)
customLayout.addWidget(QLabel('in these slots: '))
self.customSlots = QLineEdit()
customLayout.addWidget(self.customSlots)
customLayout.addWidget(QLabel('(separate numbers with commas, leave blank to merge symbols everywhere)'))
customWidget.setLayout(customLayout)
#Build up middle widget
self.middleWidget.addWidget(flexionWidget)
self.middleWidget.addWidget(ductionWidget)
self.middleWidget.addWidget(oppositionWidget)
self.middleWidget.addWidget(contactWidget)
self.middleWidget.addWidget(customWidget)
#Connect slots and signals
flexionOption.clicked.connect(self.changeMiddleWidget)
ductionOption.clicked.connect(self.changeMiddleWidget)
oppositionOption.clicked.connect(self.changeMiddleWidget)
contactOption.clicked.connect(self.changeMiddleWidget)
customOption.clicked.connect(self.changeMiddleWidget)
#Bottom buttons (OK/Cancel)
buttonLayout = QHBoxLayout()
ok = QPushButton('OK')
ok.clicked.connect(self.accept)
cancel = QPushButton('Cancel')
cancel.clicked.connect(self.reject)
buttonLayout.addWidget(ok)
buttonLayout.addWidget(cancel)
layout.addWidget(contrastBox)
layout.addWidget(self.middleWidget)
layout.addLayout(buttonLayout)
self.setLayout(layout)
def changeMiddleWidget(self, e):
self.middleWidget.setCurrentIndex(self.contrastGroup.id(self.sender()))
def accept(self):
index = self.middleWidget.currentIndex()
if index == 0:
if (self.flexionFingerSelection.currentText() == 'Thumb'
and self.flexionJointSelection.currentText() == 'Proximal'):
alert = QMessageBox()
alert.setWindowTitle('Incompatible Options')
alert.setText('Thumbs cannot be selected for proximal joint. Choose either "Medial" or "Distal"')
alert.exec_()
return
self.calcByFlexion()
elif index == 1:
self.calcByDuction()
elif index == 4:
slots = self.customSlots.text()
alert = QMessageBox()
alert.setWindowTitle('Invalid slot numbers')
alert.setText('Slot numbers must be between 1 and 34 (inclusive)')
try:
slots = [int(x.strip()) for x in slots.split(',')]
except ValueError:
alert.exec_()
return
if any(n > 34 or n < 1 for n in slots):
alert.exec_()
return
self.calcCustom(slots)
super().accept()
def calculateEntropy(self, corpus=None):
corpus_size = len(corpus) if corpus is not None else len(self.corpus)
return corpus_size, sum([1 / corpus_size * log(1 / corpus_size) for n in range(corpus_size)]) * -1
def calcByDuction(self):
corpus_size, starting_h = self.calculateEntropy()
duction = self.ductionFingerSelection.currentText()
if duction == 'Thumb/Finger':
slot = 3
elif duction == 'Index/Middle':
slot = 19
elif duction == 'Middle/Ring':
slot = 24
elif duction == 'Ring/Pinky':
slot = 29
elif duction == 'All':
slot = -1
if slot > 1:
print('{} DUCTION'.format(duction.upper()))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
ch[slot] = 'X'
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h - ending_h))
else:
print('{} DUCTION'.format(duction.upper()))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
ch[2] = 'X'
ch[19] = 'X'
ch[24] = 'X'
ch[29] = 'X'
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h - ending_h))
result = [corpus_size, starting_h, new_corpus_size, ending_h, starting_h-ending_h]
self.results = [result]
def calcCustom(self, slots):
corpus_size, starting_h = self.calculateEntropy()
slots = [n-1 for n in slots]
# minus 1 because slot numbers starts at 1 but list indices start at 0
symbolA = self.customSymbo1A.currentText()
symbolB = self.customSymbolB.currentText()
print('Merging {} and {}'.format(symbolA, symbolB))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
for slot in slots:
if ch[slot] in [symbolA, symbolB]:
ch[slot] = 'X'
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h - ending_h))
result = [corpus_size, starting_h, new_corpus_size, ending_h, starting_h-ending_h]
self.results = [result]
def calcByFlexion(self):
corpus_size, starting_h = self.calculateEntropy()
finger = self.flexionFingerSelection.currentText()
joint = self.flexionJointSelection.currentText()
jointDict = {'Proximal': 0,
'Medial': 1,
'Distal': 2,
'All': -1}
fingerDict = {'Thumb':2,
'Index': 16,
'Middle': 21,
'Ring': 26,
'Pinky': 31,
'All': -1}
offset = jointDict[joint]
slot = fingerDict[finger]
slot += offset
if slot > 0:#user chose particular fingers
print('{} {} JOINTS'.format(finger.upper(), joint.upper()))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
ch[slot] = 'X'
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h - ending_h))
self.results = [[corpus_size, starting_h, new_corpus_size, ending_h, starting_h-ending_h]]
else: #user chose an "All" option
if joint == 'All' and finger != 'All':
#all the joints on a particular finger
slot = fingerDict[finger]
print('ALL {} JOINTS'.format(finger.upper()))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
ch[slot] = 'X' #proximal
ch[slot+1] = 'X' #medial
if not finger == 'Thumb':
ch[slot+2] = 'X' #distal
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h-ending_h))
self.results = [[corpus_size, starting_h, new_corpus_size, ending_h, starting_h-ending_h]]
elif finger == 'All' and joint != 'All':
#a particular joint on all the fingers
if joint == 'Proximal':
slot = 17
elif joint == 'Medial':
slot = 18
elif joint == 'Distal':
slot = 19
print('ALL {} JOINTS'.format(joint.upper()))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
# for finger,slot in [('INDEX', 17), ('MIDDLE',22), ('RING',27), ('PINKY',32)]:
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
ch[slot] = 'X'
ch[slot+5] = 'X'
ch[slot+10] = 'X'
ch[slot+15] = 'X'
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h-ending_h))
self.results = [[corpus_size, starting_h, new_corpus_size, ending_h, starting_h-ending_h]]
elif finger == 'All' and joint == 'All':
results = list()
for finger, slot in [('THUMB', 2), ('INDEX', 17), ('MIDDLE', 22), ('RING', 27), ('PINKY', 31)]:
print('ALL {} JOINTS'.format(joint.upper()))
print('Starting size = {}\nStarting entropy = {}'.format(corpus_size, starting_h))
new_corpus = defaultdict(int)
for word in self.corpus:
ch = word.config1hand1.copy()
ch[slot] = 'X'
ch[slot+1] = 'X'
if not finger == 'Thumb':
ch[slot+2] = 'X'
new_corpus[''.join(ch)] += 1
new_corpus_size, ending_h = self.calculateEntropy(new_corpus)
print('After merging size = {}\nAfter merging entropy = {}'.format(len(new_corpus), ending_h))
print('Change in entropy = {}\n'.format(starting_h-ending_h))
results.append([corpus_size, starting_h, new_corpus_size, ending_h, starting_h-ending_h])
self.results = results
class FunctionalLoadResultsTable(QDialog):
def __init__(self, results):
super().__init__()
layout = QHBoxLayout()
table = QTableWidget()
table.setColumnCount(5)
table.setHorizontalHeaderLabels(['Starting corpus size', 'Starting entropy',
'Ending corpus size', 'Ending entropy', 'Change in entropy'])
for result in results:
table.insertRow(table.rowCount())
for i, item in enumerate(result):
newItem = QTableWidgetItem(str(item))
table.setItem(table.rowCount()-1, i, newItem)
layout.addWidget(table)
self.setLayout(layout)
|
PhonologicalCorpusTools/SLP-Annotator
|
slpa/gui/functional_load.py
|
Python
|
gpl-3.0
| 15,434
|
package controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import model.Data;
import model.DataDao;
import model.DataDaoImpl;
import model.Game;
import model.Games;
import model.MineInfo;
// CHECKSTYLE:OFF
public class MineSweeperController {
private static final Logger logger = LoggerFactory.getLogger(MineSweeperController.class);
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
private static final int TILESIZE = 30;
private int xTiles;
private int yTiles;
private Data board[][];
private Button save;
private Button back;
private Button exit;
public MineSweeperController() {
}
public void initMineSweeperController(int xTiles, int yTiles) {
this.xTiles = xTiles;
this.yTiles = yTiles;
this.board = new Data[xTiles][yTiles];
logger.debug("INFO - A fő képernyő inicializálva.");
}
public void exitGame(ActionEvent actionEvent) {
System.exit(0);
}
public BorderPane createContent(int x, int y) {
BorderPane root = new BorderPane();
DataDao data = new DataDaoImpl();
root.setPrefSize(WIDTH, HEIGHT);
initMineSweeperController(x, y);
root.setPadding(new Insets(10, 10, 10, 10));
root.setMaxWidth(WIDTH);
root.setMaxHeight(HEIGHT);
root.setCenter(populate());
HBox hbButtons = new HBox();
createButtons(data, hbButtons);
hbButtons.getChildren().addAll(back, save, exit);
root.setBottom(hbButtons);
return root;
}
public Parent loadContent(Games games, String id, int xSize, int ySize) {
BorderPane root = new BorderPane();
root.setPrefSize(WIDTH, HEIGHT);
root.setPadding(new Insets(10, 10, 10, 10));
root.setMaxWidth(WIDTH);
root.setMaxHeight(HEIGHT);
DataDao data = new DataDaoImpl();
initMineSweeperController(xSize, ySize);
for (Game game : games.getGames()) {
if (id.equals(game.getId())) {
root.setCenter(fillBoard(game));
}
}
HBox hbButtons = new HBox();
createButtons(data, hbButtons);
hbButtons.getChildren().addAll(back, save, exit);
root.setBottom(hbButtons);
logger.info("Játékállás sikeresen betöltve.");
return root;
}
private void createButtons(DataDao data, HBox hbButtons) {
hbButtons.setAlignment(Pos.CENTER);
hbButtons.setSpacing(10.0);
save = new Button("Mentés");
save.setOnMouseClicked(b -> {
data.saveMines(board);
});
back = new Button("Vissza");
back.setOnMouseClicked(b -> {
Stage dialog = new Stage();
FXMLLoader newGamefXMLLoader = new FXMLLoader(getClass().getResource("/view/NewGameDialog.fxml"));
try {
Parent backRoot = newGamefXMLLoader.load();
Scene dialogScene = new Scene(backRoot);
dialog.setScene(dialogScene);
dialog.show();
Stage actualStage = (Stage) back.getScene().getWindow();
actualStage.close();
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setContentText("Váratlan hiba történt: " + e.getMessage() + "\nKérlek próbáld újra!");
logger.error("{}", alert.getContentText());
alert.showAndWait();
if (alert.getResult() == ButtonType.OK) {
alert.close();
}
}
});
exit = new Button("Kilépés");
exit.setOnMouseClicked(b -> {
logger.info("KILÉPÉS");
System.exit(0);
});
}
public Pane populate() {
Pane root = new Pane();
double randomToGenerate = (xTiles+yTiles)/100.0;
// sorfolytonosan tölti
for (int y = 0; y < yTiles; y++) {
for (int x = 0; x < xTiles; x++) {
Data filled = new Data();
setFieldProperties(y, x, Math.random() < randomToGenerate, filled);
board[x][y] = filled;
root.getChildren().add(filled);
}
}
root.setTranslateX((WIDTH-xTiles*TILESIZE)/2-5);
fillText();
return root;
}
private Pane fillBoard(Game game) {
Pane root = new Pane();
for (MineInfo mine : game.getMines()) {
Data filled = new Data();
setFieldProperties(mine.getY(), mine.getX(), mine.isMine(), filled);
filled.setRevealed(mine.isRevealed());
if (filled.isRevealed()) {
openLoaded(filled);
}
filled.setFlagged(mine.isFlagged());
if (filled.isFlagged()) {
markLoaded(filled);
}
board[mine.getX()][mine.getY()] = filled;
root.getChildren().add(filled);
}
root.setTranslateX((WIDTH-xTiles*TILESIZE)/2-5);
fillText();
return root;
}
private void setFieldProperties(int y, int x, boolean isMine, Data filled) {
filled.setX(x);
filled.setY(y);
filled.setMine(isMine);
filled.setTile(new Rectangle(TILESIZE - 2, TILESIZE - 2));
filled.getTile().setStroke(Color.BLUE);
filled.getTile().setFill(Color.GREY);
filled.setText(new Text());
filled.getText().setFont(Font.font(18));
filled.getText().setText(filled.isMine() ? "X" : "");
filled.getText().setVisible(false);
if (filled.isMine()) {
filled.setPicture(new ImageView(new Image(getClass().getResourceAsStream("/images/imgBomb.png"))));
filled.getPicture().setFitWidth(filled.getTile().getWidth());
filled.getPicture().setFitHeight(filled.getTile().getHeight());
} else {
filled.setPicture(null);
}
filled.getChildren().addAll(filled.getTile(), filled.getText());
filled.setTranslateX(x * TILESIZE);
filled.setTranslateY(y * TILESIZE);
filled.setOnMouseClicked(e -> {
if (e.getButton().equals(MouseButton.PRIMARY)) {
open(filled);
} else if (!filled.isFlagged() && e.getButton().equals(MouseButton.SECONDARY)) {
mark(filled);
} else if (filled.isFlagged() && e.getButton().equals(MouseButton.SECONDARY)) {
removeMark(filled);
}
});
}
private void fillText() {
DataDao data = new DataDaoImpl();
for (int y = 0; y < yTiles; y++) {
for (int x = 0; x < xTiles; x++) {
Data filled = board[x][y];
if (filled.isMine()) {
continue;
}
long neighboursWithMines = data.getNeighbours(filled, board).stream().filter(s -> s.isMine()).count();
if (neighboursWithMines > 0) {
filled.getText().setText(String.valueOf(neighboursWithMines));
filled.setMinesNear((int) neighboursWithMines);
}
}
}
}
public void revealBombs() {
DataDao data = new DataDaoImpl();
for (int i = 0; i < xTiles; i++) {
for (int j = 0; j < yTiles; j++) {
if (board[i][j].isFlagged()) {
board[i][j].getChildren().remove(board[i][j].getPicture());
board[i][j].getPicture().setImage(new Image(getClass().getResourceAsStream("/images/imgBomb.png")));
}
if (board[i][j].isMine()) {
board[i][j].getPicture().setVisible(true);
board[i][j].getChildren().add(board[i][j].getPicture());
}
}
}
data.saveMines(board);
gameOver();
}
private void gameOver() {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Vége");
alert.setHeaderText("Sikertelen!");
alert.setContentText(
"Egy bombára kattintottál! Vége a játéknak. Ha a OK gombra kattintasz, újat indíthatsz!");
alert.showAndWait();
logger.info("VÉGE, eredmény: {}", alert.getHeaderText());
if (alert.getResult() == ButtonType.OK) {
Stage dialog = new Stage();
FXMLLoader newGamefXMLLoader = new FXMLLoader(getClass().getResource("/view/NewGameDialog.fxml"));
try {
Parent backRoot = newGamefXMLLoader.load();
Scene dialogScene = new Scene(backRoot);
dialog.setScene(dialogScene);
dialog.show();
Stage actualStage = (Stage) back.getScene().getWindow();
actualStage.close();
} catch (Exception e) {
Alert errorAlert = new Alert(AlertType.ERROR);
errorAlert.setTitle("Error");
alert.setContentText("Váratlan hiba történt: " + e.getMessage() + "\nKérlek próbáld újra!");
logger.error("{}", errorAlert.getContentText());
errorAlert.showAndWait();
if (errorAlert.getResult() == ButtonType.OK) {
errorAlert.close();
}
}
alert.close();
} else if (alert.getResult() == ButtonType.CANCEL) {
alert.close();
System.exit(0);
}
}
public void open(Data data) {
DataDao dataDao = new DataDaoImpl();
if (data.isRevealed()) {
return;
}
if (data.isMine()) {
if (data.isFlagged()) {
data.getPicture().setImage(null);
}
revealBombs();
} else {
data.setRevealed(true);
data.getText().setVisible(true);
data.getTile().setFill(null);
data.getChildren().remove(data.getPicture());
if (data.getText().getText().isEmpty()) {
dataDao.getNeighbours(data, board).forEach(this::open);
}
showEndDialog(data);
}
}
private void showEndDialog(Data data) {
DataDao dataDao = new DataDaoImpl();
if (board[data.getX()][data.getY()] != null && dataDao.isDone(board)) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Gratulálok");
alert.setHeaderText("Siker!");
alert.setContentText("Jól jelölted meg az összes aknát! Vége a játéknak.");
alert.showAndWait();
logger.info("VÉGE, eredmény: {}", alert.getHeaderText());
if (alert.getResult() == ButtonType.OK) {
alert.close();
}
}
}
public void openLoaded(Data data) {
if (data.isRevealed()) {
data.getText().setVisible(true);
data.getTile().setFill(null);
data.getChildren().remove(data.getPicture());
}
showEndDialog(data);
}
public void mark(Data data) {
if (data.isRevealed()) {
return;
}
data.setFlagged(true);
data.setPicture(new ImageView(new Image(getClass().getResourceAsStream("/images/imgRedFlag.png"))));
data.getPicture().setFitWidth(data.getTile().getWidth());
data.getPicture().setFitHeight(data.getTile().getHeight());
data.getPicture().setVisible(true);
data.getChildren().add(data.getPicture());
showEndDialog(data);
}
public void markLoaded(Data data) {
if (data.isFlagged()) {
data.setPicture(new ImageView(new Image(getClass().getResourceAsStream("/images/imgRedFlag.png"))));
data.getPicture().setFitWidth(data.getTile().getWidth());
data.getPicture().setFitHeight(data.getTile().getHeight());
data.getPicture().setVisible(true);
data.getChildren().add(data.getPicture());
}
showEndDialog(data);
}
public void removeMark(Data data) {
data.setFlagged(false);
data.getChildren().remove(data.getPicture());
}
public int getxTiles() {
return xTiles;
}
public void setxTiles(int xTiles) {
this.xTiles = xTiles;
}
public int getyTiles() {
return yTiles;
}
public void setyTiles(int yTiles) {
this.yTiles = yTiles;
}
public Data[][] getBoard() {
return board;
}
public void setBoard(Data[][] board) {
this.board = board;
}
}
|
rabai/minesweeper
|
minesweeper-parent/minesweeper-controller/src/main/java/controller/MineSweeperController.java
|
Java
|
gpl-3.0
| 11,491
|
<?php
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2011 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
// Handler for remote job submission.
// See http://boinc.berkeley.edu/trac/wiki/RemoteJobs
require_once("../inc/boinc_db.inc");
require_once("../inc/submit_db.inc");
require_once("../inc/xml.inc");
require_once("../inc/dir_hier.inc");
require_once("../inc/result.inc");
require_once("../inc/submit_util.inc");
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
function get_wu($name) {
$name = BoincDb::escape_string($name);
$wu = BoincWorkunit::lookup("name='$name'");
if (!$wu) xml_error(-1, "BOINC server: no job named $name was found");
return $wu;
}
function get_app($name) {
$name = BoincDb::escape_string($name);
$app = BoincApp::lookup("name='$name'");
if (!$app) xml_error(-1, "BOINC server: no app named $name was found");
return $app;
}
// estimate FLOP count for a batch.
// If estimates aren't included in the job descriptions,
// use what's in the input template
//
function batch_flop_count($r, $template) {
$x = 0;
$t = (double)$template->workunit->rsc_fpops_est;
foreach($r->batch->job as $job) {
$y = (double)$job->rsc_fpops_est;
if ($y) {
$x += $y;
} else {
$x += $t;
}
}
return $x;
}
// estimate project FLOPS based on recent average credit
//
function project_flops() {
$x = BoincUser::sum("expavg_credit");
if ($x == 0) $x = 200;
$y = 1e9*$x/200;
return $y;
}
function est_elapsed_time($r, $template) {
// crude estimate: batch FLOPs / project FLOPS
//
return batch_flop_count($r, $template) / project_flops();
}
function read_input_template($app, $r) {
if ((isset($r->batch)) && (isset($r->batch->workunit_template_file)) && ($r->batch->workunit_template_file)) {
$path = "../../templates/".$r->batch->workunit_template_file;
} else {
$path = "../../templates/$app->name"."_in";
}
return simplexml_load_file($path);
}
function check_max_jobs_in_progress($r, $user_submit) {
if (!$user_submit->max_jobs_in_progress) return;
$query = "select count(*) as total from DBNAME.result, DBNAME.batch where batch.user_id=$userid and result.batch = batch.id and result.server_state<".RESULT_SERVER_STATE_OVER;
$db = BoincDb::get();
$n = $db->get_int($query);
if ($n === false) return;
if ($n + count($r->batch->job) > $user_submit->max_jobs_in_progress) {
xml_error(-1, "BOINC server: limit on jobs in progress exceeded");
}
}
function estimate_batch($r) {
$app = get_app((string)($r->batch->app_name));
list($user, $user_submit) = authenticate_user($r, $app);
$template = read_input_template($app, $r);
$e = est_elapsed_time($r, $template);
echo "<estimate>\n<seconds>$e</seconds>\n</estimate>\n";
}
function validate_batch($jobs, $template) {
$i = 0;
$n = count($template->file_info);
foreach($jobs as $job) {
$m = count($job->input_files);
if ($n != $m) {
xml_error(-1, "BOINC server: wrong # of input files for job $i: need $n, got $m");
}
$i++;
}
}
$fanout = parse_config(get_config(), "<uldl_dir_fanout>");
// stage a file, and return the physical name
//
function stage_file($file) {
global $fanout;
$download_dir = parse_config(get_config(), "<download_dir>");
switch ($file->mode) {
case "semilocal":
case "local":
// read the file (from disk or network) to get MD5.
// Copy to download hier, using a physical name based on MD5
//
$md5 = md5_file($file->source);
if (!$md5) {
xml_error(-1, "BOINC server: Can't get MD5 of file $file->source");
}
$name = "jf_$md5";
$path = dir_hier_path($name, $download_dir, $fanout);
if (file_exists($path)) return $name;
if (!copy($file->source, $path)) {
xml_error(-1, "BOINC server: can't copy file from $file->source to $path");
}
return $name;
case "local_staged":
return $file->source;
case "inline":
$md5 = md5($file->source);
if (!$md5) {
xml_error(-1, "BOINC server: Can't get MD5 of inline data");
}
$name = "jf_$md5";
$path = dir_hier_path($name, $download_dir, $fanout);
if (file_exists($path)) return $name;
if (!file_put_contents($path, $file->source)) {
xml_error(-1, "BOINC server: can't write to file $path");
}
return $name;
}
xml_error(-1, "BOINC server: unsupported file mode: $file->mode");
}
// stage all the files
//
function stage_files(&$jobs, $template) {
foreach($jobs as $job) {
foreach ($job->input_files as $file) {
if ($file->mode != "remote") {
$file->name = stage_file($file);
}
}
}
}
function submit_jobs($jobs, $template, $app, $batch_id, $priority, $result_template_file = null, $workunit_template_file = null) {
$x = "";
foreach($jobs as $job) {
if ($job->name) {
$x .= " --wu_name $job->name";
}
if ($job->command_line) {
$x .= " --command_line \"$job->command_line\"";
}
if ($job->target_team) {
$x .= " --target_team $job->target_team";
} elseif ($job->target_user) {
$x .= " --target_user $job->target_user";
} elseif ($job->target_host) {
$x .= " --target_host $job->target_host";
}
foreach ($job->input_files as $file) {
if ($file->mode == "remote") {
$x .= " --remote_file $file->url $file->nbytes $file->md5";
} else {
$x .= " $file->name";
}
}
$x .= "\n";
}
$cmd = "cd ../..; ./bin/create_work --appname $app->name --batch $batch_id --rsc_fpops_est $job->rsc_fpops_est --priority $priority --stdin";
if ($result_template_file) {
$cmd .= " --result_template templates/$result_template_file";
}
if ($workunit_template_file) {
$cmd .= " --wu_template templates/$workunit_template_file";
}
$cmd .= " --stdin";
$h = popen($cmd, "w");
if ($h === false) {
xml_error(-1, "BOINC server: can't run create_work");
}
fwrite($h, $x);
$ret = pclose($h);
if ($ret) {
xml_error(-1, "BOINC server: create_work failed");
}
}
function xml_get_jobs($r) {
$jobs = array();
foreach($r->batch->job as $j) {
$job = new StdClass;
$job->input_files = array();
$job->command_line = (string)$j->command_line;
$job->target_team = (int)$j->target_team;
$job->target_user = (int)$j->target_user;
$job->target_host = (int)$j->target_host;
$job->name = (string)$j->name;
$job->rsc_fpops_est = (double)$j->rsc_fpops_est;
foreach ($j->input_file as $f) {
$file = new StdClass;
$file->mode = (string)$f->mode;
if ($file->mode == "remote") {
$file->url = (string)$f->url;
$file->nbytes = (double)$f->nbytes;
$file->md5 = (string)$f->md5;
} else {
$file->source = (string)$f->source;
}
$job->input_files[] = $file;
}
$jobs[] = $job;
}
return $jobs;
}
function submit_batch($r) {
$app = get_app((string)($r->batch->app_name));
list($user, $user_submit) = authenticate_user($r, $app);
$template = read_input_template($app, $r);
$jobs = xml_get_jobs($r);
validate_batch($jobs, $template);
stage_files($jobs, $template);
$njobs = count($jobs);
$now = time();
$batch_id = (int)($r->batch->batch_id);
if ($batch_id) {
$batch = BoincBatch::lookup_id($batch_id);
if (!$batch) {
xml_error(-1, "BOINC server: no batch $batch_id");
}
if ($batch->user_id != $user->id) {
xml_error(-1, "BOINC server: not owner of batch");
}
if ($batch->state != BATCH_STATE_INIT) {
xml_error(-1, "BOINC server: batch not in init state");
}
}
// - compute batch FLOP count
// - run adjust_user_priorities to increment user_submit.logical_start_time
// - use that for batch logical end time and job priority
//
$total_flops = 0;
foreach($jobs as $job) {
if ($job->rsc_fpops_est) {
$total_flops += $job->rsc_fpops_est;
} else {
$x = (double) $template->workunit->rsc_fpops_est;
if ($x) {
$total_flops += $x;
} else {
xml_error(-1, "BOINC server: no rsc_fpops_est given");
}
}
}
$cmd = "cd ../../bin; ./adjust_user_priority --user $user->id --flops $total_flops --app $app->name";
$x = exec($cmd);
if (!is_numeric($x) || (double)$x == 0) {
xml_error(-1, "BOINC server: $cmd returned $x");
}
$let = (double)$x;
if ($batch_id) {
$njobs = count($jobs);
$ret = $batch->update("njobs=$njobs, logical_end_time=$let");
if (!$ret) xml_error(-1, "BOINC server: batch->update() failed");
} else {
$batch_name = (string)($r->batch->batch_name);
$batch_id = BoincBatch::insert(
"(user_id, create_time, njobs, name, app_id, logical_end_time, state) values ($user->id, $now, $njobs, '$batch_name', $app->id, $let, ".BATCH_STATE_INIT.")"
);
if (!$batch_id) {
xml_error(-1, "BOINC server: Can't create batch: ".BoincDb::error());
}
$batch = BoincBatch::lookup_id($batch_id);
}
if ($r->batch->result_template_file) {
$result_template_file = $r->batch->result_template_file;
} else {
$result_template_file = null;
}
if ($r->batch->workunit_template_file) {
$workunit_template_file = $r->batch->workunit_template_file;
} else {
$workunit_template_file = null;
}
submit_jobs($jobs, $template, $app, $batch_id, $let, $result_template_file, $workunit_template_file);
// set state to IN_PROGRESS only after creating jobs;
// otherwise we might flag batch as COMPLETED
//
$ret = $batch->update("state= ".BATCH_STATE_IN_PROGRESS);
if (!$ret) xml_error(-1, "BOINC server: batch->update() failed");
echo "<batch_id>$batch_id</batch_id>\n";
}
function create_batch($r) {
$app = get_app((string)($r->batch->app_name));
list($user, $user_submit) = authenticate_user($r, $app);
$now = time();
$batch_name = (string)($r->batch->batch_name);
$expire_time = (double)($r->expire_time);
$batch_id = BoincBatch::insert(
"(user_id, create_time, name, app_id, state, expire_time) values ($user->id, $now, '$batch_name', $app->id, ".BATCH_STATE_INIT.", $expire_time)"
);
if (!$batch_id) {
xml_error(-1, "BOINC server: Can't create batch: ".BoincDb::error());
}
echo "<batch_id>$batch_id</batch_id>\n";
}
function print_batch_params($batch) {
$app = BoincApp::lookup_id($batch->app_id);
if (!$app) $app->name = "none";
echo "
<id>$batch->id</id>
<create_time>$batch->create_time</create_time>
<expire_time>$batch->expire_time</expire_time>
<est_completion_time>$batch->est_completion_time</est_completion_time>
<njobs>$batch->njobs</njobs>
<fraction_done>$batch->fraction_done</fraction_done>
<nerror_jobs>$batch->nerror_jobs</nerror_jobs>
<state>$batch->state</state>
<completion_time>$batch->completion_time</completion_time>
<credit_estimate>$batch->credit_estimate</credit_estimate>
<credit_canonical>$batch->credit_canonical</credit_canonical>
<name>$batch->name</name>
<app_name>$app->name</app_name>
";
}
function query_batches($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batches = BoincBatch::enum("user_id = $user->id");
echo "<batches>\n";
foreach ($batches as $batch) {
if ($batch->state < BATCH_STATE_COMPLETE) {
$wus = BoincWorkunit::enum("batch = $batch->id");
$batch = get_batch_params($batch, $wus);
}
echo " <batch>\n";
print_batch_params($batch);
echo " </batch>\n";
}
echo "</batches>\n";
}
function n_outfiles($wu) {
$path = "../../$wu->result_template_file";
$r = simplexml_load_file($path);
return count($r->file_info);
}
// return a batch specified by the command, using either ID or name
//
function get_batch($r) {
if (!empty($r->batch_id)) {
$batch_id = (int)($r->batch_id);
$batch = BoincBatch::lookup_id($batch_id);
} else if (!empty($r->batch_name)) {
$batch_name = (string)($r->batch_name);
$batch_name = BoincDb::escape_string($batch_name);
$batch = BoincBatch::lookup_name($batch_name);
} else {
xml_error(-1, "BOINC server: batch not specified");
}
if (!$batch) xml_error(-1, "BOINC server: no such batch");
return $batch;
}
function query_batch($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batch = get_batch($r);
if ($batch->user_id != $user->id) {
xml_error(-1, "BOINC server: not owner of batch");
}
$wus = BoincWorkunit::enum("batch = $batch->id");
$batch = get_batch_params($batch, $wus);
echo "<batch>\n";
print_batch_params($batch);
$n_outfiles = n_outfiles($wus[0]);
foreach ($wus as $wu) {
echo " <job>
<id>$wu->id</id>
<name>$wu->name</name>
<canonical_instance_id>$wu->canonical_resultid</canonical_instance_id>
<n_outfiles>$n_outfiles</n_outfiles>
</job>
";
}
echo "</batch>\n";
}
// variant for Condor, which doesn't care about job instances
// and refers to batches by name
//
function query_batch2($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batch_names = $r->batch_name;
$batches = array();
foreach ($batch_names as $b) {
$batch_name = (string)$b;
$batch_name = BoincDb::escape_string($batch_name);
$batch = BoincBatch::lookup_name($batch_name);
if (!$batch) {
xml_error(-1, "no batch named $batch_name");
}
if ($batch->user_id != $user->id) {
xml_error(-1, "not owner of $batch_name");
}
$batches[] = $batch;
}
$min_mod_time = (double)$r->min_mod_time;
if ($min_mod_time) {
$mod_time_clause = "and mod_time > FROM_UNIXTIME($min_mod_time)";
} else {
$mod_time_clause = "";
}
$t = dtime();
echo "<server_time>$t</server_time>\n";
echo "<jobs>\n";
foreach ($batches as $batch) {
$wus = BoincWorkunit::enum("batch = $batch->id $mod_time_clause");
echo " <batch_size>".count($wus)."</batch_size>\n";
foreach ($wus as $wu) {
if ($wu->canonical_resultid) {
$status = "DONE";
} else if ($wu->error_mask) {
$status = "ERROR";
} else {
$status = "IN_PROGRESS";
}
echo
" <job>
<job_name>$wu->name</job_name>
<status>$status</status>
</job>
";
}
}
echo "</jobs>\n";
}
function query_job($r) {
list($user, $user_submit) = authenticate_user($r, null);
$job_id = (int)($r->job_id);
$wu = BoincWorkunit::lookup_id($job_id);
if (!$wu) xml_error(-1, "no such job");
$batch = BoincBatch::lookup_id($wu->batch);
if ($batch->user_id != $user->id) {
xml_error(-1, "not owner");
}
echo "<job>\n";
$results = BoincResult::enum("workunitid=$job_id");
foreach ($results as $result) {
echo " <instance>
<name>$result->name</name>
<id>$result->id</id>
<state>".state_string($result)."</state>
";
if ($result->server_state == 5) { // over?
$paths = get_outfile_paths($result);
foreach($paths as $path) {
if (is_file($path)) {
$size = filesize($path);
echo " <outfile>
<size>$size</size>
</outfile>
";
}
}
}
echo "</instance>\n";
}
echo "</job>\n";
}
// the following for Condor.
// If the job has a canonical instance, return info about it.
// Otherwise find an instance that completed
// (possibly crashed) and return its info.
//
function query_completed_job($r) {
list($user, $user_submit) = authenticate_user($r, null);
$job_name = (string)($r->job_name);
$job_name = BoincDb::escape_string($job_name);
$wu = BoincWorkunit::lookup("name='$job_name'");
if (!$wu) xml_error(-1, "no such job");
$batch = BoincBatch::lookup_id($wu->batch);
if ($batch->user_id != $user->id) {
xml_error(-1, "not owner");
}
echo "<completed_job>\n";
echo " <error_mask>$wu->error_mask</error_mask>\n";
if ($wu->canonical_resultid) {
$result = BoincResult::lookup_id($wu->canonical_resultid);
echo " <canonical_resultid>$wu->canonical_resultid</canonical_resultid>\n";
} else {
$results = BoincResult::enum("workunitid=$job_id");
foreach ($results as $r) {
switch($r->outcome) {
case 1:
case 3:
case 6:
$result = $r;
break;
}
}
if ($result) {
echo " <error_resultid>$result->id</error_resultid>\n";
}
}
if ($result) {
echo " <exit_status>$result->exit_status</exit_status>\n";
echo " <elapsed_time>$result->elapsed_time</elapsed_time>\n";
echo " <cpu_time>$result->cpu_time</cpu_time>\n";
echo " <stderr_out><![CDATA[\n";
echo htmlspecialchars($result->stderr_out);
echo " ]]></stderr_out>\n";
}
echo "</completed_job>\n";
}
function handle_abort_batch($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batch = get_batch($r);
if ($batch->user_id != $user->id) {
xml_error(-1, "not owner");
}
abort_batch($batch);
echo "<success>1</success>";
}
// handle the abort of jobs possibly belonging to different batches
//
function handle_abort_jobs($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batch = null;
foreach ($r->job_name as $job_name) {
$job_name = BoincDb::escape_string($job_name);
$wu = BoincWorkunit::lookup("name='$job_name'");
if (!$wu) {
xml_error(-1, "No job $job_name");
}
if (!$wu->batch) {
xml_error(-1, "Job $job_name is not part of a batch");
}
if (!$batch || $wu->batch != $batch->id) {
$batch = BoincBatch::lookup_id($wu->batch);
}
if (!$batch || $batch->user_id != $user->id) {
xml_error(-1, "not owner");
}
echo "<aborted $job_name>\n";
abort_workunit($wu);
}
echo "<success>1</success>";
}
function handle_retire_batch($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batch = get_batch($r);
if ($batch->user_id != $user->id) {
xml_error(-1, "not owner");
}
retire_batch($batch);
echo "<success>1</success>";
}
function handle_set_expire_time($r) {
list($user, $user_submit) = authenticate_user($r, null);
$batch = get_batch($r);
if ($batch->user_id != $user->id) {
xml_error(-1, "not owner");
}
$expire_time = (double)($r->expire_time);
if ($batch->update("expire_time=$expire_time")) {
echo "<success>1</success>";
} else {
xml_error(-1, "update failed");
}
}
function get_templates($r) {
$app_name = (string)($r->app_name);
if ($app_name) {
$app = get_app($app_name);
} else {
$job_name = (string)($r->job_name);
$wu = get_wu($job_name);
$app = BoincApp::lookup_id($wu->appid);
}
list($user, $user_submit) = authenticate_user($r, $app);
$in = file_get_contents("../../templates/".$app->name."_in");
$out = file_get_contents("../../templates/".$app->name."_out");
if ($in === false || $out === false) {
xml_error(-1, "template file missing");
}
echo "<templates>\n$in\n$out\n</templates>\n";
}
function ping($r) {
BoincDb::get(); // errors out if DB down or web disabled
echo "<success>1</success>";
}
if (0) {
$r = simplexml_load_string("
<query_batch>
<authenticator>x</authenticator>
<batch_id>54</batch_id>
</query_batch>
");
query_batch($r);
exit;
}
if (0) {
$r = simplexml_load_string("
<query_job>
<authenticator>x</authenticator>
<job_id>312173</job_id>
</query_job>
");
query_job($r);
exit;
}
if (0) {
$r = simplexml_load_string("
<estimate_batch>
<authenticator>x</authenticator>
<batch>
<app_name>remote_test</app_name>
<batch_name>Aug 6 batch 4</batch_name>
<job>
<rsc_fpops_est>19000000000</rsc_fpops_est>
<command_line>--t 19</command_line>
<input_file>
<mode>remote</mode>
<source>http://google.com/</source>
</input_file>
</job>
</batch>
</estimate_batch>
");
estimate_batch($r);
exit;
}
if (0) {
require_once("submit_test.inc");
}
xml_header();
$r = simplexml_load_string($_POST['request']);
if (!$r) {
xml_error(-1, "can't parse request message");
}
switch ($r->getName()) {
case 'abort_batch': handle_abort_batch($r); break;
case 'abort_jobs': handle_abort_jobs($r); break;
case 'create_batch': create_batch($r); break;
case 'estimate_batch': estimate_batch($r); break;
case 'get_templates': get_templates($r); break;
case 'ping': ping($r); break;
case 'query_batch': query_batch($r); break;
case 'query_batch2': query_batch2($r); break;
case 'query_batches': query_batches($r); break;
case 'query_job': query_job($r); break;
case 'query_completed_job': query_completed_job($r); break;
case 'retire_batch': handle_retire_batch($r); break;
case 'set_expire_time': handle_set_expire_time($r); break;
case 'submit_batch': submit_batch($r); break;
default: xml_error(-1, "bad command: ".$r->getName());
}
?>
|
maexlich/boinc-igemathome
|
html/user/submit_rpc_handler.php
|
PHP
|
gpl-3.0
| 23,053
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<link rel="icon" href="../favicon.ico" type="image/x-icon" />
<link
rel="shortcut icon"
href="../favicon.ico"
type="image/x-icon"
/>
<title>Contact Us - HartCode Game Studio</title>
</head>
<body class="contact">
<div id="root"></div>
<script src="../vendors.js"></script>
<script src="../style.js"></script>
<script src="../contact.js"></script>
</body>
</html>
|
hartcode/hartcode.com
|
client/contact/index.html
|
HTML
|
gpl-3.0
| 533
|
<?php
class File extends Genome implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable {
const state = [
// Range of allowed file size(s)
'size' => [0, 2097152],
// List of allowed file type(s)
'type' => [
'application/javascript' => 1,
'application/json' => 1,
'application/xml' => 1,
'image/gif' => 1,
'image/jpeg' => 1,
'image/png' => 1,
'inode/x-empty' => 1, // Empty file
'text/css' => 1,
'text/html' => 1,
'text/javascript' => 1,
'text/plain' => 1,
'text/xml' => 1
],
// List of allowed file extension(s)
'x' => [
'css' => 1,
'gif' => 1,
'htm' => 1,
'html' => 1,
'jpe' => 1,
'jpg' => 1,
'jpeg' => 1,
'js' => 1,
'json' => 1,
'log' => 1,
'png' => 1,
'txt' => 1,
'xml' => 1
]
];
public $exist;
public $path;
public $value;
public function __construct($path = null) {
$this->value[0] = "";
if ($path && is_string($path) && 0 === strpos($path, ROOT)) {
$path = strtr($path, '/', DS);
if (!is_file($path)) {
if (!is_dir($d = dirname($path))) {
mkdir($d, 0775, true);
}
touch($path); // Create an empty file
}
$this->path = is_file($path) ? (realpath($path) ?: $path) : null;
}
$this->exist = !!$this->path;
}
public function __get(string $key) {
if (method_exists($this, $key) && (new \ReflectionMethod($this, $key))->isPublic()) {
return $this->{$key}();
}
return null;
}
public function __toString() {
return $this->exist ? $this->path : "";
}
public function _seal() {
return $this->exist ? fileperms($this->path) : null;
}
public function _size() {
return $this->exist ? filesize($this->path) : null;
}
public function URL() {
return $this->exist ? To::URL($this->path) : null;
}
public function content() {
if ($this->exist) {
$content = file_get_contents($this->path);
return false !== $content ? $content : null;
}
return null;
}
public function copy(string $to) {
$out = [null];
if ($this->exist && $path = $this->path) {
$out[0] = $path;
if (is_file($v = $to . DS . basename($path))) {
// Return `false` if file already exists
$out[1] = false;
} else {
if (!is_dir($to)) {
mkdir($to, 0775, true);
}
// Return `$v` on success, `null` on error
$out[1] = copy($path, $v) ? $v : null;
}
}
$this->value[1] = $out;
return $this;
}
public function count() {
return $this->exist ? 1 : 0;
}
public function get(...$lot) {
$i = $lot[0] ?? 0;
if ($this->exist) {
$out = null;
foreach ($this->stream() as $k => $v) {
if ($k === $i) {
$out = $v;
break;
}
}
return $out;
}
return null;
}
public function getIterator() {
return $this->stream();
}
public function jsonSerialize() {
return [$this->path => 1];
}
public function let() {
if ($this->exist) {
// Return `$path` on success, `null` on error
$out = unlink($path = $this->path) ? $path : null;
} else {
// Return `false` if file does not exist
$out = false;
}
$this->value[1] = $out;
return $this;
}
public function move(string $to, string $as = null) {
$out = [null];
if ($this->exist && $path = $this->path) {
$out[0] = $path;
if (is_file($v = $to . DS . ($as ?? basename($path)))) {
// Return `false` if file already exists
$out[1] = false;
} else {
if (!is_dir($to)) {
mkdir($to, 0775, true);
}
// Return `$v` on success, `null` on error
$out[1] = rename($path, $v) ? $v : null;
}
}
$this->value[1] = $out;
return $this;
}
public function name($x = false) {
if ($this->exist && $path = $this->path) {
if (true === $x) {
return basename($path);
}
return pathinfo($path, PATHINFO_FILENAME) . (is_string($x) ? '.' . $x : "");
}
return null;
}
public function offsetExists($i) {
return !!$this->offsetGet($i);
}
public function offsetGet($i) {
return $this->__get($i);
}
public function offsetSet($i, $value) {}
public function offsetUnset($i) {}
public function parent() {
if ($this->exist) {
$parent = dirname($this->path);
return '.' !== $parent ? $parent : null;
}
return null;
}
public function save($seal = null) {
$out = false; // Return `false` if `$this` is just a placeholder
if ($path = $this->path) {
if (isset($seal)) {
$this->seal($seal);
}
// Return `$path` on success, `null` on error
$out = file_put_contents($path, $this->value[0]) ? $path : null;
} else if (defined('DEBUG') && DEBUG) {
$c = static::class;
throw new \Exception('Please provide a file path even if it does not exist. Example: `new ' . $c . '(\'' . ROOT . DS . c2f($c) . '.txt\')`');
}
$this->value[1] = $out;
return $this;
}
public function seal($i = null) {
if (isset($i)) {
if ($this->exist) {
$i = is_string($i) ? octdec($i) : $i;
// Return `$i` on success, `null` on error
$this->value[1] = chmod($this->path, $i) ? $i : null;
} else {
// Return `false` if file does not exist
$this->value[1] = false;
}
return $this;
}
return null !== ($i = $this->_seal()) ? substr(sprintf('%o', $i), -4) : null;
}
public function set(...$lot) {
$this->value[0] = $lot[0] ?? "";
return $this;
}
public function size(string $unit = null, int $r = 2) {
if ($this->exist && is_file($path = $this->path)) {
return self::sizer(filesize($path), $unit, $r);
}
return null;
}
public function stream() {
return $this->exist ? stream($this->path) : yield from [];
}
public function time(string $format = null) {
if ($this->exist) {
$t = filectime($this->path);
return $format ? (new Time($t))($format) : $t;
}
return null;
}
public function type() {
return $this->exist ? mime_content_type($this->path) : null;
}
public function x() {
if ($this->exist) {
$path = $this->path;
if (false === strpos($path, '.')) {
return null;
}
$x = pathinfo($path, PATHINFO_EXTENSION);
return $x ? strtolower($x) : null;
}
return false; // Return `false` if file does not exist
}
public static $state = self::state;
public static function exist($path) {
if (is_array($path)) {
foreach ($path as $v) {
if ($v && is_file($v)) {
return realpath($v);
}
}
return false;
}
return is_file($path) ? realpath($path) : false;
}
public static function pull($path, string $name = null) {
if (is_string($path) && is_file($path)) {
http_response_code(200);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . ($name ?? basename($path)) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;
}
http_response_code(404);
exit;
}
public static function push(array $blob, string $folder = ROOT) {
if (!empty($blob['error'])) {
return $blob['error']; // Return the error code
}
$folder = strtr($folder, '/', DS);
if (is_file($path = $folder . DS . $blob['name'])) {
return false; // Return `false` if file already exists
}
if (!is_dir($folder)) {
mkdir($folder, 0775, true);
}
if (move_uploaded_file($blob['tmp_name'], $path)) {
return $path; // Return `$path` on success
}
return null; // Return `null` on error
}
public static function sizer(float $size, string $unit = null, int $r = 2) {
$i = log($size, 1024);
$x = ['B', 'KB', 'MB', 'GB', 'TB'];
$u = $unit ? array_search($unit, $x) : ($size > 0 ? floor($i) : 0);
$out = round($size / pow(1024, $u), $r);
return $out < 0 ? null : trim($out . ' ' . $x[$u]);
}
}
|
mecha-cms/genome
|
engine/kernel/file.php
|
PHP
|
gpl-3.0
| 9,708
|
<section class="news">
<div class="container">
<div class="row">
<[menu::getleftmenu template="leftmenu" library="leftmenu"]>
<div class="col-md-8 rightBar">
<fieldset>
<legend>Piatti: </legend>
<div class="crea">
<h3 class="margin-reset">Aggiungi un piatto</h3><br />
<section id="contact">
<form enctype="multipart/form-data" action="piatti_add.php" method="POST" >
<fieldset>
<div>
<label class="border" for="nome">nome</label>
<input class="mandatory" type="text" name="nome" id="nome" errormessage="Pippo!"/>
</div>
<div>
<label class="border" for="descrizione">descrizione</label>
<input class="mandatory" type="text" name="descrizione" id="descrizione" errormessage="Pippo!"/>
</div>
<div>
<div>
<label class="border" for="ingredienti">ingredienti</label>
<input class="mandatory" type="text" name="ingredienti" id="ingredienti" errormessage="Pippo!"/>
</div>
</div>
<div>
<label class="border" for="prezzo">prezzo</label>
<input class="mandatory" type="text" name="prezzo" id="prezzo" errormessage="Pippo!"/>
</div>
<div>
<label class="border" for="immagine">immagine</label>
<input type="file" name="file_inviato" id="immagine">
</div>
<div>
<label class="border" for="classe">tipo</label>
<input type="radio" name="tipo" id="classe" value="colazione" /> colazione <br>
<label class="border"></label>
<input type="radio" name="tipo" id="classe" value="pranzo" /> pranzo <br>
<label class="border"></label>
<input type="radio" name="tipo" id="classe" value="cena" /> cena <br><br>
</div>
<div>
<label class="border" for="giorno">piatto del giorno</label>
<input type="radio" name="piattodelgiorno" id="giorno" value="1" /> si
<input type="radio" name="piattodelgiorno" id="giorno" value="0" /> no
</div>
<div>
<label class="border" for="classe">piatto di presentazione</label>
<input type="radio" name="presentazione" id="presentazione" value="1" /> si
<input type="radio" name="presentazione" id="presentazione" value="0"/> no
</div>
</fieldset>
<div class="btn-box" >
<label class="border"></label>
<input type="submit" class="commonbtn style1 small" id="submit" value="Aggiungi" />
</div>
<div class="clearfix"></div>
</form>
</section>
</div>
<div class="btn-box" id="aggiungi">
<a href="#" class="commonbtn style1 small" >aggiungi un piatto</a>
</div>
<[eventi::getmenu template="tabella-piatti" library="tabella_piatti" ]>
</fieldset>
</div>
</div>
</div>
</section>
|
Tondan/TDW
|
Documentation/PROGETTO JONATHAN E FRANCESCO/skins/html/piatti_manager.html
|
HTML
|
gpl-3.0
| 5,261
|
<?php
// Parametri per generare la pagina
return array(
'title' => 'Ereditarietà - Interfacce',
'subtitle' => 'Design di classi senza codice',
'prev' => array(
'url' => 'ereditarieta_final',
'label' => 'Ereditarietà - Metodi e classi finali',
),
'next' => array(
'url' => 'eccezioni',
'label' => 'Eccezioni',
),
'manual' => array(
'url' => 'http://it2.php.net/manual/en/language.oop5.interfaces.php',
'label' => 'Interfacce',
),
'content' => '<p>Le <strong>interfacce</strong> sono un livello di astrazione ancora
più elevato di quello delle estensioni.</p>
<p>In uno scenario particolarmente complesso, in cui le varie fasi di sviluppo
si svolgono in contesti molto separati, può essere utile uno strumento che imponga
ad una classe di avere certe caratteristiche.</p>
<p>Possiamo pensare ad un\'interfaccia come ad un <em>template</em> di classe.</p>
<p>Si può richiedere che altre classi <em>implementino</em> quell\'interfaccia.</p>
<p class="alert alert-success">Una classe può implementare più di un\'interfaccia.</p>',
'example' => basename(__FILE__),
);
|
hujuice/oopphp
|
pages/ereditarieta_interfacce.php
|
PHP
|
gpl-3.0
| 1,377
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class invObject extends Model
{
protected $table = 'firsttable';
protected $fillable =
[
'invNum',
'description',
'room'
];
}
|
v1teka/yo
|
app/invObject.php
|
PHP
|
gpl-3.0
| 231
|
/* RetroArch - A frontend for libretro.
* Copyright (C) 2014-2018 - Ali Bouhlel
* Copyright (C) 2016-2019 - Brad Parker
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <retro_inline.h>
#include "dxgi_common.h"
#include <d3d12.h>
typedef const ID3D12PipelineState* D3D12PipelineStateRef;
/* auto-generated */
typedef ID3D12Object* D3D12Object;
typedef ID3D12DeviceChild* D3D12DeviceChild;
typedef ID3D12RootSignature* D3D12RootSignature;
typedef ID3D12RootSignatureDeserializer* D3D12RootSignatureDeserializer;
typedef ID3D12VersionedRootSignatureDeserializer* D3D12VersionedRootSignatureDeserializer;
typedef ID3D12Pageable* D3D12Pageable;
typedef ID3D12Heap* D3D12Heap;
typedef ID3D12Resource* D3D12Resource;
typedef ID3D12CommandAllocator* D3D12CommandAllocator;
typedef ID3D12Fence* D3D12Fence;
typedef ID3D12PipelineState* D3D12PipelineState;
typedef ID3D12DescriptorHeap* D3D12DescriptorHeap;
typedef ID3D12QueryHeap* D3D12QueryHeap;
typedef ID3D12CommandSignature* D3D12CommandSignature;
typedef ID3D12CommandList* D3D12CommandList;
typedef ID3D12GraphicsCommandList* D3D12GraphicsCommandList;
typedef ID3D12CommandQueue* D3D12CommandQueue;
typedef ID3D12Device* D3D12Device;
typedef ID3D12PipelineLibrary* D3D12PipelineLibrary;
typedef ID3D12Debug* D3D12Debug;
typedef ID3D12DebugDevice* D3D12DebugDevice;
typedef ID3D12DebugCommandQueue* D3D12DebugCommandQueue;
typedef ID3D12DebugCommandList* D3D12DebugCommandList;
typedef ID3D12InfoQueue* D3D12InfoQueue;
static INLINE ULONG D3D12Release(void* object)
{
return ((ID3D12Object*)object)->lpVtbl->Release((ID3D12Object*)object);
}
static INLINE ULONG D3D12ReleaseDeviceChild(D3D12DeviceChild device_child)
{
return device_child->lpVtbl->Release(device_child);
}
static INLINE ULONG D3D12ReleaseRootSignature(D3D12RootSignature root_signature)
{
return root_signature->lpVtbl->Release(root_signature);
}
static INLINE ULONG
D3D12ReleaseRootSignatureDeserializer(D3D12RootSignatureDeserializer root_signature_deserializer)
{
return root_signature_deserializer->lpVtbl->Release(root_signature_deserializer);
}
static INLINE const D3D12_ROOT_SIGNATURE_DESC*
D3D12GetRootSignatureDesc(D3D12RootSignatureDeserializer root_signature_deserializer)
{
return root_signature_deserializer->lpVtbl->GetRootSignatureDesc(root_signature_deserializer);
}
static INLINE ULONG D3D12ReleaseVersionedRootSignatureDeserializer(
D3D12VersionedRootSignatureDeserializer versioned_root_signature_deserializer)
{
return versioned_root_signature_deserializer->lpVtbl->Release(
versioned_root_signature_deserializer);
}
static INLINE HRESULT D3D12GetRootSignatureDescAtVersion(
D3D12VersionedRootSignatureDeserializer versioned_root_signature_deserializer,
D3D_ROOT_SIGNATURE_VERSION convert_to_version,
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC** desc)
{
return versioned_root_signature_deserializer->lpVtbl->GetRootSignatureDescAtVersion(
versioned_root_signature_deserializer, convert_to_version, desc);
}
static INLINE const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* D3D12GetUnconvertedRootSignatureDesc(
D3D12VersionedRootSignatureDeserializer versioned_root_signature_deserializer)
{
return versioned_root_signature_deserializer->lpVtbl->GetUnconvertedRootSignatureDesc(
versioned_root_signature_deserializer);
}
static INLINE ULONG D3D12ReleasePageable(D3D12Pageable pageable)
{
return pageable->lpVtbl->Release(pageable);
}
static INLINE ULONG D3D12ReleaseHeap(D3D12Heap heap) { return heap->lpVtbl->Release(heap); }
static INLINE ULONG D3D12ReleaseResource(void* resource)
{
return ((ID3D12Resource*)resource)->lpVtbl->Release((ID3D12Resource*)resource);
}
static INLINE HRESULT
D3D12Map(void* resource, UINT subresource, D3D12_RANGE* read_range, void** data)
{
return ((ID3D12Resource*)resource)
->lpVtbl->Map((ID3D12Resource*)resource, subresource, read_range, data);
}
static INLINE void D3D12Unmap(void* resource, UINT subresource, D3D12_RANGE* written_range)
{
((ID3D12Resource*)resource)
->lpVtbl->Unmap((ID3D12Resource*)resource, subresource, written_range);
}
static INLINE D3D12_GPU_VIRTUAL_ADDRESS D3D12GetGPUVirtualAddress(void* resource)
{
return ((ID3D12Resource*)resource)->lpVtbl->GetGPUVirtualAddress((ID3D12Resource*)resource);
}
static INLINE HRESULT D3D12WriteToSubresource(
void* resource,
UINT dst_subresource,
D3D12_BOX* dst_box,
void* src_data,
UINT src_row_pitch,
UINT src_depth_pitch)
{
return ((ID3D12Resource*)resource)
->lpVtbl->WriteToSubresource(
(ID3D12Resource*)resource, dst_subresource, dst_box, src_data, src_row_pitch,
src_depth_pitch);
}
static INLINE HRESULT D3D12ReadFromSubresource(
void* resource,
void* dst_data,
UINT dst_row_pitch,
UINT dst_depth_pitch,
UINT src_subresource,
D3D12_BOX* src_box)
{
return ((ID3D12Resource*)resource)
->lpVtbl->ReadFromSubresource(
(ID3D12Resource*)resource, dst_data, dst_row_pitch, dst_depth_pitch, src_subresource,
src_box);
}
static INLINE HRESULT D3D12GetHeapProperties(
void* resource, D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS* heap_flags)
{
return ((ID3D12Resource*)resource)
->lpVtbl->GetHeapProperties((ID3D12Resource*)resource, heap_properties, heap_flags);
}
static INLINE ULONG D3D12ReleaseCommandAllocator(D3D12CommandAllocator command_allocator)
{
return command_allocator->lpVtbl->Release(command_allocator);
}
static INLINE HRESULT D3D12ResetCommandAllocator(D3D12CommandAllocator command_allocator)
{
return command_allocator->lpVtbl->Reset(command_allocator);
}
static INLINE ULONG D3D12ReleaseFence(D3D12Fence fence) { return fence->lpVtbl->Release(fence); }
static INLINE UINT64 D3D12GetCompletedValue(D3D12Fence fence)
{
return fence && fence->lpVtbl->GetCompletedValue(fence);
}
static INLINE HRESULT D3D12SetEventOnCompletion(D3D12Fence fence, UINT64 value, HANDLE h_event)
{
return fence->lpVtbl->SetEventOnCompletion(fence, value, h_event);
}
static INLINE HRESULT D3D12SignalFence(D3D12Fence fence, UINT64 value)
{
return fence->lpVtbl->Signal(fence, value);
}
static INLINE ULONG D3D12ReleasePipelineState(D3D12PipelineState pipeline_state)
{
return pipeline_state->lpVtbl->Release(pipeline_state);
}
static INLINE HRESULT D3D12GetCachedBlob(D3D12PipelineState pipeline_state, ID3DBlob** blob)
{
return pipeline_state->lpVtbl->GetCachedBlob(pipeline_state, blob);
}
static INLINE ULONG D3D12ReleaseDescriptorHeap(D3D12DescriptorHeap descriptor_heap)
{
return descriptor_heap->lpVtbl->Release(descriptor_heap);
}
static INLINE ULONG D3D12ReleaseQueryHeap(D3D12QueryHeap query_heap)
{
return query_heap->lpVtbl->Release(query_heap);
}
static INLINE ULONG D3D12ReleaseCommandSignature(D3D12CommandSignature command_signature)
{
return command_signature->lpVtbl->Release(command_signature);
}
static INLINE ULONG D3D12ReleaseCommandList(D3D12CommandList command_list)
{
return command_list->lpVtbl->Release(command_list);
}
static INLINE ULONG D3D12ReleaseGraphicsCommandList(D3D12GraphicsCommandList graphics_command_list)
{
return graphics_command_list->lpVtbl->Release(graphics_command_list);
}
static INLINE HRESULT D3D12CloseGraphicsCommandList(D3D12GraphicsCommandList graphics_command_list)
{
return graphics_command_list->lpVtbl->Close(graphics_command_list);
}
static INLINE HRESULT D3D12ResetGraphicsCommandList(
D3D12GraphicsCommandList graphics_command_list,
D3D12CommandAllocator allocator,
D3D12PipelineState initial_state)
{
return graphics_command_list->lpVtbl->Reset(graphics_command_list, allocator, initial_state);
}
static INLINE void
D3D12ClearState(D3D12GraphicsCommandList graphics_command_list, D3D12PipelineState pipeline_state)
{
graphics_command_list->lpVtbl->ClearState(graphics_command_list, pipeline_state);
}
static INLINE void D3D12DrawInstanced(
D3D12GraphicsCommandList graphics_command_list,
UINT vertex_count_per_instance,
UINT instance_count,
UINT start_vertex_location,
UINT start_instance_location)
{
graphics_command_list->lpVtbl->DrawInstanced(
graphics_command_list, vertex_count_per_instance, instance_count, start_vertex_location,
start_instance_location);
}
static INLINE void D3D12DrawIndexedInstanced(
D3D12GraphicsCommandList graphics_command_list,
UINT index_count_per_instance,
UINT instance_count,
UINT start_index_location,
INT base_vertex_location,
UINT start_instance_location)
{
graphics_command_list->lpVtbl->DrawIndexedInstanced(
graphics_command_list, index_count_per_instance, instance_count, start_index_location,
base_vertex_location, start_instance_location);
}
static INLINE void D3D12Dispatch(
D3D12GraphicsCommandList graphics_command_list,
UINT thread_group_count_x,
UINT thread_group_count_y,
UINT thread_group_count_z)
{
graphics_command_list->lpVtbl->Dispatch(
graphics_command_list, thread_group_count_x, thread_group_count_y, thread_group_count_z);
}
static INLINE void D3D12CopyBufferRegion(
D3D12GraphicsCommandList graphics_command_list,
D3D12Resource dst_buffer,
UINT64 dst_offset,
D3D12Resource src_buffer,
UINT64 src_offset,
UINT64 num_bytes)
{
graphics_command_list->lpVtbl->CopyBufferRegion(
graphics_command_list, dst_buffer, dst_offset, (ID3D12Resource*)src_buffer, src_offset,
num_bytes);
}
static INLINE void D3D12CopyTextureRegion(
D3D12GraphicsCommandList graphics_command_list,
D3D12_TEXTURE_COPY_LOCATION* dst,
UINT dst_x,
UINT dst_y,
UINT dst_z,
D3D12_TEXTURE_COPY_LOCATION* src,
D3D12_BOX* src_box)
{
graphics_command_list->lpVtbl->CopyTextureRegion(
graphics_command_list, dst, dst_x, dst_y, dst_z, src, src_box);
}
static INLINE void D3D12CopyResource(
D3D12GraphicsCommandList graphics_command_list, void* dst_resource, void* src_resource)
{
graphics_command_list->lpVtbl->CopyResource(
graphics_command_list, (ID3D12Resource*)dst_resource, (ID3D12Resource*)src_resource);
}
static INLINE void D3D12CopyTiles(
D3D12GraphicsCommandList graphics_command_list,
void* tiled_resource,
D3D12_TILED_RESOURCE_COORDINATE* tile_region_start_coordinate,
D3D12_TILE_REGION_SIZE* tile_region_size,
void* buffer,
UINT64 buffer_start_offset_in_bytes,
D3D12_TILE_COPY_FLAGS flags)
{
graphics_command_list->lpVtbl->CopyTiles(
graphics_command_list, (ID3D12Resource*)tiled_resource, tile_region_start_coordinate,
tile_region_size, (ID3D12Resource*)buffer, buffer_start_offset_in_bytes, flags);
}
static INLINE void D3D12ResolveSubresource(
D3D12GraphicsCommandList graphics_command_list,
void* dst_resource,
UINT dst_subresource,
void* src_resource,
UINT src_subresource,
DXGI_FORMAT format)
{
graphics_command_list->lpVtbl->ResolveSubresource(
graphics_command_list, (ID3D12Resource*)dst_resource, dst_subresource,
(ID3D12Resource*)src_resource, src_subresource, format);
}
static INLINE void D3D12IASetPrimitiveTopology(
D3D12GraphicsCommandList graphics_command_list, D3D12_PRIMITIVE_TOPOLOGY primitive_topology)
{
graphics_command_list->lpVtbl->IASetPrimitiveTopology(graphics_command_list, primitive_topology);
}
static INLINE void D3D12RSSetViewports(
D3D12GraphicsCommandList graphics_command_list, UINT num_viewports, D3D12_VIEWPORT* viewports)
{
graphics_command_list->lpVtbl->RSSetViewports(graphics_command_list, num_viewports, viewports);
}
static INLINE void D3D12RSSetScissorRects(
D3D12GraphicsCommandList graphics_command_list, UINT num_rects, D3D12_RECT* rects)
{
graphics_command_list->lpVtbl->RSSetScissorRects(graphics_command_list, num_rects, rects);
}
static INLINE void
D3D12OMSetStencilRef(D3D12GraphicsCommandList graphics_command_list, UINT stencil_ref)
{
graphics_command_list->lpVtbl->OMSetStencilRef(graphics_command_list, stencil_ref);
}
static INLINE void D3D12SetPipelineState(
D3D12GraphicsCommandList graphics_command_list, D3D12PipelineStateRef pipeline_state)
{
graphics_command_list->lpVtbl->SetPipelineState(graphics_command_list, (D3D12PipelineState)pipeline_state);
}
static INLINE void D3D12ResourceBarrier(
D3D12GraphicsCommandList graphics_command_list,
UINT num_barriers,
D3D12_RESOURCE_BARRIER* barriers)
{
graphics_command_list->lpVtbl->ResourceBarrier(graphics_command_list, num_barriers, barriers);
}
static INLINE void D3D12ExecuteBundle(
D3D12GraphicsCommandList graphics_command_list, D3D12GraphicsCommandList command_list)
{
graphics_command_list->lpVtbl->ExecuteBundle(graphics_command_list, command_list);
}
static INLINE void D3D12SetComputeRootSignature(
D3D12GraphicsCommandList graphics_command_list, D3D12RootSignature root_signature)
{
graphics_command_list->lpVtbl->SetComputeRootSignature(graphics_command_list, root_signature);
}
static INLINE void D3D12SetGraphicsRootSignature(
D3D12GraphicsCommandList graphics_command_list, D3D12RootSignature root_signature)
{
graphics_command_list->lpVtbl->SetGraphicsRootSignature(graphics_command_list, root_signature);
}
static INLINE void D3D12SetComputeRootDescriptorTable(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_DESCRIPTOR_HANDLE base_descriptor)
{
graphics_command_list->lpVtbl->SetComputeRootDescriptorTable(
graphics_command_list, root_parameter_index, base_descriptor);
}
static INLINE void D3D12SetGraphicsRootDescriptorTable(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_DESCRIPTOR_HANDLE base_descriptor)
{
graphics_command_list->lpVtbl->SetGraphicsRootDescriptorTable(
graphics_command_list, root_parameter_index, base_descriptor);
}
static INLINE void D3D12SetComputeRoot32BitConstant(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
UINT src_data,
UINT dest_offset_in32_bit_values)
{
graphics_command_list->lpVtbl->SetComputeRoot32BitConstant(
graphics_command_list, root_parameter_index, src_data, dest_offset_in32_bit_values);
}
static INLINE void D3D12SetGraphicsRoot32BitConstant(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
UINT src_data,
UINT dest_offset_in32_bit_values)
{
graphics_command_list->lpVtbl->SetGraphicsRoot32BitConstant(
graphics_command_list, root_parameter_index, src_data, dest_offset_in32_bit_values);
}
static INLINE void D3D12SetComputeRoot32BitConstants(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
UINT num32_bit_values_to_set,
void* src_data,
UINT dest_offset_in32_bit_values)
{
graphics_command_list->lpVtbl->SetComputeRoot32BitConstants(
graphics_command_list, root_parameter_index, num32_bit_values_to_set, src_data,
dest_offset_in32_bit_values);
}
static INLINE void D3D12SetGraphicsRoot32BitConstants(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
UINT num32_bit_values_to_set,
void* src_data,
UINT dest_offset_in32_bit_values)
{
graphics_command_list->lpVtbl->SetGraphicsRoot32BitConstants(
graphics_command_list, root_parameter_index, num32_bit_values_to_set, src_data,
dest_offset_in32_bit_values);
}
static INLINE void D3D12SetComputeRootConstantBufferView(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_VIRTUAL_ADDRESS buffer_location)
{
graphics_command_list->lpVtbl->SetComputeRootConstantBufferView(
graphics_command_list, root_parameter_index, buffer_location);
}
static INLINE void D3D12SetGraphicsRootConstantBufferView(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_VIRTUAL_ADDRESS buffer_location)
{
graphics_command_list->lpVtbl->SetGraphicsRootConstantBufferView(
graphics_command_list, root_parameter_index, buffer_location);
}
static INLINE void D3D12SetComputeRootShaderResourceView(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_VIRTUAL_ADDRESS buffer_location)
{
graphics_command_list->lpVtbl->SetComputeRootShaderResourceView(
graphics_command_list, root_parameter_index, buffer_location);
}
static INLINE void D3D12SetGraphicsRootShaderResourceView(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_VIRTUAL_ADDRESS buffer_location)
{
graphics_command_list->lpVtbl->SetGraphicsRootShaderResourceView(
graphics_command_list, root_parameter_index, buffer_location);
}
static INLINE void D3D12SetComputeRootUnorderedAccessView(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_VIRTUAL_ADDRESS buffer_location)
{
graphics_command_list->lpVtbl->SetComputeRootUnorderedAccessView(
graphics_command_list, root_parameter_index, buffer_location);
}
static INLINE void D3D12SetGraphicsRootUnorderedAccessView(
D3D12GraphicsCommandList graphics_command_list,
UINT root_parameter_index,
D3D12_GPU_VIRTUAL_ADDRESS buffer_location)
{
graphics_command_list->lpVtbl->SetGraphicsRootUnorderedAccessView(
graphics_command_list, root_parameter_index, buffer_location);
}
static INLINE void
D3D12IASetIndexBuffer(D3D12GraphicsCommandList graphics_command_list, D3D12_INDEX_BUFFER_VIEW* view)
{
graphics_command_list->lpVtbl->IASetIndexBuffer(graphics_command_list, view);
}
static INLINE void D3D12IASetVertexBuffers(
D3D12GraphicsCommandList graphics_command_list,
UINT start_slot,
UINT num_views,
D3D12_VERTEX_BUFFER_VIEW* views)
{
graphics_command_list->lpVtbl->IASetVertexBuffers(
graphics_command_list, start_slot, num_views, views);
}
static INLINE void D3D12SOSetTargets(
D3D12GraphicsCommandList graphics_command_list,
UINT start_slot,
UINT num_views,
D3D12_STREAM_OUTPUT_BUFFER_VIEW* views)
{
graphics_command_list->lpVtbl->SOSetTargets(graphics_command_list, start_slot, num_views, views);
}
static INLINE void D3D12OMSetRenderTargets(
D3D12GraphicsCommandList graphics_command_list,
UINT num_render_target_descriptors,
D3D12_CPU_DESCRIPTOR_HANDLE* render_target_descriptors,
BOOL r_ts_single_handle_to_descriptor_range,
D3D12_CPU_DESCRIPTOR_HANDLE* depth_stencil_descriptor)
{
graphics_command_list->lpVtbl->OMSetRenderTargets(
graphics_command_list, num_render_target_descriptors, render_target_descriptors,
r_ts_single_handle_to_descriptor_range, depth_stencil_descriptor);
}
static INLINE void D3D12ClearDepthStencilView(
D3D12GraphicsCommandList graphics_command_list,
D3D12_CPU_DESCRIPTOR_HANDLE depth_stencil_view,
D3D12_CLEAR_FLAGS clear_flags,
FLOAT depth,
UINT8 stencil,
UINT num_rects,
D3D12_RECT* rects)
{
graphics_command_list->lpVtbl->ClearDepthStencilView(
graphics_command_list, depth_stencil_view, clear_flags, depth, stencil, num_rects, rects);
}
static INLINE void D3D12DiscardResource(
D3D12GraphicsCommandList graphics_command_list, void* resource, D3D12_DISCARD_REGION* region)
{
graphics_command_list->lpVtbl->DiscardResource(
graphics_command_list, (ID3D12Resource*)resource, region);
}
static INLINE void D3D12BeginQuery(
D3D12GraphicsCommandList graphics_command_list,
D3D12QueryHeap query_heap,
D3D12_QUERY_TYPE type,
UINT index)
{
graphics_command_list->lpVtbl->BeginQuery(graphics_command_list, query_heap, type, index);
}
static INLINE void D3D12EndQuery(
D3D12GraphicsCommandList graphics_command_list,
D3D12QueryHeap query_heap,
D3D12_QUERY_TYPE type,
UINT index)
{
graphics_command_list->lpVtbl->EndQuery(graphics_command_list, query_heap, type, index);
}
static INLINE void D3D12ResolveQueryData(
D3D12GraphicsCommandList graphics_command_list,
D3D12QueryHeap query_heap,
D3D12_QUERY_TYPE type,
UINT start_index,
UINT num_queries,
void* destination_buffer,
UINT64 aligned_destination_buffer_offset)
{
graphics_command_list->lpVtbl->ResolveQueryData(
graphics_command_list, query_heap, type, start_index, num_queries,
(ID3D12Resource*)destination_buffer, aligned_destination_buffer_offset);
}
static INLINE void D3D12SetPredication(
D3D12GraphicsCommandList graphics_command_list,
void* buffer,
UINT64 aligned_buffer_offset,
D3D12_PREDICATION_OP operation)
{
graphics_command_list->lpVtbl->SetPredication(
graphics_command_list, (ID3D12Resource*)buffer, aligned_buffer_offset, operation);
}
static INLINE void D3D12SetGraphicsCommandListMarker(
D3D12GraphicsCommandList graphics_command_list, UINT metadata, void* data, UINT size)
{
graphics_command_list->lpVtbl->SetMarker(graphics_command_list, metadata, data, size);
}
static INLINE void D3D12BeginGraphicsCommandListEvent(
D3D12GraphicsCommandList graphics_command_list, UINT metadata, void* data, UINT size)
{
graphics_command_list->lpVtbl->BeginEvent(graphics_command_list, metadata, data, size);
}
static INLINE void D3D12EndGraphicsCommandListEvent(D3D12GraphicsCommandList graphics_command_list)
{
graphics_command_list->lpVtbl->EndEvent(graphics_command_list);
}
static INLINE void D3D12ExecuteIndirect(
D3D12GraphicsCommandList graphics_command_list,
D3D12CommandSignature command_signature,
UINT max_command_count,
void* argument_buffer,
UINT64 argument_buffer_offset,
void* count_buffer,
UINT64 count_buffer_offset)
{
graphics_command_list->lpVtbl->ExecuteIndirect(
graphics_command_list, command_signature, max_command_count,
(ID3D12Resource*)argument_buffer, argument_buffer_offset, (ID3D12Resource*)count_buffer,
count_buffer_offset);
}
static INLINE ULONG D3D12ReleaseCommandQueue(D3D12CommandQueue command_queue)
{
return command_queue->lpVtbl->Release(command_queue);
}
static INLINE void D3D12UpdateTileMappings(
D3D12CommandQueue command_queue,
void* resource,
UINT num_resource_regions,
D3D12_TILED_RESOURCE_COORDINATE* resource_region_start_coordinates,
D3D12_TILE_REGION_SIZE* resource_region_sizes,
D3D12Heap heap,
UINT num_ranges,
D3D12_TILE_RANGE_FLAGS* range_flags,
UINT* heap_range_start_offsets,
UINT* range_tile_counts,
D3D12_TILE_MAPPING_FLAGS flags)
{
command_queue->lpVtbl->UpdateTileMappings(
command_queue, (ID3D12Resource*)resource, num_resource_regions,
resource_region_start_coordinates, resource_region_sizes, heap, num_ranges, range_flags,
heap_range_start_offsets, range_tile_counts, flags);
}
static INLINE void D3D12CopyTileMappings(
D3D12CommandQueue command_queue,
void* dst_resource,
D3D12_TILED_RESOURCE_COORDINATE* dst_region_start_coordinate,
void* src_resource,
D3D12_TILED_RESOURCE_COORDINATE* src_region_start_coordinate,
D3D12_TILE_REGION_SIZE* region_size,
D3D12_TILE_MAPPING_FLAGS flags)
{
command_queue->lpVtbl->CopyTileMappings(
command_queue, (ID3D12Resource*)dst_resource, dst_region_start_coordinate,
(ID3D12Resource*)src_resource, src_region_start_coordinate, region_size, flags);
}
static INLINE void
D3D12SetCommandQueueMarker(D3D12CommandQueue command_queue, UINT metadata, void* data, UINT size)
{
command_queue->lpVtbl->SetMarker(command_queue, metadata, data, size);
}
static INLINE void
D3D12BeginCommandQueueEvent(D3D12CommandQueue command_queue, UINT metadata, void* data, UINT size)
{
command_queue->lpVtbl->BeginEvent(command_queue, metadata, data, size);
}
static INLINE void D3D12EndCommandQueueEvent(D3D12CommandQueue command_queue)
{
command_queue->lpVtbl->EndEvent(command_queue);
}
static INLINE HRESULT
D3D12SignalCommandQueue(D3D12CommandQueue command_queue, D3D12Fence fence, UINT64 value)
{
return command_queue->lpVtbl->Signal(command_queue, fence, value);
}
static INLINE HRESULT D3D12Wait(D3D12CommandQueue command_queue, D3D12Fence fence, UINT64 value)
{
return command_queue->lpVtbl->Wait(command_queue, fence, value);
}
static INLINE HRESULT D3D12GetTimestampFrequency(D3D12CommandQueue command_queue, UINT64* frequency)
{
return command_queue->lpVtbl->GetTimestampFrequency(command_queue, frequency);
}
static INLINE HRESULT D3D12GetClockCalibration(
D3D12CommandQueue command_queue, UINT64* gpu_timestamp, UINT64* cpu_timestamp)
{
return command_queue->lpVtbl->GetClockCalibration(command_queue, gpu_timestamp, cpu_timestamp);
}
static INLINE ULONG D3D12ReleaseDevice(D3D12Device device)
{
return device->lpVtbl->Release(device);
}
static INLINE UINT D3D12GetNodeCount(D3D12Device device)
{
return device->lpVtbl->GetNodeCount(device);
}
static INLINE HRESULT D3D12CreateCommandQueue(
D3D12Device device, D3D12_COMMAND_QUEUE_DESC* desc, ID3D12CommandQueue** out)
{
return device->lpVtbl->CreateCommandQueue(device, desc, uuidof(ID3D12CommandQueue), (void**)out);
}
static INLINE HRESULT D3D12CreateCommandAllocator(
D3D12Device device, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator** out)
{
return device->lpVtbl->CreateCommandAllocator(
device, type, uuidof(ID3D12CommandAllocator), (void**)out);
}
static INLINE HRESULT D3D12CreateGraphicsPipelineState(
D3D12Device device, D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, ID3D12PipelineState** out)
{
return device->lpVtbl->CreateGraphicsPipelineState(
device, desc, uuidof(ID3D12PipelineState), (void**)out);
}
static INLINE HRESULT D3D12CreateComputePipelineState(
D3D12Device device, D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, ID3D12PipelineState** out)
{
return device->lpVtbl->CreateComputePipelineState(
device, desc, uuidof(ID3D12PipelineState), (void**)out);
}
static INLINE HRESULT D3D12CreateCommandList(
D3D12Device device,
UINT node_mask,
D3D12_COMMAND_LIST_TYPE type,
D3D12CommandAllocator command_allocator,
D3D12PipelineState initial_state,
ID3D12CommandList** out)
{
return device->lpVtbl->CreateCommandList(
device, node_mask, type, command_allocator, initial_state, uuidof(ID3D12CommandList),
(void**)out);
}
static INLINE HRESULT D3D12CheckFeatureSupport(
D3D12Device device,
D3D12_FEATURE feature,
void* feature_support_data,
UINT feature_support_data_size)
{
return device->lpVtbl->CheckFeatureSupport(
device, feature, feature_support_data, feature_support_data_size);
}
static INLINE HRESULT D3D12CreateDescriptorHeap(
D3D12Device device,
D3D12_DESCRIPTOR_HEAP_DESC* descriptor_heap_desc,
D3D12DescriptorHeap* out)
{
return device->lpVtbl->CreateDescriptorHeap(
device, descriptor_heap_desc, uuidof(ID3D12DescriptorHeap), (void**)out);
}
static INLINE UINT D3D12GetDescriptorHandleIncrementSize(
D3D12Device device, D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type)
{
return device->lpVtbl->GetDescriptorHandleIncrementSize(device, descriptor_heap_type);
}
static INLINE HRESULT D3D12CreateRootSignature(
D3D12Device device,
UINT node_mask,
void* blob_with_root_signature,
SIZE_T blob_length_in_bytes,
ID3D12RootSignature** out)
{
return device->lpVtbl->CreateRootSignature(
device, node_mask, blob_with_root_signature, blob_length_in_bytes,
uuidof(ID3D12RootSignature), (void**)out);
}
static INLINE void D3D12CreateConstantBufferView(
D3D12Device device,
D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor)
{
device->lpVtbl->CreateConstantBufferView(device, desc, dest_descriptor);
}
static INLINE void D3D12CreateShaderResourceView(
D3D12Device device,
D3D12Resource resource,
D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor)
{
device->lpVtbl->CreateShaderResourceView(device, resource, desc, dest_descriptor);
}
static INLINE void D3D12CreateUnorderedAccessView(
D3D12Device device,
void* resource,
void* counter_resource,
D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor)
{
device->lpVtbl->CreateUnorderedAccessView(
device, (ID3D12Resource*)resource, (ID3D12Resource*)counter_resource, desc,
dest_descriptor);
}
static INLINE void D3D12CreateRenderTargetView(
D3D12Device device,
void* resource,
D3D12_RENDER_TARGET_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor)
{
device->lpVtbl->CreateRenderTargetView(device, (ID3D12Resource*)resource, desc, dest_descriptor);
}
static INLINE void D3D12CreateDepthStencilView(
D3D12Device device,
void* resource,
D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor)
{
device->lpVtbl->CreateDepthStencilView(device, (ID3D12Resource*)resource, desc, dest_descriptor);
}
static INLINE void D3D12CreateSampler(
D3D12Device device, D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor)
{
device->lpVtbl->CreateSampler(device, desc, dest_descriptor);
}
static INLINE void D3D12CopyDescriptors(
D3D12Device device,
UINT num_dest_descriptor_ranges,
D3D12_CPU_DESCRIPTOR_HANDLE* dest_descriptor_range_starts,
UINT* dest_descriptor_range_sizes,
UINT num_src_descriptor_ranges,
D3D12_CPU_DESCRIPTOR_HANDLE* src_descriptor_range_starts,
UINT* src_descriptor_range_sizes,
D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heaps_type)
{
device->lpVtbl->CopyDescriptors(
device, num_dest_descriptor_ranges, dest_descriptor_range_starts,
dest_descriptor_range_sizes, num_src_descriptor_ranges, src_descriptor_range_starts,
src_descriptor_range_sizes, descriptor_heaps_type);
}
static INLINE void D3D12CopyDescriptorsSimple(
D3D12Device device,
UINT num_descriptors,
D3D12_CPU_DESCRIPTOR_HANDLE dest_descriptor_range_start,
D3D12_CPU_DESCRIPTOR_HANDLE src_descriptor_range_start,
D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heaps_type)
{
device->lpVtbl->CopyDescriptorsSimple(
device, num_descriptors, dest_descriptor_range_start, src_descriptor_range_start,
descriptor_heaps_type);
}
static INLINE D3D12_RESOURCE_ALLOCATION_INFO D3D12GetResourceAllocationInfo(
D3D12Device device,
UINT visible_mask,
UINT num_resource_descs,
D3D12_RESOURCE_DESC* resource_descs)
{
return device->lpVtbl->GetResourceAllocationInfo(
device, visible_mask, num_resource_descs, resource_descs);
}
static INLINE D3D12_HEAP_PROPERTIES
D3D12GetCustomHeapProperties(D3D12Device device, UINT node_mask, D3D12_HEAP_TYPE heap_type)
{
return device->lpVtbl->GetCustomHeapProperties(device, node_mask, heap_type);
}
static INLINE HRESULT D3D12CreateCommittedResource(
D3D12Device device,
D3D12_HEAP_PROPERTIES* heap_properties,
D3D12_HEAP_FLAGS heap_flags,
D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES initial_resource_state,
D3D12_CLEAR_VALUE* optimized_clear_value,
ID3D12Resource** out)
{
return device->lpVtbl->CreateCommittedResource(
device, heap_properties, heap_flags, desc, initial_resource_state, optimized_clear_value,
uuidof(ID3D12Resource), (void**)out);
}
static INLINE HRESULT D3D12CreateHeap(D3D12Device device, D3D12_HEAP_DESC* desc, ID3D12Heap** out)
{
return device->lpVtbl->CreateHeap(device, desc, uuidof(ID3D12Heap), (void**)out);
}
static INLINE HRESULT D3D12CreatePlacedResource(
D3D12Device device,
D3D12Heap heap,
UINT64 heap_offset,
D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES initial_state,
D3D12_CLEAR_VALUE* optimized_clear_value,
ID3D12Resource** out)
{
return device->lpVtbl->CreatePlacedResource(
device, heap, heap_offset, desc, initial_state, optimized_clear_value,
uuidof(ID3D12Resource), (void**)out);
}
static INLINE HRESULT D3D12CreateReservedResource(
D3D12Device device,
D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES initial_state,
D3D12_CLEAR_VALUE* optimized_clear_value,
ID3D12Resource** out)
{
return device->lpVtbl->CreateReservedResource(
device, desc, initial_state, optimized_clear_value, uuidof(ID3D12Resource), (void**)out);
}
static INLINE HRESULT D3D12CreateFence(
D3D12Device device, UINT64 initial_value, D3D12_FENCE_FLAGS flags, ID3D12Fence** out)
{
return device->lpVtbl->CreateFence(
device, initial_value, flags, uuidof(ID3D12Fence), (void**)out);
}
static INLINE HRESULT D3D12GetDeviceRemovedReason(D3D12Device device)
{
return device->lpVtbl->GetDeviceRemovedReason(device);
}
static INLINE void D3D12GetCopyableFootprints(
D3D12Device device,
D3D12_RESOURCE_DESC* resource_desc,
UINT first_subresource,
UINT num_subresources,
UINT64 base_offset,
D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts,
UINT* num_rows,
UINT64* row_size_in_bytes,
UINT64* total_bytes)
{
device->lpVtbl->GetCopyableFootprints(
device, resource_desc, first_subresource, num_subresources, base_offset, layouts, num_rows,
row_size_in_bytes, total_bytes);
}
static INLINE HRESULT
D3D12CreateQueryHeap(D3D12Device device, D3D12_QUERY_HEAP_DESC* desc, ID3D12Heap** out)
{
return device->lpVtbl->CreateQueryHeap(device, desc, uuidof(ID3D12Heap), (void**)out);
}
static INLINE HRESULT D3D12SetStablePowerState(D3D12Device device, BOOL enable)
{
return device->lpVtbl->SetStablePowerState(device, enable);
}
static INLINE HRESULT D3D12CreateCommandSignature(
D3D12Device device,
D3D12_COMMAND_SIGNATURE_DESC* desc,
D3D12RootSignature root_signature,
ID3D12CommandSignature** out)
{
return device->lpVtbl->CreateCommandSignature(
device, desc, root_signature, uuidof(ID3D12CommandSignature), (void**)out);
}
static INLINE void D3D12GetResourceTiling(
D3D12Device device,
void* tiled_resource,
UINT* num_tiles_for_entire_resource,
D3D12_PACKED_MIP_INFO* packed_mip_desc,
D3D12_TILE_SHAPE* standard_tile_shape_for_non_packed_mips,
UINT* num_subresource_tilings,
UINT first_subresource_tiling_to_get,
D3D12_SUBRESOURCE_TILING* subresource_tilings_for_non_packed_mips)
{
device->lpVtbl->GetResourceTiling(
device, (ID3D12Resource*)tiled_resource, num_tiles_for_entire_resource, packed_mip_desc,
standard_tile_shape_for_non_packed_mips, num_subresource_tilings,
first_subresource_tiling_to_get, subresource_tilings_for_non_packed_mips);
}
static INLINE LUID D3D12GetAdapterLuid(D3D12Device device)
{
return device->lpVtbl->GetAdapterLuid(device);
}
static INLINE ULONG D3D12ReleasePipelineLibrary(D3D12PipelineLibrary pipeline_library)
{
return pipeline_library->lpVtbl->Release(pipeline_library);
}
static INLINE HRESULT
D3D12StorePipeline(D3D12PipelineLibrary pipeline_library, LPCWSTR name, D3D12PipelineState pipeline)
{
return pipeline_library->lpVtbl->StorePipeline(pipeline_library, name, pipeline);
}
static INLINE HRESULT D3D12LoadGraphicsPipeline(
D3D12PipelineLibrary pipeline_library,
LPCWSTR name,
D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
ID3D12PipelineState** out)
{
return pipeline_library->lpVtbl->LoadGraphicsPipeline(
pipeline_library, name, desc, uuidof(ID3D12PipelineState), (void**)out);
}
static INLINE HRESULT D3D12LoadComputePipeline(
D3D12PipelineLibrary pipeline_library,
LPCWSTR name,
D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
ID3D12PipelineState** out)
{
return pipeline_library->lpVtbl->LoadComputePipeline(
pipeline_library, name, desc, uuidof(ID3D12PipelineState), (void**)out);
}
static INLINE SIZE_T D3D12GetSerializedSize(D3D12PipelineLibrary pipeline_library)
{
return pipeline_library->lpVtbl->GetSerializedSize(pipeline_library);
}
static INLINE HRESULT
D3D12Serialize(D3D12PipelineLibrary pipeline_library, void* data, SIZE_T data_size_in_bytes)
{
return pipeline_library->lpVtbl->Serialize(pipeline_library, data, data_size_in_bytes);
}
static INLINE ULONG D3D12ReleaseDebug(D3D12Debug debug) { return debug->lpVtbl->Release(debug); }
static INLINE void D3D12EnableDebugLayer(D3D12Debug debug)
{
debug->lpVtbl->EnableDebugLayer(debug);
}
static INLINE ULONG D3D12ReleaseDebugDevice(D3D12DebugDevice debug_device)
{
return debug_device->lpVtbl->Release(debug_device);
}
static INLINE HRESULT
D3D12SetDebugDeviceFeatureMask(D3D12DebugDevice debug_device, D3D12_DEBUG_FEATURE mask)
{
return debug_device->lpVtbl->SetFeatureMask(debug_device, mask);
}
static INLINE D3D12_DEBUG_FEATURE D3D12GetDebugDeviceFeatureMask(D3D12DebugDevice debug_device)
{
return debug_device->lpVtbl->GetFeatureMask(debug_device);
}
static INLINE HRESULT
D3D12ReportLiveDeviceObjects(D3D12DebugDevice debug_device, D3D12_RLDO_FLAGS flags)
{
return debug_device->lpVtbl->ReportLiveDeviceObjects(debug_device, flags);
}
static INLINE ULONG D3D12ReleaseDebugCommandQueue(D3D12DebugCommandQueue debug_command_queue)
{
return debug_command_queue->lpVtbl->Release(debug_command_queue);
}
static INLINE BOOL D3D12AssertDebugCommandQueueResourceState(
D3D12DebugCommandQueue debug_command_queue, void* resource, UINT subresource, UINT state)
{
return debug_command_queue->lpVtbl->AssertResourceState(
debug_command_queue, (ID3D12Resource*)resource, subresource, state);
}
static INLINE ULONG D3D12ReleaseDebugCommandList(D3D12DebugCommandList debug_command_list)
{
return debug_command_list->lpVtbl->Release(debug_command_list);
}
static INLINE BOOL D3D12AssertDebugCommandListResourceState(
D3D12DebugCommandList debug_command_list, void* resource, UINT subresource, UINT state)
{
return debug_command_list->lpVtbl->AssertResourceState(
debug_command_list, (ID3D12Resource*)resource, subresource, state);
}
static INLINE HRESULT D3D12SetDebugCommandListFeatureMask(
D3D12DebugCommandList debug_command_list, D3D12_DEBUG_FEATURE mask)
{
return debug_command_list->lpVtbl->SetFeatureMask(debug_command_list, mask);
}
static INLINE D3D12_DEBUG_FEATURE
D3D12GetDebugCommandListFeatureMask(D3D12DebugCommandList debug_command_list)
{
return debug_command_list->lpVtbl->GetFeatureMask(debug_command_list);
}
static INLINE ULONG D3D12ReleaseInfoQueue(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->Release(info_queue);
}
static INLINE HRESULT
D3D12SetMessageCountLimit(D3D12InfoQueue info_queue, UINT64 message_count_limit)
{
return info_queue->lpVtbl->SetMessageCountLimit(info_queue, message_count_limit);
}
static INLINE void D3D12ClearStoredMessages(D3D12InfoQueue info_queue)
{
info_queue->lpVtbl->ClearStoredMessages(info_queue);
}
#ifndef __WINRT__
static INLINE HRESULT D3D12GetMessageA(
D3D12InfoQueue info_queue,
UINT64 message_index,
D3D12_MESSAGE* message,
SIZE_T* message_byte_length)
{
return info_queue->lpVtbl->GetMessageA(info_queue, message_index, message, message_byte_length);
}
#endif
static INLINE UINT64 D3D12GetNumMessagesAllowedByStorageFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetNumMessagesAllowedByStorageFilter(info_queue);
}
static INLINE UINT64 D3D12GetNumMessagesDeniedByStorageFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetNumMessagesDeniedByStorageFilter(info_queue);
}
static INLINE UINT64 D3D12GetNumStoredMessages(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetNumStoredMessages(info_queue);
}
static INLINE UINT64 D3D12GetNumStoredMessagesAllowedByRetrievalFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetNumStoredMessagesAllowedByRetrievalFilter(info_queue);
}
static INLINE UINT64 D3D12GetNumMessagesDiscardedByMessageCountLimit(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetNumMessagesDiscardedByMessageCountLimit(info_queue);
}
static INLINE UINT64 D3D12GetMessageCountLimit(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetMessageCountLimit(info_queue);
}
static INLINE HRESULT
D3D12AddStorageFilterEntries(D3D12InfoQueue info_queue, D3D12_INFO_QUEUE_FILTER* filter)
{
return info_queue->lpVtbl->AddStorageFilterEntries(info_queue, filter);
}
static INLINE HRESULT D3D12GetStorageFilter(
D3D12InfoQueue info_queue, D3D12_INFO_QUEUE_FILTER* filter, SIZE_T* filter_byte_length)
{
return info_queue->lpVtbl->GetStorageFilter(info_queue, filter, filter_byte_length);
}
static INLINE void D3D12ClearStorageFilter(D3D12InfoQueue info_queue)
{
info_queue->lpVtbl->ClearStorageFilter(info_queue);
}
static INLINE HRESULT D3D12PushEmptyStorageFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->PushEmptyStorageFilter(info_queue);
}
static INLINE HRESULT D3D12PushCopyOfStorageFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->PushCopyOfStorageFilter(info_queue);
}
static INLINE HRESULT
D3D12PushStorageFilter(D3D12InfoQueue info_queue, D3D12_INFO_QUEUE_FILTER* filter)
{
return info_queue->lpVtbl->PushStorageFilter(info_queue, filter);
}
static INLINE void D3D12PopStorageFilter(D3D12InfoQueue info_queue)
{
info_queue->lpVtbl->PopStorageFilter(info_queue);
}
static INLINE UINT D3D12GetStorageFilterStackSize(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetStorageFilterStackSize(info_queue);
}
static INLINE HRESULT
D3D12AddRetrievalFilterEntries(D3D12InfoQueue info_queue, D3D12_INFO_QUEUE_FILTER* filter)
{
return info_queue->lpVtbl->AddRetrievalFilterEntries(info_queue, filter);
}
static INLINE HRESULT D3D12GetRetrievalFilter(
D3D12InfoQueue info_queue, D3D12_INFO_QUEUE_FILTER* filter, SIZE_T* filter_byte_length)
{
return info_queue->lpVtbl->GetRetrievalFilter(info_queue, filter, filter_byte_length);
}
static INLINE void D3D12ClearRetrievalFilter(D3D12InfoQueue info_queue)
{
info_queue->lpVtbl->ClearRetrievalFilter(info_queue);
}
static INLINE HRESULT D3D12PushEmptyRetrievalFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->PushEmptyRetrievalFilter(info_queue);
}
static INLINE HRESULT D3D12PushCopyOfRetrievalFilter(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->PushCopyOfRetrievalFilter(info_queue);
}
static INLINE HRESULT
D3D12PushRetrievalFilter(D3D12InfoQueue info_queue, D3D12_INFO_QUEUE_FILTER* filter)
{
return info_queue->lpVtbl->PushRetrievalFilter(info_queue, filter);
}
static INLINE void D3D12PopRetrievalFilter(D3D12InfoQueue info_queue)
{
info_queue->lpVtbl->PopRetrievalFilter(info_queue);
}
static INLINE UINT D3D12GetRetrievalFilterStackSize(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetRetrievalFilterStackSize(info_queue);
}
static INLINE HRESULT D3D12AddMessage(
D3D12InfoQueue info_queue,
D3D12_MESSAGE_CATEGORY category,
D3D12_MESSAGE_SEVERITY severity,
D3D12_MESSAGE_ID i_d,
LPCSTR description)
{
return info_queue->lpVtbl->AddMessage(info_queue, category, severity, i_d, description);
}
static INLINE HRESULT D3D12AddApplicationMessage(
D3D12InfoQueue info_queue, D3D12_MESSAGE_SEVERITY severity, LPCSTR description)
{
return info_queue->lpVtbl->AddApplicationMessage(info_queue, severity, description);
}
static INLINE HRESULT
D3D12SetBreakOnCategory(D3D12InfoQueue info_queue, D3D12_MESSAGE_CATEGORY category, BOOL b_enable)
{
return info_queue->lpVtbl->SetBreakOnCategory(info_queue, category, b_enable);
}
static INLINE HRESULT
D3D12SetBreakOnSeverity(D3D12InfoQueue info_queue, D3D12_MESSAGE_SEVERITY severity, BOOL b_enable)
{
return info_queue->lpVtbl->SetBreakOnSeverity(info_queue, severity, b_enable);
}
static INLINE HRESULT
D3D12SetBreakOnID(D3D12InfoQueue info_queue, D3D12_MESSAGE_ID i_d, BOOL b_enable)
{
return info_queue->lpVtbl->SetBreakOnID(info_queue, i_d, b_enable);
}
static INLINE BOOL
D3D12GetBreakOnCategory(D3D12InfoQueue info_queue, D3D12_MESSAGE_CATEGORY category)
{
return info_queue->lpVtbl->GetBreakOnCategory(info_queue, category);
}
static INLINE BOOL
D3D12GetBreakOnSeverity(D3D12InfoQueue info_queue, D3D12_MESSAGE_SEVERITY severity)
{
return info_queue->lpVtbl->GetBreakOnSeverity(info_queue, severity);
}
static INLINE BOOL D3D12GetBreakOnID(D3D12InfoQueue info_queue, D3D12_MESSAGE_ID i_d)
{
return info_queue->lpVtbl->GetBreakOnID(info_queue, i_d);
}
static INLINE void D3D12SetMuteDebugOutput(D3D12InfoQueue info_queue, BOOL b_mute)
{
info_queue->lpVtbl->SetMuteDebugOutput(info_queue, b_mute);
}
static INLINE BOOL D3D12GetMuteDebugOutput(D3D12InfoQueue info_queue)
{
return info_queue->lpVtbl->GetMuteDebugOutput(info_queue);
}
/* end of auto-generated */
static INLINE HRESULT D3D12GetDebugInterface_(D3D12Debug* out)
{
return D3D12GetDebugInterface(uuidof(ID3D12Debug), (void**)out);
}
static INLINE HRESULT
D3D12CreateDevice_(DXGIAdapter adapter, D3D_FEATURE_LEVEL MinimumFeatureLevel, D3D12Device* out)
{
return D3D12CreateDevice(
(IUnknown*)adapter, MinimumFeatureLevel, uuidof(ID3D12Device), (void**)out);
}
static INLINE HRESULT D3D12CreateGraphicsCommandList(
D3D12Device device,
UINT node_mask,
D3D12_COMMAND_LIST_TYPE type,
D3D12CommandAllocator command_allocator,
D3D12PipelineState initial_state,
D3D12GraphicsCommandList* out)
{
return device->lpVtbl->CreateCommandList(
device, node_mask, type, command_allocator, initial_state,
uuidof(ID3D12GraphicsCommandList), (void**)out);
}
static INLINE void D3D12ClearRenderTargetView(
D3D12GraphicsCommandList command_list,
D3D12_CPU_DESCRIPTOR_HANDLE render_target_view,
const FLOAT colorRGBA[4],
UINT num_rects,
const D3D12_RECT* rects)
{
command_list->lpVtbl->ClearRenderTargetView(
command_list, render_target_view, colorRGBA, num_rects, rects);
}
static INLINE void D3D12ExecuteCommandLists(
D3D12CommandQueue command_queue,
UINT num_command_lists,
const D3D12CommandList* command_lists)
{
command_queue->lpVtbl->ExecuteCommandLists(command_queue, num_command_lists, command_lists);
}
static INLINE void D3D12ExecuteGraphicsCommandLists(
D3D12CommandQueue command_queue,
UINT num_command_lists,
const D3D12GraphicsCommandList* command_lists)
{
command_queue->lpVtbl->ExecuteCommandLists(
command_queue, num_command_lists, (ID3D12CommandList* const*)command_lists);
}
static INLINE HRESULT
DXGIGetSwapChainBuffer(DXGISwapChain swapchain, UINT buffer, D3D12Resource* surface)
{
return swapchain->lpVtbl->GetBuffer(swapchain, buffer, uuidof(ID3D12Resource), (void**)surface);
}
static INLINE void D3D12SetDescriptorHeaps(
D3D12GraphicsCommandList command_list,
UINT num_descriptor_heaps,
const D3D12DescriptorHeap* descriptor_heaps)
{
command_list->lpVtbl->SetDescriptorHeaps(command_list, num_descriptor_heaps, descriptor_heaps);
}
#if 0 /* function prototype is wrong ... */
static INLINE D3D12_CPU_DESCRIPTOR_HANDLE D3D12GetCPUDescriptorHandleForHeapStart(
D3D12DescriptorHeap descriptor_heap)
{
return descriptor_heap->lpVtbl->GetCPUDescriptorHandleForHeapStart(descriptor_heap);
}
static INLINE D3D12_GPU_DESCRIPTOR_HANDLE D3D12GetGPUDescriptorHandleForHeapStart(
D3D12DescriptorHeap descriptor_heap)
{
return descriptor_heap->lpVtbl->GetGPUDescriptorHandleForHeapStart(descriptor_heap);
}
#else
static INLINE D3D12_CPU_DESCRIPTOR_HANDLE
D3D12GetCPUDescriptorHandleForHeapStart(D3D12DescriptorHeap descriptor_heap)
{
D3D12_CPU_DESCRIPTOR_HANDLE out;
((void(STDMETHODCALLTYPE*)(ID3D12DescriptorHeap*, D3D12_CPU_DESCRIPTOR_HANDLE*))
descriptor_heap->lpVtbl->GetCPUDescriptorHandleForHeapStart)(descriptor_heap, &out);
return out;
}
static INLINE D3D12_GPU_DESCRIPTOR_HANDLE
D3D12GetGPUDescriptorHandleForHeapStart(D3D12DescriptorHeap descriptor_heap)
{
D3D12_GPU_DESCRIPTOR_HANDLE out;
((void(STDMETHODCALLTYPE*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*))
descriptor_heap->lpVtbl->GetGPUDescriptorHandleForHeapStart)(descriptor_heap, &out);
return out;
}
#endif
/* internal */
#include <retro_math.h>
#include <retro_common_api.h>
#include <gfx/math/matrix_4x4.h>
#include "../common/d3dcompiler_common.h"
#include "../../retroarch.h"
#include "../drivers_shader/slang_process.h"
#define D3D12_MAX_GPU_COUNT 16
typedef struct d3d12_vertex_t
{
float position[2];
float texcoord[2];
float color[4];
} d3d12_vertex_t;
typedef struct
{
struct
{
float x, y, w, h;
} pos;
struct
{
float u, v, w, h;
} coords;
UINT32 colors[4];
struct
{
float scaling;
float rotation;
} params;
} d3d12_sprite_t;
typedef struct
{
D3D12DescriptorHeap handle; /* descriptor pool */
D3D12_DESCRIPTOR_HEAP_DESC desc;
D3D12_CPU_DESCRIPTOR_HANDLE cpu; /* descriptor */
D3D12_GPU_DESCRIPTOR_HANDLE gpu; /* descriptor */
UINT stride;
bool* map;
int start;
} d3d12_descriptor_heap_t;
typedef struct
{
D3D12Resource handle;
D3D12Resource upload_buffer;
D3D12_RESOURCE_DESC desc;
/* the first view is srv, the rest are mip levels uavs */
D3D12_CPU_DESCRIPTOR_HANDLE cpu_descriptor[D3D12_MAX_TEXTURE_DIMENSION_2_TO_EXP - 5];
D3D12_GPU_DESCRIPTOR_HANDLE gpu_descriptor[D3D12_MAX_TEXTURE_DIMENSION_2_TO_EXP - 5];
D3D12_GPU_DESCRIPTOR_HANDLE sampler;
D3D12_CPU_DESCRIPTOR_HANDLE rt_view;
D3D12_PLACED_SUBRESOURCE_FOOTPRINT layout;
UINT num_rows;
UINT64 row_size_in_bytes;
UINT64 total_bytes;
d3d12_descriptor_heap_t* srv_heap;
bool dirty;
float4_t size_data;
} d3d12_texture_t;
#ifndef ALIGN
#ifdef _MSC_VER
#define ALIGN(x) __declspec(align(x))
#else
#define ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
typedef struct ALIGN(16)
{
math_matrix_4x4 mvp;
struct
{
float width;
float height;
} OutputSize;
float time;
} d3d12_uniform_t;
typedef struct
{
unsigned cur_mon_id;
#ifdef __WINRT__
DXGIFactory2 factory;
#else
DXGIFactory factory;
#endif
DXGIAdapter adapter;
D3D12Device device;
IDXGIAdapter1 *adapters[D3D12_MAX_GPU_COUNT];
struct string_list *gpu_list;
struct
{
D3D12CommandQueue handle;
D3D12CommandAllocator allocator;
D3D12GraphicsCommandList cmd;
D3D12Fence fence;
HANDLE fenceEvent;
UINT64 fenceValue;
} queue;
struct
{
D3D12RootSignature cs_rootSignature; /* descriptor layout */
D3D12RootSignature sl_rootSignature; /* descriptor layout */
D3D12RootSignature rootSignature; /* descriptor layout */
d3d12_descriptor_heap_t srv_heap; /* ShaderResouceView descritor heap */
d3d12_descriptor_heap_t rtv_heap; /* RenderTargetView descritor heap */
d3d12_descriptor_heap_t sampler_heap;
} desc;
struct
{
DXGISwapChain handle;
D3D12Resource renderTargets[2];
D3D12_CPU_DESCRIPTOR_HANDLE desc_handles[2];
D3D12_VIEWPORT viewport;
D3D12_RECT scissorRect;
float clearcolor[4];
int frame_index;
bool vsync;
} chain;
struct
{
d3d12_texture_t texture[GFX_MAX_FRAME_HISTORY + 1];
D3D12Resource ubo;
D3D12_CONSTANT_BUFFER_VIEW_DESC ubo_view;
D3D12Resource vbo;
D3D12_VERTEX_BUFFER_VIEW vbo_view;
D3D12_VIEWPORT viewport;
D3D12_RECT scissorRect;
float4_t output_size;
int rotation;
} frame;
struct
{
D3D12Resource vbo;
D3D12_VERTEX_BUFFER_VIEW vbo_view;
d3d12_texture_t texture;
float alpha;
bool enabled;
bool fullscreen;
} menu;
struct
{
D3D12PipelineStateRef pipe;
D3D12PipelineState pipe_blend;
D3D12PipelineState pipe_noblend;
D3D12PipelineState pipe_font;
D3D12Resource vbo;
D3D12_VERTEX_BUFFER_VIEW vbo_view;
int offset;
int capacity;
bool enabled;
} sprites;
#ifdef HAVE_OVERLAY
struct
{
D3D12Resource vbo;
D3D12_VERTEX_BUFFER_VIEW vbo_view;
d3d12_texture_t* textures;
bool enabled;
bool fullscreen;
int count;
} overlays;
#endif
struct
{
D3D12PipelineState pipe;
D3D12_GPU_DESCRIPTOR_HANDLE sampler;
D3D12Resource buffers[SLANG_CBUFFER_MAX];
D3D12_CONSTANT_BUFFER_VIEW_DESC buffer_view[SLANG_CBUFFER_MAX];
d3d12_texture_t rt;
d3d12_texture_t feedback;
D3D12_VIEWPORT viewport;
D3D12_RECT scissorRect;
pass_semantics_t semantics;
uint32_t frame_count;
int32_t frame_direction;
D3D12_GPU_DESCRIPTOR_HANDLE textures;
D3D12_GPU_DESCRIPTOR_HANDLE samplers;
} pass[GFX_MAX_SHADERS];
struct video_shader* shader_preset;
d3d12_texture_t luts[GFX_MAX_TEXTURES];
D3D12PipelineState pipes[GFX_MAX_SHADERS];
D3D12PipelineState mipmapgen_pipe;
d3d12_uniform_t ubo_values;
D3D12Resource ubo;
D3D12_CONSTANT_BUFFER_VIEW_DESC ubo_view;
DXGI_FORMAT format;
D3D12_GPU_DESCRIPTOR_HANDLE samplers[RARCH_FILTER_MAX][RARCH_WRAP_MAX];
math_matrix_4x4 mvp, mvp_no_rot;
struct video_viewport vp;
bool resize_chain;
bool keep_aspect;
bool resize_viewport;
bool resize_render_targets;
bool init_history;
D3D12Resource menu_pipeline_vbo;
D3D12_VERTEX_BUFFER_VIEW menu_pipeline_vbo_view;
#ifdef DEBUG
D3D12Debug debugController;
#endif
} d3d12_video_t;
typedef enum {
ROOT_ID_TEXTURE_T = 0,
ROOT_ID_SAMPLER_T,
ROOT_ID_UBO,
ROOT_ID_PC,
ROOT_ID_MAX,
} root_signature_parameter_index_t;
typedef enum {
CS_ROOT_ID_TEXTURE_T = 0,
CS_ROOT_ID_UAV_T,
CS_ROOT_ID_CONSTANTS,
CS_ROOT_ID_MAX,
} compute_root_index_t;
RETRO_BEGIN_DECLS
extern D3D12_RENDER_TARGET_BLEND_DESC d3d12_blend_enable_desc;
bool d3d12_init_base(d3d12_video_t* d3d12);
bool d3d12_init_descriptors(d3d12_video_t* d3d12);
void d3d12_init_samplers(d3d12_video_t* d3d12);
bool d3d12_init_pipeline(
D3D12Device device,
D3DBlob vs_code,
D3DBlob ps_code,
D3DBlob gs_code,
D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
D3D12PipelineState* out);
bool d3d12_init_swapchain(d3d12_video_t* d3d12, int width, int height, void *corewindow);
bool d3d12_init_queue(d3d12_video_t* d3d12);
D3D12_GPU_VIRTUAL_ADDRESS
d3d12_create_buffer(D3D12Device device, UINT size_in_bytes, D3D12Resource* buffer);
void d3d12_init_texture(D3D12Device device, d3d12_texture_t* tex);
void d3d12_release_texture(d3d12_texture_t* texture);
void d3d12_update_texture(
int width,
int height,
int pitch,
DXGI_FORMAT format,
const void* data,
d3d12_texture_t* texture);
void d3d12_upload_texture(D3D12GraphicsCommandList cmd,
d3d12_texture_t* texture, void *userdata);
void d3d12_create_fullscreen_quad_vbo(
D3D12Device device, D3D12_VERTEX_BUFFER_VIEW* view, D3D12Resource* vbo);
DXGI_FORMAT d3d12_get_closest_match(D3D12Device device, D3D12_FEATURE_DATA_FORMAT_SUPPORT* desired);
#if !defined(__cplusplus) || defined(CINTERFACE)
static INLINE void d3d12_resource_transition(
D3D12GraphicsCommandList cmd,
D3D12Resource resource,
D3D12_RESOURCE_STATES state_before,
D3D12_RESOURCE_STATES state_after)
{
D3D12_RESOURCE_BARRIER barrier;
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
barrier.Transition.pResource = resource;
barrier.Transition.StateBefore = state_before;
barrier.Transition.StateAfter = state_after;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
D3D12ResourceBarrier(cmd, 1, &barrier);
}
static INLINE void d3d12_set_texture(D3D12GraphicsCommandList cmd, const d3d12_texture_t* texture)
{
D3D12SetGraphicsRootDescriptorTable(cmd, ROOT_ID_TEXTURE_T, texture->gpu_descriptor[0]);
}
static INLINE void
d3d12_set_sampler(D3D12GraphicsCommandList cmd, D3D12_GPU_DESCRIPTOR_HANDLE sampler)
{
D3D12SetGraphicsRootDescriptorTable(cmd, ROOT_ID_SAMPLER_T, sampler);
}
static INLINE void
d3d12_set_texture_and_sampler(D3D12GraphicsCommandList cmd, const d3d12_texture_t* texture)
{
D3D12SetGraphicsRootDescriptorTable(cmd, ROOT_ID_TEXTURE_T, texture->gpu_descriptor[0]);
D3D12SetGraphicsRootDescriptorTable(cmd, ROOT_ID_SAMPLER_T, texture->sampler);
}
#endif
RETRO_END_DECLS
|
heuripedes/RetroArch
|
gfx/common/d3d12_common.h
|
C
|
gpl-3.0
| 62,933
|
export const articleResources = [
{
topicId: 'urn:topic:170363',
id: 'urn:resource:345297a3-4134-4622-b325-c8245edb11dd',
name: 'Hva er en idé?',
resourceTypes: [],
contentUri: 'urn:article:339',
title: 'Hva er en idé?',
introduction:
'Det kan være vanskelig å begripe hva en idé er. Ideer er tett knyttet til tanker og hjernearbeid, de er nesten i slekt med drømmer. Det er vanskelig å sette ord på hva ideen handler om, og hvorfor den er god. ',
tag: 'Illustrasjoner',
type: 'Fagstoff',
additional: true,
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:6fd9f440-d91d-4bb0-89d4-757e564f77b9',
name: 'Ideer og idéutvikling',
resourceTypes: [],
contentUri: 'urn:article:165',
introduction:
'Idéutvikling og kreativt arbeid i mediebransjen handler om kommunikasjon, uansett om det dreier seg om utvikling av fortelleteknikker, teknologi eller det å kombinere kjente uttrykk på nye måter.',
title: 'Ideer og idéutvikling',
tag: 'Film',
type: 'Fagstoff',
additional: true,
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:0079aa08-8ed9-484a-bbd6-71d9297d8cab',
name: 'Kreativ kommunikasjon',
resourceTypes: [],
contentUri: 'urn:article:166',
introduction:
'Idéutvikling og kreativt arbeid i mediebransjen handler om kommunikasjon, uansett om det dreier seg om utvikling av fortelleteknikker, teknologi eller det å kombinere kjente uttrykk på nye måter.',
title: 'Kreativ kommunikasjon',
tag: 'Film',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:a7a49c0a-32ea-4343-8b11-bd6d65c24f87',
name: 'Refleksjonsoppgave om ideer og idéutvikling',
resourceTypes: [],
contentUri: 'urn:article:340',
title: 'Refleksjonsoppgave om ideer og idéutvikling',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b50',
name: 'Hvordan oppstår ideer?',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer?',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b51',
name: 'Hvordan oppstår ideer 2',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer 2',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b52',
name: 'Hvordan oppstår ideer 3',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer 3',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b53',
name: 'Hvordan oppstår ideer 4',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer 4',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b54',
name: 'Hvordan oppstår ideer 5',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer?',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170364',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b55',
name: 'Hvordan oppstår ideer 6',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer?',
type: 'Fagstoff',
},
{
topicId: 'urn:topic:170365',
id: 'urn:resource:38f1980f-8944-4c1c-b40f-531ae04e5b56',
name: 'Hvordan oppstår ideer 7',
resourceTypes: [],
contentUri: 'urn:article:341',
title: 'Hvordan oppstår ideer?',
type: 'Fagstoff',
},
];
export const learningPathResources = [
{
topicId: 'urn:topic:170363',
id: 'urn:resource:883281e0-c5ec-42d8-8365-ceb12265ce9b',
name: 'Teknikker for idéutvikling',
resourceTypes: [],
contentUri: 'urn:learningpath:30',
coverPhotoUrl: 'http://test.api.ndla.no/image-api/raw/tegner_ide.png',
title: 'Teknikker for idéutvikling',
introduction:
'Evnen til å skape og utvikle ideer står sentralt i arbeidet med medieuttrykk og kommunikasjon. I denne læringsstien kan du lære deg ulike stategier og teknikker for idéutvikling.',
type: 'Læringsstier',
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:116ce6b7-2abe-4977-9fa9-11641bfc9b2b',
name: 'Klar, ferdig, kreativ!',
type: 'Læringsstier',
resourceTypes: [
{
id: 'urn:resource-type:2',
name: 'Læringssti',
},
],
contentUri: 'urn:learningpath:91',
coverPhotoUrl: 'http://test.api.ndla.no/image-api/raw/Ide.jpg',
title: 'Klar, ferdig, kreativ!',
introduction: 'Om ulike faser i idéskapningsprosessen.',
},
{
topicId: 'urn:topic:170364',
id: 'urn:resource:',
name: 'Refleksjonsoppgave om ideer og idéutvikling',
type: 'Læringsstier',
resourceTypes: [
{
id: 'urn:resource-type:3',
name: 'Læringsstier',
},
],
contentUri: 'urn:learningpath:340',
coverPhotoUrl: 'http://test.api.ndla.no/image-api/raw/Ide.jpg',
title: 'Refleksjonsoppgave om ideer og idéutvikling',
introduction: 'Om ulike faser i idéskapningsprosessen.',
},
];
export const exerciseResources = [
{
topicId: 'urn:topic:170363',
id: 'urn:resource:883281e0-c5ec-42d8-8365-ceb12265ce9b',
name: 'Teknikker for idéutvikling',
resourceTypes: [],
contentUri: 'urn:exercises:30',
coverPhotoUrl: 'http://test.api.ndla.no/image-api/raw/tegner_ide.png',
title: 'Teknikker for idéutvikling',
introduction:
'Evnen til å skape og utvikle ideer står sentralt i arbeidet med medieuttrykk og kommunikasjon. I denne læringsstien kan du lære deg ulike stategier og teknikker for idéutvikling.',
type: 'Oppgaver og aktiviteter',
additional: true,
},
{
topicId: 'urn:topic:170363',
id: 'urn:resource:116ce6b7-2abe-4977-9fa9-11641bfc9b2b',
name: 'Klar, ferdig, kreativ!',
type: 'Oppgaver og aktiviteter',
resourceTypes: [
{
id: 'urn:resource-type:2',
name: 'Oppgaver',
},
],
contentUri: 'urn:exercises:91',
coverPhotoUrl: 'http://test.api.ndla.no/image-api/raw/Ide.jpg',
title: 'Klar, ferdig, kreativ!',
introduction: 'Om ulike faser i idéskapningsprosessen.',
},
{
topicId: 'urn:topic:170364',
id: 'urn:resource:',
name: 'Refleksjonsoppgave om ideer og idéutvikling',
type: 'Oppgaver og aktiviteter',
resourceTypes: [
{
id: 'urn:resource-type:3',
name: 'Oppgaver',
},
],
contentUri: 'urn:exercises:340',
coverPhotoUrl: 'http://test.api.ndla.no/image-api/raw/Ide.jpg',
title: 'Refleksjonsoppgave om ideer og idéutvikling',
introduction: 'Om ulike faser i idéskapningsprosessen.',
},
];
|
netliferesearch/frontend-packages
|
packages/designmanual/dummydata/mockResources.js
|
JavaScript
|
gpl-3.0
| 6,891
|
#!/bin/bash
# Change working directory
cd /
# Create script folder
mkdir EasyLinux
cd EasyLinux/
# Download scripts
wget https://raw.githubusercontent.com/Miguel-Dorta/EasyLinux/master/scripts/user-inputs.sh
wget https://raw.githubusercontent.com/Miguel-Dorta/EasyLinux/master/scripts/installer.sh
wget https://raw.githubusercontent.com/Miguel-Dorta/EasyLinux/master/scripts/chroot-script.sh
chmod +x *
# Run scripts
./user-inputs.sh
./installer.sh
# Copy and run scripts in the new system
cp -R /EasyLinux/ /mnt/EasyLinux/
arch-chroot /mnt << EOF
/EasyLinux/chroot-script.sh
exit
EOF
# Umount partitions & reboot
umount -R /mnt
reboot
|
Miguel-Dorta/EasyLinux
|
easylinux.sh
|
Shell
|
gpl-3.0
| 645
|
/*
Napraviti konkurentni program koji u funkciji visina pita korisnika koliko je visok.
Nakon toga korisnik unosi svoju visinu. Na kraju u funkciji se ispisuje uneta visina.
Kreirati 2 niti od date funkcije. Ispratiti ispis.
*/
#include <iostream>
#include <thread>
using namespace std;
// Funkcija koa učitava visinu, a zatim je ispisuje
void visina() {
int h;
cout << "Koliko ste visoki?" << endl;
cin >> h;
cout << "Vasa visina je: " << h << endl;
}
int main() {
// Kreiranje niti
thread t1(visina);
thread t2(visina);
// Čekanje da se niti završe
t1.join();
t2.join();
// Dolazi do štetnog preplitanja, zbog toga
// što se ne može uticati na to kad će se desiti
return 0;
}
|
randomCharacter/OS
|
v04/stetno_preplitanje/main.cpp
|
C++
|
gpl-3.0
| 744
|
/*
* Copyright © 2011 magical
*
* This file is part of spriterip; it is licensed under the GNU GPLv3
* and comes with NO WARRANTY. See rip.c for details.
*/
#ifndef NARC_H
#define NARC_H
#include "nitro.h" /* struct format_info */
#include "common.h" /* u32 */
struct NARC;
extern struct format_info NARC_format;
extern void *narc_load_file(struct NARC *self, int index);
extern u32 narc_get_file_size(struct NARC *self, int index);
extern u32 narc_get_file_count(struct NARC *self);
#endif /* NARC_H */
|
magical/pokemon-nds-sprites
|
narc.h
|
C
|
gpl-3.0
| 515
|
/*
This file is part of QToyunda software
Copyright (C) 2013 Sylvain "Skarsnik" Colinet <scolinet@gmail.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/>.
*/
#ifndef NEWTIMEDIALOG_H
#define NEWTIMEDIALOG_H
#include <QDialog>
namespace Ui {
class NewTimeDialog;
}
class NewTimeDialog : public QDialog
{
Q_OBJECT
public:
explicit NewTimeDialog(QWidget *parent = 0);
~NewTimeDialog();
QString lyrFile;
QString frmFile;
QString iniFile;
QString videoFile;
QString subFile;
QString baseDir;
private slots:
void on_titleEdit_textEdited(const QString &arg1);
void on_prefixEdit_textEdited(const QString &arg1);
void on_videoChooseButton_clicked();
void on_lyrChooseButton_clicked();
void on_frmChooseButton_clicked();
void on_buttonBox_accepted();
private:
Ui::NewTimeDialog *ui;
bool m_lyrChoosed;
bool m_frmChoosed;
bool m_iniChoosed;
void setBaseDir(QString file);
};
#endif // NEWTIMEDIALOG_H
|
Toyunda/toyunda
|
QToyTime/newtimedialog.h
|
C
|
gpl-3.0
| 1,621
|
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
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/
**********************************************************************/
//
// Main.java
//
// Salvador Garc�a L�pez
//
// Created by Salvador Garc�a L�pez 19-7-2004.
// Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//
package keel.Algorithms.Instance_Selection.GA_MSE_CC_FSM;
public class Main {
public static void main (String args[]) {
GA_MSE_CC_FSM ga;
if (args.length != 1)
System.err.println("Error. A parameter is only needed.");
else {
ga = new GA_MSE_CC_FSM (args[0]);
ga.ejecutar();
}
}
}
|
adofsauron/KEEL
|
src/keel/Algorithms/Instance_Selection/GA_MSE_CC_FSM/Main.java
|
Java
|
gpl-3.0
| 1,655
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__).'/Acl.php';
class User
{
private $CI;
private $table = 'users';
private $lang;
private $acl;
private $errors = array();
private $user_id;
private $user_user;
private $user_name;
private $user_email;
private $user_status;
private $user_active;
private $user_role;
private $user_avatar;
private $pattern = "/^([-a-z0-9_-])+$/i";
public function __construct($options = array())
{
$this->CI =& get_instance();
$this->_set_language(isset($options['lang']) ? $options['lang'] : null);
$row = null;
if(isset($options['id']) && (int)$options['id'] > 0) {
$row = $this->_row(array('id' => (int)$options['id']));
if(sizeof($row) == 0) {
show_error($this->CI->lang->line('user_error_invalid_user'));
}
} elseif((int) $this->CI->session->userdata('user_id') > 0) {
$row = $this->_row(array('id' => $this->CI->session->userdata('user_id')));
if(sizeof($row) == 0 || $row->active != 1 || $row->status != 1) {
$this->CI->session->sess_destroy();
$this->_load(null);
return;
}
}
$this->_load($row);
}
public function __get($name)
{
$property = 'user_' . $name;
if(isset($this->$property)) {
return $this->$property;
}
}
public function token()
{
$token = md5(uniqid(rand(), true));
$this->CI->session->set_userdata('token', $token);
return $token;
}
public function errors()
{
return $this->errors;
}
public function permissions()
{
return $this->acl->permissions;
}
public function site_permissions()
{
return $this->acl->site_permissions;
}
public function has_permission($name)
{
return $this->acl->has_permission($name);
}
public function is_logged_in()
{
if($this->user_id > 0) {
return $this->user_id == (int) $this->CI->session->userdata('user_id');
}
return FALSE;
}
public function login($user, $password, $hash = 'sha256')
{
if(empty($user) || !preg_match($this->pattern, $user)) {
$this->errors[] = $this->CI->lang->line('user_error_username');
}
if(empty($password)) {
$this->errors[] = $this->CI->lang->line('user_error_empty_password');
}
if(count($this->errors)) {
return FALSE;
}
$this->CI->load->library('encrypt');
$row = $this->_row(array('user' => $user, 'password' => $this->CI->encrypt->password($password, $hash)));
if(sizeof($row) == 0 || $row->active != 1 || $row->status != 1) {
$this->errors[] = $this->CI->lang->line('user_error_wrong_credentials');
return FALSE;
}
$this->_load($row);
return TRUE;
}
private function _load($row = null)
{
if($row == null || sizeof($row) == 0) {
$this->user_id = 0;
$this->user_user = $this->CI->lang->line('cms_general_label_site_visitor_user');
$this->user_name = $this->CI->lang->line('cms_general_label_site_visitor_name');
$this->user_email = '';
$this->user_active = 0;
$this->user_status = 0;
$this->user_role = 0;
$this->user_avatar = '';
$this->acl = new Acl(array('lang' => $this->lang));
return;
}
$this->user_id = $row->id;
$this->user_user = $row->user;
$this->user_name = $row->name;
$this->user_email = $row->email;
$this->user_active = $row->active;
$this->user_status = $row->status;
$this->user_role = $row->role;
$this->user_avatar = $row->avatar;
$this->acl = new Acl(array('id' => $row->id,'lang' => $this->lang));
}
private function _row($where = null, $select = null)
{
if(is_array($where)) {
$this->CI->db->where($where);
}
if(is_array($select)) {
$this->CI->db->select($select);
}
return $this->CI->db->get($this->table)->row();
}
private function _set_language($lang = null)
{
$languages = array('english', 'spanish');
if( !$lang) {
if(in_array($this->CI->config->item('language'), $languages)) {
$lang = $this->CI->config->item('language');
} else {
$lang = $languages[0];
}
} else {
if( !in_array($lang, $languages)) {
$lang = $languages[0];
}
}
$this->lang = $lang;
$this->CI->load->language('user', $lang);
}
}
/* End of file User.php */
/* Location: ./application/libraries/User.php */
|
jolupeza/mailing-ad
|
application/libraries/User.php
|
PHP
|
gpl-3.0
| 5,006
|
#ifdef DECAF_GL
#include "glsl2/glsl2_translate.h"
#include "gpu_config.h"
#include "latte/latte_formats.h"
#include "latte/latte_registers.h"
#include "latte/latte_disassembler.h"
#include "opengl_constants.h"
#include "opengl_driver.h"
#include <common/decaf_assert.h>
#include <common/log.h>
#include <common/murmur3.h>
#include <common/platform_dir.h>
#include <common/strutils.h>
#include <fstream>
#include <glbinding/gl/gl.h>
#include <libcpu/mem.h>
#include <spdlog/spdlog.h>
namespace opengl
{
// TODO: This is really some kind of 'nsight compat mode'... Maybe
// it should even be a configurable option (related to force_sync).
static const auto USE_PERSISTENT_MAP = true;
// This represents the number of bytes of padding to attach to the end
// of an attribute buffer. This is neccessary for cases where the game
// fetches past the edge of a buffer, but does not use it.
static const auto BUFFER_PADDING = 16;
// Enable workaround for NVIDIA GLSL compiler bug which incorrectly fails
// on "layout(xfb_buffer = A, xfb_stride = B)" syntax when some buffers
// have different strides than others.
static const auto NVIDIA_GLSL_WORKAROUND = true;
static void
dumpRawShader(const std::string &type, ppcaddr_t data, uint32_t size, bool isSubroutine = false)
{
if (!gpu::config::dump_shaders) {
return;
}
std::string filePath = fmt::format("dump/gpu_{}_{:08x}.txt", type, data);
if (platform::fileExists(filePath)) {
return;
}
platform::createDirectory("dump");
auto file = std::ofstream{ filePath, std::ofstream::out };
// Disassemble
auto output = latte::disassemble(gsl::make_span(mem::translate<uint8_t>(data), size), isSubroutine);
file << output << std::endl;
}
static void
dumpTranslatedShader(const std::string &type, ppcaddr_t data, const std::string &shaderSource)
{
if (!gpu::config::dump_shaders) {
return;
}
std::string filePath = fmt::format("dump/gpu_{}_{:08x}.glsl", type, data);
if (platform::fileExists(filePath)) {
return;
}
platform::createDirectory("dump");
auto file = std::ofstream{ filePath, std::ofstream::out };
file << shaderSource << std::endl;
}
static gl::GLenum
getDataFormatGlType(latte::SQ_DATA_FORMAT format)
{
// Some Special Cases
switch (format) {
case latte::SQ_DATA_FORMAT::FMT_10_10_10_2:
case latte::SQ_DATA_FORMAT::FMT_2_10_10_10:
return gl::GL_UNSIGNED_INT;
}
auto bitCount = latte::getDataFormatComponentBits(format);
switch (bitCount) {
case 8:
return gl::GL_UNSIGNED_BYTE;
case 16:
return gl::GL_UNSIGNED_SHORT;
case 32:
return gl::GL_UNSIGNED_INT;
default:
decaf_abort(fmt::format("Unimplemented attribute bit count: {} for {}", bitCount, format));
}
}
static void
deleteShaderObject(FetchShader *shader)
{
gl::glDeleteVertexArrays(1, &shader->object);
}
static void
deleteShaderObject(VertexShader *shader)
{
gl::glDeleteProgram(shader->object);
}
static void
deleteShaderObject(PixelShader *shader)
{
gl::glDeleteProgram(shader->object);
}
template <typename ShaderPtrType> static bool
invalidateShaderIfChanged(ShaderPtrType &shader,
uint64_t shaderKey,
std::unordered_map<uint64_t, ShaderPtrType> &shaders,
ResourceMemoryMap &resourceMap)
{
if (!shader || !shader->needRebuild) {
return false;
}
// Check whether the shader has actually changed; we want to avoid
// recompiling shaders if possible, since that's very slow.
// Note that we don't save this, which means we have to compute it
// twice if we end up recreating the shader, but that cost is tiny
// compared to the time it takes to actually create the shader.
uint64_t newHash[2] = { 0, 0 };
MurmurHash3_x64_128(mem::translate(shader->cpuMemStart), shader->cpuMemEnd - shader->cpuMemStart, 0, newHash);
if (newHash[0] == shader->cpuMemHash[0] && newHash[1] == shader->cpuMemHash[1]) {
shader->needRebuild = false;
return false;
}
// The shader contents have changed, so delete the existing object
deleteShaderObject(shader);
shader->object = 0;
shader->refCount--;
if (shader->refCount == 0) {
resourceMap.removeResource(shader);
delete shader;
}
shader = nullptr;
// Also clear out the table entry (but leave it allocated since we're
// about to reuse it). Do this last in case shader is referencing the
// entry itself.
shaders[shaderKey] = nullptr;
return true;
}
bool GLDriver::checkActiveShader()
{
auto pgm_start_fs = getRegister<latte::SQ_PGM_START_FS>(latte::Register::SQ_PGM_START_FS);
auto pgm_start_vs = getRegister<latte::SQ_PGM_START_VS>(latte::Register::SQ_PGM_START_VS);
auto pgm_start_ps = getRegister<latte::SQ_PGM_START_PS>(latte::Register::SQ_PGM_START_PS);
auto pgm_size_fs = getRegister<latte::SQ_PGM_SIZE_FS>(latte::Register::SQ_PGM_SIZE_FS);
auto pgm_size_vs = getRegister<latte::SQ_PGM_SIZE_VS>(latte::Register::SQ_PGM_SIZE_VS);
auto pgm_size_ps = getRegister<latte::SQ_PGM_SIZE_PS>(latte::Register::SQ_PGM_SIZE_PS);
auto cb_shader_mask = getRegister<latte::CB_SHADER_MASK>(latte::Register::CB_SHADER_MASK);
auto db_shader_control = getRegister<latte::DB_SHADER_CONTROL>(latte::Register::DB_SHADER_CONTROL);
auto sx_alpha_test_control = getRegister<latte::SX_ALPHA_TEST_CONTROL>(latte::Register::SX_ALPHA_TEST_CONTROL);
auto sx_alpha_ref = getRegister<latte::SX_ALPHA_REF>(latte::Register::SX_ALPHA_REF);
auto vgt_strmout_en = getRegister<latte::VGT_STRMOUT_EN>(latte::Register::VGT_STRMOUT_EN);
auto pa_cl_clip_cntl = getRegister<latte::PA_CL_CLIP_CNTL>(latte::Register::PA_CL_CLIP_CNTL);
auto vgt_primitive_type = getRegister<latte::VGT_PRIMITIVE_TYPE>(latte::Register::VGT_PRIMITIVE_TYPE);
auto isScreenSpace = (vgt_primitive_type.PRIM_TYPE() == latte::VGT_DI_PRIMITIVE_TYPE::RECTLIST);
if (!pgm_start_fs.PGM_START()) {
gLog->error("Fetch shader was not set");
return false;
}
if (!pgm_start_vs.PGM_START()) {
gLog->error("Vertex shader was not set");
return false;
}
if (!vgt_strmout_en.STREAMOUT() && !pgm_start_ps.PGM_START()) {
gLog->error("Pixel shader was not set (and transform feedback was not enabled)");
return false;
}
auto fsPgmAddress = pgm_start_fs.PGM_START() << 8;
auto vsPgmAddress = pgm_start_vs.PGM_START() << 8;
auto psPgmAddress = pgm_start_ps.PGM_START() << 8;
auto fsPgmSize = pgm_size_fs.PGM_SIZE() << 3;
auto vsPgmSize = pgm_size_vs.PGM_SIZE() << 3;
auto psPgmSize = pgm_size_ps.PGM_SIZE() << 3;
auto z_order = db_shader_control.Z_ORDER();
auto early_z = (z_order == latte::DB_Z_ORDER::EARLY_Z_THEN_LATE_Z || z_order == latte::DB_Z_ORDER::EARLY_Z_THEN_RE_Z);
auto alphaTestFunc = sx_alpha_test_control.ALPHA_FUNC();
if (!sx_alpha_test_control.ALPHA_TEST_ENABLE() || sx_alpha_test_control.ALPHA_TEST_BYPASS()) {
alphaTestFunc = latte::REF_FUNC::ALWAYS;
}
// We don't currently handle offsets, so panic if any are nonzero
decaf_check(getRegister<uint32_t>(latte::Register::SQ_PGM_CF_OFFSET_PS) == 0);
decaf_check(getRegister<uint32_t>(latte::Register::SQ_PGM_CF_OFFSET_VS) == 0);
decaf_check(getRegister<uint32_t>(latte::Register::SQ_PGM_CF_OFFSET_GS) == 0);
decaf_check(getRegister<uint32_t>(latte::Register::SQ_PGM_CF_OFFSET_ES) == 0);
decaf_check(getRegister<uint32_t>(latte::Register::SQ_PGM_CF_OFFSET_FS) == 0);
// Make FS key
auto fsShaderKey = static_cast<uint64_t>(fsPgmAddress) << 32;
// Make VS key
auto vsShaderKey = static_cast<uint64_t>(vsPgmAddress) << 32;
vsShaderKey ^= (isScreenSpace ? 1ull : 0ull) << 31;
if (vgt_strmout_en.STREAMOUT()) {
vsShaderKey |= 1;
for (auto i = 0u; i < latte::MaxStreamOutBuffers; ++i) {
auto vgt_strmout_vtx_stride = getRegister<uint32_t>(latte::Register::VGT_STRMOUT_VTX_STRIDE_0 + 16 * i);
vsShaderKey ^= vgt_strmout_vtx_stride << (1ull + 7 * i);
}
}
// Make PS key
uint64_t psShaderKey;
if (pa_cl_clip_cntl.RASTERISER_DISABLE()) {
psShaderKey = 0;
} else {
psShaderKey = static_cast<uint64_t>(psPgmAddress) << 32;
psShaderKey |= static_cast<uint64_t>(alphaTestFunc) << 28;
psShaderKey |= static_cast<uint64_t>(early_z) << 27;
psShaderKey |= static_cast<uint64_t>(db_shader_control.Z_EXPORT_ENABLE()) << 26;
psShaderKey |= cb_shader_mask.value & 0xFF;
}
if (mActiveShader
&& mActiveShader->fetch && !mActiveShader->fetch->needRebuild && mActiveShader->fetchKey == fsShaderKey
&& mActiveShader->vertex && !mActiveShader->vertex->needRebuild && mActiveShader->vertexKey == vsShaderKey
&& (!mActiveShader->pixel || !mActiveShader->pixel->needRebuild) && mActiveShader->pixelKey == psShaderKey) {
// We already have the current shader bound, nothing special to do.
return true;
}
auto shaderKey = ShaderPipelineKey { fsShaderKey, vsShaderKey, psShaderKey };
auto &pipeline = mShaderPipelines[shaderKey];
// If the pipeline already exists, check whether any of its component
// shaders need to be rebuilt
if (pipeline.object) {
if (invalidateShaderIfChanged(pipeline.fetch, fsShaderKey, mFetchShaders, mResourceMap)
|| invalidateShaderIfChanged(pipeline.vertex, vsShaderKey, mVertexShaders, mResourceMap)
|| invalidateShaderIfChanged(pipeline.pixel, psShaderKey, mPixelShaders, mResourceMap)) {
gl::glDeleteProgramPipelines(1, &pipeline.object);
pipeline.object = 0;
}
}
auto getProgramLog = [](auto program) {
gl::GLint logLength = 0;
std::string logMessage;
gl::glGetProgramiv(program, gl::GL_INFO_LOG_LENGTH, &logLength);
logMessage.resize(logLength);
gl::glGetProgramInfoLog(program, logLength, &logLength, &logMessage[0]);
return logMessage;
};
// Generate shader if needed
if (!pipeline.object) {
// Parse fetch shader if needed
auto &fetchShader = mFetchShaders[fsShaderKey];
invalidateShaderIfChanged(fetchShader, fsShaderKey, mFetchShaders, mResourceMap);
if (!fetchShader) {
auto aluDivisor0 = getRegister<uint32_t>(latte::Register::VGT_INSTANCE_STEP_RATE_0);
auto aluDivisor1 = getRegister<uint32_t>(latte::Register::VGT_INSTANCE_STEP_RATE_1);
fetchShader = new FetchShader {};
fetchShader->cpuMemStart = fsPgmAddress;
fetchShader->cpuMemEnd = fsPgmAddress + fsPgmSize;
MurmurHash3_x64_128(mem::translate(fetchShader->cpuMemStart),
fetchShader->cpuMemEnd - fetchShader->cpuMemStart,
0, fetchShader->cpuMemHash);
fetchShader->dirtyMemory = false;
mResourceMap.addResource(fetchShader);
dumpRawShader("fetch", fsPgmAddress, fsPgmSize, true);
fetchShader->disassembly = latte::disassemble(gsl::make_span(mem::translate<uint8_t>(fsPgmAddress), fsPgmSize), true);
if (!parseFetchShader(*fetchShader, mem::translate(fsPgmAddress), fsPgmSize)) {
gLog->error("Failed to parse fetch shader");
return false;
}
// Setup attrib format
gl::glCreateVertexArrays(1, &fetchShader->object);
if (gpu::config::debug) {
std::string label = fmt::format("fetch shader @ 0x{:08X}", fsPgmAddress);
gl::glObjectLabel(gl::GL_VERTEX_ARRAY, fetchShader->object, -1, label.c_str());
}
auto bufferUsed = std::array<bool, latte::MaxAttributes> { false };
auto bufferDivisor = std::array<uint32_t, latte::MaxAttributes> { 0 };
for (auto &attrib : fetchShader->attribs) {
auto resourceId = attrib.buffer + latte::SQ_RES_OFFSET::VS_TEX_RESOURCE_0;
if (resourceId >= latte::SQ_RES_OFFSET::VS_ATTRIB_RESOURCE_0 && resourceId < latte::SQ_RES_OFFSET::VS_ATTRIB_RESOURCE_0 + 0x10) {
auto attribBufferId = resourceId - latte::SQ_RES_OFFSET::VS_ATTRIB_RESOURCE_0;
auto type = getDataFormatGlType(attrib.format);
auto components = latte::getDataFormatComponents(attrib.format);
auto divisor = 0u;
gl::glEnableVertexArrayAttrib(fetchShader->object, attrib.location);
gl::glVertexArrayAttribIFormat(fetchShader->object, attrib.location, components, type, attrib.offset);
gl::glVertexArrayAttribBinding(fetchShader->object, attrib.location, attribBufferId);
if (attrib.type == latte::SQ_VTX_FETCH_TYPE::INSTANCE_DATA) {
if (attrib.srcSelX == latte::SQ_SEL::SEL_W) {
divisor = 1;
} else if (attrib.srcSelX == latte::SQ_SEL::SEL_Y) {
divisor = aluDivisor0;
} else if (attrib.srcSelX == latte::SQ_SEL::SEL_Z) {
divisor = aluDivisor1;
} else {
decaf_abort(fmt::format("Unexpected SRC_SEL_X {} for alu divisor", attrib.srcSelX));
}
}
decaf_assert(!bufferUsed[attribBufferId] || bufferDivisor[attribBufferId] == divisor,
"Multiple attributes conflict on buffer divisor mode");
bufferUsed[attribBufferId] = true;
bufferDivisor[attribBufferId] = divisor;
} else {
decaf_abort("We do not yet support binding of non-attribute buffers");
}
}
for (auto bufferId = 0; bufferId < latte::MaxAttributes; ++bufferId) {
if (bufferUsed[bufferId]) {
gl::glVertexArrayBindingDivisor(fetchShader->object, bufferId, bufferDivisor[bufferId]);
}
}
}
pipeline.fetch = fetchShader;
pipeline.fetch->refCount++;
pipeline.fetchKey = fsShaderKey;
// Compile vertex shader if needed
auto &vertexShader = mVertexShaders[vsShaderKey];
invalidateShaderIfChanged(vertexShader, vsShaderKey, mVertexShaders, mResourceMap);
if (!vertexShader) {
vertexShader = new VertexShader;
vertexShader->cpuMemStart = vsPgmAddress;
vertexShader->cpuMemEnd = vsPgmAddress + vsPgmSize;
MurmurHash3_x64_128(mem::translate(vertexShader->cpuMemStart),
vertexShader->cpuMemEnd - vertexShader->cpuMemStart,
0, vertexShader->cpuMemHash);
vertexShader->dirtyMemory = false;
mResourceMap.addResource(vertexShader);
dumpRawShader("vertex", vsPgmAddress, vsPgmSize);
if (!compileVertexShader(*vertexShader, *fetchShader, mem::translate(vsPgmAddress), vsPgmSize, isScreenSpace)) {
gLog->error("Failed to recompile vertex shader");
return false;
}
dumpTranslatedShader("vertex", vsPgmAddress, vertexShader->code);
// Create OpenGL Shader
const gl::GLchar *code[] = { vertexShader->code.c_str() };
vertexShader->object = gl::glCreateShaderProgramv(gl::GL_VERTEX_SHADER, 1, code);
if (gpu::config::debug) {
std::string label = fmt::format("vertex shader @ 0x{:08X}", vsPgmAddress);
gl::glObjectLabel(gl::GL_PROGRAM, vertexShader->object, -1, label.c_str());
}
// Check if shader compiled & linked properly
gl::GLint isLinked = 0;
gl::glGetProgramiv(vertexShader->object, gl::GL_LINK_STATUS, &isLinked);
if (!isLinked) {
auto log = getProgramLog(vertexShader->object);
gLog->error("OpenGL failed to compile vertex shader:\n{}", log);
gLog->error("Fetch Disassembly:\n{}\n", fetchShader->disassembly);
gLog->error("Shader Disassembly:\n{}\n", vertexShader->disassembly);
gLog->error("Shader Code:\n{}\n", vertexShader->code);
return false;
}
// Get uniform locations
vertexShader->uniformRegisters = gl::glGetUniformLocation(vertexShader->object, "VR");
vertexShader->uniformViewport = gl::glGetUniformLocation(vertexShader->object, "uViewport");
// Get attribute locations
vertexShader->attribLocations.fill(0);
for (auto &attrib : fetchShader->attribs) {
auto name = fmt::format("fs_out_{}", attrib.location);
vertexShader->attribLocations[attrib.location] = gl::glGetAttribLocation(vertexShader->object, name.c_str());
}
}
pipeline.vertex = vertexShader;
pipeline.vertex->refCount++;
pipeline.vertexKey = vsShaderKey;
if (pa_cl_clip_cntl.RASTERISER_DISABLE()) {
// Rasterization disabled; no pixel shader used
pipeline.pixel = nullptr;
} else {
// Transform feedback disabled; compile pixel shader if needed
auto &pixelShader = mPixelShaders[psShaderKey];
invalidateShaderIfChanged(pixelShader, psShaderKey, mPixelShaders, mResourceMap);
if (!pixelShader) {
pixelShader = new PixelShader;
pixelShader->cpuMemStart = psPgmAddress;
pixelShader->cpuMemEnd = psPgmAddress + psPgmSize;
MurmurHash3_x64_128(mem::translate(pixelShader->cpuMemStart),
pixelShader->cpuMemEnd - pixelShader->cpuMemStart,
0, pixelShader->cpuMemHash);
pixelShader->dirtyMemory = false;
mResourceMap.addResource(pixelShader);
dumpRawShader("pixel", psPgmAddress, psPgmSize);
if (!compilePixelShader(*pixelShader, *vertexShader, mem::translate(psPgmAddress), psPgmSize)) {
gLog->error("Failed to recompile pixel shader");
return false;
}
dumpTranslatedShader("pixel", psPgmAddress, pixelShader->code);
// Create OpenGL Shader
const gl::GLchar *code[] = { pixelShader->code.c_str() };
pixelShader->object = gl::glCreateShaderProgramv(gl::GL_FRAGMENT_SHADER, 1, code);
if (gpu::config::debug) {
std::string label = fmt::format("pixel shader @ 0x{:08X}", psPgmAddress);
gl::glObjectLabel(gl::GL_PROGRAM, pixelShader->object, -1, label.c_str());
}
// Check if shader compiled & linked properly
gl::GLint isLinked = 0;
gl::glGetProgramiv(pixelShader->object, gl::GL_LINK_STATUS, &isLinked);
if (!isLinked) {
auto log = getProgramLog(pixelShader->object);
gLog->error("OpenGL failed to compile pixel shader:\n{}", log);
gLog->error("Shader Disassembly:\n{}\n", pixelShader->disassembly);
gLog->error("Shader Code:\n{}\n", pixelShader->code);
return false;
}
// Get uniform locations
pixelShader->uniformRegisters = gl::glGetUniformLocation(pixelShader->object, "PR");
pixelShader->uniformAlphaRef = gl::glGetUniformLocation(pixelShader->object, "uAlphaRef");
pixelShader->sx_alpha_test_control = sx_alpha_test_control;
}
pipeline.pixel = pixelShader;
pipeline.pixel->refCount++;
}
pipeline.pixelKey = psShaderKey;
// Create pipeline
gl::glCreateProgramPipelines(1, &pipeline.object);
if (gpu::config::debug) {
std::string label;
if (pipeline.pixel) {
label = fmt::format("shader set: fs = 0x{:08X}, vs = 0x{:08X}, ps = 0x{:08X}", fsPgmAddress, vsPgmAddress, psPgmAddress);
} else {
label = fmt::format("shader set: fs = 0x{:08X}, vs = 0x{:08X}, ps = none", fsPgmAddress, vsPgmAddress);
}
gl::glObjectLabel(gl::GL_PROGRAM_PIPELINE, pipeline.object, -1, label.c_str());
}
gl::glUseProgramStages(pipeline.object, gl::GL_VERTEX_SHADER_BIT, pipeline.vertex->object);
gl::glUseProgramStages(pipeline.object, gl::GL_FRAGMENT_SHADER_BIT, pipeline.pixel ? pipeline.pixel->object : 0);
}
// Set active shader
mActiveShader = &pipeline;
// Set alpha reference
if (mActiveShader->pixel && alphaTestFunc != latte::REF_FUNC::ALWAYS && alphaTestFunc != latte::REF_FUNC::NEVER) {
gl::glProgramUniform1f(mActiveShader->pixel->object, mActiveShader->pixel->uniformAlphaRef, sx_alpha_ref.ALPHA_REF());
}
// Bind fetch shader
gl::glBindVertexArray(pipeline.fetch->object);
// Bind vertex + pixel shader
gl::glBindProgramPipeline(pipeline.object);
return true;
}
int
GLDriver::countModifiedUniforms(latte::Register firstReg,
uint32_t lastUniformUpdate)
{
auto firstUniform = (firstReg - latte::Register::AluConstRegisterBase) / (4 * 4);
decaf_check(firstUniform == 0 || firstUniform == 256);
// We track uniforms in groups of 16 vectors, as a balance between the
// cost of uploading many unchanged uniforms and the cost of checking
// many individual uniforms for changes.
auto offset = firstUniform / 16;
for (auto i = 16u; i > 0; --i) {
// lastUniformUpdate is set to the newly incremented uniform update
// generation at the time of the last upload, so any uniforms whose
// update generation is at least that value need to be uploaded.
// Need to be careful with this comparison in case of wraparound!
auto diff = mLastUniformUpdate[offset + (i-1)] - lastUniformUpdate;
if (diff <= 0x7FFFFFFF) { // i.e. signed(diff) >= 0
return i * 16;
}
}
return 0;
}
bool GLDriver::checkActiveUniforms()
{
auto sq_config = getRegister<latte::SQ_CONFIG>(latte::Register::SQ_CONFIG);
if (!mActiveShader) {
return true;
}
if (sq_config.DX9_CONSTS()) {
// Upload uniform registers
if (mActiveShader->vertex && mActiveShader->vertex->object) {
auto uploadCount = countModifiedUniforms(latte::Register::SQ_ALU_CONSTANT0_256, mActiveShader->vertex->lastUniformUpdate);
if (uploadCount > 0) {
auto values = reinterpret_cast<float *>(&mRegisters[latte::Register::SQ_ALU_CONSTANT0_256 / 4]);
gl::glProgramUniform4fv(mActiveShader->vertex->object, mActiveShader->vertex->uniformRegisters, uploadCount, values);
mActiveShader->vertex->lastUniformUpdate = ++mUniformUpdateGen;
}
}
if (mActiveShader->pixel && mActiveShader->pixel->object) {
auto uploadCount = countModifiedUniforms(latte::Register::SQ_ALU_CONSTANT0_0, mActiveShader->pixel->lastUniformUpdate);
if (uploadCount > 0) {
auto values = reinterpret_cast<float *>(&mRegisters[latte::Register::SQ_ALU_CONSTANT0_0 / 4]);
gl::glProgramUniform4fv(mActiveShader->pixel->object, mActiveShader->pixel->uniformRegisters, uploadCount, values);
mActiveShader->pixel->lastUniformUpdate = ++mUniformUpdateGen;
}
}
} else {
if (mActiveShader->vertex && mActiveShader->vertex->object) {
for (auto i = 0u; i < latte::MaxUniformBlocks; ++i) {
auto sq_alu_const_cache_vs = getRegister<uint32_t>(latte::Register::SQ_ALU_CONST_CACHE_VS_0 + 4 * i);
auto sq_alu_const_buffer_size_vs = getRegister<uint32_t>(latte::Register::SQ_ALU_CONST_BUFFER_SIZE_VS_0 + 4 * i);
auto used = mActiveShader->vertex->usedUniformBlocks[i];
auto bufferObject = gl::GLuint { 0 };
if (!used || !sq_alu_const_buffer_size_vs) {
bufferObject = 0;
} else {
auto addr = sq_alu_const_cache_vs << 8;
auto size = sq_alu_const_buffer_size_vs << 8;
// Check that we can fit the uniform block into OpenGL buffers
decaf_assert(size <= opengl::MaxUniformBlockSize,
fmt::format("Active uniform block with data size {} greater than what OpenGL supports {}", size, opengl::MaxUniformBlockSize));
auto buffer = getDataBuffer(addr, size, true, false);
bufferObject = buffer->object;
}
// Bind (or unbind) block
if (mUniformBlockCache[i].vsObject != bufferObject) {
mUniformBlockCache[i].vsObject = bufferObject;
gl::glBindBufferBase(gl::GL_UNIFORM_BUFFER, i, bufferObject);
}
}
}
if (mActiveShader->pixel && mActiveShader->pixel->object) {
for (auto i = 0u; i < latte::MaxUniformBlocks; ++i) {
auto sq_alu_const_cache_ps = getRegister<uint32_t>(latte::Register::SQ_ALU_CONST_CACHE_PS_0 + 4 * i);
auto sq_alu_const_buffer_size_ps = getRegister<uint32_t>(latte::Register::SQ_ALU_CONST_BUFFER_SIZE_PS_0 + 4 * i);
auto used = mActiveShader->pixel->usedUniformBlocks[i];
auto bufferObject = gl::GLuint { 0 };
if (!used || !sq_alu_const_buffer_size_ps) {
bufferObject = 0;
} else {
auto addr = sq_alu_const_cache_ps << 8;
auto size = sq_alu_const_buffer_size_ps << 8;
auto buffer = getDataBuffer(addr, size, true, false);
bufferObject = buffer->object;
}
// Bind (or unbind) block
if (mUniformBlockCache[i].psObject != bufferObject) {
mUniformBlockCache[i].psObject = bufferObject;
gl::glBindBufferBase(gl::GL_UNIFORM_BUFFER, 16 + i, bufferObject);
}
}
}
}
return true;
}
DataBuffer *
GLDriver::getDataBuffer(uint32_t address,
uint32_t size,
bool isInput,
bool isOutput)
{
decaf_check(size);
decaf_check(isInput || isOutput);
DataBuffer *buffer = &mDataBuffers[address];
if (buffer->object
&& buffer->allocatedSize >= size
&& !(isInput && !buffer->isInput)
&& !(isOutput && !buffer->isOutput)) {
return buffer; // No changes needed
}
auto oldObject = buffer->object;
auto oldSize = buffer->allocatedSize;
auto oldMappedBuffer = buffer->mappedBuffer;
if (oldObject && (address != buffer->cpuMemStart || address + size != buffer->cpuMemEnd)) {
if (buffer->isOutput) {
mOutputBufferMap.removeResource(buffer);
}
mResourceMap.removeResource(buffer);
}
buffer->cpuMemStart = address;
buffer->cpuMemEnd = address + size;
buffer->allocatedSize = size;
buffer->mappedBuffer = nullptr;
buffer->isInput |= isInput;
buffer->isOutput |= isOutput;
// Never map output (transform feedback) buffers, because the only way
// to safely read data from them is by first calling glFinish(). With
// a non-mapped buffer, when we call glGet[Named]BufferSubData(), the
// driver can potentially wait just until that buffer is up to date
// without having to block on all other commands.
auto shouldMap = USE_PERSISTENT_MAP && !buffer->isOutput;
gl::glCreateBuffers(1, &buffer->object);
if (gpu::config::debug) {
const char *type = "output-only";
if (buffer->isInput) {
type = buffer->isOutput ? "input/output" : "input-only";
}
auto label = fmt::format("{} buffer @ 0x{:08X}", type, address);
gl::glObjectLabel(gl::GL_BUFFER, buffer->object, -1, label.c_str());
}
auto usage = gl::BufferStorageMask::GL_NONE_BIT;
if (buffer->isInput) {
if (shouldMap) {
usage |= gl::GL_MAP_WRITE_BIT;
} else {
usage |= gl::GL_DYNAMIC_STORAGE_BIT;
}
}
if (buffer->isOutput) {
usage |= gl::GL_CLIENT_STORAGE_BIT;
}
if (shouldMap) {
usage |= gl::GL_MAP_PERSISTENT_BIT;
}
gl::glNamedBufferStorage(buffer->object, size + BUFFER_PADDING, nullptr, usage);
if (oldObject) {
if (oldMappedBuffer) {
gl::glUnmapNamedBuffer(oldObject);
buffer->mappedBuffer = nullptr;
}
gl::glCopyNamedBufferSubData(oldObject, buffer->object, 0, 0, std::min(oldSize, size));
gl::glDeleteBuffers(1, &oldObject);
}
if (shouldMap) {
auto access = gl::GL_MAP_PERSISTENT_BIT;
if (buffer->isInput) {
access |= gl::GL_MAP_WRITE_BIT | gl::GL_MAP_FLUSH_EXPLICIT_BIT;
}
if (buffer->isOutput) {
access |= gl::GL_MAP_READ_BIT;
}
buffer->mappedBuffer = gl::glMapNamedBufferRange(buffer->object, 0, size + BUFFER_PADDING, access);
}
// Unconditionally upload the initial data store for attribute and
// uniform buffers. This has to be done after mapping, since if we're
// using maps, we can't update the buffer via glBufferSubData (because
// we didn't specify GL_DYNAMIC_STORAGE_BIT).
if (isInput) {
if (!oldObject) {
uploadDataBuffer(buffer, 0, size);
} else if (size > oldSize) {
uploadDataBuffer(buffer, oldSize, size - oldSize);
}
}
mResourceMap.addResource(buffer);
if (buffer->isOutput) {
mOutputBufferMap.addResource(buffer);
}
return buffer;
}
void
GLDriver::downloadDataBuffer(DataBuffer *buffer,
uint32_t offset,
uint32_t size)
{
if (buffer->mappedBuffer) {
// We only map input-only buffers (see getDataBuffer()), so there's
// no need for a memory barrier here.
decaf_check(!buffer->isOutput);
memcpy(mem::translate<char>(buffer->cpuMemStart) + offset,
static_cast<char *>(buffer->mappedBuffer) + offset,
size);
} else {
gl::glGetNamedBufferSubData(buffer->object, offset, size,
mem::translate<char>(buffer->cpuMemStart) + offset);
}
}
void
GLDriver::uploadDataBuffer(DataBuffer *buffer,
uint32_t offset,
uint32_t size)
{
// Avoid uploading the data if it hasn't changed.
uint64_t newHash[2] = { 0, 0 };
MurmurHash3_x64_128(mem::translate(buffer->cpuMemStart), buffer->allocatedSize, 0, newHash);
if (newHash[0] != buffer->cpuMemHash[0] || newHash[1] != buffer->cpuMemHash[1]) {
buffer->cpuMemHash[0] = newHash[0];
buffer->cpuMemHash[1] = newHash[1];
// We currently can't detect where the change occurred, so upload
// the entire buffer. If we don't do this, the following sequence
// will result in incorrect GPU-side data:
// 1) Client modifies two disjoint regions A and B of the buffer.
// 2) Client calls GX2Invalidate() on region A.
// 3) We detect that the hash has changed and upload region A.
// 4) Client calls GX2Invalidate() on region B.
// 5) We detect that the hash is unchanged and don't upload
// region B.
// Now region B has incorrect data on the host GPU.
// TODO: Find a better way to allow partial updates.
offset = 0;
size = buffer->allocatedSize;
if (buffer->mappedBuffer) {
memcpy(static_cast<char *>(buffer->mappedBuffer) + offset,
mem::translate<char>(buffer->cpuMemStart) + offset,
size);
gl::glFlushMappedNamedBufferRange(buffer->object, offset, size);
buffer->dirtyMap = true;
} else {
gl::glNamedBufferSubData(buffer->object, offset, size,
mem::translate<char>(buffer->cpuMemStart) + offset);
}
}
}
bool
GLDriver::checkActiveAttribBuffers()
{
if (!mActiveShader
|| !mActiveShader->fetch || !mActiveShader->fetch->object
|| !mActiveShader->vertex || !mActiveShader->vertex->object) {
return false;
}
auto needMemoryBarrier = false;
for (auto i = 0u; i < latte::MaxAttributes; ++i) {
auto resourceOffset = (latte::SQ_RES_OFFSET::VS_ATTRIB_RESOURCE_0 + i) * 7;
auto sq_vtx_constant_word0 = getRegister<latte::SQ_VTX_CONSTANT_WORD0_N>(latte::Register::SQ_VTX_CONSTANT_WORD0_0 + 4 * resourceOffset);
auto sq_vtx_constant_word1 = getRegister<latte::SQ_VTX_CONSTANT_WORD1_N>(latte::Register::SQ_VTX_CONSTANT_WORD1_0 + 4 * resourceOffset);
auto sq_vtx_constant_word2 = getRegister<latte::SQ_VTX_CONSTANT_WORD2_N>(latte::Register::SQ_VTX_CONSTANT_WORD2_0 + 4 * resourceOffset);
auto sq_vtx_constant_word6 = getRegister<latte::SQ_VTX_CONSTANT_WORD6_N>(latte::Register::SQ_VTX_CONSTANT_WORD6_0 + 4 * resourceOffset);
auto addr = sq_vtx_constant_word0.BASE_ADDRESS();
auto size = sq_vtx_constant_word1.SIZE() + 1;
auto stride = sq_vtx_constant_word2.STRIDE();
auto bufferObject = gl::GLuint { 0 };
if (addr == 0 || size == 0) {
bufferObject = 0;
stride = 0;
} else {
auto buffer = getDataBuffer(addr, size, true, false);
bufferObject = buffer->object;
needMemoryBarrier |= buffer->dirtyMap;
buffer->dirtyMap = false;
}
if (mActiveShader->fetch->mAttribBufferCache[i].object != bufferObject
|| mActiveShader->fetch->mAttribBufferCache[i].stride != stride) {
mActiveShader->fetch->mAttribBufferCache[i].object = bufferObject;
mActiveShader->fetch->mAttribBufferCache[i].stride = stride;
gl::glBindVertexBuffer(i, bufferObject, 0, stride);
}
}
if (needMemoryBarrier) {
gl::glMemoryBarrier(gl::GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
}
return true;
}
bool
GLDriver::checkAttribBuffersBound()
{
// We assume that checkActiveAttribBuffers has already failed the
// draw if there is something wrong at a higher level.
for (auto i = 0; i < mActiveShader->fetch->attribs.size(); ++i) {
auto &attrib = mActiveShader->fetch->attribs[i];
auto resourceOffset = (latte::SQ_RES_OFFSET::VS_TEX_RESOURCE_0 + attrib.buffer) * 7;
auto sq_vtx_constant_word0 = getRegister<latte::SQ_VTX_CONSTANT_WORD0_N>(latte::Register::SQ_VTX_CONSTANT_WORD0_0 + 4 * resourceOffset);
if (!sq_vtx_constant_word0.BASE_ADDRESS()) {
return false;
}
}
return true;
}
bool GLDriver::parseFetchShader(FetchShader &shader, void *buffer, size_t size)
{
auto program = reinterpret_cast<latte::ControlFlowInst *>(buffer);
for (auto i = 0; i < size / 2; i++) {
auto &cf = program[i];
switch (cf.word1.CF_INST()) {
case latte::SQ_CF_INST_VTX:
case latte::SQ_CF_INST_VTX_TC:
{
auto vfPtr = reinterpret_cast<latte::VertexFetchInst *>(program + cf.word0.ADDR());
auto count = ((cf.word1.COUNT_3() << 3) | cf.word1.COUNT()) + 1;
for (auto j = 0u; j < count; ++j) {
auto &vf = vfPtr[j];
if (vf.word0.VTX_INST() != latte::SQ_VTX_INST_SEMANTIC) {
gLog->error("Unexpected fetch shader VTX_INST {}", vf.word0.VTX_INST());
continue;
}
// Parse new attrib
shader.attribs.emplace_back();
auto &attrib = shader.attribs.back();
attrib.bytesPerElement = vf.word0.MEGA_FETCH_COUNT() + 1;
attrib.format = vf.word1.DATA_FORMAT();
attrib.buffer = vf.word0.BUFFER_ID();
attrib.location = vf.gpr.DST_GPR();
attrib.offset = vf.word2.OFFSET();
attrib.formatComp = vf.word1.FORMAT_COMP_ALL();
attrib.numFormat = vf.word1.NUM_FORMAT_ALL();
attrib.endianSwap = vf.word2.ENDIAN_SWAP();
attrib.dstSel[0] = vf.word1.DST_SEL_X();
attrib.dstSel[1] = vf.word1.DST_SEL_Y();
attrib.dstSel[2] = vf.word1.DST_SEL_Z();
attrib.dstSel[3] = vf.word1.DST_SEL_W();
attrib.type = vf.word0.FETCH_TYPE();
attrib.srcSelX = vf.word0.SRC_SEL_X();
}
break;
}
case latte::SQ_CF_INST_RETURN:
case latte::SQ_CF_INST_END_PROGRAM:
return true;
default:
gLog->error("Unexpected fetch shader instruction {}", cf.word1.CF_INST());
}
if (cf.word1.END_OF_PROGRAM()) {
return true;
}
}
return false;
}
static const char *
getGLSLDataInFormat(latte::SQ_DATA_FORMAT format, latte::SQ_NUM_FORMAT num, latte::SQ_FORMAT_COMP comp)
{
switch (format) {
case latte::SQ_DATA_FORMAT::FMT_2_10_10_10:
case latte::SQ_DATA_FORMAT::FMT_10_10_10_2:
return "uint";
}
auto channels = latte::getDataFormatComponents(format);
switch (channels) {
case 1:
return "uint";
case 2:
return "uvec2";
case 3:
return "uvec3";
case 4:
return "uvec4";
default:
decaf_abort(fmt::format("Unimplemented attribute channel count: {} for {}", channels, format));
}
}
bool GLDriver::compileVertexShader(VertexShader &vertex, FetchShader &fetch, uint8_t *buffer, size_t size, bool isScreenSpace)
{
auto sq_config = getRegister<latte::SQ_CONFIG>(latte::Register::SQ_CONFIG);
auto spi_vs_out_config = getRegister<latte::SPI_VS_OUT_CONFIG>(latte::Register::SPI_VS_OUT_CONFIG);
std::array<FetchShader::Attrib *, 32> semanticAttribs;
semanticAttribs.fill(nullptr);
glsl2::Shader shader;
shader.type = glsl2::Shader::VertexShader;
for (auto i = 0; i < latte::MaxSamplers; ++i) {
auto resourceOffset = (latte::SQ_RES_OFFSET::VS_TEX_RESOURCE_0 + i) * 7;
auto sq_tex_resource_word0 = getRegister<latte::SQ_TEX_RESOURCE_WORD0_N>(latte::Register::SQ_TEX_RESOURCE_WORD0_0 + 4 * resourceOffset);
shader.samplerDim[i] = sq_tex_resource_word0.DIM();
}
if (sq_config.DX9_CONSTS()) {
shader.uniformRegistersEnabled = true;
} else {
shader.uniformBlocksEnabled = true;
}
vertex.disassembly = latte::disassemble(gsl::make_span(buffer, size));
if (!glsl2::translate(shader, gsl::make_span(buffer, size))) {
gLog->error("Failed to decode vertex shader\n{}", vertex.disassembly);
return false;
}
vertex.usedUniformBlocks = shader.usedUniformBlocks;
fmt::MemoryWriter out;
out << shader.fileHeader;
out << "#define bswap16(v) (packUnorm4x8(unpackUnorm4x8(v).yxwz))\n";
out << "#define bswap32(v) (packUnorm4x8(unpackUnorm4x8(v).wzyx))\n";
out << "#define signext2(v) ((v ^ 0x2) - 0x2)\n";
out << "#define signext8(v) ((v ^ 0x80) - 0x80)\n";
out << "#define signext10(v) ((v ^ 0x200) - 0x200)\n";
out << "#define signext16(v) ((v ^ 0x8000) - 0x8000)\n";
// Vertex Shader Inputs
for (auto &attrib : fetch.attribs) {
semanticAttribs[attrib.location] = &attrib;
out << "//";
out << " " << latte::getDataFormatName(attrib.format);
if (attrib.formatComp == latte::SQ_FORMAT_COMP::SIGNED) {
out << " SIGNED";
} else {
out << " UNSIGNED";
}
if (attrib.numFormat == latte::SQ_NUM_FORMAT::INT) {
out << " INT";
} else if (attrib.numFormat == latte::SQ_NUM_FORMAT::NORM) {
out << " NORM";
} else if (attrib.numFormat == latte::SQ_NUM_FORMAT::SCALED) {
out << " SCALED";
}
if (attrib.endianSwap == latte::SQ_ENDIAN::NONE) {
out << " SWAP_NONE";
} else if (attrib.endianSwap == latte::SQ_ENDIAN::SWAP_8IN32) {
out << " SWAP_8IN32";
} else if (attrib.endianSwap == latte::SQ_ENDIAN::SWAP_8IN16) {
out << " SWAP_8IN16";
} else if (attrib.endianSwap == latte::SQ_ENDIAN::AUTO) {
out << " SWAP_AUTO";
}
out << "\n";
out << "layout(location = " << attrib.location << ")";
out << " in "
<< getGLSLDataInFormat(attrib.format, attrib.numFormat, attrib.formatComp)
<< " fs_out_" << attrib.location << ";\n";
}
out << '\n';
// Vertex Shader Exports
decaf_check(!spi_vs_out_config.VS_PER_COMPONENT());
vertex.outputMap.fill(0xff);
for (auto i = 0u; i <= spi_vs_out_config.VS_EXPORT_COUNT(); i++) {
auto regId = i / 4;
auto spi_vs_out_id = getRegister<latte::SPI_VS_OUT_ID_N>(latte::Register::SPI_VS_OUT_ID_0 + 4 * regId);
auto semanticNum = i % 4;
uint8_t semanticId = 0xff;
if (semanticNum == 0) {
semanticId = spi_vs_out_id.SEMANTIC_0();
} else if (semanticNum == 1) {
semanticId = spi_vs_out_id.SEMANTIC_1();
} else if (semanticNum == 2) {
semanticId = spi_vs_out_id.SEMANTIC_2();
} else if (semanticNum == 3) {
semanticId = spi_vs_out_id.SEMANTIC_3();
}
if (semanticId == 0xff) {
// Stop looping when we hit the end marker
break;
}
decaf_check(vertex.outputMap[semanticId] == 0xff);
vertex.outputMap[semanticId] = i;
out << "layout(location = " << i << ")";
out << " out vec4 vs_out_" << semanticId << ";\n";
}
out << '\n';
// Transform feedback outputs
for (auto i = 0u; i < latte::MaxStreamOutBuffers; ++i) {
vertex.usedFeedbackBuffers[i] = !shader.feedbacks[i].empty();
if (vertex.usedFeedbackBuffers[i]) {
auto vgt_strmout_vtx_stride = getRegister<uint32_t>(latte::Register::VGT_STRMOUT_VTX_STRIDE_0 + 16 * i);
auto stride = vgt_strmout_vtx_stride * 4;
if (NVIDIA_GLSL_WORKAROUND) {
out
<< "layout(xfb_buffer = " << i << ") out;\n"
<< "layout(xfb_stride = " << stride
<< ") out feedback_block" << i << " {\n";
} else {
out
<< "layout(xfb_buffer = " << i
<< ", xfb_stride = " << stride
<< ") out feedback_block" << i << " {\n";
}
for (auto &xfb : shader.feedbacks[i]) {
out << " layout(xfb_offset = " << xfb.offset << ") out ";
if (xfb.size == 1) {
out << "float";
} else {
out << "vec" << xfb.size;
}
out << " feedback_" << xfb.streamIndex << "_" << xfb.offset << ";\n";
}
out << "};\n";
}
}
out << '\n';
if (isScreenSpace) {
vertex.isScreenSpace = true;
out << "uniform vec4 uViewport;\n";
}
out
<< "void main()\n"
<< "{\n"
<< shader.codeHeader;
// Assign fetch shader output to our GPR
for (auto i = 0u; i < 32; ++i) {
auto sq_vtx_semantic = getRegister<latte::SQ_VTX_SEMANTIC_N>(latte::Register::SQ_VTX_SEMANTIC_0 + i * 4);
auto id = sq_vtx_semantic.SEMANTIC_ID();
if (id == 0xff) {
continue;
}
auto attrib = semanticAttribs[id];
if (!attrib) {
gLog->error("Invalid semantic mapping: {}", id);
continue;
}
fmt::MemoryWriter nameWriter;
nameWriter << "fs_out_" << attrib->location;
auto name = nameWriter.str();
auto channels = latte::getDataFormatComponents(attrib->format);
auto isFloat = latte::getDataFormatIsFloat(attrib->format);
std::string chanVal[4];
uint32_t chanBitCount[4];
if (attrib->format == latte::SQ_DATA_FORMAT::FMT_10_10_10_2 || attrib->format == latte::SQ_DATA_FORMAT::FMT_2_10_10_10) {
decaf_check(channels == 4);
auto val = name;
if (attrib->endianSwap == latte::SQ_ENDIAN::SWAP_8IN32) {
val = "bswap32(" + val + ")";
} else if (attrib->endianSwap == latte::SQ_ENDIAN::SWAP_8IN16) {
decaf_abort("Unexpected 8IN16 swap for 10_10_10_2");
} else if (attrib->endianSwap == latte::SQ_ENDIAN::NONE) {
// Nothing to do
} else {
decaf_abort("Unexpected endian swap mode");
}
if (attrib->format == latte::SQ_DATA_FORMAT::FMT_10_10_10_2) {
chanVal[0] = std::string("((") + val + std::string(" >> 22) & 0x3ff)");
chanVal[1] = std::string("((") + val + std::string(" >> 12) & 0x3ff)");
chanVal[2] = std::string("((") + val + std::string(" >> 2) & 0x3ff)");
chanVal[3] = std::string("((") + val + std::string(" >> 0) & 0x3)");
} else if (attrib->format == latte::SQ_DATA_FORMAT::FMT_2_10_10_10) {
chanVal[3] = std::string("((") + val + std::string(" >> 30) & 0x3)");
chanVal[2] = std::string("((") + val + std::string(" >> 20) & 0x3ff)");
chanVal[1] = std::string("((") + val + std::string(" >> 10) & 0x3ff)");
chanVal[0] = std::string("((") + val + std::string(" >> 0) & 0x3ff)");
} else {
decaf_abort("Unexpected format");
}
if (attrib->formatComp == latte::SQ_FORMAT_COMP::SIGNED) {
chanVal[0] = "int(signext10(" + chanVal[0] + "))";
chanVal[1] = "int(signext10(" + chanVal[1] + "))";
chanVal[2] = "int(signext10(" + chanVal[2] + "))";
chanVal[3] = "int(" + chanVal[3] + ")";
} else {
// Good to go!
}
chanBitCount[0] = 10;
chanBitCount[1] = 10;
chanBitCount[2] = 10;
chanBitCount[3] = 2;
} else {
static const char * ChannelSelNorm[] = { "x" ,"y", "z", "w" };
auto compBits = latte::getDataFormatComponentBits(attrib->format);
for (auto ch = 0u; ch < channels; ++ch) {
auto &val = chanVal[ch];
val = name;
if (attrib->endianSwap == latte::SQ_ENDIAN::NONE) {
// Nothing to do except select the appropriate component.
if (channels > 1) {
val = val + "." + ChannelSelNorm[ch];
}
} else {
if (compBits == 32) {
if (attrib->endianSwap == latte::SQ_ENDIAN::SWAP_8IN32) {
if (channels > 1) {
val = val + "." + ChannelSelNorm[ch];
}
val = "bswap32(" + val + ")";
} else {
decaf_abort("Unexpected endian swap mode for 32-bit components");
}
} else if (compBits == 16) {
if (attrib->endianSwap == latte::SQ_ENDIAN::SWAP_8IN16) {
if (channels > 1) {
val = val + "." + ChannelSelNorm[ch];
}
val = "bswap16(" + val + ")";
} else {
decaf_abort("Unexpected endian swap mode for 16-bit components");
}
} else if (compBits == 8) {
static const char * ChannelSel8In16[] = { "y", "x", "w", "z" };
static const char * ChannelSel8In32[] = { "w", "z", "y", "x" };
if (attrib->endianSwap == latte::SQ_ENDIAN::SWAP_8IN16) {
decaf_check(channels == 2 || channels == 4);
val = val + "." + ChannelSel8In16[ch];
} else if (attrib->endianSwap == latte::SQ_ENDIAN::SWAP_8IN32) {
decaf_check(channels == 4);
val = val + "." + ChannelSel8In32[ch];
} else {
decaf_abort("Unexpected endian swap mode for 8-bit components");
}
} else {
decaf_abort("Unexpected component bit count with swapping");
}
}
if (isFloat) {
if (compBits == 32) {
val = "uintBitsToFloat(" + val + ")";
} else if (compBits == 16) {
val = "unpackHalf2x16(" + val + ").x";
} else {
decaf_abort("Unexpected float component bit count");
}
} else {
if (attrib->formatComp == latte::SQ_FORMAT_COMP::SIGNED) {
if (compBits == 8) {
val = "int(signext8(" + val + "))";
} else if (compBits == 16) {
val = "int(signext16(" + val + "))";
} else if (compBits == 32) {
val = "int(" + val + ")";
} else {
decaf_abort("Unexpected signed component bit count");
}
} else {
// Already the right format!
}
}
chanBitCount[ch] = compBits;
}
}
for (auto ch = 0u; ch < channels; ++ch) {
if (attrib->numFormat == latte::SQ_NUM_FORMAT::NORM) {
uint32_t valMax = (1ul << chanBitCount[ch]) - 1;
if (attrib->formatComp == latte::SQ_FORMAT_COMP::SIGNED) {
chanVal[ch] = fmt::format("clamp(float({}) / {}.0, -1.0, 1.0)", chanVal[ch], valMax / 2);
} else {
chanVal[ch] = fmt::format("float({}) / {}.0", chanVal[ch], valMax);
}
} else if (attrib->numFormat == latte::SQ_NUM_FORMAT::INT) {
if (attrib->formatComp == latte::SQ_FORMAT_COMP::SIGNED) {
chanVal[ch] = "intBitsToFloat(int(" + chanVal[ch] + "))";
} else {
chanVal[ch] = "uintBitsToFloat(uint(" + chanVal[ch] + "))";
}
} else if (attrib->numFormat == latte::SQ_NUM_FORMAT::SCALED) {
chanVal[ch] = "float(" + chanVal[ch] + ")";
} else {
decaf_abort("Unexpected attribute number format");
}
}
if (channels == 1) {
out << "float _" << name << " = " << chanVal[0] << ";\n";
} else if (channels == 2) {
out << "vec2 _" << name << " = vec2(\n";
out << " " << chanVal[0] << ",\n";
out << " " << chanVal[1] << ");\n";
} else if (channels == 3) {
out << "vec3 _" << name << " = vec3(\n";
out << " " << chanVal[0] << ",\n";
out << " " << chanVal[1] << ",\n";
out << " " << chanVal[2] << ");\n";
} else if (channels == 4) {
out << "vec4 _" << name << " = vec4(\n";
out << " " << chanVal[0] << ",\n";
out << " " << chanVal[1] << ",\n";
out << " " << chanVal[2] << ",\n";
out << " " << chanVal[3] << ");\n";
} else {
decaf_abort("Unexpected format channel count");
}
name = "_" + name;
// Write the register assignment
out << "R[" << (i + 1) << "] = ";
switch (channels) {
case 1:
out << "vec4(" << name << ", 0.0, 0.0, 1.0);\n";
break;
case 2:
out << "vec4(" << name << ", 0.0, 1.0);\n";
break;
case 3:
out << "vec4(" << name << ", 1.0);\n";
break;
case 4:
out << name << ";\n";
break;
}
}
out << '\n' << shader.codeBody << '\n';
for (auto &exp : shader.exports) {
switch (exp.type) {
case latte::SQ_EXPORT_TYPE::POS:
if (!isScreenSpace) {
out << "gl_Position = exp_position_" << exp.id << ";\n";
} else {
out << "gl_Position = (exp_position_" << exp.id << " - vec4(uViewport.xy, 0.0, 0.0)) * vec4(uViewport.zw, 1.0, 1.0);\n";
}
break;
case latte::SQ_EXPORT_TYPE::PARAM: {
decaf_check(!spi_vs_out_config.VS_PER_COMPONENT());
auto regId = exp.id / 4;
auto spi_vs_out_id = getRegister<latte::SPI_VS_OUT_ID_N>(latte::Register::SPI_VS_OUT_ID_0 + 4 * regId);
auto semanticNum = exp.id % 4;
uint8_t semanticId = 0xff;
if (semanticNum == 0) {
semanticId = spi_vs_out_id.SEMANTIC_0();
} else if (semanticNum == 1) {
semanticId = spi_vs_out_id.SEMANTIC_1();
} else if (semanticNum == 2) {
semanticId = spi_vs_out_id.SEMANTIC_2();
} else if (semanticNum == 3) {
semanticId = spi_vs_out_id.SEMANTIC_3();
}
if (semanticId != 0xff) {
out << "vs_out_" << semanticId << " = exp_param_" << exp.id << ";\n";
} else {
// This just helps when debugging to understand why it is missing...
out << "// vs_out_none = exp_param_" << exp.id << ";\n";
}
} break;
case latte::SQ_EXPORT_TYPE::PIXEL:
decaf_abort("Unexpected pixel export in vertex shader.");
}
}
out << "}\n";
out << "/* VERTEX SHADER DISASSEMBLY\n" << vertex.disassembly << "\n*/\n";
out << "/* FETCH SHADER DISASSEMBLY\n" << fetch.disassembly << "\n*/\n";
vertex.code = out.str();
return true;
}
bool GLDriver::compilePixelShader(PixelShader &pixel, VertexShader &vertex, uint8_t *buffer, size_t size)
{
auto sq_config = getRegister<latte::SQ_CONFIG>(latte::Register::SQ_CONFIG);
auto spi_ps_in_control_0 = getRegister<latte::SPI_PS_IN_CONTROL_0>(latte::Register::SPI_PS_IN_CONTROL_0);
auto spi_ps_in_control_1 = getRegister<latte::SPI_PS_IN_CONTROL_1>(latte::Register::SPI_PS_IN_CONTROL_1);
auto cb_shader_mask = getRegister<latte::CB_SHADER_MASK>(latte::Register::CB_SHADER_MASK);
auto db_shader_control = getRegister<latte::DB_SHADER_CONTROL>(latte::Register::DB_SHADER_CONTROL);
auto sx_alpha_test_control = getRegister<latte::SX_ALPHA_TEST_CONTROL>(latte::Register::SX_ALPHA_TEST_CONTROL);
decaf_assert(!db_shader_control.STENCIL_REF_EXPORT_ENABLE(), "Stencil exports not implemented");
glsl2::Shader shader;
shader.type = glsl2::Shader::PixelShader;
// Gather Samplers
for (auto i = 0; i < latte::MaxSamplers; ++i) {
auto resourceOffset = (latte::SQ_RES_OFFSET::PS_TEX_RESOURCE_0 + i) * 7;
auto sq_tex_resource_word0 = getRegister<latte::SQ_TEX_RESOURCE_WORD0_N>(latte::Register::SQ_TEX_RESOURCE_WORD0_0 + 4 * resourceOffset);
shader.samplerDim[i] = sq_tex_resource_word0.DIM();
}
if (sq_config.DX9_CONSTS()) {
shader.uniformRegistersEnabled = true;
} else {
shader.uniformBlocksEnabled = true;
}
pixel.disassembly = latte::disassemble(gsl::make_span(buffer, size));
if (!glsl2::translate(shader, gsl::make_span(buffer, size))) {
gLog->error("Failed to decode pixel shader\n{}", pixel.disassembly);
return false;
}
pixel.samplerUsage = shader.samplerUsage;
pixel.usedUniformBlocks = shader.usedUniformBlocks;
fmt::MemoryWriter out;
out << shader.fileHeader;
out << "uniform float uAlphaRef;\n";
auto z_order = db_shader_control.Z_ORDER();
auto early_z = (z_order == latte::DB_Z_ORDER::EARLY_Z_THEN_LATE_Z || z_order == latte::DB_Z_ORDER::EARLY_Z_THEN_RE_Z);
if (early_z) {
if (sx_alpha_test_control.ALPHA_TEST_ENABLE() && !sx_alpha_test_control.ALPHA_TEST_BYPASS()) {
gLog->debug("Ignoring early-Z because alpha test is enabled");
early_z = false;
} else if (db_shader_control.KILL_ENABLE()) {
gLog->debug("Ignoring early-Z because shader discard is enabled");
early_z = false;
} else {
decaf_assert(!shader.usesDiscard, "Shader uses discard but KILL_ENABLE is not set");
for (auto &exp : shader.exports) {
if (exp.type == latte::SQ_EXPORT_TYPE::PIXEL && exp.id == 61) {
gLog->debug("Ignoring early-Z because shader writes gl_FragDepth");
early_z = false;
break;
}
}
}
if (early_z) {
out << "layout(early_fragment_tests) in;\n";
}
}
if (spi_ps_in_control_0.POSITION_ENA()) {
if (!spi_ps_in_control_0.POSITION_CENTROID()) {
out << "layout(pixel_center_integer) ";
}
out << "in vec4 gl_FragCoord;\n";
}
// Pixel Shader Inputs
std::array<bool, 256> semanticUsed = { false };
for (auto i = 0u; i < spi_ps_in_control_0.NUM_INTERP(); ++i) {
auto spi_ps_input_cntl = getRegister<latte::SPI_PS_INPUT_CNTL_N>(latte::Register::SPI_PS_INPUT_CNTL_0 + i * 4);
auto semanticId = spi_ps_input_cntl.SEMANTIC();
decaf_check(semanticId != 0xff);
auto vsOutputLoc = vertex.outputMap[semanticId];
if (semanticId == 0xff) {
// Missing semantic means we need to apply the default values instead...
continue;
}
if (semanticUsed[semanticId]) {
continue;
} else {
semanticUsed[semanticId] = true;
}
out << "layout(location = " << vsOutputLoc << ")";
if (spi_ps_input_cntl.FLAT_SHADE()) {
out << " flat";
}
out << " in vec4 vs_out_" << semanticId << ";\n";
}
out << '\n';
// Pixel Shader Exports
auto maskBits = cb_shader_mask.value;
for (auto i = 0; i < 8; ++i) {
if (maskBits & 0xf) {
out << "out vec4 ps_out_" << i << ";\n";
}
maskBits >>= 4;
}
out << '\n';
out
<< "void main()\n"
<< "{\n"
<< shader.codeHeader;
// Assign vertex shader output to our GPR
for (auto i = 0u; i < spi_ps_in_control_0.NUM_INTERP(); ++i) {
auto spi_ps_input_cntl = getRegister<latte::SPI_PS_INPUT_CNTL_N>(latte::Register::SPI_PS_INPUT_CNTL_0 + i * 4);
uint8_t semanticId = spi_ps_input_cntl.SEMANTIC();
decaf_check(semanticId != 0xff);
auto vsOutputLoc = vertex.outputMap[semanticId];
out << "R[" << i << "] = ";
if (vsOutputLoc != 0xff) {
out << "vs_out_" << semanticId;
} else {
if (spi_ps_input_cntl.DEFAULT_VAL() == 0) {
out << "vec4(0, 0, 0, 0)";
} else if (spi_ps_input_cntl.DEFAULT_VAL() == 1) {
out << "vec4(0, 0, 0, 1)";
} else if (spi_ps_input_cntl.DEFAULT_VAL() == 2) {
out << "vec4(1, 1, 1, 0)";
} else if (spi_ps_input_cntl.DEFAULT_VAL() == 3) {
out << "vec4(1, 1, 1, 1)";
} else {
decaf_abort("Invalid PS input DEFAULT_VAL");
}
}
out << ";\n";
}
if (spi_ps_in_control_0.POSITION_ENA()) {
out << "R[" << spi_ps_in_control_0.POSITION_ADDR() << "] = gl_FragCoord;";
}
decaf_assert(!spi_ps_in_control_0.PARAM_GEN(),
fmt::format("Unsupported spi_ps_in_control_0.PARAM_GEN {}, PARAM_GEN_ADDR {}",
spi_ps_in_control_0.PARAM_GEN(),
spi_ps_in_control_0.PARAM_GEN_ADDR()));
decaf_check(!spi_ps_in_control_1.GEN_INDEX_PIX());
decaf_check(!spi_ps_in_control_1.FIXED_PT_POSITION_ENA());
out << '\n' << shader.codeBody << '\n';
for (auto &exp : shader.exports) {
switch (exp.type) {
case latte::SQ_EXPORT_TYPE::PIXEL:
if (exp.id == 61) {
if (!db_shader_control.Z_EXPORT_ENABLE()) {
gLog->warn("Depth export is masked by db_shader_control");
} else {
out << "gl_FragDepth = exp_pixel_" << exp.id << ".x;\n";
}
} else {
auto mask = (cb_shader_mask.value >> (4 * exp.id)) & 0x0F;
if (!mask) {
gLog->warn("Export is masked by cb_shader_mask");
} else {
std::string strMask;
if (mask & (1 << 0)) {
strMask.push_back('x');
}
if (mask & (1 << 1)) {
strMask.push_back('y');
}
if (mask & (1 << 2)) {
strMask.push_back('z');
}
if (mask & (1 << 3)) {
strMask.push_back('w');
}
if (sx_alpha_test_control.ALPHA_TEST_ENABLE() && !sx_alpha_test_control.ALPHA_TEST_BYPASS()) {
out << "// Alpha Test ";
switch (sx_alpha_test_control.ALPHA_FUNC()) {
case latte::REF_FUNC::NEVER:
out << "REF_NEVER\n";
out << "discard;\n";
break;
case latte::REF_FUNC::LESS:
out << "REF_LESS\n";
out << "if (!(exp_pixel_" << exp.id << ".w < uAlphaRef)) {\n";
out << " discard;\n}\n";
break;
case latte::REF_FUNC::EQUAL:
out << "REF_EQUAL\n";
out << "if (!(exp_pixel_" << exp.id << ".w == uAlphaRef)) {\n";
out << " discard;\n}\n";
break;
case latte::REF_FUNC::LESS_EQUAL:
out << "REF_LESS_EQUAL\n";
out << "if (!(exp_pixel_" << exp.id << ".w <= uAlphaRef)) {\n";
out << " discard;\n}\n";
break;
case latte::REF_FUNC::GREATER:
out << "REF_GREATER\n";
out << "if (!(exp_pixel_" << exp.id << ".w > uAlphaRef)) {\n";
out << " discard;\n}\n";
break;
case latte::REF_FUNC::NOT_EQUAL:
out << "REF_NOT_EQUAL\n";
out << "if (!(exp_pixel_" << exp.id << ".w != uAlphaRef)) {\n";
out << " discard;\n}\n";
break;
case latte::REF_FUNC::GREATER_EQUAL:
out << "REF_GREATER_EQUAL\n";
out << "if (!(exp_pixel_" << exp.id << ".w >= uAlphaRef)) {\n";
out << " discard;\n}\n";
break;
case latte::REF_FUNC::ALWAYS:
out << "REF_ALWAYS\n";
break;
}
}
out
<< "ps_out_" << exp.id << "." << strMask
<< " = exp_pixel_" << exp.id << "." << strMask;
out << ";\n";
}
}
break;
case latte::SQ_EXPORT_TYPE::POS:
decaf_abort("Unexpected position export in pixel shader.");
break;
case latte::SQ_EXPORT_TYPE::PARAM:
decaf_abort("Unexpected parameter export in pixel shader.");
break;
}
}
out << "}\n";
out << "/* PIXEL SHADER DISASSEMBLY\n" << pixel.disassembly << "\n*/\n";
pixel.code = out.str();
return true;
}
} // namespace opengl
#endif // ifdef DECAF_GL
|
petmac/decaf-emu
|
src/libgpu/src/opengl/opengl_shader.cpp
|
C++
|
gpl-3.0
| 61,809
|
#!/usr/bin/perl -w
# Copyright 2007, 2008, 2009, 2010, 2011 Kevin Ryde
# This file is part of Chart.
#
# Chart 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.
#
# Chart 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 Chart. If not, see <http://www.gnu.org/licenses/>.
use strict;
use warnings;
use Gtk2 '-init';
use App::Chart::Gtk2::DownloadDialog;
use Devel::FindRef;
{
my $dialog = App::Chart::Gtk2::DownloadDialog->popup;
# unmap here because it's setup for hide-on-delete
$dialog->signal_connect (unmap => sub { Gtk2->main_quit });
App::Chart::chart_dirbroadcast()->listen;
Gtk2->main;
exit 0;
}
{
my $dialog = App::Chart::Gtk2::DownloadDialog->new;
$dialog->destroy;
print Devel::FindRef::track ($dialog);
Scalar::Util::weaken ($dialog);
print defined $dialog ? "defined\n" : "not defined\n";
exit 0;
}
|
gitpan/chart-app
|
devel/run-download-dialog.pl
|
Perl
|
gpl-3.0
| 1,271
|
<?php
print "<B><U>Sentencia for (ejemplo file023.php)</U></B><BR>";
// Caso1:
// Las tres expresiones informadas
for ($var1 = 3; $var1 >= 1; $var1--) {
print "Caso 1: " .$var1 . "<BR>";
}
// Caso 2:
// No hay inicialización (se hace antes)
$var1 = 3;
for (;$var1 >= 1; $var1--) {
print "Caso 2: " .$var1 . "<BR>";
}
//Caso 3:
// No hay expresión 2 (control de bucle)
for ($var1 = 3;;$var1--) {
// al no haber expresión 2, debe haber una sentencia break
// para que no haya bucle infinito
if ($var1 == 2) {
print "Caso 3: sale por sentencia break<BR>";
break;
}
print "Caso 3: " .$var1 . "<BR>";
}
//Caso 4:
// No hay expresiones explícitas en la sentencia for:
// se omiten las tres
// La expresión de inicialización: se omite, por lo que
// la variable será cero (o el valor que traiga de antes)
// La expresión de control de bucle: se define dentro del bloque
// en este caso es if ($var2 == 2)
// La expresión de incremento/decremento: se omite, por lo que
// dentro del bloque se incluye la sentencia ++$var2
for (;;) {
// al no haber expresión 2, debe haber una sentencia break
// para que no haya bucle infinito
if ($var2 == 2) {
print "Caso 4: sale por sentencia break<BR>";
break;
}
print "Caso 4: " . ++$var2 . "<BR>";
}
//Caso 5:
// Sintaxis alternativa
for ($var1 = 3; $var1 >= 1; $var1--):
print "Caso 5: " .$var1 . "<BR>";
endfor;
?>
|
ricardo7227/DAW
|
DIW/aaa_profe/Intranet/Departamentos/Informatica/web/profesores/santiago/P4/code/file023.php
|
PHP
|
gpl-3.0
| 1,433
|
#!/bin/sh
#############################################################################
##
## Copyright (C) 2016 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is the build configuration utility of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and The Qt Company. For licensing terms
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3 as published by the Free Software
## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
#############################################################################
# This script updates the suite from W3C's CVS server.
#
# NOTE: the files checked out CANNOT be added to Qt's
# repository at the moment, due to legal complications. However,
# when the test suite is publically released, it is possible as
# according to W3C's usual license agreements.
echo "*** This script typically doesn't need to be run, and it needs to be updated anyway."
exit 1
# This is W3C's internal CVS server, not the public dev.w3.org.
export CVSROOT="fenglich@cvs.w3.org:path is currently unknown"
echo "*** Enter 'anonymous' as password. ***"
cvs login
mv catalog.xml catalogUnresolved.xml
xmllint --noent --output catalog.xml catalogUnresolved.xml
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtxmlpatterns/tests/auto/xmlpatternsxslts/XSLTS/updateSuite.sh
|
Shell
|
gpl-3.0
| 1,961
|
// MESSAGE MISSION_ITEM PACKING
#define MAVLINK_MSG_ID_MISSION_ITEM 39
typedef struct __mavlink_mission_item_t
{
float param1; ///< PARAM1, see MAV_CMD enum
float param2; ///< PARAM2, see MAV_CMD enum
float param3; ///< PARAM3, see MAV_CMD enum
float param4; ///< PARAM4, see MAV_CMD enum
float x; ///< PARAM5 / local: x position, global: latitude
float y; ///< PARAM6 / y position: global: longitude
float z; ///< PARAM7 / z position: global: altitude (relative or absolute, depending on frame.
uint16_t seq; ///< Sequence
uint16_t command; ///< The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs
uint8_t target_system; ///< System ID
uint8_t target_component; ///< Component ID
uint8_t frame; ///< The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h
uint8_t current; ///< false:0, true:1
uint8_t autocontinue; ///< autocontinue to next wp
} mavlink_mission_item_t;
#define MAVLINK_MSG_ID_MISSION_ITEM_LEN 37
#define MAVLINK_MSG_ID_39_LEN 37
#define MAVLINK_MSG_ID_MISSION_ITEM_CRC 254
#define MAVLINK_MSG_ID_39_CRC 254
#define MAVLINK_MESSAGE_INFO_MISSION_ITEM { \
"MISSION_ITEM", \
14, \
{ { "param1", NULL, MAVLINK_TYPE_FLOAT, 0, 0, offsetof(mavlink_mission_item_t, param1) }, \
{ "param2", NULL, MAVLINK_TYPE_FLOAT, 0, 4, offsetof(mavlink_mission_item_t, param2) }, \
{ "param3", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_mission_item_t, param3) }, \
{ "param4", NULL, MAVLINK_TYPE_FLOAT, 0, 12, offsetof(mavlink_mission_item_t, param4) }, \
{ "x", NULL, MAVLINK_TYPE_FLOAT, 0, 16, offsetof(mavlink_mission_item_t, x) }, \
{ "y", NULL, MAVLINK_TYPE_FLOAT, 0, 20, offsetof(mavlink_mission_item_t, y) }, \
{ "z", NULL, MAVLINK_TYPE_FLOAT, 0, 24, offsetof(mavlink_mission_item_t, z) }, \
{ "seq", NULL, MAVLINK_TYPE_UINT16_T, 0, 28, offsetof(mavlink_mission_item_t, seq) }, \
{ "command", NULL, MAVLINK_TYPE_UINT16_T, 0, 30, offsetof(mavlink_mission_item_t, command) }, \
{ "target_system", NULL, MAVLINK_TYPE_UINT8_T, 0, 32, offsetof(mavlink_mission_item_t, target_system) }, \
{ "target_component", NULL, MAVLINK_TYPE_UINT8_T, 0, 33, offsetof(mavlink_mission_item_t, target_component) }, \
{ "frame", NULL, MAVLINK_TYPE_UINT8_T, 0, 34, offsetof(mavlink_mission_item_t, frame) }, \
{ "current", NULL, MAVLINK_TYPE_UINT8_T, 0, 35, offsetof(mavlink_mission_item_t, current) }, \
{ "autocontinue", NULL, MAVLINK_TYPE_UINT8_T, 0, 36, offsetof(mavlink_mission_item_t, autocontinue) }, \
} \
}
/**
* @brief Pack a mission_item message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param target_system System ID
* @param target_component Component ID
* @param seq Sequence
* @param frame The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h
* @param command The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs
* @param current false:0, true:1
* @param autocontinue autocontinue to next wp
* @param param1 PARAM1, see MAV_CMD enum
* @param param2 PARAM2, see MAV_CMD enum
* @param param3 PARAM3, see MAV_CMD enum
* @param param4 PARAM4, see MAV_CMD enum
* @param x PARAM5 / local: x position, global: latitude
* @param y PARAM6 / y position: global: longitude
* @param z PARAM7 / z position: global: altitude (relative or absolute, depending on frame.
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_mission_item_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint8_t target_system, uint8_t target_component, uint16_t seq, uint8_t frame, uint16_t command, uint8_t current, uint8_t autocontinue, float param1, float param2, float param3, float param4, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_MISSION_ITEM_LEN];
_mav_put_float(buf, 0, param1);
_mav_put_float(buf, 4, param2);
_mav_put_float(buf, 8, param3);
_mav_put_float(buf, 12, param4);
_mav_put_float(buf, 16, x);
_mav_put_float(buf, 20, y);
_mav_put_float(buf, 24, z);
_mav_put_uint16_t(buf, 28, seq);
_mav_put_uint16_t(buf, 30, command);
_mav_put_uint8_t(buf, 32, target_system);
_mav_put_uint8_t(buf, 33, target_component);
_mav_put_uint8_t(buf, 34, frame);
_mav_put_uint8_t(buf, 35, current);
_mav_put_uint8_t(buf, 36, autocontinue);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#else
mavlink_mission_item_t packet;
packet.param1 = param1;
packet.param2 = param2;
packet.param3 = param3;
packet.param4 = param4;
packet.x = x;
packet.y = y;
packet.z = z;
packet.seq = seq;
packet.command = command;
packet.target_system = target_system;
packet.target_component = target_component;
packet.frame = frame;
packet.current = current;
packet.autocontinue = autocontinue;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_MISSION_ITEM;
#if MAVLINK_CRC_EXTRA
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_MISSION_ITEM_LEN, MAVLINK_MSG_ID_MISSION_ITEM_CRC);
#else
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
}
/**
* @brief Pack a mission_item message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param target_system System ID
* @param target_component Component ID
* @param seq Sequence
* @param frame The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h
* @param command The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs
* @param current false:0, true:1
* @param autocontinue autocontinue to next wp
* @param param1 PARAM1, see MAV_CMD enum
* @param param2 PARAM2, see MAV_CMD enum
* @param param3 PARAM3, see MAV_CMD enum
* @param param4 PARAM4, see MAV_CMD enum
* @param x PARAM5 / local: x position, global: latitude
* @param y PARAM6 / y position: global: longitude
* @param z PARAM7 / z position: global: altitude (relative or absolute, depending on frame.
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_mission_item_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint8_t target_system,uint8_t target_component,uint16_t seq,uint8_t frame,uint16_t command,uint8_t current,uint8_t autocontinue,float param1,float param2,float param3,float param4,float x,float y,float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_MISSION_ITEM_LEN];
_mav_put_float(buf, 0, param1);
_mav_put_float(buf, 4, param2);
_mav_put_float(buf, 8, param3);
_mav_put_float(buf, 12, param4);
_mav_put_float(buf, 16, x);
_mav_put_float(buf, 20, y);
_mav_put_float(buf, 24, z);
_mav_put_uint16_t(buf, 28, seq);
_mav_put_uint16_t(buf, 30, command);
_mav_put_uint8_t(buf, 32, target_system);
_mav_put_uint8_t(buf, 33, target_component);
_mav_put_uint8_t(buf, 34, frame);
_mav_put_uint8_t(buf, 35, current);
_mav_put_uint8_t(buf, 36, autocontinue);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#else
mavlink_mission_item_t packet;
packet.param1 = param1;
packet.param2 = param2;
packet.param3 = param3;
packet.param4 = param4;
packet.x = x;
packet.y = y;
packet.z = z;
packet.seq = seq;
packet.command = command;
packet.target_system = target_system;
packet.target_component = target_component;
packet.frame = frame;
packet.current = current;
packet.autocontinue = autocontinue;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_MISSION_ITEM;
#if MAVLINK_CRC_EXTRA
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_MISSION_ITEM_LEN, MAVLINK_MSG_ID_MISSION_ITEM_CRC);
#else
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
}
/**
* @brief Encode a mission_item struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param mission_item C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_mission_item_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_mission_item_t* mission_item)
{
return mavlink_msg_mission_item_pack(system_id, component_id, msg, mission_item->target_system, mission_item->target_component, mission_item->seq, mission_item->frame, mission_item->command, mission_item->current, mission_item->autocontinue, mission_item->param1, mission_item->param2, mission_item->param3, mission_item->param4, mission_item->x, mission_item->y, mission_item->z);
}
/**
* @brief Encode a mission_item struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param mission_item C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_mission_item_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_mission_item_t* mission_item)
{
return mavlink_msg_mission_item_pack_chan(system_id, component_id, chan, msg, mission_item->target_system, mission_item->target_component, mission_item->seq, mission_item->frame, mission_item->command, mission_item->current, mission_item->autocontinue, mission_item->param1, mission_item->param2, mission_item->param3, mission_item->param4, mission_item->x, mission_item->y, mission_item->z);
}
/**
* @brief Send a mission_item message
* @param chan MAVLink channel to send the message
*
* @param target_system System ID
* @param target_component Component ID
* @param seq Sequence
* @param frame The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h
* @param command The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs
* @param current false:0, true:1
* @param autocontinue autocontinue to next wp
* @param param1 PARAM1, see MAV_CMD enum
* @param param2 PARAM2, see MAV_CMD enum
* @param param3 PARAM3, see MAV_CMD enum
* @param param4 PARAM4, see MAV_CMD enum
* @param x PARAM5 / local: x position, global: latitude
* @param y PARAM6 / y position: global: longitude
* @param z PARAM7 / z position: global: altitude (relative or absolute, depending on frame.
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_mission_item_send(mavlink_channel_t chan, uint8_t target_system, uint8_t target_component, uint16_t seq, uint8_t frame, uint16_t command, uint8_t current, uint8_t autocontinue, float param1, float param2, float param3, float param4, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_MISSION_ITEM_LEN];
_mav_put_float(buf, 0, param1);
_mav_put_float(buf, 4, param2);
_mav_put_float(buf, 8, param3);
_mav_put_float(buf, 12, param4);
_mav_put_float(buf, 16, x);
_mav_put_float(buf, 20, y);
_mav_put_float(buf, 24, z);
_mav_put_uint16_t(buf, 28, seq);
_mav_put_uint16_t(buf, 30, command);
_mav_put_uint8_t(buf, 32, target_system);
_mav_put_uint8_t(buf, 33, target_component);
_mav_put_uint8_t(buf, 34, frame);
_mav_put_uint8_t(buf, 35, current);
_mav_put_uint8_t(buf, 36, autocontinue);
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, buf, MAVLINK_MSG_ID_MISSION_ITEM_LEN, MAVLINK_MSG_ID_MISSION_ITEM_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, buf, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
#else
mavlink_mission_item_t packet;
packet.param1 = param1;
packet.param2 = param2;
packet.param3 = param3;
packet.param4 = param4;
packet.x = x;
packet.y = y;
packet.z = z;
packet.seq = seq;
packet.command = command;
packet.target_system = target_system;
packet.target_component = target_component;
packet.frame = frame;
packet.current = current;
packet.autocontinue = autocontinue;
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, (const char *)&packet, MAVLINK_MSG_ID_MISSION_ITEM_LEN, MAVLINK_MSG_ID_MISSION_ITEM_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, (const char *)&packet, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
#endif
}
#if MAVLINK_MSG_ID_MISSION_ITEM_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_mission_item_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint8_t target_system, uint8_t target_component, uint16_t seq, uint8_t frame, uint16_t command, uint8_t current, uint8_t autocontinue, float param1, float param2, float param3, float param4, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_float(buf, 0, param1);
_mav_put_float(buf, 4, param2);
_mav_put_float(buf, 8, param3);
_mav_put_float(buf, 12, param4);
_mav_put_float(buf, 16, x);
_mav_put_float(buf, 20, y);
_mav_put_float(buf, 24, z);
_mav_put_uint16_t(buf, 28, seq);
_mav_put_uint16_t(buf, 30, command);
_mav_put_uint8_t(buf, 32, target_system);
_mav_put_uint8_t(buf, 33, target_component);
_mav_put_uint8_t(buf, 34, frame);
_mav_put_uint8_t(buf, 35, current);
_mav_put_uint8_t(buf, 36, autocontinue);
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, buf, MAVLINK_MSG_ID_MISSION_ITEM_LEN, MAVLINK_MSG_ID_MISSION_ITEM_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, buf, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
#else
mavlink_mission_item_t *packet = (mavlink_mission_item_t *)msgbuf;
packet->param1 = param1;
packet->param2 = param2;
packet->param3 = param3;
packet->param4 = param4;
packet->x = x;
packet->y = y;
packet->z = z;
packet->seq = seq;
packet->command = command;
packet->target_system = target_system;
packet->target_component = target_component;
packet->frame = frame;
packet->current = current;
packet->autocontinue = autocontinue;
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, (const char *)packet, MAVLINK_MSG_ID_MISSION_ITEM_LEN, MAVLINK_MSG_ID_MISSION_ITEM_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_ITEM, (const char *)packet, MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
#endif
}
#endif
#endif
// MESSAGE MISSION_ITEM UNPACKING
/**
* @brief Get field target_system from mission_item message
*
* @return System ID
*/
static inline uint8_t mavlink_msg_mission_item_get_target_system(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 32);
}
/**
* @brief Get field target_component from mission_item message
*
* @return Component ID
*/
static inline uint8_t mavlink_msg_mission_item_get_target_component(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 33);
}
/**
* @brief Get field seq from mission_item message
*
* @return Sequence
*/
static inline uint16_t mavlink_msg_mission_item_get_seq(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 28);
}
/**
* @brief Get field frame from mission_item message
*
* @return The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h
*/
static inline uint8_t mavlink_msg_mission_item_get_frame(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 34);
}
/**
* @brief Get field command from mission_item message
*
* @return The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs
*/
static inline uint16_t mavlink_msg_mission_item_get_command(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 30);
}
/**
* @brief Get field current from mission_item message
*
* @return false:0, true:1
*/
static inline uint8_t mavlink_msg_mission_item_get_current(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 35);
}
/**
* @brief Get field autocontinue from mission_item message
*
* @return autocontinue to next wp
*/
static inline uint8_t mavlink_msg_mission_item_get_autocontinue(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 36);
}
/**
* @brief Get field param1 from mission_item message
*
* @return PARAM1, see MAV_CMD enum
*/
static inline float mavlink_msg_mission_item_get_param1(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 0);
}
/**
* @brief Get field param2 from mission_item message
*
* @return PARAM2, see MAV_CMD enum
*/
static inline float mavlink_msg_mission_item_get_param2(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 4);
}
/**
* @brief Get field param3 from mission_item message
*
* @return PARAM3, see MAV_CMD enum
*/
static inline float mavlink_msg_mission_item_get_param3(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 8);
}
/**
* @brief Get field param4 from mission_item message
*
* @return PARAM4, see MAV_CMD enum
*/
static inline float mavlink_msg_mission_item_get_param4(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 12);
}
/**
* @brief Get field x from mission_item message
*
* @return PARAM5 / local: x position, global: latitude
*/
static inline float mavlink_msg_mission_item_get_x(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 16);
}
/**
* @brief Get field y from mission_item message
*
* @return PARAM6 / y position: global: longitude
*/
static inline float mavlink_msg_mission_item_get_y(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 20);
}
/**
* @brief Get field z from mission_item message
*
* @return PARAM7 / z position: global: altitude (relative or absolute, depending on frame.
*/
static inline float mavlink_msg_mission_item_get_z(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 24);
}
/**
* @brief Decode a mission_item message into a struct
*
* @param msg The message to decode
* @param mission_item C-struct to decode the message contents into
*/
static inline void mavlink_msg_mission_item_decode(const mavlink_message_t* msg, mavlink_mission_item_t* mission_item)
{
#if MAVLINK_NEED_BYTE_SWAP
mission_item->param1 = mavlink_msg_mission_item_get_param1(msg);
mission_item->param2 = mavlink_msg_mission_item_get_param2(msg);
mission_item->param3 = mavlink_msg_mission_item_get_param3(msg);
mission_item->param4 = mavlink_msg_mission_item_get_param4(msg);
mission_item->x = mavlink_msg_mission_item_get_x(msg);
mission_item->y = mavlink_msg_mission_item_get_y(msg);
mission_item->z = mavlink_msg_mission_item_get_z(msg);
mission_item->seq = mavlink_msg_mission_item_get_seq(msg);
mission_item->command = mavlink_msg_mission_item_get_command(msg);
mission_item->target_system = mavlink_msg_mission_item_get_target_system(msg);
mission_item->target_component = mavlink_msg_mission_item_get_target_component(msg);
mission_item->frame = mavlink_msg_mission_item_get_frame(msg);
mission_item->current = mavlink_msg_mission_item_get_current(msg);
mission_item->autocontinue = mavlink_msg_mission_item_get_autocontinue(msg);
#else
memcpy(mission_item, _MAV_PAYLOAD(msg), MAVLINK_MSG_ID_MISSION_ITEM_LEN);
#endif
}
|
UncleRus/MultiOSD
|
firmware/telemetry/mavlink/lib/common/mavlink_msg_mission_item.h
|
C
|
gpl-3.0
| 20,633
|
#!/usr/bin/perl
# Copyright Biblibre 2007 - CILEA 2011
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# Koha 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 Koha; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use strict;
use warnings;
use CGI;
use C4::Output;
use C4::Context;
use C4::Search;
use C4::Auth;
use C4::Output;
use C4::Biblio;
use C4::Koha;
use MARC::Record;
use C4::Branch;
use C4::ItemType;
sub plugin_parameters {
my ( $dbh, $record, $tagslib, $i, $tabloop ) = @_;
return "";
}
sub plugin_javascript {
my ( $dbh, $record, $tagslib, $field_number, $tabloop ) = @_;
my $function_name = $field_number;
my $res = "
<script type='text/javascript'>
function Focus$function_name(subfield_managed) {
return 1;
}
function Blur$function_name(subfield_managed) {
return 1;
}
function Clic$function_name(i) {
defaultvalue=document.getElementById(\"$field_number\").value;
window.open(\"/cgi-bin/koha/cataloguing/plugin_launcher.pl?plugin_name=marc21_linking_section.pl&index=\" + i + \"&result=\"+defaultvalue,\"marc21_field_7\"+i+\"\",'width=900,height=700,toolbar=false,scrollbars=yes');
}
</script>
";
return ( $function_name, $res );
}
# sub plugin
#
# input arg :
# -- op could be equals to
# * fillinput :
# * do_search :
#
sub plugin {
my ($input) = @_;
my $dbh = C4::Context->dbh;
my $query = new CGI;
my $op = $query->param('op');
my $type = $query->param('type');
my $startfrom = $query->param('startfrom');
$startfrom = 0 if ( !defined $startfrom );
my ( $template, $loggedinuser, $cookie );
my $resultsperpage;
my $searchdesc;
if ( $op eq "fillinput" ) {
my $biblionumber = $query->param('biblionumber');
my $index = $query->param('index');
my $marcrecord;
# open template
( $template, $loggedinuser, $cookie ) = get_template_and_user(
{
template_name =>
"cataloguing/value_builder/marc21_linking_section.tt",
query => $query,
type => "intranet",
authnotrequired => 0,
flagsrequired => { editcatalogue => '*' },
debug => 1,
}
);
#get marc record
$marcrecord = GetMarcBiblio($biblionumber);
my $subfield_value_9 = $biblionumber;
my $subfield_value_0 = $biblionumber;
#my $subfield_value_0;
#$subfield_value_0 = $marcrecord->field('001')->data
# if $marcrecord->field('001');
my $subfield_value_w;
if ( $marcrecord->field('001') ) {
$subfield_value_w = $marcrecord->field('001')->data;
}
else {
$subfield_value_w = $biblionumber;
}
my $subfield_value_a;
my $subfield_value_c;
my $subfield_value_d;
my $subfield_value_e;
my $subfield_value_h;
my $subfield_value_i;
my $subfield_value_p;
my $subfield_value_t;
if ( $marcrecord->field('245') ) {
$subfield_value_t = $marcrecord->title();
}
my $subfield_value_u;
my $subfield_value_v;
my $subfield_value_x;
my $subfield_value_y;
my $subfield_value_z;
$subfield_value_x = $marcrecord->field('022')->subfield("a")
if ( $marcrecord->field('022') );
$subfield_value_z = $marcrecord->field('020')->subfield("a")
if ( $marcrecord->field('020') );
# escape the 's
$subfield_value_9 =~ s/'/\\'/g;
$subfield_value_0 =~ s/'/\\'/g;
$subfield_value_a =~ s/'/\\'/g;
$subfield_value_c =~ s/'/\\'/g;
$subfield_value_d =~ s/'/\\'/g;
$subfield_value_e =~ s/'/\\'/g;
$subfield_value_h =~ s/'/\\'/g;
$subfield_value_i =~ s/'/\\'/g;
$subfield_value_p =~ s/'/\\'/g;
$subfield_value_t =~ s/'/\\'/g;
$subfield_value_u =~ s/'/\\'/g;
$subfield_value_v =~ s/'/\\'/g;
$subfield_value_w =~ s/'/\\'/g;
$subfield_value_x =~ s/'/\\'/g;
$subfield_value_y =~ s/'/\\'/g;
$subfield_value_z =~ s/'/\\'/g;
$template->param(
fillinput => 1,
index => $query->param('index') . "",
biblionumber => $biblionumber ? $biblionumber : "",
subfield_value_9 => "$subfield_value_9",
subfield_value_0 => "$subfield_value_0",
subfield_value_a => "$subfield_value_a",
subfield_value_c => "$subfield_value_c",
subfield_value_d => "$subfield_value_d",
subfield_value_e => "$subfield_value_e",
subfield_value_h => "$subfield_value_h",
subfield_value_i => "$subfield_value_i",
subfield_value_p => "$subfield_value_p",
subfield_value_t => "$subfield_value_t",
subfield_value_u => "$subfield_value_u",
subfield_value_v => "$subfield_value_v",
subfield_value_w => "$subfield_value_w",
subfield_value_x => "$subfield_value_x",
subfield_value_y => "$subfield_value_y",
subfield_value_z => "$subfield_value_z",
);
###############################################################
}
elsif ( $op eq "do_search" ) {
my $search = $query->param('search');
my $itype = $query->param('itype');
my $startfrom = $query->param('startfrom');
my $resultsperpage = $query->param('resultsperpage') || 20;
my $orderby;
my $QParser;
$QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
my $op;
if ($QParser) {
$op = '&&';
} else {
$op = 'and';
}
$search = 'kw:' . $search . " $op mc-itemtype:" . $itype if $itype;
my ( $errors, $results, $total_hits ) =
SimpleSearch( $search, $startfrom * $resultsperpage,
$resultsperpage );
if ( defined $errors ) {
$results = [];
}
my $total = @{$results};
# warn " biblio count : ".$total;
( $template, $loggedinuser, $cookie ) = get_template_and_user(
{
template_name =>
"cataloguing/value_builder/marc21_linking_section.tt",
query => $query,
type => 'intranet',
authnotrequired => 0,
debug => 1,
}
);
# multi page display gestion
my $displaynext = 0;
my $displayprev = $startfrom;
if ( ( $total_hits - ( ( $startfrom + 1 ) * ($resultsperpage) ) ) > 0 )
{
$displaynext = 1;
}
my @arrayresults;
my @field_data = ($search);
for ( my $i = 0 ; $i < $resultsperpage ; $i++ ) {
my $record = C4::Search::new_record_from_zebra( 'biblioserver', $results->[$i] );
my $rechash = TransformMarcToKoha( $dbh, $record );
my $pos;
my $countitems = $rechash->{itembumber} ? 1 : 0;
while ( index( $rechash->{itemnumber}, '|', $pos ) > 0 ) {
$countitems += 1;
$pos = index( $rechash->{itemnumber}, '|', $pos ) + 1;
}
$rechash->{totitem} = $countitems;
my @holdingbranches = split /\|/, $rechash->{holdingbranch};
my @itemcallnumbers = split /\|/, $rechash->{itemcallnumber};
my $CN;
for ( my $i = 0 ; $i < @holdingbranches ; $i++ ) {
$CN .=
$holdingbranches[$i] . " ( " . $itemcallnumbers[$i] . " ) |";
}
$CN =~ s/ \|$//;
$rechash->{CN} = $CN;
push @arrayresults, $rechash;
}
# for(my $i = 0 ; $i <= $#marclist ; $i++)
# {
# push @field_data, { term => "marclist", val=>$marclist[$i] };
# push @field_data, { term => "and_or", val=>$and_or[$i] };
# push @field_data, { term => "excluding", val=>$excluding[$i] };
# push @field_data, { term => "operator", val=>$operator[$i] };
# push @field_data, { term => "value", val=>$value[$i] };
# }
my @numbers = ();
if ( $total > $resultsperpage ) {
for ( my $i = 1 ; $i < $total / $resultsperpage + 1 ; $i++ ) {
if ( $i < 16 ) {
my $highlight = 0;
( $startfrom == ( $i - 1 ) ) && ( $highlight = 1 );
push @numbers,
{
number => $i,
highlight => $highlight,
searchdata => \@field_data,
startfrom => ( $i - 1 )
};
}
}
}
my $from = $startfrom * $resultsperpage + 1;
my $to;
if ( $total_hits < $from + $resultsperpage ) {
$to = $total_hits;
}
else {
$to = $from + $resultsperpage;
}
my $defaultview =
'BiblioDefaultView' . C4::Context->preference('BiblioDefaultView');
# my $link="/cgi-bin/koha/cataloguing/value_builder/unimarc4XX.pl?op=do_search&q=$search_desc&resultsperpage=$resultsperpage&startfrom=$startfrom&search=$search";
# foreach my $sort (@sort_by){
# $link.="&sort_by=".$sort."&";
# }
# $template->param(
# pagination_bar => pagination_bar(
# $link,
# getnbpages($hits, $results_per_page),
# $page,
# 'page'
# ),
# );
$template->param(
result => \@arrayresults,
index => $query->param('index') . "",
startfrom => $startfrom,
displaynext => $displaynext,
displayprev => $displayprev,
resultsperpage => $resultsperpage,
orderby => $orderby,
startfromnext => $startfrom + 1,
startfromprev => $startfrom - 1,
searchdata => \@field_data,
total => $total_hits,
from => $from,
to => $to,
numbers => \@numbers,
search => $search,
$defaultview => 1,
Search => 0
);
}
else {
( $template, $loggedinuser, $cookie ) = get_template_and_user(
{
template_name =>
"cataloguing/value_builder/marc21_linking_section.tt",
query => $query,
type => "intranet",
authnotrequired => 0,
}
);
my @itemtypes = C4::ItemType->all;
$template->param(
itypeloop => \@itemtypes,
index => $query->param('index'),
Search => 1,
);
}
output_html_with_http_headers $query, $cookie, $template->output;
}
1;
|
KohaAloha/Zz1
|
cataloguing/value_builder/marc21_linking_section.pl
|
Perl
|
gpl-3.0
| 13,581
|
# encoding=utf8
# pylint: disable=W0611
""" The utility
Author: lipixun
Created Time : 日 2/12 14:14:50 2017
File Name: utils.py
Description:
"""
from spec import DataPath
# Import json
try:
import simplejson as json
except ImportError:
import json
# NLTK
import nltk
nltk.data.path = [ DataPath ]
|
lipixun/newsanalyzer4w
|
newsanalyzer/utils.py
|
Python
|
gpl-3.0
| 329
|
/*-
* Copyright (c) 2016, NGSPipes Team <ngspipes@gmail.com>
* All rights reserved.
*
* This file is part of NGSPipes <http://ngspipes.github.io/>.
*
* 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 editor.userInterface.controllers;
import components.FXMLFile;
import editor.dataAccess.Uris;
import editor.logic.entities.EditorStep;
import editor.userInterface.utils.UIUtils;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import jfxutils.ComponentException;
import jfxutils.IInitializable;
public class FXMLStepsOrderController implements IInitializable<EditorStep>{
public static Node mount(EditorStep step) throws ComponentException {
String fXMLPath = Uris.FXML_STEPS_ORDER;
FXMLFile<Node, EditorStep> fxmlFile = new FXMLFile<>(fXMLPath, step);
fxmlFile.build();
return fxmlFile.getRoot();
}
private static final Image DEFAULT_TOOL_LOGO = new Image(Uris.TOOL_LOGO_IMAGE);
@FXML
private Label lOrder;
@FXML
private Label lTool;
@FXML
private Label lCommand;
@FXML
private ImageView iVLogo;
private EditorStep step;
@Override
public void init(EditorStep step) throws ComponentException {
this.step = step;
load();
}
private void load(){
setOrder(step.getOrder());
lTool.setText(step.getToolDescriptor().getName());
lCommand.setText(step.getCommandDescriptor().getName());
iVLogo.setImage(DEFAULT_TOOL_LOGO);
UIUtils.loadLogo(iVLogo, step.getToolDescriptor());
step.orderEvent.addListener(this::setOrder);
}
private void setOrder(int order){
lOrder.setText(Integer.toString(order));
}
}
|
ngspipes/editor
|
src/main/java/editor/userInterface/controllers/FXMLStepsOrderController.java
|
Java
|
gpl-3.0
| 2,283
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strlcat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jquenel <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/12 14:16:07 by jquenel #+# #+# */
/* Updated: 2017/11/13 10:05:56 by jquenel ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_strlcat(char *dest, const char *src, size_t size)
{
size_t i;
size_t j;
size_t len;
i = ft_strlen(dest);
len = ft_strlen(src) + (size < i ? size : i);
j = 0;
while ((int)i < (int)(size - 1))
{
dest[i++] = (src[j] ? src[j] : '\0');
if (src[j])
j++;
}
dest[i] = '\0';
return (len);
}
|
jquenel/libft
|
get_next_line/libft/ft_strlcat.c
|
C
|
gpl-3.0
| 1,227
|
<?php
/**
* Ce fichier fait parti de l'application de sondage du MEDDE/METL
* Cette application est un doodle-like permettant aux utilisateurs
* d'effectuer des sondages sur des dates ou bien d'autres criteres
*
* L'application est écrite en PHP5,HTML et Javascript
* et utilise une base de données postgresql et un annuaire LDAP pour l'authentification
*
* @author Thomas Payen
* @author PNE Annuaire et Messagerie
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Program\Lib\Request;
class Session_Memcache implements \SessionHandlerInterface {
/**
* @var \Memcache
*/
private $memcache;
/**
* @var int
*/
private $lifetime;
/**
* Constructeur par défaut de la classe session_memcache
*/
public function __construct() {
if (isset(\Config\IHM::$SESSION_LIFETIME))
$this->lifetime = \Config\IHM::$SESSION_LIFETIME * 60;
else
$this->lifetime = 60 * 60;
}
/**
* Ré-initialise une session existante ou en crée une nouvelle. Appelé lorsqu'une session est démarée ou lors de l'appel à session_start().
* @param string $save_path
* @param string $sessionid
*/
public function open($save_path, $sessionid) {
$this->memcache = new \Memcache();
$servers = \Config\IHM::$MEMCACHE_SERVER;
if (!is_array($servers))
$servers = array(\Config\IHM::$MEMCACHE_SERVER);
foreach($servers as $host) {
list($host, $port) = explode(':', $host);
if (!$port) $port = 11211;
$this->memcache->addserver($host, $port,
true, 1, 1, 15, false);
}
return true;
}
/**
* Ferme la session courante. Cette fonction est appelée automatiquement lors de la fermeture de la session, ou explicitement via session_write_close().
*/
public function close() {
return $this->memcache->close();
}
/**
* Lit les données de session depuis le support de stockage et retourne le résultat. Appelé juste après que la session démarre ou lorsque session_start() est appelée. Notez qu'avant que cette méthode ne soit appelée, SessionHandlerInterface::open() est invoquée.
*
* Cette méthode est appelée par PHP lui-même lorsque la session démarre. Cette méthode devrait retourner les données de session lues depuis le support de stockage en fonction de l'ID de session. La chaine retournée devrait être encodée par le même mécanisme de sérialisation que celui utilisé pour écrire les données lors de SessionHandlerInterface::write(). Si rien n'est lu, une chaine vide est retournée.
*
* Les données retournées par cette méthode seront décodées en interne par PHP en utilisant le mécanisme de désérialisation spécifié dans session.serialize_handler. Les données résultantes seront utilisées pour peupler $_SESSION.
*
* Notez que l'algorithme de sérialisation peut être différent de unserialize() et peut être utilisé manuellement au moyen de session_decode().
*
* @param string $sessionid
* @return string
*/
public function read($sessionid) {
if ($data = $this->memcache->get($sessionid))
return $data;
else
return "";
}
/**
* Ecrit les données de session dans le support de stockage. Appelé par session_write_close(), lorsque session_register_shutdown() échoue, et aussi durant la phase de terminaison de la requête. Note: SessionHandlerInterface::close() est appelée immediatement après.
*
* PHP appelera cette fonction lorsque la session est sur le point d'être sauvegardée et fermée. Il encode les données issues de $_SESSION vers une chaine sérialisée et la passe avec l'ID de session au support de stockage. La fonction de sérialisation est fournie dans session.serialize_handler.
*
* Cette méthode est appelée par PHP après qu'il ait fermé les tampons de sortie, sauf si vous l'invoquez vous-même au moyen de session_write_close().
*
* @param string $sessionid
* @param string $sessiondata
*/
public function write($sessionid, $sessiondata) {
return $this->memcache->set($sessionid, $sessiondata,
MEMCACHE_COMPRESSED, $this->lifetime + 60);
}
/**
* Détruit une session. Appelée par session_regenerate_id() (avec $destroy = TRUE), session_destroy() et lorsque session_decode() échoue.
* @param string $sessionid
*/
public function destroy($sessionid) {
if ($sessionid)
$this->memcache->delete($sessionid);
return true;
}
/**
* Nettoie les vieilles sessions expirées. Appelée par session_start(), en fonction de session.gc_divisor, session.gc_probability et session.gc_lifetime.
* @see SessionHandlerInterface::gc()
*/
public function gc($maxlifetime) {
return true;
}
}
|
messagerie-melanie2/Pegase
|
program/lib/request/session_memcache.php
|
PHP
|
gpl-3.0
| 5,627
|
/*
* This file is part of MUSIC.
* Copyright (C) 2009 INCF
*
* MUSIC 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.
*
* MUSIC 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/>.
*/
// NOTE: rename to Interpolator?
#ifndef MUSIC_SAMPLER_HH
#include <music/data_map.hh>
namespace MUSIC {
class Sampler {
DataMap* dataMap_;
DataMap* interpolationDataMap_;
bool hasSampled;
ContDataT* prevSample_;
ContDataT* sample_;
ContDataT* interpolationData_;
int elementSize;
int size;
public:
Sampler ();
~Sampler ();
void configure (DataMap* dataMap);
void initialize ();
DataMap* dataMap () { return dataMap_; }
// this class manages one single copy of the interpolation DataMap
DataMap* interpolationDataMap ();
void newSample ();
void sampleOnce ();
void sample ();
ContDataT* insert ();
void interpolate (double interpolationCoefficient);
void interpolateToApplication (double interpolationCoefficient);
private:
void swapBuffers (ContDataT*& b1, ContDataT*& b2);
void interpolateTo (DataMap* dataMap, double interpolationCoefficient);
void interpolate (int from,
int n,
double interpolationCoefficient,
double* dest);
void interpolate (int from,
int n,
float interpolationCoefficient,
float* dest);
};
}
#define MUSIC_SAMPLER_HH
#endif
|
favreau/music
|
src/music/sampler.hh
|
C++
|
gpl-3.0
| 1,923
|
<!DOCTYPE html>
<!--[if lt IE 7]> <html lang="en" ng-app="myApp" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html lang="en" ng-app="myApp" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html lang="en" ng-app="myApp" class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en" ng-app="myApp" class="no-js"> <!--<![endif]-->
<head>
<base href="/">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My AngularJS App</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="node_modules/angular-ui-bootstrap/dist/ui-bootstrap-csp.css">
</head>
<body>
<ul class="menu">
<li><a ui-sref="view1">view1</a></li>
<li><a ui-sref="view2">view2</a></li>
<li><a ui-sref="mygharseva-home">mygharseva</a></li>
</ul>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div ui-view></div>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>
-->
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-ui-router/release/angular-ui-router.js"></script>
<script src="node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js"></script>
<script src="app.js"></script>
<script src="view1/view1.js"></script>
<script src="view2/view2.js"></script>
<script src="components/version/version.js"></script>
<script src="components/version/version-directive.js"></script>
<script src="components/version/interpolate-filter.js"></script>
<!--
mygharseva
-->
<script src="mygharseva/home/mygharseva.home.config.js"></script>
<script src="mygharseva/home/mygharseva.home.MgsHomeController.js"></script>
<script src="mygharseva/home/mygharseva.home.directive.js"></script>
<script type="text/javascript" src="mygharseva/home/mygharseva.home.MenusFactory.js"></script>
</body>
</html>
|
rohittiwarirvt/mylaravelangular
|
public/index.html
|
HTML
|
gpl-3.0
| 2,272
|
OpenCart 1.5.5.1 = 683abf34d644796ee8f1fa885ac47d8f
OpenCart 1.5.6.1 = fea179d996ea99bc68c0c09077cd1501
|
gohdan/DFC
|
known_files/hashes/catalog/controller/checkout/login.php
|
PHP
|
gpl-3.0
| 104
|
@(field: forms.CostItemField,
questions: Map[String, Question],
answers: Map[String, String],
errs: Seq[forms.validation.FieldError],
hints: Seq[forms.validation.FieldHint])
@import helpers._
@import eu.timepit.refined.auto._
@errors = @{
errs.filter(p => p.path == field.name || p.path.startsWith(s"${field.name}."))
}
@errorClass = @{
if(errors.nonEmpty) "error" else ""
}
@errorClassFor(f: forms.Field) = @{
if(errs.exists(_.path == f.name)) "error" else ""
}
@errorsFor(f: forms.Field) = @{
errs.filter(_.path == f.name)
}
@errorBlock(f: forms.Field) = @{
if(errorsFor(f).nonEmpty) {
<span class="error-message">{errorsFor(f).head.err}</span>
}
}
@questions.get(field.name).map { q => <p class="question">@q.text</p>
@q.longDescription.map { desc => @splitLines(desc).map { text => <p>@text</p> } }
<details>
<summary role="button"><span class="summary">Help with this section</span></summary>
<div class="panel panel-border-narrow">@for(line <- splitLines(q.helpText)) {
<p>@line</p>
}</div>
</details>
}
<div class="column-full no-lr-padding">
@defining(field.itemNameField) { f =>
<div class="column-half no-l-padding">
<div class="form-group @errorClassFor(f)">
<label for="@f.name">@f.label</label>
@errorBlock(f)
<input type="text" id="@f.name" class="form-control text-field" title="@f.name" name="@f.name"
value='@answers.get(f.name)'>
</div>
</div>
}
@defining(field.costField) { f =>
<div class="column-half no-lr-padding">
<div class="form-group @errorClassFor(f)">
<div class="pull-right-lg-only">
<label for="@f.name">@f.label</label>
@errorBlock(f)
<div class="input-icon">
<i>£</i>
<input type="text" id="@f.name" class="form-control text-field currency" title="@f.name" name="@f.name" value='@answers.get(f.name)'>
</div>
</div>
</div>
</div>
}
</div>
@defining(field.justificationField) { f =>
<div class="column-full no-lr-padding">
<div class='form-group @errorClassFor(f)'>
<label for="@f.name">@f.label</label>
@errorBlock(f)
<textarea id="@f.name" class="form-control textarea-resize" title="@f.name" name="@f.name">@answers.get(f.name)</textarea>
<div class="inline right-align hint-text" id="@(f.name)_hint_text">@hints.find(_.path == f.name).map(_.hint)</div>
</div>
</div>
}
|
UKGovernmentBEIS/rifs-frontend-play
|
src/main/twirl/views/renderers/costItemField.scala.html
|
HTML
|
gpl-3.0
| 2,722
|
\section{Examples}\label{sec:examples}
We exemplarily solve the following problems in ASP:
$N$-Coloring (Section~\ref{subsec:ex:color}),
Traveling Salesperson (Section~\ref{subsec:ex:tsp}), and
Blocks-World Planning (Section~\ref{subsec:ex:block}).
While the first problem could likewise be solved within neighboring paradigms,
the second one requires checking reachability,
something that is rather hard to encode in either
Boolean Satisfiability~\cite{bihemawa08a} or
Constraint Programming~\cite{robewa06a}.
The third problem coming from the area of planning
illustrates incremental solving with \iclingo.
\subsection{$N$-Coloring}\label{subsec:ex:color}
As already mentioned in Section~\ref{subsec:asp},
it is custom in ASP to provide a \emph{uniform}
problem definition~\cite{martru99a,niemela99a,schlipf95a}.
We follow this methodology and separate the encoding
from an instance of the following problem:
given a (directed) graph, decide whether each node can be assigned
one of~$N$ colors such that any pair of adjacent nodes is colored differently.
Note that this problem is NP-complete for~$N\geq 3$
(see, e.g.,~\cite{papadimitriou94a}),
and thus it seems unlikely that a worst-case polynomial algorithm
can be found.
In view of this,
it is convenient to reduce the particular problem to
a declarative problem solving paradigm like ASP,
where efficient off-the-shelf tools like \gringo\ and \clasp\
are ready to solve the problem reasonably well.
Such a reduction is now exemplified.
\subsubsection{Problem Instance}\label{subsec:color:instance}
\input{figures/graph}
We consider directed graphs specified via facts over predicates
\pred{node}/$1$ and \pred{edge}/$2$.%
\footnote{%
Directedness is not an issue in $N$-Coloring,
but we will reuse our directed example graph in Section~\ref{subsec:ex:tsp}.}
The graph shown in Figure~\ref{fig:graph} is represented by the following set of facts:
%
\lstinputlisting{examples/graph.lp}
%
Recall from Section~\ref{subsec:lang:gringo} that~``\code{..}'' and~``\code{;}''
in the head expand to multiple rules, which are facts here.
Thus, the instance contains six nodes and 17 directed edges.
\subsubsection{Problem Encoding}\label{subsec:color:encoding}
We now proceed by encoding $N$-coloring via non-ground rules that are
independent of particular instances.
Typically, an encoding consists of a \emph{Generate}, a \emph{Define},
and a \emph{Test} part~\cite{lifschitz02a}.
As $N$-Coloring has a rather simple pattern, the following encoding does
not contain any Define part:
%
\lstinputlisting{examples/color.lp}
%
In Line~2, we use the \code{\#const} declarative,
described in Section~\ref{subsec:gringo:meta},
to install~\const{3} as default value for constant~\const{n} that is to be replaced
with the number~$N$ of colors.
(The default value can be overridden by invoking \gringo\ with option
\code{--const n=$N$}.)
The Generate rule in Line~4 makes use of the \const{count} aggregate
(cf.\ Section~\ref{subsec:gringo:aggregate}).
For our example graph and~\const{1} substituted for~\var{X},
we obtain the following ground rule:%
\marginlabel{%
The full ground program is obtained by invoking:\\
\code{\mbox{~}gringo -t \textbackslash\\
\mbox{~}examples/color.lp \textbackslash\\
\mbox{~}examples/graph.lp}}
%
\begin{lstlisting}[numbers=none]
1 { color(1,1), color(1,2), color(1,3) } 1.
\end{lstlisting}
%
Note that~\code{\pred{node}(\const{1})} has been removed from the body,
as it is derived via a corresponding fact,
and similar ground instances are obtained for the other nodes~\const{2} to~\const{6}.
Furthermore, for each instance of \pred{edge}/2,
we obtain~\code{n} ground instances of the integrity constraint in Line~6,
prohibiting that the same color~\var{C} is assigned to the adjacent nodes.
Given~\code{\const{n}=\const{3}},
we get the following ground instances due to \code{\pred{edge}(\const{1},\const{2})}:
%
\begin{lstlisting}[numbers=none]
:- color(1,1), color(2,1).
:- color(1,2), color(2,2).
:- color(1,3), color(2,3).
\end{lstlisting}
%
Again note that \code{\pred{edge}(\const{1},\const{2})},
derived via a fact, has been removed from the body.
\subsubsection{Problem Solution}\label{subsec:color:solution}
\input{figures/color}
Provided that a given graph is colorable with~\const{n} colors,
a solution can be read off an answer set of the program consisting
of the instance and the encoding.
For the graph in Figure~\ref{fig:graph},
the following answer set can be computed:%
\marginlabel{%
To find an answer set, invoke:\\
\code{\mbox{~}gringo \textbackslash\\
\mbox{~}examples/color.lp \textbackslash\\
\mbox{~}examples/graph.lp |\rlap{\:\textbackslash}\\
\mbox{~}clasp}\\
or alternatively:\\
\code{\mbox{~}clingo \textbackslash\\
\mbox{~}examples/color.lp \textbackslash\\
\mbox{~}examples/graph.lp}}
%
\begin{lstlisting}[numbers=none]
Answer: 1
... color(1,2) color(2,1) color(3,1) color(4,3) color(5,2) color(6,3)
\end{lstlisting}
%
Note that we have omitted the six instances of \pred{node}/$1$ and the
17 instances of \pred{edge}/$2$ in order to emphasize the actual solution,
which is depicted in Figure~\ref{fig:color}.
Such output projection can also be specified within a logic program file by
using the declaratives \code{\#hide} and \code{\#show},
described in Section~\ref{subsec:gringo:meta}.
\subsection{Traveling Salesperson}\label{subsec:ex:tsp}
We now consider the well-known Traveling Salesperson Problem (TSP),
where the task is to decide whether there is a round trip that visits
each node in a graph exactly once (viz., a Hamiltonian cycle) and whose
accumulated edge costs must not exceed some budget~$B$.
We tackle a slightly more general variant of the problem by not
a priori fixing~$B$ to any integer.
Rather,
we want to compute a minimum budget~$B$ along with a round trip of cost~$B$.
This problem is FP$^\textrm{NP}$-complete (cf.~\cite{papadimitriou94a}),
that is, it can be solved with a polynomial number of queries to an NP-oracle.
As with $N$-Coloring,
we provide a uniform problem definition by separating the encoding from instances.
\subsubsection{Problem Instance}\label{subsec:tsp:instance}
\input{figures/costs}
We reuse graph specifications in terms of predicates \pred{node}/$1$ and \pred{edge}/$2$
as in Section~\ref{subsec:color:instance}.
In addition, facts over predicate \pred{cost}/$3$ are used to define edge costs:
%
\lstinputlisting{examples/costs.lp}
%
Figure~\ref{fig:costs} shows the (directed) graph from Figure~\ref{fig:graph}
along with the associated edge costs.
Symmetric edges have the same costs here,
but differing costs would also be possible.
\subsubsection{Problem Encoding}\label{subsec:tsp:encoding}
The first subproblem consists of describing a Hamiltonian cycle,
constituting a candidate for a minimum-cost round trip.
Using the Generate-Define-Test pattern~\cite{lifschitz02a},
we encode this subproblem via the following non-ground rules:
%
\lstinputlisting{examples/ham.lp}
%
The Generate rules in Line~2 and~3 assert that every node must have
exactly one outgoing and exactly one incoming edge, respectively,
belonging to the cycle.
By inserting the available edges, for node~\const{1},
Line~2 and~3 are grounded as follows:%
\marginlabel{%
The full ground program is obtained by invoking:\\
\code{\mbox{~}gringo -t \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/min.lp \textbackslash\\
\mbox{~}examples/costs.lp \textbackslash\\
\mbox{~}examples/graph.lp}}
%
\begin{lstlisting}[numbers=none]
1 { cycle(1,2), cycle(1,3), cycle(1,4) } 1.
1 { cycle(3,1), cycle(4,1) } 1.
\end{lstlisting}
%
Observe that the first rule groups all outgoing edges of node~\const{1},
while the second one does the same for incoming edges.
We proceed by considering the Define rules in Line~5 and~6,
which recursively check whether nodes are reached by a cycle candidate
produced via the Generate part.
Note that the rule in Line~5 builds on the assumption that the cycle
``starts'' at node~\code{1}, that is,
any successor~\var{Y} of~\code{1} is reached by the cycle.
The second rule in Line~6 states that, from a reached node~\var{X},
an adjacent node~\var{Y} can be reached via a further edge in the cycle.
Note that this definition admits positive recursion
among the ground instances of \pred{reached}/$1$,
in which case a ground program is called \emph{non-tight}~\cite{erdlif03a,fages94a}.
The ``correct'' treatment of (positive) recursion due to the justification
requirement w.r.t.\ the reduct (cf.\ Section~\ref{subsec:semantics})
is a particular feature of answer set semantics,
which is hard to mimic in either
Boolean Satisfiability~\cite{bihemawa08a} or
Constraint Programming~\cite{robewa06a}.
In our present problem, this feature makes sure that all nodes are reached
by a global cycle from node~\code{1}, thus, excluding isolated subcycles.
In fact, the Test in Line~8 stipulates that every node in the given graph
is reached, that is, the instances of \pred{cycle}/$2$ in an answer set
must be the edges of a Hamiltonian cycle.%
\marginlabel{%
To compute the six Hamiltonian cycles
for the graph in Figure~\ref{fig:graph}, invoke:\\
\code{\mbox{~}gringo \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/graph.lp |\rlap{\:\textbackslash}\\
\mbox{~}clasp -n 0}\\
or alternatively:\\
\code{\mbox{~}clingo -n 0 \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/graph.lp}}
Finally, the additional Display part in Line~10 and~11 states that answer
sets should be projected to instances of \pred{cycle}/$2$, as only they
describe a solution.
We have so far not considered edge costs,
and answer sets for the above
part of the encoding correspond to Hamiltonian cycles,
that is, candidates for a minimum-cost round trip.
In order to minimize costs,
we add the following optimization statement:
%
\lstinputlisting[firstnumber=13]{examples/min.lp}
%
Here, edges belonging to the cycle are weighted according to their costs.
After grounding, the minimization in Line~14 ranges over~17 instances
of \pred{cycle}/$2$, one for each weighted edge in Figure~\ref{fig:costs}.
\subsubsection{Problem Solution}\label{subsec:tsp:solution}
\input{figures/tsp}
Finally, we explain how the unique minimum-cost round trip
(depicted in Figure~\ref{fig:tsp}) can be computed.
The catch is that we are now interested in optimal answer sets,
rather than in arbitrary ones.
In order to determine the optimum, we can start by gradually
decreasing the costs associated to answer sets
until we cannot find a strictly better one anymore.
To this end, it is important to invoke \clasp\ (or \clingo)
with option ``\code{-n~0}'' (cf.\ Section~\ref{subsec:opt:clasp}),
making it enumerate successively better answer sets
w.r.t.\ the provided optimization statements (cf.\ Section~\ref{subsec:gringo:optimize}).
Any answer set is printed as soon as it has been computed,
and the last one is optimal.
If there are multiple optimal answer sets, an arbitrary one among them is computed.
For the graph in Figure~\ref{fig:costs},
the optimal answer set (cf.\ Figure~\ref{fig:tsp}) is unique,
and its computation can proceed as follows:%
\marginlabel{%
To compute the minimum-cost round trip
for the graph in Figure~\ref{fig:costs}, invoke:\\
\code{\mbox{~}gringo \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/min.lp \textbackslash\\
\mbox{~}examples/costs.lp \textbackslash\\
\mbox{~}examples/graph.lp |\rlap{\:\textbackslash}\\
\mbox{~}clasp -n 0}\\
or alternatively:\\
\code{\mbox{~}clingo -n 0 \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/min.lp \textbackslash\\
\mbox{~}examples/costs.lp \textbackslash\\
\mbox{~}examples/graph.lp}}
%
\begin{lstlisting}[numbers=none]
Answer: 1
cycle(1,3) cycle(2,4) cycle(3,5) \
cycle(4,1) cycle(5,6) cycle(6,2)
Optimization: 13
Answer: 2
cycle(1,2) cycle(2,5) cycle(3,4) \
cycle(4,1) cycle(5,6) cycle(6,3)
Optimization: 11
\end{lstlisting}
%
Given that no answer is obtained after the second one,
we know that~\code{11} is the optimum value,
but there might be more optimal answer sets that have not been computed yet.
In order to find them too, we can use the following command line options
of \clasp\ (cf.\ Section~\ref{subsec:opt:clasp}):
``\code{--opt-value=11}'' in order to initialize the optimum and
``\code{--opt-all}'' to compute also equitable
(rather than only strictly better) answer sets.%
\marginlabel{%
The full invocation is:\\
\code{\mbox{~}gringo \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/min.lp \textbackslash\\
\mbox{~}examples/costs.lp \textbackslash\\
\mbox{~}examples/graph.lp |\rlap{\:\textbackslash}\\
\mbox{~}clasp -n 0 \textbackslash\\
\mbox{~}--opt-value=11 \textbackslash\\
\mbox{~}--opt-all}\\
or alternatively:\\
\code{\mbox{~}clingo -n 0 \textbackslash\\
\mbox{~}--opt-value=11 \textbackslash\\
\mbox{~}--opt-all \textbackslash\\
\mbox{~}examples/ham.lp \textbackslash\\
\mbox{~}examples/min.lp \textbackslash\\
\mbox{~}examples/costs.lp \textbackslash\\
\mbox{~}examples/graph.lp}}
After obtaining only the second answer given above,
we are sure that this is the unique optimal answer set,
whose associated edge costs (cf.\ Figure~\ref{fig:tsp}) correspond to
the reported optimization value~\code{11}.
Note that, with \const{maximize} statements in the input, this correlation
might be less straightforward because they are compiled into \const{minimize}
statements in the process of generating \lparse's output format~\cite{lparseManual}.
Furthermore, if there are multiple optimization statements,
\clasp\ (or \clingo) will report separate optimization values ordered by significance.
Finally, the two-stage invocation scheme exercised above,
first determining the optimum and afterwards all (and only) optimal answer sets,
is recommended for general use.
Otherwise,
if using option ``\code{--opt-all}'' right away without knowing the optimum,
one risks the enumeration of plenty suboptimal answer sets.
We also invite everyone to explore command line option ``\code{--opt-restart}''
(cf.\ Section~\ref{subsec:opt:clasp})
in order to see whether it improves search efficiency on optimization problems.
\subsection{Blocks-World Planning}\label{subsec:ex:block}
The Blocks-World is a well-known planning domain,
where finding \emph{shortest} plans has received particular attention~\cite{gupnau92a}.
In an eventually propositional formalism like ASP,
a bound on the plan length must be fixed before search can proceed.
This is usually accomplished by including some constant~\const{t}
in an encoding, which is then replaced with the actual bound during grounding.
Of course, if the length of a shortest plan is unknown,
an ASP system must repeatedly be queried while varying the bound.
With a traditional ASP system, processing
the same planning problem with a different bound
involves grounding and solving from scratch.
In order to reduce such redundancies,
the incremental ASP system \iclingo~\cite{gekakaosscth08a}
can gradually increase a bound, % thereby,
doing only the necessary additions in each step.
Note that planning is a natural application domain for \iclingo,
but other problems including some mutable bound can be addressed too, thus,
\iclingo\ is not a specialized planning system.
However, we use Blocks-World Planning to illustrate the exploitation of
\iclingo's incremental computation mode.
\subsubsection{Problem Instance}\label{subsec:block:instance}
As with the other two problems above,
an instance is given by a set of facts, here,
over predicates \pred{block}/$1$ (declaring blocks),
\pred{init}/$1$ (defining the initial state), and
\pred{goal}/$1$ (specifying the goal state).
A well-known Blocks-World instance is described by:%
\footnote{%
Blocks-World instances ``\code{examples/world$i$.lp}'' for
$i\in\{\code{0},\code{1},\code{2},\code{3},\code{4}\}$
are adaptations of the instances provided at~\cite{erdemBW}.}
%
\lstinputlisting{examples/world0.lp}
%
Note that the facts in Line~13--15 and~24--26 specify the initial
and the goal state depicted in Line~9-11 and~19--22, respectively.
We here use (uninterpreted) function \const{on}/$2$ to illustrate another
important feature available in \gringo, \clingo, and~\iclingo, namely,
the possibility of instantiating variables to compound terms.
\subsubsection{Problem Encoding}\label{subsec:block:encoding}
Our Blocks-World Planning encoding for \iclingo\ makes use of declaratives
\const{\#base}, \const{\#cumulative}, and \const{\#volatile},
separating the encoding into a static, a cumulative, and a volatile (query) part.
Each of them can be further refined into Generate, Define, Test, and Display constituents,
as indicated in the comments below:
%
\lstinputlisting{examples/blocks.lp}
%
In the initial \const{\#base} part (Line~1--5),
we define blocks and constant \const{table}
as instances of predicate \pred{location}/$1$.
Moreover, we use instances of \pred{init}/$1$
to initialize predicate \pred{holds}/$2$ for step~\const{0}, thus,
defining the conditions before the first incremental step.
Note that variable~\var{F} is instantiated to compound terms
over function \const{on}/$2$.
The \const{\#cumulative} statement in Line~7 declares constant~\code{t}
as a placeholder for step numbers in the cumulative encoding part below.
Here, the Generate rule in Line~9 states that exactly one block~\var{X}
must be moved to a location~\var{Y} (different from~\var{X}) at each step~\code{t}.
The integrity constraint in Line~11--13 is used to test whether
moving block~\var{X} to location~\var{Y} is possible at step~\code{t}
by denying~\code{\pred{move}(X,Y,t)} to hold if there
is either some block~\var{A} on~\var{X} or some block~\var{B} distinct from~\var{X} on~\var{Y}
(this condition is only checked if~\var{Y} is a block, viz., different from constant \const{table})
at step~\code{t-1}.
Finally, the Define rule in Line~15 propagates
a move to the state at step~\code{t},
while the rule in Line~16--17 states that a block~\var{X} stays on a location~\var{Z}
if it is not moved to any other location~\var{Y}.
Note that we require atoms \code{\pred{block}(\var{X})} and \code{\pred{location}(\var{Z})}
to bind variables~\var{X} and~\var{Z} in the body of the latter rule,
as recursive predicate \pred{holds}/$2$ cannot be used for this purpose
(cf.\ the definition of level-restrictedness in Section~\ref{subsec:lambda}).
The \const{\#volatile} statement in Line~19 declares the next part as a
query depending on step number~\const{t}, but not accumulated over
successive steps.
In fact, the integrity constraint in Line~21 tests whether goal conditions are
satisfied at step~\const{t}.
Our incremental encoding concludes with a second \const{\#base} part,
as specified in Line~23.
Note that, for the meta-statements with Display functionality (Line~25--26),
it is actually unimportant whether they belong to a static, cumulative, or
volatile program part, as answer sets are projected
(to instances of \pred{move}/$3$) in either case.
However, by ending the encoding file with a \const{\#base} statement,
we make sure that the contents of a concatenated instance file
is included in the static program part.
This is also the default of \iclingo\
(as well as of \gringo\ and \clingo\ that can be used for non-incremental computations),
but applying this default behavior triggers a warning (cf.\ Section~\ref{subsec:warn}).%
\marginlabel{%
To observe the ground program dealt with internally \iclingo\
at a step $n$, invoke:\\
\code{\mbox{~}gringo -t \textbackslash\\
\mbox{~}--ifixed=$n$ \textbackslash\\
\mbox{~}examples/blocks.lp \textbackslash\\
\mbox{~}examples/world$i$.lp}
where $i\in\{\code{0},\code{1},\code{2},\code{3},\code{4}\}$.}
Finally, let us stress important prerequisites for obtaining
a well-defined incremental computation result from \iclingo.
First, the ground instances of head atoms of rules in the
static, cumulative, and volatile program part must be pairwisely disjoint.
Furthermore, ground instances of head atoms in the volatile part
must not occur in the static and cumulative parts,
and those of the cumulative part must not be used in the static part.
Finally, ground instances of head atoms in either the cumulative or the volatile part
must be different for each pair of distinct steps.
This is the case for our encoding because both atoms over \pred{move}/$3$
and those over \pred{holds}/$2$ include~\const{t} as an argument in the
heads of the rules in Line~9, 15, and~16--17.
As the smallest step number to replace~\const{t} with is~\const{1},
there also is no clash with the ground atoms over \pred{holds}/$2$
obtained from the head of the static rule in Line~5.
Further details on the sketched requirements and their formal background can
be found in~\cite{gekakaosscth08a}.
Arguably, many problems including some mutable bound can be encoded
such that the prerequisites apply.
Some attention should of course be spent on
putting rules into the right program parts.
\subsubsection{Problem Solution}\label{subsec:block:solution}
We can now use \iclingo\ to \emph{incrementally} compute the shortest
sequence of moves that brings us from the initial to the goal state
depicted in the instance in Section~\ref{subsec:block:instance}:%
\marginlabel{%
To this end, invoke:\\
\code{\mbox{~}iclingo -n 0 \textbackslash\\
\mbox{~}examples/blocks.lp \textbackslash\\
\mbox{~}examples/world0.lp}}
%
\begin{lstlisting}[numbers=none]
Answer: 1
move(b2,table,1) move(b1,b0,2) move(b2,b1,3)
\end{lstlisting}
%
This unique answer set tells us that the given problem instance can
be solved by moving block~\const{b2} to the~\const{table} in order to
then put~\const{b1} on top of~\const{b0} and finally~\const{b2} on top of~\const{b1}.
This solution is computed by \iclingo\ in three grounding and solving steps,
where, starting from the \const{\#base} program, constant~\const{t}
is successively replaced with step numbers~\const{1}, \const{2}, and~\const{3}
in the~\const{\#cumulative} and in the~\const{\#volatile} part.
While the query postulated in the~\const{\#volatile} part cannot be
fulfilled in steps~\const{1} and~\const{2}, \iclingo\
stops its incremental computation after finding an answer set in step~\const{3}.
The scheme of iterating steps until finding at least one answer set
is the default behavior of~\iclingo,
which can be customized via command line options
(cf.\ Section~\ref{subsec:opt:iclingo}).
Finally, let us describe how solutions obtained via an incremental computation
can be computed in the standard way, that is, in a single pass.
To this end, the step number can be fixed to some~$n$ via
option ``\code{--ifixed=$n$}'' (cf.\ Section~\ref{subsec:opt:gringo}),
\marginlabel{%
For non-incremental solving, invoke:\\
\code{\mbox{~}gringo --ifixed=$n$ \textbackslash\\
\mbox{~}examples/blocks.lp \textbackslash\\
\mbox{~}examples/world$i$.lp |\rlap{\textbackslash}\\
\mbox{~}clasp -n 0}\\
or alternatively:\\
\code{\mbox{~}clingo -n 0 \textbackslash\\
\mbox{~}--ifixed=$n$ \textbackslash\\
\mbox{~}examples/blocks.lp \textbackslash\\
\mbox{~}examples/world$i$.lp}
where $i\in\{\code{0},\code{1},\code{2},\code{3},\code{4}\}$.}
enabling \gringo\ or \clingo\ to generate the ground program present
inside \iclingo\ at step~$n$.
Note that \const{\#volatile} parts are here only instantiated for the final step~$n$,
while \const{\#cumulative} rules are added for all steps $\const{1},\dots,n$.
Option ``\code{--ifixed=$n$}'' can be useful for investigating the contents
of a ground program dealt with at step~$n$ or for using an external solver
(other than \clasp).
In the latter case, repeated invocations with varying~$n$
are required if the bound of an optimal solution is a priori unknown.
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "guide"
%%% End:
|
grote/Online-ASP
|
doc/guide/examples.tex
|
TeX
|
gpl-3.0
| 24,168
|
// Author Notes:
// This file has been translated from English to Brazilian Portuguese by Seta00 from instantsfun.es
// This is the Import/Export Language File
<?php
define("_MENUIMPORTEXPORT","Importar/Exportar");
define("_DATAIMPORTEXPORT","Importar/Exportar dados");
define("_DATABASE","Salvar o banco de dados");
define("_BACKUPBANS","Salvar os bans em um arquivo .sql");
define("_LOCALBACKUPS","Backups locais");
define("_BANSIEXPORT","Importar/exportar bans");
define("_BACKUPALL","Salvar o banco de dados completo em um arquivo .sql");
define("_BACKUP","Criar Backup");
define("_RESTORE","Restaurar");
define("_IMPORT","Importar");
define("_EXPORT","Exportar");
define("_ONLYSTRUCTUR","Salvar somente a estrutura");
define("_INCLUDEDROP","Adicionar DROP TABLE");
define("_INCLUDEDELETE","Adicionar DELETE FROM");
define("_DOWNLOADAFTER","Baixar arquivo após criá-lo");
define("_UPLOADBACKUP","Enviar backup");
define("_BACKUPSUCCESS","Backup criado com sucesso");
define("_BACKUPFAILNOFILE","Falha no Backup: o arquivo não pôde ser criado!");
define("_IMPORTED","Bans importados");
define("_FAILED","falhas");
define("_DELALLIMPORTED","Apagar todos os bans importados");
define("_DELETEDBANS","Número de bans deletados");
define("_DBHOST","Host do banco de dados");
define("_DBUSER","Nome do usuário");
define("_DBPASSWORD","Senha");
define("_DBDATABASE","Banco de dados");
define("_DBTABLE","Tabela de bans");
define("_CONCHECK","Checar conexão");
define("_SET","Definir");
define("_ONLYPERMANENT","Somente bans permanentes");
define("_DELETELOCALTABLE","apagar os bans atuais antes da importação");
define("_SETALLNOTIMPORTED","Definir todos os bans como 'não importados'");
define("_INCLUDEREASON","Incluir razões de ban");
define("_EXPORTSUCCESS","Exportação concluída com sucesso");
define("_EXPORTFAILED","ERRO: a exportação falhou!");
define("_EXPORTED","Ban Exportados");
define("_IN","entrada");
define("_UPDATEDBANSNOTIMPORTED","Bans marcados como 'não importados'");
define("_DBDATAOK","Banco de dados OK");
define("_DBLOGINFAILED","Falha no login do banco de dados!");
define("_DBSELECTDBFAILED","Banco de dados não encontrado!");
define("_TABLESSELECTFAILED","Tabela não encontrada!");
define("_LOCALTABLEDELETED","Bans existentes foram deletados!");
define("_TITLEIEXPORT","Importar/exportar");
//alerts
define("_DELBACKUP","Você realmente deseja apagar este backup?");
define("_DATAIMPORT","Começar a importação?");
define("_DELIMPORT","Você realmente deseja apagar os dados importados?");
define("_SETIMPORT","Dados importados NÃO PODEM ser importados separadamente!");
//import from/export in
define("_IMP_FILE", "Importado do arquivo banned.cfg");
define("_IMP_DB", "Importado do banco de dados AMXBans 5.x");
define("_EXP_FILE", "Exportado para o arquivo banned.cfg");
?>
|
Ni3znajomy/AMXBans_amx
|
Web/language/lang.brazilian portuguese.iexport.php
|
PHP
|
gpl-3.0
| 2,883
|
/*
* Copyright 2014 Christian Weber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arrow.parser.xml.bpmn.element;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.arrow.model.gateway.impl.ComplexGateway;
/**
* {@link Converter} implementation used to convert BPMN
* {@link ComplexGateway} instances.
*
* @author christian.weber
* @since 1.0.0
*/
public class ComplexGatewayConverter implements Converter {
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("rawtypes")
public boolean canConvert(Class type) {
return ComplexGateway.class.isAssignableFrom(type);
}
/**
* {@inheritDoc}
*/
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
ComplexGateway gateway = new ComplexGateway();
gateway.setId(reader.getAttribute("id"));
gateway.setName(reader.getAttribute("name"));
if (reader.hasMoreChildren()) {
reader.moveDown();
while ("extensionElements".equals(reader.getNodeName()) && reader.hasMoreChildren()) {
reader.moveDown();
if ("class".equals(reader.getNodeName())) {
gateway.setClassName(reader.getValue());
}
else if ("bean".equals(reader.getNodeName())) {
gateway.setBeanName(reader.getValue());
}
reader.moveUp();
}
reader.moveUp();
}
return gateway;
}
}
|
christian-weber/arrow
|
arrow-xml/src/main/java/org/arrow/parser/xml/bpmn/element/ComplexGatewayConverter.java
|
Java
|
gpl-3.0
| 2,451
|
using System;
using System.Linq;
namespace PKHeX.Core
{
public class PK4 : PKM // 4th Generation PKM File
{
public static readonly byte[] ExtraBytes =
{
0x42, 0x43, 0x5E, 0x63, 0x64, 0x65, 0x66, 0x67, 0x87
};
public sealed override int SIZE_PARTY => PKX.SIZE_4PARTY;
public override int SIZE_STORED => PKX.SIZE_4STORED;
public override int Format => 4;
public override PersonalInfo PersonalInfo => PersonalTable.HGSS.getFormeEntry(Species, AltForm);
public PK4(byte[] decryptedData = null, string ident = null)
{
Data = (byte[])(decryptedData ?? new byte[SIZE_PARTY]).Clone();
PKMConverter.checkEncrypted(ref Data);
Identifier = ident;
if (Data.Length != SIZE_PARTY)
Array.Resize(ref Data, SIZE_PARTY);
}
public override PKM Clone() { return new PK4(Data); }
// Future Attributes
public override uint EncryptionConstant { get { return PID; } set { } }
public override int Nature { get { return (int)(PID%25); } set { } }
public override int CurrentFriendship { get { return OT_Friendship; } set { OT_Friendship = value; } }
public override int CurrentHandler { get { return 0; } set { } }
public override int AbilityNumber { get { return 1 << PIDAbility; } set { } }
// Structure
public override uint PID { get { return BitConverter.ToUInt32(Data, 0x00); } set { BitConverter.GetBytes(value).CopyTo(Data, 0x00); } }
public override ushort Sanity { get { return BitConverter.ToUInt16(Data, 0x04); } set { BitConverter.GetBytes(value).CopyTo(Data, 0x04); } }
public override ushort Checksum { get { return BitConverter.ToUInt16(Data, 0x06); } set { BitConverter.GetBytes(value).CopyTo(Data, 0x06); } }
#region Block A
public override int Species { get { return BitConverter.ToUInt16(Data, 0x08); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x08); } }
public override int HeldItem { get { return BitConverter.ToUInt16(Data, 0x0A); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x0A); } }
public override int TID { get { return BitConverter.ToUInt16(Data, 0x0C); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x0C); } }
public override int SID { get { return BitConverter.ToUInt16(Data, 0x0E); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x0E); } }
public override uint EXP { get { return BitConverter.ToUInt32(Data, 0x10); } set { BitConverter.GetBytes(value).CopyTo(Data, 0x10); } }
public override int OT_Friendship { get { return Data[0x14]; } set { Data[0x14] = (byte)value; } }
public override int Ability { get { return Data[0x15]; } set { Data[0x15] = (byte)value; } }
public override int MarkValue { get { return Data[0x16]; } protected set { Data[0x16] = (byte)value; } }
public override int Language { get { return Data[0x17]; } set { Data[0x17] = (byte)value; } }
public override int EV_HP { get { return Data[0x18]; } set { Data[0x18] = (byte)value; } }
public override int EV_ATK { get { return Data[0x19]; } set { Data[0x19] = (byte)value; } }
public override int EV_DEF { get { return Data[0x1A]; } set { Data[0x1A] = (byte)value; } }
public override int EV_SPE { get { return Data[0x1B]; } set { Data[0x1B] = (byte)value; } }
public override int EV_SPA { get { return Data[0x1C]; } set { Data[0x1C] = (byte)value; } }
public override int EV_SPD { get { return Data[0x1D]; } set { Data[0x1D] = (byte)value; } }
public override int CNT_Cool { get { return Data[0x1E]; } set { Data[0x1E] = (byte)value; } }
public override int CNT_Beauty { get { return Data[0x1F]; } set { Data[0x1F] = (byte)value; } }
public override int CNT_Cute { get { return Data[0x20]; } set { Data[0x20] = (byte)value; } }
public override int CNT_Smart { get { return Data[0x21]; } set { Data[0x21] = (byte)value; } }
public override int CNT_Tough { get { return Data[0x22]; } set { Data[0x22] = (byte)value; } }
public override int CNT_Sheen { get { return Data[0x23]; } set { Data[0x23] = (byte)value; } }
private byte RIB0 { get { return Data[0x24]; } set { Data[0x24] = value; } } // Sinnoh 1
private byte RIB1 { get { return Data[0x25]; } set { Data[0x25] = value; } } // Sinnoh 2
private byte RIB2 { get { return Data[0x26]; } set { Data[0x26] = value; } } // Unova 1
private byte RIB3 { get { return Data[0x27]; } set { Data[0x27] = value; } } // Unova 2
public bool RibbonChampionSinnoh { get { return (RIB0 & (1 << 0)) == 1 << 0; } set { RIB0 = (byte)(RIB0 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonAbility { get { return (RIB0 & (1 << 1)) == 1 << 1; } set { RIB0 = (byte)(RIB0 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonAbilityGreat { get { return (RIB0 & (1 << 2)) == 1 << 2; } set { RIB0 = (byte)(RIB0 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonAbilityDouble { get { return (RIB0 & (1 << 3)) == 1 << 3; } set { RIB0 = (byte)(RIB0 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonAbilityMulti { get { return (RIB0 & (1 << 4)) == 1 << 4; } set { RIB0 = (byte)(RIB0 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonAbilityPair { get { return (RIB0 & (1 << 5)) == 1 << 5; } set { RIB0 = (byte)(RIB0 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonAbilityWorld { get { return (RIB0 & (1 << 6)) == 1 << 6; } set { RIB0 = (byte)(RIB0 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonAlert { get { return (RIB0 & (1 << 7)) == 1 << 7; } set { RIB0 = (byte)(RIB0 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonShock { get { return (RIB1 & (1 << 0)) == 1 << 0; } set { RIB1 = (byte)(RIB1 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonDowncast { get { return (RIB1 & (1 << 1)) == 1 << 1; } set { RIB1 = (byte)(RIB1 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonCareless { get { return (RIB1 & (1 << 2)) == 1 << 2; } set { RIB1 = (byte)(RIB1 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonRelax { get { return (RIB1 & (1 << 3)) == 1 << 3; } set { RIB1 = (byte)(RIB1 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonSnooze { get { return (RIB1 & (1 << 4)) == 1 << 4; } set { RIB1 = (byte)(RIB1 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonSmile { get { return (RIB1 & (1 << 5)) == 1 << 5; } set { RIB1 = (byte)(RIB1 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonGorgeous { get { return (RIB1 & (1 << 6)) == 1 << 6; } set { RIB1 = (byte)(RIB1 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonRoyal { get { return (RIB1 & (1 << 7)) == 1 << 7; } set { RIB1 = (byte)(RIB1 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonGorgeousRoyal { get { return (RIB2 & (1 << 0)) == 1 << 0; } set { RIB2 = (byte)(RIB2 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonFootprint { get { return (RIB2 & (1 << 1)) == 1 << 1; } set { RIB2 = (byte)(RIB2 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonRecord { get { return (RIB2 & (1 << 2)) == 1 << 2; } set { RIB2 = (byte)(RIB2 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonEvent { get { return (RIB2 & (1 << 3)) == 1 << 3; } set { RIB2 = (byte)(RIB2 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonLegend { get { return (RIB2 & (1 << 4)) == 1 << 4; } set { RIB2 = (byte)(RIB2 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonChampionWorld { get { return (RIB2 & (1 << 5)) == 1 << 5; } set { RIB2 = (byte)(RIB2 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonBirthday { get { return (RIB2 & (1 << 6)) == 1 << 6; } set { RIB2 = (byte)(RIB2 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonSpecial { get { return (RIB2 & (1 << 7)) == 1 << 7; } set { RIB2 = (byte)(RIB2 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonSouvenir { get { return (RIB3 & (1 << 0)) == 1 << 0; } set { RIB3 = (byte)(RIB3 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonWishing { get { return (RIB3 & (1 << 1)) == 1 << 1; } set { RIB3 = (byte)(RIB3 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonClassic { get { return (RIB3 & (1 << 2)) == 1 << 2; } set { RIB3 = (byte)(RIB3 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonPremier { get { return (RIB3 & (1 << 3)) == 1 << 3; } set { RIB3 = (byte)(RIB3 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RIB3_4 { get { return (RIB3 & (1 << 4)) == 1 << 4; } set { RIB3 = (byte)(RIB3 & ~(1 << 4) | (value ? 1 << 4 : 0)); } } // Unused
public bool RIB3_5 { get { return (RIB3 & (1 << 5)) == 1 << 5; } set { RIB3 = (byte)(RIB3 & ~(1 << 5) | (value ? 1 << 5 : 0)); } } // Unused
public bool RIB3_6 { get { return (RIB3 & (1 << 6)) == 1 << 6; } set { RIB3 = (byte)(RIB3 & ~(1 << 6) | (value ? 1 << 6 : 0)); } } // Unused
public bool RIB3_7 { get { return (RIB3 & (1 << 7)) == 1 << 7; } set { RIB3 = (byte)(RIB3 & ~(1 << 7) | (value ? 1 << 7 : 0)); } } // Unused
#endregion
#region Block B
public override int Move1 { get { return BitConverter.ToUInt16(Data, 0x28); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x28); } }
public override int Move2 { get { return BitConverter.ToUInt16(Data, 0x2A); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x2A); } }
public override int Move3 { get { return BitConverter.ToUInt16(Data, 0x2C); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x2C); } }
public override int Move4 { get { return BitConverter.ToUInt16(Data, 0x2E); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x2E); } }
public override int Move1_PP { get { return Data[0x30]; } set { Data[0x30] = (byte)value; } }
public override int Move2_PP { get { return Data[0x31]; } set { Data[0x31] = (byte)value; } }
public override int Move3_PP { get { return Data[0x32]; } set { Data[0x32] = (byte)value; } }
public override int Move4_PP { get { return Data[0x33]; } set { Data[0x33] = (byte)value; } }
public override int Move1_PPUps { get { return Data[0x34]; } set { Data[0x34] = (byte)value; } }
public override int Move2_PPUps { get { return Data[0x35]; } set { Data[0x35] = (byte)value; } }
public override int Move3_PPUps { get { return Data[0x36]; } set { Data[0x36] = (byte)value; } }
public override int Move4_PPUps { get { return Data[0x37]; } set { Data[0x37] = (byte)value; } }
public uint IV32 { get { return BitConverter.ToUInt32(Data, 0x38); } set { BitConverter.GetBytes(value).CopyTo(Data, 0x38); } }
public override int IV_HP { get { return (int)(IV32 >> 00) & 0x1F; } set { IV32 = (uint)((IV32 & ~(0x1F << 00)) | (uint)((value > 31 ? 31 : value) << 00)); } }
public override int IV_ATK { get { return (int)(IV32 >> 05) & 0x1F; } set { IV32 = (uint)((IV32 & ~(0x1F << 05)) | (uint)((value > 31 ? 31 : value) << 05)); } }
public override int IV_DEF { get { return (int)(IV32 >> 10) & 0x1F; } set { IV32 = (uint)((IV32 & ~(0x1F << 10)) | (uint)((value > 31 ? 31 : value) << 10)); } }
public override int IV_SPE { get { return (int)(IV32 >> 15) & 0x1F; } set { IV32 = (uint)((IV32 & ~(0x1F << 15)) | (uint)((value > 31 ? 31 : value) << 15)); } }
public override int IV_SPA { get { return (int)(IV32 >> 20) & 0x1F; } set { IV32 = (uint)((IV32 & ~(0x1F << 20)) | (uint)((value > 31 ? 31 : value) << 20)); } }
public override int IV_SPD { get { return (int)(IV32 >> 25) & 0x1F; } set { IV32 = (uint)((IV32 & ~(0x1F << 25)) | (uint)((value > 31 ? 31 : value) << 25)); } }
public override bool IsEgg { get { return ((IV32 >> 30) & 1) == 1; } set { IV32 = (uint)((IV32 & ~0x40000000) | (uint)(value ? 0x40000000 : 0)); } }
public override bool IsNicknamed { get { return ((IV32 >> 31) & 1) == 1; } set { IV32 = (IV32 & 0x7FFFFFFF) | (value ? 0x80000000 : 0); } }
private byte RIB4 { get { return Data[0x3C]; } set { Data[0x3C] = value; } } // Hoenn 1a
private byte RIB5 { get { return Data[0x3D]; } set { Data[0x3D] = value; } } // Hoenn 1b
private byte RIB6 { get { return Data[0x3E]; } set { Data[0x3E] = value; } } // Hoenn 2a
private byte RIB7 { get { return Data[0x3F]; } set { Data[0x3F] = value; } } // Hoenn 2b
public bool RibbonG3Cool { get { return (RIB4 & (1 << 0)) == 1 << 0; } set { RIB4 = (byte)(RIB4 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonG3CoolSuper { get { return (RIB4 & (1 << 1)) == 1 << 1; } set { RIB4 = (byte)(RIB4 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonG3CoolHyper { get { return (RIB4 & (1 << 2)) == 1 << 2; } set { RIB4 = (byte)(RIB4 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonG3CoolMaster { get { return (RIB4 & (1 << 3)) == 1 << 3; } set { RIB4 = (byte)(RIB4 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonG3Beauty { get { return (RIB4 & (1 << 4)) == 1 << 4; } set { RIB4 = (byte)(RIB4 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonG3BeautySuper { get { return (RIB4 & (1 << 5)) == 1 << 5; } set { RIB4 = (byte)(RIB4 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonG3BeautyHyper { get { return (RIB4 & (1 << 6)) == 1 << 6; } set { RIB4 = (byte)(RIB4 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonG3BeautyMaster { get { return (RIB4 & (1 << 7)) == 1 << 7; } set { RIB4 = (byte)(RIB4 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonG3Cute { get { return (RIB5 & (1 << 0)) == 1 << 0; } set { RIB5 = (byte)(RIB5 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonG3CuteSuper { get { return (RIB5 & (1 << 1)) == 1 << 1; } set { RIB5 = (byte)(RIB5 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonG3CuteHyper { get { return (RIB5 & (1 << 2)) == 1 << 2; } set { RIB5 = (byte)(RIB5 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonG3CuteMaster { get { return (RIB5 & (1 << 3)) == 1 << 3; } set { RIB5 = (byte)(RIB5 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonG3Smart { get { return (RIB5 & (1 << 4)) == 1 << 4; } set { RIB5 = (byte)(RIB5 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonG3SmartSuper { get { return (RIB5 & (1 << 5)) == 1 << 5; } set { RIB5 = (byte)(RIB5 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonG3SmartHyper { get { return (RIB5 & (1 << 6)) == 1 << 6; } set { RIB5 = (byte)(RIB5 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonG3SmartMaster { get { return (RIB5 & (1 << 7)) == 1 << 7; } set { RIB5 = (byte)(RIB5 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonG3Tough { get { return (RIB6 & (1 << 0)) == 1 << 0; } set { RIB6 = (byte)(RIB6 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonG3ToughSuper { get { return (RIB6 & (1 << 1)) == 1 << 1; } set { RIB6 = (byte)(RIB6 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonG3ToughHyper { get { return (RIB6 & (1 << 2)) == 1 << 2; } set { RIB6 = (byte)(RIB6 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonG3ToughMaster { get { return (RIB6 & (1 << 3)) == 1 << 3; } set { RIB6 = (byte)(RIB6 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonChampionG3Hoenn { get { return (RIB6 & (1 << 4)) == 1 << 4; } set { RIB6 = (byte)(RIB6 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonWinning { get { return (RIB6 & (1 << 5)) == 1 << 5; } set { RIB6 = (byte)(RIB6 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonVictory { get { return (RIB6 & (1 << 6)) == 1 << 6; } set { RIB6 = (byte)(RIB6 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonArtist { get { return (RIB6 & (1 << 7)) == 1 << 7; } set { RIB6 = (byte)(RIB6 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonEffort { get { return (RIB7 & (1 << 0)) == 1 << 0; } set { RIB7 = (byte)(RIB7 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonChampionBattle { get { return (RIB7 & (1 << 1)) == 1 << 1; } set { RIB7 = (byte)(RIB7 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonChampionRegional{ get { return (RIB7 & (1 << 2)) == 1 << 2; } set { RIB7 = (byte)(RIB7 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonChampionNational{ get { return (RIB7 & (1 << 3)) == 1 << 3; } set { RIB7 = (byte)(RIB7 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonCountry { get { return (RIB7 & (1 << 4)) == 1 << 4; } set { RIB7 = (byte)(RIB7 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonNational { get { return (RIB7 & (1 << 5)) == 1 << 5; } set { RIB7 = (byte)(RIB7 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonEarth { get { return (RIB7 & (1 << 6)) == 1 << 6; } set { RIB7 = (byte)(RIB7 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonWorld { get { return (RIB7 & (1 << 7)) == 1 << 7; } set { RIB7 = (byte)(RIB7 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public override bool FatefulEncounter { get { return (Data[0x40] & 1) == 1; } set { Data[0x40] = (byte)(Data[0x40] & ~0x01 | (value ? 1 : 0)); } }
public override int Gender { get { return (Data[0x40] >> 1) & 0x3; } set { Data[0x40] = (byte)(Data[0x40] & ~0x06 | (value << 1)); } }
public override int AltForm { get { return Data[0x40] >> 3; } set { Data[0x40] = (byte)(Data[0x40] & 0x07 | (value << 3)); } }
// 0x43-0x47 Unused
#endregion
#region Block C
public override string Nickname
{
get
{
return PKX.array2strG4(Data.Skip(0x48).Take(22).ToArray())
.Replace("\uFF0D", "\u30FC") // Japanese chōonpu
.Replace("\uE08F", "\u2640") // nidoran
.Replace("\uE08E", "\u2642") // nidoran
.Replace("\u2019", "\u0027"); // farfetch'd
}
set
{
if (value.Length > 11)
value = value.Substring(0, 11); // Hard cap
string TempNick = value // Replace Special Characters and add Terminator
.Replace("\u30FC", "\uFF0D") // Japanese chōonpu
.Replace("\u2640", "\uE08F") // nidoran
.Replace("\u2642", "\uE08E") // nidoran
.Replace("\u0027", "\u2019"); // farfetch'd
PKX.str2arrayG4(TempNick).CopyTo(Data, 0x48);
}
}
// 0x5E unused
public override int Version { get { return Data[0x5F]; } set { Data[0x5F] = (byte)value; } }
private byte RIB8 { get { return Data[0x60]; } set { Data[0x60] = value; } } // Sinnoh 3
private byte RIB9 { get { return Data[0x61]; } set { Data[0x61] = value; } } // Sinnoh 4
private byte RIBA { get { return Data[0x62]; } set { Data[0x62] = value; } } // Sinnoh 5
private byte RIBB { get { return Data[0x63]; } set { Data[0x63] = value; } } // Sinnoh 6
public bool RibbonG4Cool { get { return (RIB8 & (1 << 0)) == 1 << 0; } set { RIB8 = (byte)(RIB8 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonG4CoolGreat { get { return (RIB8 & (1 << 1)) == 1 << 1; } set { RIB8 = (byte)(RIB8 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonG4CoolUltra { get { return (RIB8 & (1 << 2)) == 1 << 2; } set { RIB8 = (byte)(RIB8 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonG4CoolMaster { get { return (RIB8 & (1 << 3)) == 1 << 3; } set { RIB8 = (byte)(RIB8 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonG4Beauty { get { return (RIB8 & (1 << 4)) == 1 << 4; } set { RIB8 = (byte)(RIB8 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonG4BeautyGreat { get { return (RIB8 & (1 << 5)) == 1 << 5; } set { RIB8 = (byte)(RIB8 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonG4BeautyUltra { get { return (RIB8 & (1 << 6)) == 1 << 6; } set { RIB8 = (byte)(RIB8 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonG4BeautyMaster { get { return (RIB8 & (1 << 7)) == 1 << 7; } set { RIB8 = (byte)(RIB8 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonG4Cute { get { return (RIB9 & (1 << 0)) == 1 << 0; } set { RIB9 = (byte)(RIB9 & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonG4CuteGreat { get { return (RIB9 & (1 << 1)) == 1 << 1; } set { RIB9 = (byte)(RIB9 & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonG4CuteUltra { get { return (RIB9 & (1 << 2)) == 1 << 2; } set { RIB9 = (byte)(RIB9 & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonG4CuteMaster { get { return (RIB9 & (1 << 3)) == 1 << 3; } set { RIB9 = (byte)(RIB9 & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RibbonG4Smart { get { return (RIB9 & (1 << 4)) == 1 << 4; } set { RIB9 = (byte)(RIB9 & ~(1 << 4) | (value ? 1 << 4 : 0)); } }
public bool RibbonG4SmartGreat { get { return (RIB9 & (1 << 5)) == 1 << 5; } set { RIB9 = (byte)(RIB9 & ~(1 << 5) | (value ? 1 << 5 : 0)); } }
public bool RibbonG4SmartUltra { get { return (RIB9 & (1 << 6)) == 1 << 6; } set { RIB9 = (byte)(RIB9 & ~(1 << 6) | (value ? 1 << 6 : 0)); } }
public bool RibbonG4SmartMaster { get { return (RIB9 & (1 << 7)) == 1 << 7; } set { RIB9 = (byte)(RIB9 & ~(1 << 7) | (value ? 1 << 7 : 0)); } }
public bool RibbonG4Tough { get { return (RIBA & (1 << 0)) == 1 << 0; } set { RIBA = (byte)(RIBA & ~(1 << 0) | (value ? 1 << 0 : 0)); } }
public bool RibbonG4ToughGreat { get { return (RIBA & (1 << 1)) == 1 << 1; } set { RIBA = (byte)(RIBA & ~(1 << 1) | (value ? 1 << 1 : 0)); } }
public bool RibbonG4ToughUltra { get { return (RIBA & (1 << 2)) == 1 << 2; } set { RIBA = (byte)(RIBA & ~(1 << 2) | (value ? 1 << 2 : 0)); } }
public bool RibbonG4ToughMaster { get { return (RIBA & (1 << 3)) == 1 << 3; } set { RIBA = (byte)(RIBA & ~(1 << 3) | (value ? 1 << 3 : 0)); } }
public bool RIBA_4 { get { return (RIBA & (1 << 4)) == 1 << 4; } set { RIBA = (byte)(RIBA & ~(1 << 4) | (value ? 1 << 4 : 0)); } } // Unused
public bool RIBA_5 { get { return (RIBA & (1 << 5)) == 1 << 5; } set { RIBA = (byte)(RIBA & ~(1 << 5) | (value ? 1 << 5 : 0)); } } // Unused
public bool RIBA_6 { get { return (RIBA & (1 << 6)) == 1 << 6; } set { RIBA = (byte)(RIBA & ~(1 << 6) | (value ? 1 << 6 : 0)); } } // Unused
public bool RIBA_7 { get { return (RIBA & (1 << 7)) == 1 << 7; } set { RIBA = (byte)(RIBA & ~(1 << 7) | (value ? 1 << 7 : 0)); } } // Unused
public bool RIBB_0 { get { return (RIBB & (1 << 0)) == 1 << 0; } set { RIBB = (byte)(RIBB & ~(1 << 0) | (value ? 1 << 0 : 0)); } } // Unused
public bool RIBB_1 { get { return (RIBB & (1 << 1)) == 1 << 1; } set { RIBB = (byte)(RIBB & ~(1 << 1) | (value ? 1 << 1 : 0)); } } // Unused
public bool RIBB_2 { get { return (RIBB & (1 << 2)) == 1 << 2; } set { RIBB = (byte)(RIBB & ~(1 << 2) | (value ? 1 << 2 : 0)); } } // Unused
public bool RIBB_3 { get { return (RIBB & (1 << 3)) == 1 << 3; } set { RIBB = (byte)(RIBB & ~(1 << 3) | (value ? 1 << 3 : 0)); } } // Unused
public bool RIBB_4 { get { return (RIBB & (1 << 4)) == 1 << 4; } set { RIBB = (byte)(RIBB & ~(1 << 4) | (value ? 1 << 4 : 0)); } } // Unused
public bool RIBB_5 { get { return (RIBB & (1 << 5)) == 1 << 5; } set { RIBB = (byte)(RIBB & ~(1 << 5) | (value ? 1 << 5 : 0)); } } // Unused
public bool RIBB_6 { get { return (RIBB & (1 << 6)) == 1 << 6; } set { RIBB = (byte)(RIBB & ~(1 << 6) | (value ? 1 << 6 : 0)); } } // Unused
public bool RIBB_7 { get { return (RIBB & (1 << 7)) == 1 << 7; } set { RIBB = (byte)(RIBB & ~(1 << 7) | (value ? 1 << 7 : 0)); } } // Unused
// 0x64-0x67 Unused
#endregion
#region Block D
public override string OT_Name
{
get
{
return PKX.array2strG4(Data.Skip(0x68).Take(16).ToArray())
.Replace("\uFF0D", "\u30FC") // Japanese chōonpu
.Replace("\uE08F", "\u2640") // Nidoran ♂
.Replace("\uE08E", "\u2642") // Nidoran ♀
.Replace("\u2019", "\u0027"); // Farfetch'd
}
set
{
if (value.Length > 7)
value = value.Substring(0, 7); // Hard cap
string TempNick = value // Replace Special Characters and add Terminator
.Replace("\u30FC", "\uFF0D") // Japanese chōonpu
.Replace("\u2640", "\uE08F") // Nidoran ♂
.Replace("\u2642", "\uE08E") // Nidoran ♀
.Replace("\u0027", "\u2019"); // Farfetch'd
PKX.str2arrayG4(TempNick).CopyTo(Data, 0x68);
}
}
public override int Egg_Year { get { return Data[0x78]; } set { Data[0x78] = (byte)value; } }
public override int Egg_Month { get { return Data[0x79]; } set { Data[0x79] = (byte)value; } }
public override int Egg_Day { get { return Data[0x7A]; } set { Data[0x7A] = (byte)value; } }
public override int Met_Year { get { return Data[0x7B]; } set { Data[0x7B] = (byte)value; } }
public override int Met_Month { get { return Data[0x7C]; } set { Data[0x7C] = (byte)value; } }
public override int Met_Day { get { return Data[0x7D]; } set { Data[0x7D] = (byte)value; } }
public override int Egg_Location
{
get
{
ushort hgssloc = BitConverter.ToUInt16(Data, 0x44);
if (hgssloc != 0)
return hgssloc;
return BitConverter.ToUInt16(Data, 0x7E);
}
set
{
if (value == 0)
{
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x44);
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x7E);
}
else if (PtHGSS)
{
BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x44);
BitConverter.GetBytes((ushort)0xBBA).CopyTo(Data, 0x7E); // Faraway Place (for DP display)
}
else if ((value < 2000 && value > 111) || (value < 3000 && value > 2010))
{
// Met location not in DP, set to Mystery Zone (0, illegal) as opposed to Faraway Place
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x44);
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x7E);
}
else
{
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x44);
BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x7E);
}
}
}
public override int Met_Location
{
get
{
ushort hgssloc = BitConverter.ToUInt16(Data, 0x46);
if (hgssloc != 0)
return hgssloc;
return BitConverter.ToUInt16(Data, 0x80);
}
set
{
if (value == 0)
{
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x46);
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x80);
}
else if (PtHGSS)
{
BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x46);
BitConverter.GetBytes((ushort)0xBBA).CopyTo(Data, 0x80); // Faraway Place (for DP display)
}
else if ((value < 2000 && value > 111) || (value < 3000 && value > 2010))
{
// Met location not in DP, set to Mystery Zone (0, illegal) as opposed to Faraway Place
BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x46);
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x80);
}
else
{
BitConverter.GetBytes((ushort)0).CopyTo(Data, 0x46);
BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x80);
}
}
}
private byte PKRS { get { return Data[0x82]; } set { Data[0x82] = value; } }
public override int PKRS_Days { get { return PKRS & 0xF; } set { PKRS = (byte)(PKRS & ~0xF | value); } }
public override int PKRS_Strain { get { return PKRS >> 4; } set { PKRS = (byte)(PKRS & 0xF | (value << 4)); } }
public override int Ball
{
get
{
// Pokemon obtained in HGSS have the HGSS ball set (@0x86)
// However, this info is not set when receiving a wondercard!
// The PGT contains a preformatted PK4 file, which is slightly modified.
// No HGSS balls were used, and no HGSS ball info is set.
// Sneaky way = return the higher of the two values.
return Math.Max(Data[0x86], Data[0x83]);
}
set
{
// Ball to display in DPPt
Data[0x83] = (byte)(value <= 0x10 ? value : 4); // Cap at Cherish Ball
// HGSS Exclusive Balls -- If the user wants to screw things up, let them. Any legality checking could catch hax.
if (value > 0x10 || (HGSS && !FatefulEncounter))
Data[0x86] = (byte)(value <= 0x18 ? value : 4); // Cap at Comp Ball
else
Data[0x86] = 0; // Unused
}
}
public override int Met_Level { get { return Data[0x84] & ~0x80; } set { Data[0x84] = (byte)((Data[0x84] & 0x80) | value); } }
public override int OT_Gender { get { return Data[0x84] >> 7; } set { Data[0x84] = (byte)((Data[0x84] & ~0x80) | value << 7); } }
public override int EncounterType { get { return Data[0x85]; } set { Data[0x85] = (byte)value; } }
// Unused 0x87
#endregion
public override int Stat_Level { get { return Data[0x8C]; } set { Data[0x8C] = (byte)value; } }
public override int Stat_HPCurrent { get { return BitConverter.ToUInt16(Data, 0x8E); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x8E); } }
public override int Stat_HPMax { get { return BitConverter.ToUInt16(Data, 0x90); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x90); } }
public override int Stat_ATK { get { return BitConverter.ToUInt16(Data, 0x92); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x92); } }
public override int Stat_DEF { get { return BitConverter.ToUInt16(Data, 0x94); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x94); } }
public override int Stat_SPE { get { return BitConverter.ToUInt16(Data, 0x96); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x96); } }
public override int Stat_SPA { get { return BitConverter.ToUInt16(Data, 0x98); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x98); } }
public override int Stat_SPD { get { return BitConverter.ToUInt16(Data, 0x9A); } set { BitConverter.GetBytes((ushort)value).CopyTo(Data, 0x9A); } }
public override int PSV => (int)((PID >> 16 ^ PID & 0xFFFF) >> 3);
public override int TSV => (TID ^ SID) >> 3;
public override int Characteristic
{
get
{
// Characteristic with PID%6
int pm6 = (int)(PID % 6); // PID MOD 6
int maxIV = IVs.Max();
int pm6stat = 0;
for (int i = 0; i < 6; i++)
{
pm6stat = (pm6 + i) % 6;
if (IVs[pm6stat] == maxIV)
break; // P%6 is this stat
}
return pm6stat * 5 + maxIV % 5;
}
}
// Legality Extensions
public override bool WasEgg => GenNumber < 4 ? base.WasEgg : Species == 490 && Egg_Location == 3001 || Legal.EggLocations4.Contains(Egg_Location);
public override bool WasEvent => Met_Location >= 3000 && Met_Location <= 3076 || FatefulEncounter;
public override bool WasIngameTrade => Met_Location == 2001; // Trade
public override bool WasEventEgg => WasEgg && Species == 490; // Manaphy was the only generation 4 released event egg
// Methods
public override byte[] Encrypt()
{
RefreshChecksum();
return PKX.encryptArray45(Data);
}
public BK4 convertToBK4()
{
BK4 bk4 = new BK4();
TransferPropertiesWithReflection(this, bk4);
// Fix Non-Reflectable properties
Array.Copy(Data, 0x78, bk4.Data, 0x78, 6); // Met Info
// Preserve Trash Bytes
for (int i = 0; i < 11; i++) // Nickname
{
bk4.Data[0x48 + 2*i] = Data[0x48 + 2*i + 1];
bk4.Data[0x48 + 2*i + 1] = Data[0x48 + 2*i];
}
for (int i = 0; i < 8; i++) // OT_Name
{
bk4.Data[0x68 + 2*i] = Data[0x68 + 2*i + 1];
bk4.Data[0x68 + 2*i + 1] = Data[0x68 + 2*i];
}
bk4.Sanity = 0x4000;
bk4.RefreshChecksum();
return bk4;
}
public PK5 convertToPK5()
{
// Double Check Location Data to see if we're already a PK5
if (Data[0x5F] < 0x10 && BitConverter.ToUInt16(Data, 0x80) > 0x4000)
return new PK5(Data);
DateTime moment = DateTime.Now;
PK5 pk5 = new PK5(Data) // Convert away!
{
OT_Friendship = 70,
// Apply new met date
MetDate = moment
};
// Arceus Type Changing -- Plate forcibly removed.
if (pk5.Species == 493)
{
pk5.AltForm = 0;
pk5.HeldItem = 0;
}
else
{
pk5.HeldItem = Legal.HeldItems_BW.Contains((ushort) HeldItem) ? HeldItem : 0;
}
// Fix PP
pk5.Move1_PP = pk5.getMovePP(pk5.Move1, pk5.Move1_PPUps);
pk5.Move2_PP = pk5.getMovePP(pk5.Move2, pk5.Move2_PPUps);
pk5.Move3_PP = pk5.getMovePP(pk5.Move3, pk5.Move3_PPUps);
pk5.Move4_PP = pk5.getMovePP(pk5.Move4, pk5.Move4_PPUps);
// Disassociate Nature and PID, pk4 getter does PID%25
pk5.Nature = Nature;
// Delete Platinum/HGSS Met Location Data
BitConverter.GetBytes((uint)0).CopyTo(pk5.Data, 0x44);
// Met / Crown Data Detection
pk5.Met_Location = pk5.Gen4 && pk5.FatefulEncounter && Array.IndexOf(Legal.CrownBeasts, pk5.Species) >= 0
? (pk5.Species == 251 ? 30010 : 30012) // Celebi : Beast
: 30001; // Pokétransfer (not Crown)
// Delete HGSS Data
BitConverter.GetBytes((ushort)0).CopyTo(pk5.Data, 0x86);
pk5.Ball = Ball;
// Transfer Nickname and OT Name
pk5.Nickname = Nickname;
pk5.OT_Name = OT_Name;
// Fix Level
pk5.Met_Level = PKX.getLevel(pk5.Species, pk5.EXP);
// Remove HM moves; Defog should be kept if both are learned.
int[] banned = Moves.Contains(250) && Moves.Contains(432) // Whirlpool & Defog
? new[] {15, 19, 57, 70, 250, 249, 127, 431} // No Whirlpool
: new[] {15, 19, 57, 70, 249, 127, 431};// Transfer via advantageous game
int[] newMoves = pk5.Moves;
for (int i = 0; i < 4; i++)
if (banned.Contains(newMoves[i]))
newMoves[i] = 0;
pk5.Moves = newMoves;
pk5.FixMoves();
pk5.RefreshChecksum();
return pk5;
}
}
}
|
suloku/PKHeX
|
PKHeX/PKM/PK4.cs
|
C#
|
gpl-3.0
| 37,115
|
(function($) {
$.fn.swipeEvents = function() {
return this.each(function() {
var startX,
startY,
$this = $(this);
$this.on('touchstart', touchstart);
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
startX = touches[0].pageX;
startY = touches[0].pageY;
$this.on('touchmove', touchmove);
$this.on('touchend', touchend);
}
event.preventDefault();
}
function touchmove(event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
var deltaX = startX - touches[0].pageX;
var deltaY = startY - touches[0].pageY;
if (deltaX >= 50) {
$this.trigger("swipeLeft");
}
if (deltaX <= -50) {
$this.trigger("swipeRight");
}
if (deltaY >= 50) {
$this.trigger("swipeUp");
}
if (deltaY <= -50) {
$this.trigger("swipeDown");
}
if (Math.abs(deltaX) >= 50 || Math.abs(deltaY) >= 50) {
$this.off('touchmove', touchmove);
$this.off('touchend', touchend);
}
}
event.preventDefault();
}
function touchend(event) {
$this.off('touchmove', touchmove);
event.preventDefault();
}
});
};
})(jQuery);
|
Qantas94Heavy/gamepad-shim
|
site/js/lib/jquery.swipe-events.js
|
JavaScript
|
gpl-3.0
| 1,495
|
<?php
namespace Agi\Action;
use Agi\Wrapper;
use Ivoz\Core\Infrastructure\Persistence\Doctrine\Model\Helper\CriteriaHelper;
use Ivoz\Provider\Domain\Model\CallForwardSetting\CallForwardSettingInterface;
use Ivoz\Provider\Domain\Model\ResidentialDevice\ResidentialDeviceInterface;
class ResidentialCallAction
{
/**
* @var Wrapper
*/
protected $agi;
/**
* @var ResidentialDeviceInterface
*/
protected $residentialDevice;
/**
* @var ResidentialStatusAction
*/
protected $residentialStatusAction;
/**
* ResidentialCallAction constructor.
* @param Wrapper $agi
* @param ResidentialStatusAction $residentialStatusAction
*/
public function __construct(
Wrapper $agi,
ResidentialStatusAction $residentialStatusAction
)
{
$this->agi = $agi;
$this->residentialStatusAction = $residentialStatusAction;
}
/**
* @param ResidentialDeviceInterface|null $residentialDevice
* @return $this
*/
public function setResidentialDevice(ResidentialDeviceInterface $residentialDevice = null)
{
$this->residentialDevice = $residentialDevice;
return $this;
}
public function process()
{
// Local variables to improve readability
$residentialDevice = $this->residentialDevice;
if (is_null($residentialDevice)) {
$this->agi->error("Residential Device is not properly defined. Check configuration.");
return;
}
// Get dialed number
$number = $this->agi->getExtension();
// Some verbose dolan pls
$this->agi->notice("Preparing call to %s through account %s", $number, $residentialDevice);
// Check if user has call forwarding enabled
$forwarded = $this->residentialStatusAction
->setResidentialDevice($residentialDevice)
->setDialStatus(ResidentialStatusAction::Forwarded)
->process();
if ($forwarded) {
return;
}
// Get device endpoint
$endpointName = $residentialDevice->getSorcery();
// Configure Dial options
$timeout = $this->getDialTimeout();
$options = "";
if ($this->getResidentialStatusRequired()) {
$options .= "g";
}
// Call the PSJIP endpoint
$this->agi->setVariable("DIAL_EXT", $number);
$this->agi->setVariable("DIAL_DST", "PJSIP/$endpointName");
$this->agi->setVariable("__DIAL_ENDPOINT", $endpointName);
$this->agi->setVariable("DIAL_TIMEOUT", $timeout);
$this->agi->setVariable("DIAL_OPTS", $options);
// Redirect to the calling dialplan context
$this->agi->redirect('call-residential', $number);
}
/**
* If Device has NoAnswer Call forward setting, return the dial timeout
*
* @return string
*/
private function getDialTimeout()
{
$timeout = null;
// Get active NoAnswer call forwards
$criteria = [
array('callForwardType', 'eq', 'noAnswer'),
array('enabled', 'eq', '1'),
];
/**
* @var CallForwardSettingInterface[] $cfwSettings
*/
$cfwSettings = $this->residentialDevice
->getCallForwardSettings(
CriteriaHelper::fromArray($criteria)
);
foreach ($cfwSettings as $cfwSetting) {
$cfwType = $cfwSetting->getCallTypeFilter();
if ($cfwType == "both" || $cfwType == $this->agi->getCallType()) {
$this->agi->verbose("Call Forward No answer enabled [%s]. Setting call timeout.", $cfwSetting);
$timeout = $cfwSetting->getNoAnswerTimeout();
}
}
return ($timeout)?:"";
}
/**
* Determine if we must check call status after dialing the residential device
*
* @return boolean
*/
private function getResidentialStatusRequired()
{
// internal or external call
$callType = $this->agi->getCallType();
// Build the criteria to look for call forward settings
$criteria = [
'or' => array(
array('callForwardType', 'eq', 'noAnswer'),
array('callForwardType', 'eq', 'busy'),
array('callForwardType', 'eq', 'userNotRegistered'),
),
'or' => array(
array('callTypeFilter', 'eq', 'both'),
array('callTypeFilter', 'eq', $callType),
),
array('enabled', 'eq', '1')
];
/** @var CallForwardSettingInterface[] $cfwSettings */
$cfwSettings = $this->residentialDevice
->getCallForwardSettings(
CriteriaHelper::fromArray($criteria)
);
// Return true if any of the requested Call forwards exist
$settingNotEmpty = !empty($cfwSettings);
return $settingNotEmpty;
}
}
|
manfer/ivozprovider
|
asterisk/agi/src/Agi/Action/ResidentialCallAction.php
|
PHP
|
gpl-3.0
| 4,985
|
SELECT COUNT(*) AS `Total number of runs` from runs;
SELECT * from processing_status_codes;
SELECT processing_status_code, COUNT(*) from runs GROUP BY processing_status_code;
SELECT station_name, COUNT(*) from runs WHERE run_date >= '2015-02-23' GROUP BY station_name;
SELECT COUNT(*) from runs WHERE run_date >= '2015-02-23';
SELECT station_name, COUNT(*) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.8 AND num_track_events/(run_stop - run_start) > 8. AND num_track_events/(run_stop - run_start) < 80. GROUP BY station_name;
SELECT COUNT(*) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.8 AND num_track_events/(run_stop - run_start) > 8. AND num_track_events/(run_stop - run_start) < 80.;
SELECT station_name, COUNT(*) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.4 AND num_track_events/(run_stop - run_start) > 4. AND num_track_events/(run_stop - run_start) < 100. GROUP BY station_name;
SELECT COUNT(*) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.4 AND num_track_events/(run_stop - run_start) > 4. AND num_track_events/(run_stop - run_start) < 100.;
SELECT station_name, SUM(num_track_events) from runs WHERE run_date >= '2015-02-23' GROUP BY station_name;
SELECT SUM(num_track_events) from runs WHERE run_date >= '2015-02-23';
SELECT station_name, SUM(num_track_events) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.8 AND num_track_events/(run_stop - run_start) > 8. AND num_track_events/(run_stop - run_start) < 80. GROUP BY station_name;
SELECT SUM(num_track_events) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.8 AND num_track_events/(run_stop - run_start) > 8. AND num_track_events/(run_stop - run_start) < 80.;
SELECT station_name, SUM(num_track_events) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.4 AND num_track_events/(run_stop - run_start) > 4. AND num_track_events/(run_stop - run_start) < 100. GROUP BY station_name;
SELECT SUM(num_track_events) from runs WHERE run_date >= '2015-02-23' AND num_events > 1000 AND (run_stop - run_start) > 60. AND (run_stop - run_start) < 28800. AND num_track_events/num_events > 0.4 AND num_track_events/(run_stop - run_start) > 4. AND num_track_events/(run_stop - run_start) < 100.;
|
centrofermi/e3pipe
|
db/e3stat.sql
|
SQL
|
gpl-3.0
| 3,008
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.items.bags;
import java.util.ArrayList;
import java.util.Iterator;
import com.watabou.pixeldungeon.Badges;
import com.watabou.pixeldungeon.actors.Char;
import com.watabou.pixeldungeon.actors.hero.Hero;
import com.watabou.pixeldungeon.items.Item;
import com.watabou.pixeldungeon.scenes.GameScene;
import com.watabou.pixeldungeon.windows.WndBag;
import com.watabou.utils.Bundlable;
import com.watabou.utils.Bundle;
public class Bag extends Item implements Iterable<Item> {
public static final String AC_OPEN = "OPEN";
{
image = 11;
defaultAction = AC_OPEN;
}
public Char owner;
public ArrayList<Item> items = new ArrayList<Item>();
public int size = 1;
@Override
public ArrayList<String> actions( Hero hero ) {
ArrayList<String> actions = super.actions( hero );
return actions;
}
@Override
public void execute( Hero hero, String action ) {
if (action.equals( AC_OPEN )) {
GameScene.show( new WndBag( this, null, WndBag.Mode.ALL, null ) );
} else {
super.execute( hero, action );
}
}
@Override
public boolean collect( Bag container ) {
if (super.collect( container )) {
owner = container.owner;
for (Item item : container.items.toArray( new Item[0] )) {
if (grab( item )) {
item.detachAll( container );
item.collect( this );
}
}
Badges.validateAllBagsBought( this );
return true;
} else {
return false;
}
}
@Override
public Item detach( Bag container ) {
owner = null;
return super.detach( container );
}
@Override
public boolean isUpgradable() {
return false;
}
@Override
public boolean isIdentified() {
return true;
}
public void clear() {
items.clear();
}
private static final String ITEMS = "inventory";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( ITEMS, items );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
for (Bundlable item : bundle.getCollection( ITEMS )) {
((Item)item).collect( this );
};
}
public boolean contains( Item item ) {
for (Item i : items) {
if (i == item) {
return true;
} else if (i instanceof Bag && ((Bag)i).contains( item )) {
return true;
}
}
return false;
}
public boolean grab( Item item ) {
return false;
}
@Override
public Iterator<Item> iterator() {
return new ItemIterator();
}
private class ItemIterator implements Iterator<Item> {
private int index = 0;
private Iterator<Item> nested = null;
@Override
public boolean hasNext() {
if (nested != null) {
return nested.hasNext() || index < items.size();
} else {
return index < items.size();
}
}
@Override
public Item next() {
if (nested != null && nested.hasNext()) {
return nested.next();
} else {
nested = null;
Item item = items.get( index++ );
if (item instanceof Bag) {
nested = ((Bag)item).iterator();
}
return item;
}
}
@Override
public void remove() {
if (nested != null) {
nested.remove();
} else {
items.remove( index );
}
}
}
}
|
andersrosbaek/pixel-dungeon
|
src/com/watabou/pixeldungeon/items/bags/Bag.java
|
Java
|
gpl-3.0
| 3,924
|
/**
* @(#)clientPolling.java
* @author A.T.
* @version 1.00 2012/1/11
*/
import java.rmi.*;
import java.rmi.registry.*;
public class clientPolling
{
public static void main(String[] args)
throws Exception
{
ejemploPolling RefObRemoto = (ejemploPolling)Naming.lookup("//localhost/Servidor_Polling");
while(!RefObRemoto.igualDiez())
{System.out.println("Incremento remoto del contador");
RefObRemoto.datoInc();
}
System.out.print("El contador remoto llego a diez y se sale...");
}
}
|
zerokullneo/PCTR
|
PCTR-Codigos/Codigos_tema7/src/Polling/clientPolling.java
|
Java
|
gpl-3.0
| 554
|
/*
* Copyright (C) 2011-2012 Matias Valdenegro <matias.valdenegro@gmail.com>
* This file is part of KResearch.
*
* kesearch is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* kresearch 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 KResearch. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ATTACHMENTELEMENT_H_
#define ATTACHMENTELEMENT_H_
#include <QWidget>
class AttachmentElement : QWidget
{
public:
AttachmentElement();
virtual ~AttachmentElement();
};
#endif /* ATTACHMENTELEMENT_H_ */
|
mvaldenegro/KResearch
|
src/ui/infopanel/AttachmentElement.h
|
C
|
gpl-3.0
| 940
|
package org.thoughtcrime.redphone.registration;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import org.thoughtcrime.redphone.Constants;
import org.thoughtcrime.redphone.R;
import org.thoughtcrime.redphone.RedPhoneService;
import org.thoughtcrime.redphone.directory.DirectoryUpdateReceiver;
import org.thoughtcrime.redphone.directory.NumberFilter;
import org.thoughtcrime.redphone.gcm.GCMRegistrarHelper;
import org.thoughtcrime.redphone.monitor.MonitorConfigUpdateReceiver;
import org.thoughtcrime.redphone.signaling.AccountCreationException;
import org.thoughtcrime.redphone.signaling.AccountCreationSocket;
import org.thoughtcrime.redphone.signaling.DirectoryResponse;
import org.thoughtcrime.redphone.signaling.RateLimitExceededException;
import org.thoughtcrime.redphone.signaling.SignalingException;
import org.thoughtcrime.redphone.ui.AccountVerificationTimeoutException;
import org.thoughtcrime.redphone.util.PeriodicActionUtils;
import org.thoughtcrime.redphone.util.Util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The RegisterationService handles the actual process of registration. If it receives an
* intent with a REGISTER_NUMBER_ACTION, it does the following through an executor:
*
* 1) Generate secrets.
* 2) Register the specified number and those secrets with the server.
* 3) Wait for a challenge SMS.
* 4) Verify the challenge with the server.
* 5) Start the GCM registration process.
* 6) Retrieve the current directory.
*
* The RegistrationService broadcasts its state throughout this process, and also makes its
* state available through service binding. This enables a View to display progress.
*
* @author Moxie Marlinspike
*
*/
public class RegistrationService extends Service {
public static final String NOTIFICATION_TITLE = "org.thoughtcrime.redphone.NOTIFICATION_TITLE";
public static final String NOTIFICATION_TEXT = "org.thoughtcrime.redphone.NOTIFICATION_TEXT";
public static final String REGISTER_NUMBER_ACTION = "org.thoughtcrime.redphone.RegistrationService.REGISTER_NUMBER";
public static final String VOICE_REGISTER_NUMBER_ACTION = "org.thoughtcrime.redphone.RegistrationService.VOICE_REGISTER_NUMBER";
public static final String VOICE_REQUESTED_ACTION = "org.thoughtcrime.redphone.RegistrationService.VOICE_REQUESTED";
public static final String CHALLENGE_EVENT = "org.thoughtcrime.redphone.CHALLENGE_EVENT";
public static final String REGISTRATION_EVENT = "org.thoughtcrime.redphone.REGISTRATION_EVENT";
public static final String CHALLENGE_EXTRA = "CAAChallenge";
private static final long REGISTRATION_TIMEOUT_MILLIS = 120000;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final Binder binder = new RegistrationServiceBinder();
private volatile RegistrationState registrationState = new RegistrationState(RegistrationState.STATE_IDLE);
private volatile Handler registrationStateHandler;
private volatile ChallengeReceiver receiver;
private String challenge;
private long verificationStartTime;
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (intent != null) {
final String action = intent.getAction();
if (action.equals(REGISTER_NUMBER_ACTION) ||
action.equals(VOICE_REGISTER_NUMBER_ACTION) ||
action.equals(VOICE_REQUESTED_ACTION))
{
executor.execute(new Runnable() {
@Override
public void run() {
if (action.equals(REGISTER_NUMBER_ACTION)) handleRegistrationIntent(intent);
else if (action.equals(VOICE_REGISTER_NUMBER_ACTION)) handleVoiceRegistrationIntent(intent);
else if (action.equals(VOICE_REQUESTED_ACTION)) handleVoiceRequestedIntent(intent);
}
});
}
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
executor.shutdown();
shutdown();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void shutdown() {
shutdownChallengeListener();
markAsVerifying(false);
registrationState = new RegistrationState(RegistrationState.STATE_IDLE);
}
public synchronized int getSecondsRemaining() {
long millisPassed;
if (verificationStartTime == 0) millisPassed = 0;
else millisPassed = System.currentTimeMillis() - verificationStartTime;
return Math.max((int)(REGISTRATION_TIMEOUT_MILLIS - millisPassed) / 1000, 0);
}
public RegistrationState getRegistrationState() {
return registrationState;
}
private synchronized void initializeChallengeListener() {
this.challenge = null;
receiver = new ChallengeReceiver();
IntentFilter filter = new IntentFilter(CHALLENGE_EVENT);
registerReceiver(receiver, filter);
}
private synchronized void shutdownChallengeListener() {
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}
}
private void handleVoiceRequestedIntent(Intent intent) {
setState(new RegistrationState(RegistrationState.STATE_VOICE_REQUESTED,
intent.getStringExtra("e164number"),
intent.getStringExtra("password")));
}
private void handleVoiceRegistrationIntent(Intent intent) {
markAsVerifying(true);
String number = intent.getStringExtra("e164number");
String password = intent.getStringExtra("password");
String key = intent.getStringExtra("key");
AccountCreationSocket socket = null;
try {
setState(new RegistrationState(RegistrationState.STATE_VERIFYING_VOICE, number));
markAsVerified(number, password, key);
socket = new AccountCreationSocket(this, number, password);
GCMRegistrarHelper.registerClient(this, true);
retrieveDirectory(socket);
setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number));
broadcastComplete(true);
stopService(new Intent(this, RedPhoneService.class));
} catch (SignalingException se) {
Log.w("RegistrationService", se);
setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number));
broadcastComplete(false);
} finally {
if (socket != null)
socket.close();
}
}
private void handleRegistrationIntent(Intent intent) {
markAsVerifying(true);
AccountCreationSocket socket = null;
String number = intent.getStringExtra("e164number");
try {
String password = Util.getSecret(18);
String key = Util.getSecret(40);
initializeChallengeListener();
setState(new RegistrationState(RegistrationState.STATE_CONNECTING, number));
socket = new AccountCreationSocket(this, number, password);
socket.createAccount(false);
socket.close();
setState(new RegistrationState(RegistrationState.STATE_VERIFYING_SMS, number));
String challenge = waitForChallenge();
socket = new AccountCreationSocket(this, number, password);
socket.verifyAccount(challenge, key);
markAsVerified(number, password, key);
GCMRegistrarHelper.registerClient(this, true);
retrieveDirectory(socket);
socket.close();
setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number));
broadcastComplete(true);
stopService(new Intent(this, RedPhoneService.class));
} catch (SignalingException se) {
Log.w("RegistrationService", se);
setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number));
broadcastComplete(false);
} catch (AccountVerificationTimeoutException avte) {
Log.w("RegistrationService", avte);
setState(new RegistrationState(RegistrationState.STATE_TIMEOUT, number));
broadcastComplete(false);
} catch (AccountCreationException ace) {
Log.w("RegistrationService", ace);
setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number));
broadcastComplete(false);
} catch (RateLimitExceededException e) {
Log.w("RegistrationService", e);
setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number));
broadcastComplete(false);
} finally {
if (socket != null)
socket.close();
shutdownChallengeListener();
}
}
private synchronized String waitForChallenge() throws AccountVerificationTimeoutException {
this.verificationStartTime = System.currentTimeMillis();
if (this.challenge == null) {
try {
wait(REGISTRATION_TIMEOUT_MILLIS);
} catch (InterruptedException e) {
throw new IllegalArgumentException(e);
}
}
if (this.challenge == null)
throw new AccountVerificationTimeoutException();
return this.challenge;
}
private synchronized void challengeReceived(String challenge) {
this.challenge = challenge;
notifyAll();
}
private void retrieveDirectory(AccountCreationSocket socket) {
try {
DirectoryResponse response = socket.getNumberFilter();
if (response != null) {
NumberFilter numberFilter = new NumberFilter(response.getFilter(), response.getHashCount());
numberFilter.serializeToFile(this);
}
} catch (SignalingException se) {
Log.w("RegistrationService", se);
}
PeriodicActionUtils.scheduleUpdate(this, DirectoryUpdateReceiver.class);
}
private void markAsVerifying(boolean verifying) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = preferences.edit();
editor.putBoolean(Constants.VERIFYING_PREFERENCE, verifying);
editor.commit();
}
private void markAsVerified(String number, String password, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = preferences.edit();
editor.putBoolean(Constants.VERIFYING_PREFERENCE, false);
editor.putBoolean(Constants.REGISTERED_PREFERENCE, true);
editor.putString(Constants.NUMBER_PREFERENCE, number);
editor.putString(Constants.PASSWORD_PREFERENCE, password);
editor.putString(Constants.KEY_PREFERENCE, key);
editor.putLong(Constants.PASSWORD_COUNTER_PREFERENCE, 1L);
editor.commit();
}
private void setState(RegistrationState state) {
this.registrationState = state;
if (registrationStateHandler != null) {
registrationStateHandler.obtainMessage(state.state, state).sendToTarget();
}
}
private void broadcastComplete(boolean success) {
Intent intent = new Intent();
intent.setAction(REGISTRATION_EVENT);
if (success) {
intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_complete));
intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_redphone_registration_has_successfully_completed));
} else {
intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_error));
intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_redphone_registration_has_encountered_a_problem));
}
this.sendOrderedBroadcast(intent, null);
}
public void setRegistrationStateHandler(Handler registrationStateHandler) {
this.registrationStateHandler = registrationStateHandler;
}
public class RegistrationServiceBinder extends Binder {
public RegistrationService getService() {
return RegistrationService.this;
}
}
private class ChallengeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("RegistrationService", "Got a challenge broadcast...");
challengeReceived(intent.getStringExtra(CHALLENGE_EXTRA));
}
}
public static class RegistrationState {
public static final int STATE_IDLE = 0;
public static final int STATE_CONNECTING = 1;
public static final int STATE_VERIFYING_SMS = 2;
public static final int STATE_TIMER = 3;
public static final int STATE_COMPLETE = 4;
public static final int STATE_TIMEOUT = 5;
public static final int STATE_NETWORK_ERROR = 6;
public static final int STATE_VOICE_REQUESTED = 7;
public static final int STATE_VERIFYING_VOICE = 8;
public final int state;
public final String number;
public final String password;
public RegistrationState(int state) {
this(state, null);
}
public RegistrationState(int state, String number) {
this(state, number, null);
}
public RegistrationState(int state, String number, String password) {
this.state = state;
this.number = number;
this.password = password;
}
}
}
|
rkolli1008/TalkSecure
|
src/org/thoughtcrime/redphone/registration/RegistrationService.java
|
Java
|
gpl-3.0
| 13,383
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.12.01 um 11:24:07 AM CET
//
package de.nrw.verbraucherschutz.idv.daten;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java-Klasse für Warenbewegungsbewertung complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="Warenbewegungsbewertung">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>decimal">
* <attGroup ref="{http://verbraucherschutz.nrw.de/idv/daten/2016.2/warenrueckverfolgung}warenbewegungsbewertungAttributes"/>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Warenbewegungsbewertung", propOrder = {
"value"
})
public class Warenbewegungsbewertung {
@XmlValue
protected BigDecimal value;
@XmlAttribute(name = "typ", required = true)
protected String typ;
@XmlAttribute(name = "id", required = true)
protected String id;
@XmlAttribute(name = "betrieb", required = true)
protected String betrieb;
/**
* Ruft den Wert der value-Eigenschaft ab.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getValue() {
return value;
}
/**
* Legt den Wert der value-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Ruft den Wert der typ-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTyp() {
return typ;
}
/**
* Legt den Wert der typ-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTyp(String value) {
this.typ = value;
}
/**
* Ruft den Wert der id-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Legt den Wert der id-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Ruft den Wert der betrieb-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBetrieb() {
return betrieb;
}
/**
* Legt den Wert der betrieb-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBetrieb(String value) {
this.betrieb = value;
}
}
|
SiLeBAT/BfROpenLab
|
de.nrw.verbraucherschutz.idv/src/de/nrw/verbraucherschutz/idv/daten/Warenbewegungsbewertung.java
|
Java
|
gpl-3.0
| 3,455
|
package net.royqh.easypersist.entity.model.jpa;
/**
* Created by Roy on 2016/2/10.
*/
public class UniqueConstraint {
private String name="";
private String[] columnNames={};
public String getName() {
return name;
}
public String[] getColumnNames() {
return columnNames;
}
public void setName(String name) {
this.name = name;
}
public void setColumnNames(String[] columnNames) {
this.columnNames = columnNames;
}
}
|
royqh1979/EasyPersist
|
src/net/royqh/easypersist/entity/model/jpa/UniqueConstraint.java
|
Java
|
gpl-3.0
| 494
|
Ext.define('Sky.model.Release', {
extend: 'common.model.Release'
});
|
linea-it/dri
|
frontend/sky/app/model/Release.js
|
JavaScript
|
gpl-3.0
| 75
|
/*
* Copyright (C) 2012-2014 Arctium <http://arctium.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace WorldServer.Game.WorldEntities
{
public class Skill
{
public uint Id { get; set; }
public uint SkillLevel { get; set; }
}
}
|
gidsola/Arctium-WoW
|
WorldServer/Game/WorldEntities/Skill.cs
|
C#
|
gpl-3.0
| 879
|
/*
* COPYRIGHT (C) 2017-2021, zhllxt
*
* author : zhllxt
* email : 37792738@qq.com
*
* Distributed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
* (See accompanying file LICENSE or see <http://www.gnu.org/licenses/>)
*/
#ifndef __ASIO2_RPC_SERVER_HPP__
#define __ASIO2_RPC_SERVER_HPP__
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <asio2/base/detail/push_options.hpp>
#include <asio2/config.hpp>
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
# include <asio2/tcp/tcp_server.hpp>
# include <asio2/tcp/tcps_server.hpp>
#else
# include <asio2/http/ws_server.hpp>
# include <asio2/http/wss_server.hpp>
#endif
#include <asio2/rpc/rpc_session.hpp>
namespace asio2::detail
{
ASIO2_CLASS_FORWARD_DECLARE_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
template<class derived_t, class executor_t>
class rpc_server_impl_t
: public executor_t
, public rpc_invoker_t<typename executor_t::session_type>
{
friend executor_t;
ASIO2_CLASS_FRIEND_DECLARE_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
public:
using super = executor_t;
using self = rpc_server_impl_t<derived_t, executor_t>;
using executor_type = executor_t;
using session_type = typename super::session_type;
protected:
using super::async_send;
public:
/**
* @constructor
*/
template<class ...Args>
explicit rpc_server_impl_t(
Args&&... args
)
: super(std::forward<Args>(args)...)
, rpc_invoker_t<typename executor_t::session_type>()
{
}
/**
* @destructor
*/
~rpc_server_impl_t()
{
this->stop();
}
/**
* @function : start the server
* @param host A string identifying a location. May be a descriptive name or
* a numeric address string.
* @param service A string identifying the requested service. This may be a
* descriptive name or a numeric string corresponding to a port number.
*/
template<typename String, typename StrOrInt, typename... Args>
inline bool start(String&& host, StrOrInt&& service, Args&&... args)
{
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(service),
condition_helper::make_condition(asio2::use_dgram, std::forward<Args>(args)...));
#else
static_assert(is_websocket_server<executor_t>::value);
return executor_t::template start(
std::forward<String>(host), std::forward<StrOrInt>(service));
#endif
}
public:
/**
* @function : call a rpc function for each session
*/
template<class return_t, class Rep, class Period, class ...Args>
inline void call(std::chrono::duration<Rep, Period> timeout, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template call<return_t>(timeout, name, args...);
});
}
/**
* @function : call a rpc function for each session
*/
template<class return_t, class Rep, class Period, class ...Args>
inline void call(error_code& ec, std::chrono::duration<Rep, Period> timeout,
const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template call<return_t>(ec, timeout, name, args...);
});
}
/**
* @function : call a rpc function for each session
*/
template<class return_t, class ...Args>
inline void call(const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template call<return_t>(name, args...);
});
}
/**
* @function : call a rpc function for each session
*/
template<class return_t, class ...Args>
inline void call(error_code& ec, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template call<return_t>(ec, name, args...);
});
}
/**
* @function : asynchronous call a rpc function for each session
* Callback signature : void(asio::error_code ec, int result)
* if result type is void, the Callback signature is : void(asio::error_code ec)
* Because the result value type is not specified in the first template parameter,
* so the result value type must be specified in the Callback lambda.
*/
template<class Callback, class ...Args>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(const Callback& fn, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->async_call(fn, name, args...);
});
}
/**
* @function : asynchronous call a rpc function for each session
* Callback signature : void(asio::error_code ec, int result)
* if result type is void, the Callback signature is : void(asio::error_code ec)
* Because the result value type is not specified in the first template parameter,
* so the result value type must be specified in the Callback lambda
*/
template<class Callback, class Rep, class Period, class ...Args>
inline typename std::enable_if_t<is_callable_v<Callback>, void>
async_call(const Callback& fn, std::chrono::duration<Rep, Period> timeout,
const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->async_call(fn, timeout, name, args...);
});
}
/**
* @function : asynchronous call a rpc function for each session
* Callback signature : void(asio::error_code ec, return_t result) the return_t
* is the first template parameter.
* if result type is void, the Callback signature is : void(asio::error_code ec)
*/
template<class return_t, class Callback, class ...Args>
inline void async_call(const Callback& fn, const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template async_call<return_t>(fn, name, args...);
});
}
/**
* @function : asynchronous call a rpc function for each session
* Callback signature : void(asio::error_code ec, return_t result) the return_t
* is the first template parameter.
* if result type is void, the Callback signature is : void(asio::error_code ec)
*/
template<class return_t, class Callback, class Rep, class Period, class ...Args>
inline void async_call(const Callback& fn, std::chrono::duration<Rep, Period> timeout,
const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->template async_call<return_t>(fn, timeout, name, args...);
});
}
/**
* @function : asynchronous call a rpc function for each session
* Don't care whether the call succeeds
*/
template<class ...Args>
inline void async_call(const std::string& name, const Args&... args)
{
this->sessions_.for_each([&](std::shared_ptr<session_type>& session_ptr) mutable
{
session_ptr->async_call(name, args...);
});
}
protected:
template<typename... Args>
inline std::shared_ptr<session_type> _make_session(Args&&... args)
{
return super::_make_session(std::forward<Args>(args)..., *this);
}
protected:
};
}
namespace asio2
{
#if !defined(ASIO2_USE_WEBSOCKET_RPC)
/// Using tcp dgram mode as the underlying communication support
template<class session_t>
class rpc_server_t : public detail::rpc_server_impl_t<rpc_server_t<session_t>,
detail::tcp_server_impl_t<rpc_server_t<session_t>, session_t>>
{
public:
using detail::rpc_server_impl_t<rpc_server_t<session_t>, detail::tcp_server_impl_t<
rpc_server_t<session_t>, session_t>>::rpc_server_impl_t;
};
using rpc_server = rpc_server_t<rpc_session>;
#if defined(ASIO2_USE_SSL)
template<class session_t>
class rpcs_server_t : public detail::rpc_server_impl_t<rpcs_server_t<session_t>,
detail::tcps_server_impl_t<rpcs_server_t<session_t>, session_t>>
{
public:
using detail::rpc_server_impl_t<rpcs_server_t<session_t>, detail::tcps_server_impl_t<
rpcs_server_t<session_t>, session_t>>::rpc_server_impl_t;
};
using rpcs_server = rpcs_server_t<rpcs_session>;
#endif
#else
/// Using websocket as the underlying communication support
template<class session_t>
class rpc_server_t : public detail::rpc_server_impl_t<rpc_server_t<session_t>,
detail::ws_server_impl_t<rpc_server_t<session_t>, session_t>>
{
public:
using detail::rpc_server_impl_t<rpc_server_t<session_t>, detail::ws_server_impl_t<
rpc_server_t<session_t>, session_t>>::rpc_server_impl_t;
};
using rpc_server = rpc_server_t<rpc_session>;
#if defined(ASIO2_USE_SSL)
template<class session_t>
class rpcs_server_t : public detail::rpc_server_impl_t<rpcs_server_t<session_t>,
detail::wss_server_impl_t<rpcs_server_t<session_t>, session_t>>
{
public:
using detail::rpc_server_impl_t<rpcs_server_t<session_t>, detail::wss_server_impl_t<
rpcs_server_t<session_t>, session_t>>::rpc_server_impl_t;
};
using rpcs_server = rpcs_server_t<rpcs_session>;
#endif
#endif
}
#include <asio2/base/detail/pop_options.hpp>
#endif // !__ASIO2_RPC_SERVER_HPP__
|
zhllxt/asio2
|
asio2/rpc/rpc_server.hpp
|
C++
|
gpl-3.0
| 9,398
|
# Task1-CLI-Menu
# A command line application that does some math
#Run
php app.php
|
john-barbu/Task1-CLI-Menu
|
README.md
|
Markdown
|
gpl-3.0
| 85
|
import express from 'express'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import TelegramBot from 'node-telegram-bot-api'
import log from 'log-to-file-and-console-node'
import botHandler from './routes/botHandler'
import root from './routes/root'
const app = express()
const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {polling: true})
app.use(morgan('combined', {'stream': log.stream}))
app.use(bodyParser.json())
app.use('/', root)
bot.on('message', msg => {
botHandler.onMessage(msg, bot)
})
bot.onText(/\/content(f|F)arm(h|H)elp/, msg => {
botHandler.onHelp(msg, bot)
})
module.exports = app
|
siutsin/ihatecontentfarms-telegram-bot
|
src/app.js
|
JavaScript
|
gpl-3.0
| 638
|
SELECT *
FROM Pharmacy
WHERE working_hours LIKE '%10:00 - 18:00%'
INTERSECT
SELECT username, password, name, surname, working_hours, phone
FROM Pharmacy P JOIN Pharmacy_Drug PD
ON P.username = PD.Pharmacy_Username
JOIN Drug D
ON D.ID = PD.Drug_ID
WHERE title = 'Otrivin'
|
dimitrisniras/University-Projects
|
Database Systems (SQL)/Assignment 3/sql queries/SQLQuery4.sql
|
SQL
|
gpl-3.0
| 291
|
#include <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/cpu/Loops.h>
#include <ATen/quantized/QTensorImpl.h>
#include <ATen/quantized/Quantizer.h>
namespace at {
namespace native {
Tensor quantize_per_tensor_cpu(
const Tensor& self,
double scale,
int64_t zero_point,
ScalarType dtype) {
auto quantizer = make_per_tensor_affine_quantizer(scale, zero_point, dtype);
return quantizer->quantize(self);
}
Tensor quantize_per_channel_cpu(
const Tensor& self,
const Tensor& scales,
const Tensor& zero_points,
int64_t axis,
ScalarType dtype) {
auto quantizer =
make_per_channel_affine_quantizer(scales, zero_points, axis, dtype);
return quantizer->quantize(self);
}
Tensor dequantize_quant(const Tensor& self) {
return get_qtensorimpl(self)->quantizer()->dequantize(self);
}
double q_scale_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
TORCH_CHECK(quantizer->qscheme() == kPerTensorAffine);
return static_cast<PerTensorAffineQuantizer*>(quantizer.get())->scale();
}
int64_t q_zero_point_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
TORCH_CHECK(quantizer->qscheme() == kPerTensorAffine);
return static_cast<PerTensorAffineQuantizer*>(quantizer.get())->zero_point();
}
Tensor q_per_channel_scales_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
TORCH_CHECK(quantizer->qscheme() == kPerChannelAffine);
return at::tensor(
static_cast<PerChannelAffineQuantizer*>(quantizer.get())->scales(),
self.options().dtype(at::kDouble));
}
Tensor q_per_channel_zero_points_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
TORCH_CHECK(quantizer->qscheme() == kPerChannelAffine);
return at::tensor(
static_cast<PerChannelAffineQuantizer*>(quantizer.get())->zero_points(),
self.options().dtype(at::kLong));
}
int64_t q_per_channel_axis_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
TORCH_CHECK(quantizer->qscheme() == kPerChannelAffine);
return static_cast<PerChannelAffineQuantizer*>(quantizer.get())->axis();
}
// When input Tensor is non-dense, i.e. the allocated memory
// is larger than the memory used by all the elements, we'll
// convert it to dense tensor, otherwise we'll keep the memory
// format of the output the same as input
Tensor int_repr_quant(const Tensor& self) {
Tensor dst;
AT_DISPATCH_QINT_TYPES(self.scalar_type(), "int_repr", [&]() {
dst = at::empty(
self.sizes(),
self.options().dtype(UNDERLYING_TYPE),
self.suggest_memory_format());
auto iter = TensorIterator();
iter.add_output(dst);
iter.add_input(self);
iter.dont_compute_common_dtype();
iter.build();
cpu_kernel(iter, [](scalar_t value) -> underlying_t { return value.val_; });
});
return dst;
}
Tensor make_per_tensor_quantized_tensor_cpu(
const Tensor& self,
double scale,
int64_t zero_point) {
Tensor dst = at::_empty_affine_quantized(
self.sizes(),
self.options().dtype(toQIntType(self.scalar_type())),
scale,
zero_point);
Tensor self_contig = self.contiguous();
AT_DISPATCH_QINT_TYPES(dst.scalar_type(), "make_per_tensor_quantized_tensor", [&]() {
underlying_t* self_data = self_contig.data_ptr<underlying_t>();
underlying_t* dst_data =
reinterpret_cast<underlying_t*>(dst.data_ptr<scalar_t>());
if (self.numel() > 0) {
memcpy(dst_data, self_data, self.nbytes());
}
});
return dst;
}
Tensor make_per_channel_quantized_tensor_cpu(
const Tensor& self,
const Tensor& scales,
const Tensor& zero_points,
int64_t axis) {
Tensor dst = at::_empty_per_channel_affine_quantized(
self.sizes(),
scales,
zero_points,
axis,
self.options().dtype(toQIntType(self.scalar_type())));
Tensor self_contig = self.contiguous();
AT_DISPATCH_QINT_TYPES(
dst.scalar_type(), "per_channel_affine_qtensor", [&]() {
underlying_t* self_data = self_contig.data_ptr<underlying_t>();
underlying_t* dst_data =
reinterpret_cast<underlying_t*>(dst.data_ptr<scalar_t>());
if (self.numel() > 0) {
memcpy(dst_data, self_data, self.nbytes());
}
});
return dst;
}
Tensor& set_storage(
Tensor& self,
Storage storage,
int64_t storage_offset,
IntArrayRef sizes,
IntArrayRef strides) {
auto* self_ = self.unsafeGetTensorImpl();
self_->set_storage(storage);
self_->set_storage_offset(storage_offset);
self_->set_sizes_and_strides(sizes, strides);
return self;
}
QScheme qscheme_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
return quantizer->qscheme();
}
Tensor& set_quantizer_(Tensor& self, ConstQuantizerPtr quantizer) {
get_qtensorimpl(self)->set_quantizer_(quantizer);
return self;
}
Tensor quantized_clone(const Tensor& self, c10::optional<c10::MemoryFormat> optional_memory_format) {
// TODO: add per channel support
TORCH_INTERNAL_ASSERT(
self.qscheme() == at::kPerTensorAffine,
"clone for quantized Tensor only works for PerTensorAffine scheme right now");
auto memory_format =
optional_memory_format.value_or(MemoryFormat::Contiguous);
// TODO: To support all features of MemoryFormat::Preserve we need to add
// _empty_affine_quantized_strided function and use it similarly to
// Tensor clone(const Tensor& src, c10::optional<c10::MemoryFormat> optional_memory_format)
// if (self.is_non_overlapping_and_dense()) -> _empty_affine_quantized_strided
if (memory_format == MemoryFormat::Preserve) {
memory_format = self.suggest_memory_format();
}
Tensor dst = at::_empty_affine_quantized(
self.sizes(),
self.options(),
self.q_scale(),
self.q_zero_point(),
memory_format);
at::native::copy_(dst, self, false);
return dst;
}
bool quantized_equal(const Tensor& self, const Tensor& other) {
if (!other.is_quantized()) {
return false;
}
// Delegate to virtual equalTo method. This will ensure different concrete
// Quantizers can have specific logic for comparison
auto self_quantizer = get_qtensorimpl(self)->quantizer();
auto other_quantizer = get_qtensorimpl(other)->quantizer();
if (!self_quantizer->equalTo(other_quantizer)) {
return false;
}
// Sizes and element types must be the same
if (self.sizes() != other.sizes()) {
return false;
}
if (self.element_size() != other.element_size()) {
return false;
}
// Data must be the same
auto self_contig = self.contiguous();
auto other_contig = other.contiguous();
void* self_data = self_contig.data_ptr();
void* other_data = other_contig.data_ptr();
return 0 == memcmp(self_data, other_data, self.numel() * self.element_size());
}
} // namespace native
} // namespace at
|
lavima/MLLib
|
src/torch/aten/src/ATen/native/quantized/QTensor.cpp
|
C++
|
gpl-3.0
| 6,961
|
#include "dataservicebase.h"
DataServiceBase::DataServiceBase(QSqlDatabase *db, QObject *parent) :
QObject(parent)
{
this->db = db;
}
QString DataServiceBase::getStringFromDatabase( QString queryString, QString parameter)
{
QString result;
if(!db->isOpen())
db->open();
QSqlQuery query;
query.prepare(queryString);
if(!parameter.isEmpty())
query.bindValue(0, parameter);
query.exec();
while(query.next())
result = query.value(0).toString();
return result;
}
QStringList DataServiceBase::getStringListFromDatabase( QString queryString, QString parameter)
{
QStringList result;
if(!db->isOpen())
db->open();
QSqlQuery query;
query.prepare(queryString);
if(!parameter.isEmpty())
query.bindValue(0,parameter);
query.exec();
while(query.next())
result.append(query.value(0).toString());
return result;
}
int DataServiceBase::getCountFromDatabase(QString queryString)
{
int result;
if(!db->isOpen())
db->open();
QSqlQuery query;
query.prepare(queryString);
query.exec();
while(query.next())
result = query.value(0).toInt();
return result;
}
QDateTime DataServiceBase::getDateTimeFromDatabase(QString queryString, QString parameter)
{
QDateTime result;
if(!db->isOpen())
db->open();
QSqlQuery query;
query.prepare(queryString);
if(!parameter.isEmpty())
query.bindValue(0,parameter);
query.exec();
while(query.next())
result = query.value(0).toDateTime();
return result;
}
void DataServiceBase::executeNonQuery( QString sqlString, QString parameter /*= ""*/ )
{
if(!db->isOpen())
db->open();
QSqlQuery query;
query.prepare(sqlString);
if(!parameter.isEmpty())
query.bindValue(0,parameter);
query.exec();
}
void DataServiceBase::executeNonQuery( QString sqlString, QString firstParameter, QString secondParameter )
{
if(!db->isOpen())
db->open();
QSqlQuery query;
query.prepare(sqlString);
query.bindValue(0,firstParameter);
query.bindValue(1,secondParameter);
query.exec();
}
void DataServiceBase::executeNonQuery( QSqlQuery query )
{
if(!db->isOpen())
db->open();
query.exec();
}
|
kelsos/mra
|
src/services/database/dataservicebase.cpp
|
C++
|
gpl-3.0
| 2,170
|
/*
* Copyright (c) 2002-2020 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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/>.
*/
export default class AdjacentAngles {
findRuns(AngleList, minSeparation) {
let p = 0
let start = 0
let end = 0
const runs = []
const minStart = function() {
if (runs.length === 0) {
return 0
} else {
return runs[0].start
}
}
var scanForDensePair = function() {
start = p
end = AngleList.wrapIndex(p + 1)
if (end === minStart()) {
return 'done'
} else {
p = end
if (tooDense(start, end)) {
return extendEnd
} else {
return scanForDensePair
}
}
}
var extendEnd = function() {
if (p === minStart()) {
return 'done'
} else if (tooDense(start, AngleList.wrapIndex(p + 1))) {
end = AngleList.wrapIndex(p + 1)
p = end
return extendEnd
} else {
p = start
return extendStart
}
}
var extendStart = function() {
const candidateStart = AngleList.wrapIndex(p - 1)
if (tooDense(candidateStart, end) && candidateStart !== end) {
start = candidateStart
p = start
return extendStart
} else {
runs.push({
start,
end
})
p = end
return scanForDensePair
}
}
var tooDense = function(start, end) {
const run = {
start,
end
}
return AngleList.angle(run) < AngleList.length(run) * minSeparation
}
let stepCount = 0
let step = scanForDensePair
while (step !== 'done') {
if (stepCount++ > AngleList.totalLength() * 10) {
console.log(
'Warning: failed to layout arrows',
(() => {
const result = []
for (const key of Object.keys(AngleList.list || {})) {
const value = AngleList.list[key]
result.push(`${key}: ${value.angle}`)
}
return result
})().join('\n'),
minSeparation
)
break
}
step = step()
}
return runs
}
}
|
akollegger/neo4j-browser
|
src/browser/modules/D3Visualization/lib/visualization/utils/adjacentAngles.js
|
JavaScript
|
gpl-3.0
| 2,818
|
/*
* Copyright (c) 2017 ELAN e.V.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package de.elanev.studip.android.app.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import de.elanev.studip.android.app.planner.presentation.view.PlannerActivity;
import timber.log.Timber;
/**
* Helper class for accessing the shared preferences of the app easier. It offers an
* interface for all shared preference options needed in this app.
*
* @author joern
*/
public class Prefs {
private static final String APP_PREFS_NAME = "prefs";
private static final String API_SETTINGS_STRING = "apiSettingsString";
private static final String PLANNER_PREFERRED_PORTRAIT_VIEW = "plannerPreferredPortraitView";
private static final String PLANNER_PREFERRED_LANDSCAPE_VIEW = "plannerPreferredLandscapeView";
private static final String PLANNER_PREFERRED_TIMETABLE_DAYS_COUNT = "plannerPreferredTimetableViewDayCount";
private static final String CURRENT_USER_ID = "current-user-id";
private static final String APP_SIGNED_IN = "app-signed-in";
private static final String ENDPOINT_EMAIL = "app-endpoint-email";
private static final String ENDPOINT_NAME = "app-endpoint-name";
private static final String ENDPOINT_BASE_URL = "app-endpoint-base-url";
private SharedPreferences mPrefs;
public Prefs(Context context) {
this.mPrefs = context.getSharedPreferences(APP_PREFS_NAME, Context.MODE_PRIVATE);
}
/*
* Clears the SharedPreferences
*/
public void clearPrefs() {
Timber.i("Clearing prefs!");
mPrefs.edit()
.clear()
.apply();
}
//TODO: Use for sign in tutorial
// /**
// * Checks if the app was started before. If it was not started before it will return true
// *
// * @return true if the current start is the first start of the app on the current device, else
// * false
// */
// public boolean isFirstStart() {
// return mPrefs.getBoolean(APP_FIRST_START, true);
// }
//
// /**
// * Set the app as started. This will cause the isFirstStart() method to return false.
// */
// public void setAppStarted() {
// mPrefs.edit()
// .putBoolean(APP_FIRST_START, false)
// .apply();
// }
// TODO: Do we really need this anymore?
// /**
// * Checks if insecure credentials from earlier versions of the app exist.
// *
// * @return true if there are insecure credentials form earlier versions,
// * otherwise false
// */
// public boolean legacyDataExists() {
// String accessToken = mPrefs.getString("accessToken", null);
// String accessTokenSecret = mPrefs.getString("accessTokenSecret", null);
// String serverName = mPrefs.getString("serverName", null);
// String serverUrl = mPrefs.getString("serverUrl", null);
// String serverKey = mPrefs.getString("serverKey", null);
// String serverSecret = mPrefs.getString("serverSecret", null);
//
// return accessToken != null || accessTokenSecret != null || serverName != null
// || serverUrl != null || serverKey != null || serverSecret != null;
// }
/**
* Returns the stored API settings JSON String representation
*
* @return JSON String of the API settings
*/
public String getApiSettings() {
return mPrefs.getString(API_SETTINGS_STRING, "");
}
/**
* Saves a String representation of the API settings in the shared preferences.
*
* @param apiSettings JSON String representation of the API settings to save
*/
public void setApiSettings(String apiSettings) {
mPrefs.edit()
.putString(API_SETTINGS_STRING, apiSettings)
.apply();
}
//TODO: Use this in for checking if user allow mobile usage for heavy downloads
// /**
// * Returns whether the user allowed downloading via mobile data connection previously
// *
// * @return true if the user allowed downloading via mobile data, false otherwise
// */
// public boolean isAllowMobileData() {
// return mPrefs.getBoolean(ALLOW_MOBILE_DATA, false);
// }
//
// /**
// * Store the users decision to allow downloading via mobile data connection
// *
// * @param isAllowed the value to store
// */
// public void setAllowMobile(boolean isAllowed) {
// mPrefs.edit()
// .putBoolean(ALLOW_MOBILE_DATA, isAllowed)
// .apply();
// }
/**
* Returns the users preferred planner view based on the passed orientation of the devices. We
* store
* the preferred view of the landscape and portrait orientation.
*
* @param orientation orientation for which the preferred view should be returned
* @return the preferred view of the planner for the passed orientation
*/
public String getPreferredPlannerView(int orientation) {
String preferredView;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
preferredView = mPrefs.getString(PLANNER_PREFERRED_PORTRAIT_VIEW,
PlannerActivity.PLANNER_VIEW_LIST);
} else {
preferredView = mPrefs.getString(PLANNER_PREFERRED_LANDSCAPE_VIEW,
PlannerActivity.PLANNER_VIEW_TIMETABLE);
}
return preferredView;
}
/**
* Stores the preferred planner view for the passed orientation. We store the preferred view for
* landscape and portrait orientation.
*
* @param orientation the orientation for which the preferred view should be stored
* @param view the preferred view for the passed orientation
*/
public void setPlannerPreferredView(int orientation, String view) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
mPrefs.edit()
.putString(PLANNER_PREFERRED_PORTRAIT_VIEW, view)
.apply();
} else {
mPrefs.edit()
.putString(PLANNER_PREFERRED_LANDSCAPE_VIEW, view)
.apply();
}
}
/**
* Returns the user's preferred count of days which should be displayed in the timetable view of
* the planner.
*
* @return The count of days which should be displayed in the timetable view.
*/
public int getPreferredPlannerTimetableViewDayCount() {
return mPrefs.getInt(PLANNER_PREFERRED_TIMETABLE_DAYS_COUNT, 1);
}
/**
* Stores the users preferred count of days which should be displayed in the timetable view of
* the planner.
*
* @param count The user's preferred count of days.
*/
public void setPrefPlannerTimetableViewDayCount(int count) {
mPrefs.edit()
.putInt(PLANNER_PREFERRED_TIMETABLE_DAYS_COUNT, count)
.apply();
}
public String getCurrentUserId() {
return mPrefs.getString(CURRENT_USER_ID, "");
}
public void setCurrentUserId(String userId) {
mPrefs.edit()
.putString(CURRENT_USER_ID, userId.trim())
.apply();
}
public boolean isAppAuthorized() {
return mPrefs.getBoolean(APP_SIGNED_IN, false);
}
public void setAppAuthorized(boolean auth) {
mPrefs.edit()
.putBoolean(APP_SIGNED_IN, auth)
.apply();
}
public String getEndpointEmail() {
return mPrefs.getString(ENDPOINT_EMAIL, "");
}
public void setEndpointEmail(String email) {
mPrefs.edit()
.putString(ENDPOINT_EMAIL, email)
.apply();
}
public String getEndpointName() {
return mPrefs.getString(ENDPOINT_NAME, "");
}
public void setEndpointName(String endpointName) {
mPrefs.edit()
.putString(ENDPOINT_NAME, endpointName)
.apply();
}
public String getBaseUrl() {
return mPrefs.getString(ENDPOINT_BASE_URL, "");
}
public void setBaseUrl(String baseUrl) {
mPrefs.edit()
.putString(ENDPOINT_BASE_URL, baseUrl)
.apply();
}
}
|
elan-ev/StudIPAndroidApp
|
app/src/main/java/de/elanev/studip/android/app/util/Prefs.java
|
Java
|
gpl-3.0
| 7,921
|
<div id="screenshare-container" style="width:100%;height:100%;display:flex;align-items:stretch;align-content: stretch;">
<div style="flex:1;display:flex;justify-content: center;align-items: center;">
<div style="text-align:center;border: 5px solid #ccc;padding: 40px 50px;border-radius: 8px;background:linear-gradient(to bottom, #e9f1fa 0%, #ffffff 100%)">
<div style="font-weight:bold;font-size:12px;padding:0">
<audio id="contactaudio" controls autoplay></audio>
</div>
<div style="margin-top:20px;font-size:26px">Sharing your screen to <span data-bind="text: contact_name"></span></div>
<div><button data-bind="click: hangup" style="font-size:20px;padding:5px 30px;margin-top:20px">Stop screen share</button></div>
</div>
</div>
</div>
|
streembit/streembitui
|
lib/app/views/screenshare/screen.html
|
HTML
|
gpl-3.0
| 876
|
<HTML>
<HEAD>
<meta charset="UTF-8">
<title>EntityResponse.type - koalanlp</title>
<link rel="stylesheet" href="../../../style.css">
</HEAD>
<BODY>
<a href="../../index.html">koalanlp</a> / <a href="../index.html">kr.bydelta.koala.etri</a> / <a href="index.html">EntityResponse</a> / <a href="./type.html">type</a><br/>
<br/>
<h1>type</h1>
<a name="kr.bydelta.koala.etri.EntityResponse$type"></a>
<code><span class="keyword">val </span><span class="identifier">type</span><span class="symbol">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html"><span class="identifier">String</span></a></code> <a href="https://github.com/koalanlp/koalanlp/blob/master/etri/src/main/kotlin/kr/bydelta/koala/etri/data.kt#L86">(source)</a>
<p>개체명의 유형 (세분류)</p>
</BODY>
</HTML>
|
nearbydelta/KoreanAnalyzer
|
docs/api/koalanlp/kr.bydelta.koala.etri/-entity-response/type.html
|
HTML
|
gpl-3.0
| 845
|
#!/bin/sh
##
# Set up inotifywatch to automatically chown any newly created file in the mount directory. The userid and groupid of the *host*
# mounted directory will be used for each new file. This gets around the problem where the storage client is run as root in the
# Docker container, so files created are owned by root. If the host user doesn't have sudo privileges, then they won't be able to
# access the download and log files.
#
##
nohup inotifywait -q -m -r /icgc/mnt -e create --format '%w%f' | while read f; do chown $(stat -c '%u' /icgc/mnt):$(stat -c '%g' /icgc/mnt) $f; done &
/icgc/score-client/bin/score-client "$@"
|
icgc/icgc-get
|
icgc-storage-client-proxy.sh
|
Shell
|
gpl-3.0
| 637
|
module WebParsing.PostParser
(addPostToDatabase) where
import qualified Data.Text as T
import Data.Either (fromRight)
import Data.Maybe (maybe)
import Data.List (find)
import Data.Text (strip)
import Control.Monad.Trans (liftIO)
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
import Data.List.Split (split, splitWhen, whenElt, keepDelimsL)
import Database.Tables
import Database.DataType (PostType(..))
import Database.Persist.Sqlite (insert_, SqlPersistM)
import Database.Persist (insertUnique)
import qualified Text.Parsec as P
import Text.Parsec.Text (Parser)
import WebParsing.ReqParser (parseReqs)
import WebParsing.ParsecCombinators (parseUntil, text)
addPostToDatabase :: [Tag T.Text] -> SqlPersistM ()
addPostToDatabase programElements = do
let fullPostName = maybe "" (strip . fromTagText) $ find isTagText programElements
requirementLines = reqHtmlToLines $ last $ sections isRequirementSection programElements
requirements = concatMap parseRequirement requirementLines
liftIO $ print fullPostName
case P.parse postInfoParser "POSt information" fullPostName of
Left _ -> return ()
Right post -> do
postExists <- insertUnique post
case postExists of
Just key ->
mapM_ (insert_ . PostCategory key) requirements
Nothing -> return ()
where
isRequirementSection = tagOpenAttrLit "div" ("class", "field-content")
-- | Parse a Post value from its title.
-- Titles are usually of the form "Actuarial Science Major (Science Program)".
postInfoParser :: Parser Post
postInfoParser = do
deptName <- parseDepartmentName
postType <- parsePostType P.<|> return Other
return $ Post postType deptName "" ""
where
parseDepartmentName :: Parser T.Text
parseDepartmentName = parseUntil $ P.choice [
P.lookAhead parsePostType >> return (),
P.char '(' >> return ()
]
parsePostType :: Parser PostType
parsePostType = do
postTypeName <- P.choice $ map (P.try . text) ["Specialist", "Major", "Minor"]
return $ read $ T.unpack postTypeName
-- | Split requirements HTML into individual lines.
reqHtmlToLines :: [Tag T.Text] -> [[T.Text]]
reqHtmlToLines tags =
let sects = split (keepDelimsL $ whenElt isSectionSplit) tags
sectionsNoNotes = filter (not . isNoteSection) sects
paragraphs = concatMap (splitWhen (isTagOpenName "p")) sectionsNoNotes
lines' = map (map (T.strip . convertLine) . splitLines) paragraphs
in
lines'
where
isSectionSplit :: Tag T.Text -> Bool
isSectionSplit tag =
isTagText tag &&
any (flip T.isInfixOf $ fromTagText tag) ["First", "Second", "Third", "Higher", "Notes", "NOTES"]
isNoteSection :: [Tag T.Text] -> Bool
isNoteSection (sectionTitleTag:_) =
isTagText sectionTitleTag && (any (flip T.isInfixOf $ fromTagText $ sectionTitleTag) ["Notes", "NOTES"])
isNoteSection [] = False
splitLines :: [Tag T.Text] -> [[Tag T.Text]]
splitLines = splitWhen (\tag -> isTagOpenName "br" tag || isTagOpenName "li" tag)
convertLine :: [Tag T.Text] -> T.Text
convertLine [] = ""
convertLine (t:ts)
| isTagOpenName "li" t = T.append "0." (innerText ts)
| otherwise = innerText (t:ts)
parseRequirement :: [T.Text] -> [T.Text]
parseRequirement requirement = map parseSingleReq $ filter isReq requirement
where
isReq t = T.length t >= 7 &&
not (any (flip T.isInfixOf $ t) ["First", "Second", "Third", "Higher"])
parseSingleReq =
T.pack . show .
parseReqs . -- Using parser for new Req type
T.unpack .
fromRight "" .
P.parse getLineText "Reading a requirement line" .
T.strip
-- Strips the optional leading numbering (#.) from a line.
getLineText :: Parser T.Text
getLineText = do
P.optional (P.digit >> P.char '.' >> P.space)
parseUntil P.eof
|
christinem/courseography
|
app/WebParsing/PostParser.hs
|
Haskell
|
gpl-3.0
| 4,147
|
#ifndef ACTIONPOOL_H
#define ACTIONPOOL_H
#include <QObject>
#include "action.h"
class Action;
class ActionPool : public QObject
{
Q_OBJECT
public:
explicit ActionPool(QObject *parent = 0);
virtual ~ActionPool();
QList<Action*> actions() const;
void addAction(Action*);
bool removeAction(Action*);
bool contains(Action*) const;
Action* actionFromParent(GameObject*) const;
int size() const;
signals:
void destroyed(ActionPool*);
private slots:
void onActionDestroyed(QObject*);
private:
QList<Action*> mActions;
};
#endif // ACTIONPOOL_H
|
fr33mind/Belle
|
editor/actionpool.h
|
C
|
gpl-3.0
| 596
|
package greymerk.roguelike.worldgen.filter;
import java.util.Random;
import greymerk.roguelike.theme.ITheme;
import greymerk.roguelike.worldgen.Cardinal;
import greymerk.roguelike.worldgen.Coord;
import greymerk.roguelike.worldgen.IBlockFactory;
import greymerk.roguelike.worldgen.IBounded;
import greymerk.roguelike.worldgen.IWorldEditor;
import greymerk.roguelike.worldgen.blocks.BlockType;
import greymerk.roguelike.worldgen.shapes.IShape;
import greymerk.roguelike.worldgen.shapes.RectWireframe;
public class WireframeFilter implements IFilter{
@Override
public void apply(IWorldEditor editor, Random rand, ITheme theme, IBounded box) {
Coord start = box.getStart();
Coord end = box.getEnd();
start.add(Cardinal.UP, 100);
end.add(Cardinal.UP, 100);
IShape shape = new RectWireframe(start, end);
IBlockFactory block = BlockType.get(BlockType.SEA_LANTERN);
shape.fill(editor, rand, block);
}
}
|
Greymerk/minecraft-roguelike
|
src/main/java/greymerk/roguelike/worldgen/filter/WireframeFilter.java
|
Java
|
gpl-3.0
| 926
|
package com.akhramovichsa.pong.Screens;
import com.akhramovichsa.pong.PongGame;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import java.util.logging.FileHandler;
/**
*
*/
public class FirstScreen implements Screen {
private static final int WORLD_WIDTH = PongGame.WORLD_WIDTH;
private static final int WORLD_HEIGHT = PongGame.WORLD_HEIGHT;
private Game game;
private OrthographicCamera camera;
private Stage stage;
private SpriteBatch batch;
private BitmapFont font, font_big;
public FirstScreen(PongGame _game) {
game = _game;
}
@Override
public void show() {
camera = new OrthographicCamera();
camera.setToOrtho(false, WORLD_WIDTH, WORLD_HEIGHT);
camera.update();
batch = new SpriteBatch();
batch.setProjectionMatrix(camera.combined);
/*
FileHandle[] dirHandle = Gdx.files.internal("./").list();
for(FileHandle file: dirHandle) {
Gdx.app.log("aaa", file.toString());
}
*/
// Звуки
final Sound f_sharp_5 = Gdx.audio.newSound(Gdx.files.internal("data/pongblip_f_sharp_5.mp3"));
// Шрифты
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("data/04b_24.ttf"));
// FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("data/04b_03b.ttf"));
// FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("data/04b_08.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 60; // 80; // WORLD_HEIGHT / 10;
font = generator.generateFont(parameter);
parameter.size = 120; // 160;
font_big = generator.generateFont(parameter);
generator.dispose();
Label.LabelStyle label_style = new Label.LabelStyle();
label_style.font = font;
label_style.fontColor = Color.WHITE;
Label.LabelStyle label_big_style = new Label.LabelStyle();
label_big_style.font = font_big;
label_big_style.fontColor = Color.WHITE;
//-------------------------------------------------------//
// PONG //
//-------------------------------------------------------//
Label label_pong = new Label("PONG", label_big_style);
//-------------------------------------------------------//
// 1 PLAYER //
//-------------------------------------------------------//
Label label_1_player = new Label("PLAY TO", label_style);
/*
label_1_player.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// Gdx.app.log("button", "clicked 1 player");
f_sharp_5.play();
game.setScreen(new GameScreen((PongGame) game));
dispose();
}
});
*/
// Игра до 1 победы
Label label_1_win = new Label("1 WIN", label_style);
label_1_win.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
f_sharp_5.play();
game.setScreen(new GameScreen((PongGame) game, 1));
dispose();
}
});
// Игра до 3 побед
Label label_3_wins = new Label("3 WINS", label_style);
label_3_wins.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
f_sharp_5.play();
game.setScreen(new GameScreen((PongGame) game, 3));
dispose();
}
});
// Игра до 5 побед
Label label_5_wins = new Label("5 WINS", label_style);
label_5_wins.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
f_sharp_5.play();
game.setScreen(new GameScreen((PongGame) game, 5));
dispose();
}
});
// Игра до 10 побед
Label label_10_wins = new Label("10 WINS", label_style);
label_10_wins.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
f_sharp_5.play();
game.setScreen(new GameScreen((PongGame) game, 10));
dispose();
}
});
//-------------------------------------------------------//
// 2 PLAYERS //
//-------------------------------------------------------//
Label label_2_players = new Label("2 PLAYERS", label_style);
label_2_players.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// Gdx.app.log("button", "clicked 2 players");
f_sharp_5.play();
}
});
//-------------------------------------------------------//
// SETTINGS //
//-------------------------------------------------------//
Label label_settings = new Label("SETTINGS", label_style);
label_settings.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// Gdx.app.log("button", "clicked settings");
f_sharp_5.play();
}
});
//-------------------------------------------------------//
// EXIT //
//-------------------------------------------------------//
Label label_exit = new Label("EXIT", label_style);
label_exit.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
// Gdx.app.log("button", "clicked exit");
f_sharp_5.play();
Gdx.app.exit();
// label_1_player.setText("PONG 1");
}
});
//-------------------------------------------------------//
// ТАБЛИЦА //
//-------------------------------------------------------//
final Table table = new Table();
// table.setDebug(true);
// table.setFillParent(true);
table.setPosition(WORLD_WIDTH / 2f, WORLD_HEIGHT / 2f);
table.add(label_pong).expandX().center().pad(WORLD_HEIGHT / 32);
table.row();
table.add(label_1_player).expandX().center().pad(WORLD_HEIGHT / 32);
table.row();
table.add(label_1_win).expandX().center().pad(WORLD_HEIGHT / 32);
table.row();
table.add(label_3_wins).expandX().center().pad(WORLD_HEIGHT / 32);
table.row();
table.add(label_5_wins).expandX().center().pad(WORLD_HEIGHT / 32);
// table.row();
// table.add(label_settings).expandX().center().pad(WORLD_HEIGHT / 32);
table.row();
table.add(label_exit).expandX().center();
stage = new Stage();
stage.getViewport().setCamera(camera);
Gdx.input.setInputProcessor(stage);
stage.addActor(table);
// stage.addActor(label_2_players);
// stage.addActor(label_settings);
// stage.addActor(label_exit);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// batch.begin();
stage.draw();
// batch.end();
}
@Override
public void resize(int width, int height) {
// camera.setToOrtho(false, WORLD_WIDTH, WORLD_HEIGHT);
// camera.update();
// stage.getViewport().setCamera(camera);
stage.getViewport().update(width,height, false);
// stage.getCamera().update();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
batch.dispose();
stage.dispose();
font.dispose();
font_big.dispose();
}
}
|
akhramovichsa/pong
|
core/src/com/akhramovichsa/pong/Screens/FirstScreen.java
|
Java
|
gpl-3.0
| 9,266
|
package com.andyadc.designpattern.decorator.cafe.decorator;
import com.andyadc.designpattern.decorator.cafe.Drink;
/**
* @author andaicheng
* @version 2017/1/14
*/
public class Milk extends Decorator {
public Milk(Drink drink) {
super(drink);
super.setDescription("Milk");
super.setPrice(2.5f);
}
}
|
andyadc/java-study
|
design-pattern/src/main/java/com/andyadc/designpattern/decorator/cafe/decorator/Milk.java
|
Java
|
gpl-3.0
| 355
|
/*
* NovaGuilds - Bukkit plugin
* Copyright (C) 2018 Marcin (CTRL) Wieczorek
*
* 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 co.marcin.novaguilds.command.guild;
import co.marcin.novaguilds.api.basic.NovaGuild;
import co.marcin.novaguilds.api.basic.NovaPlayer;
import co.marcin.novaguilds.command.abstractexecutor.AbstractCommandExecutor;
import co.marcin.novaguilds.enums.GuildPermission;
import co.marcin.novaguilds.enums.Message;
import co.marcin.novaguilds.enums.VarKey;
import co.marcin.novaguilds.manager.PlayerManager;
import co.marcin.novaguilds.util.TabUtils;
import co.marcin.novaguilds.util.TagUtils;
import org.bukkit.command.CommandSender;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class CommandGuildKick extends AbstractCommandExecutor {
@Override
public void execute(CommandSender sender, String[] args) throws Exception {
NovaPlayer nPlayer = PlayerManager.getPlayer(sender);
if(!nPlayer.hasGuild()) {
Message.CHAT_GUILD_NOTINGUILD.send(sender);
return;
}
NovaGuild guild = nPlayer.getGuild();
if(!nPlayer.hasPermission(GuildPermission.KICK)) {
Message.CHAT_GUILD_NOGUILDPERM.send(sender);
return;
}
if(args.length == 0) {
Message.CHAT_PLAYER_ENTERNAME.send(sender);
return;
}
NovaPlayer nPlayerKick = PlayerManager.getPlayer(args[0]);
if(nPlayerKick == null) {
Message.CHAT_PLAYER_NOTEXISTS.send(sender);
return;
}
if(!nPlayerKick.hasGuild()) {
Message.CHAT_PLAYER_HASNOGUILD.send(sender);
return;
}
if(!nPlayerKick.getGuild().getName().equalsIgnoreCase(guild.getName())) {
Message.CHAT_PLAYER_NOTINYOURGUILD.send(sender);
return;
}
if(nPlayer.getName().equalsIgnoreCase(nPlayerKick.getName())) {
Message.CHAT_GUILD_KICKYOURSELF.send(sender);
return;
}
//all passed
guild.removePlayer(nPlayerKick);
nPlayerKick.cancelToolProgress();
if(nPlayerKick.isOnline()) {
guild.hideVaultHologram(nPlayerKick.getPlayer());
}
Map<VarKey, String> vars = new HashMap<>();
vars.put(VarKey.PLAYER_NAME, nPlayerKick.getName());
vars.put(VarKey.GUILD_NAME, guild.getName());
Message.BROADCAST_GUILD_KICKED.clone().vars(vars).broadcast();
//tab/tag
TagUtils.refresh();
TabUtils.refresh();
}
@Override
protected Collection<String> tabCompleteOptions(CommandSender sender, String[] args) {
Set<String> options = new HashSet<>();
NovaPlayer nPlayer = PlayerManager.getPlayer(sender);
if(nPlayer.hasGuild()) {
for(NovaPlayer guildMember : nPlayer.getGuild().getPlayers()) {
if(!guildMember.isLeader() && !guildMember.equals(nPlayer)) {
options.add(guildMember.getName());
}
}
}
return options;
}
}
|
MarcinWieczorek/NovaGuilds
|
src/main/java/co/marcin/novaguilds/command/guild/CommandGuildKick.java
|
Java
|
gpl-3.0
| 3,401
|
package edu.stanford.nlp.mt.decoder.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import edu.stanford.nlp.mt.decoder.AbstractInferer;
import edu.stanford.nlp.mt.decoder.feat.FeatureExtractor;
import edu.stanford.nlp.mt.stats.SimilarityMeasures;
import edu.stanford.nlp.mt.tm.ConcreteRule;
import edu.stanford.nlp.mt.tm.DynamicTranslationModel;
import edu.stanford.nlp.mt.tm.Rule;
import edu.stanford.nlp.mt.train.SymmetricalWordAlignment;
import edu.stanford.nlp.mt.util.CoverageSet;
import edu.stanford.nlp.mt.util.IString;
import edu.stanford.nlp.mt.util.InputProperties;
import edu.stanford.nlp.mt.util.InputProperty;
import edu.stanford.nlp.mt.util.PhraseAlignment;
import edu.stanford.nlp.mt.util.Sequence;
import edu.stanford.nlp.mt.util.Sequences;
/**
* For constructing synthetic rules.
*
* @author Spence Green
*
*/
public final class SyntheticRules {
private static final Logger logger = LogManager.getLogger(SyntheticRules.class.getName());
private static final PhraseAlignment UNIGRAM_ALIGNMENT = PhraseAlignment.getPhraseAlignment("(0)");
private static final PhraseAlignment MONOTONE_ALIGNMENT = PhraseAlignment.getPhraseAlignment(PhraseAlignment.MONOTONE_ALIGNMENT);
public static final String PHRASE_TABLE_NAME = "synthetic";
private static final int MAX_SYNTHETIC_ORDER = 3;
private static final int MAX_TARGET_ORDER = 5;
private SyntheticRules() {}
/**
* Create a synthetic translation rule.
*
* @param source
* @param target
* @param sourceIndex
* @param phraseScoreNames
* @return
*/
public static <TK,FV> ConcreteRule<TK,FV> makeSyntheticUnigramRule(Sequence<TK> source, Sequence<TK> target,
CoverageSet sourceCoverage, String[] phraseScoreNames, Scorer<FV> scorer,
FeatureExtractor<TK,FV> featurizer,
double cnt_f_e, int cnt_e, int cnt_f, InputProperties inputProperties, Sequence<TK> sourceSequence,
int sourceInputId) {
if (source.size() != 1 || target.size() != 1) throw new IllegalArgumentException(String.format("Non-unigram arguments %d %d", source.size(), target.size()));
return makeSyntheticRule(source, target, sourceCoverage, phraseScoreNames, scorer, featurizer,
cnt_f_e, cnt_e, cnt_f, inputProperties, sourceSequence, sourceInputId, UNIGRAM_ALIGNMENT);
}
/**
* Create a synthetic translation rule.
*
* @param source
* @param target
* @param sourceCoverage
* @param phraseScoreNames
* @param scorer
* @param featurizer
* @param cnt_f_e
* @param cnt_e
* @param cnt_f
* @param inputProperties
* @param sourceSequence
* @param sourceInputId
* @param align
* @return
*/
public static <TK,FV> ConcreteRule<TK, FV> makeSyntheticRule(Sequence<TK> source, Sequence<TK> target,
CoverageSet sourceCoverage, String[] phraseScoreNames, Scorer<FV> scorer,
FeatureExtractor<TK,FV> featurizer,
double cnt_f_e, int cnt_e, int cnt_f, InputProperties inputProperties, Sequence<TK> sourceSequence,
int sourceInputId, PhraseAlignment align) {
// Baseline dense features
float[] scores = new float[phraseScoreNames.length];
scores[0] = (float) (Math.log(cnt_f_e) - Math.log(cnt_e));
scores[1] = scores[0];
scores[2] = (float) (Math.log(cnt_f_e) - Math.log(cnt_f));
scores[3] = scores[2];
if (scores.length == 6) {
// Extended features
scores[4] = cnt_f_e > 1 ? (float) Math.log(cnt_f_e) : 0.0f;
scores[5] = cnt_f_e <= 1 ? -1.0f : 0.0f;
}
Rule<TK> abstractRule = new Rule<>(scores, phraseScoreNames, target, source,
align, PHRASE_TABLE_NAME);
ConcreteRule<TK,FV> rule = new ConcreteRule<>(abstractRule, sourceCoverage, featurizer,
scorer, sourceSequence, sourceInputId, inputProperties);
return rule;
}
/**
* Create a new rule from an existing rule by replacing the target side.
*
* @param base
* @param target
* @param scorer
* @param featurizer
* @param sourceSequence
* @param inputProperties
* @param sourceInputId
* @return
*/
public static <TK,FV> ConcreteRule<TK,FV> makeSyntheticRule(ConcreteRule<TK,FV> base,
Sequence<TK> target, PhraseAlignment align, Scorer<FV> scorer, FeatureExtractor<TK,FV> featurizer,
Sequence<TK> sourceSequence, InputProperties inputProperties, int sourceInputId) {
Rule<TK> baseRule = base.abstractRule;
Rule<TK> newRule = new Rule<>(baseRule.scores, baseRule.phraseScoreNames, target, baseRule.source,
align, PHRASE_TABLE_NAME);
newRule.reoderingScores = baseRule.reoderingScores;
newRule.forwardOrientation = baseRule.forwardOrientation;
newRule.backwardOrientation = baseRule.backwardOrientation;
ConcreteRule<TK,FV> rule = new ConcreteRule<>(newRule, base.sourceCoverage, featurizer,
scorer, sourceSequence, sourceInputId, inputProperties);
return rule;
}
@SuppressWarnings("unchecked")
public static <TK,FV> void augmentRuleGrid(RuleGrid<TK,FV> ruleGrid,
Sequence<TK> prefix, int sourceInputId, Sequence<TK> sourceSequence,
AbstractInferer<TK, FV> inferer, InputProperties inputProperties) {
// Fetch translation models
final List<DynamicTranslationModel<FV>> tmList = new ArrayList<>(2);
tmList.add((DynamicTranslationModel<FV>) inferer.phraseGenerator);
if (inputProperties.containsKey(InputProperty.ForegroundTM)) {
tmList.add((DynamicTranslationModel<FV>) inputProperties.get(InputProperty.ForegroundTM));
}
final String[] featureNames = (String[]) inferer.phraseGenerator.getFeatureNames().toArray();
// e2f align prefix to source with Cooc table and lexical similarity as backoff. This will
// need to change for languages with different orthographies.
SymmetricalWordAlignment alignInverse = alignInverse(sourceSequence, prefix, tmList);
// f2e align with Cooc table and lexical similarity. Includes deletion rules.
SymmetricalWordAlignment align = align(sourceSequence, prefix, tmList);
// Symmetrize Apply. Start with intersection. Then try grow.
SymmetricalWordAlignment sym = intersect(align, alignInverse);
// WSGDEBUG
// System.err.println(sym.toString());
// Extract phrases using the same heuristics as the DynamicTM
CoverageSet targetCoverage = new CoverageSet(prefix.size());
CoverageSet prefixSourceCoverage = new CoverageSet(sourceSequence.size());
for (int order = 1; order <= MAX_SYNTHETIC_ORDER; ++order) {
for (int i = 0, sz = sourceSequence.size() - order; i <= sz; ++i) {
List<RuleBound> rules = extractRules(sym, i, order, MAX_TARGET_ORDER);
for (RuleBound r : rules) {
targetCoverage.set(r.ei, r.ej);
prefixSourceCoverage.set(r.fi, r.fj);
CoverageSet cov = new CoverageSet(sourceSequence.size());
cov.set(r.fi, r.fj);
Sequence<TK> src = sourceSequence.subsequence(r.fi, r.fj);
Sequence<TK> tgt = prefix.subsequence(r.ei, r.ej);
int[][] e2f = new int[tgt.size()][src.size()];
for (int eIdx = r.ei; eIdx < r.ej; ++eIdx) {
e2f[eIdx - r.ei] = sym.e2f(eIdx).stream().mapToInt(a -> a - r.fi).toArray();
}
PhraseAlignment alignment = new PhraseAlignment(e2f);
int cnt_f = 0, cnt_e = 0;
double cnt_fe = 0.0;
if (src.size() == 1 && tgt.size() == 1) { // Unigram rule
cnt_f = tmList.stream().mapToInt(tm -> tm.getSourceLexCount((IString) src.get(0))).sum();
cnt_e = tmList.stream().mapToInt(tm -> tm.getTargetLexCount((IString) tgt.get(0))).sum();
cnt_fe = tmList.stream().mapToInt(tm -> tm.getJointLexCount((IString) src.get(0), (IString) tgt.get(0))).sum();
if (cnt_f == 0) cnt_f = 1;
if (cnt_e == 0) cnt_e = 1;
if (cnt_fe == 0) cnt_fe = 1e-9;
} else {
cnt_f = 1;
cnt_e = 1;
cnt_fe = 1e-9;
}
ConcreteRule<TK,FV> syntheticRule = SyntheticRules.makeSyntheticRule(src, tgt,
cov, featureNames, inferer.scorer, inferer.featurizer, cnt_fe, cnt_e, cnt_f,
inputProperties, sourceSequence, sourceInputId, alignment);
ruleGrid.addEntry(syntheticRule);
// WSGDEBUG
// System.err.printf("Ext: %s%n", syntheticRule);
}
}
}
// Get source coverage and add source deletions
CoverageSet sourceCoverage = new CoverageSet(sourceSequence.size());
final int maxSourceCoverage = Math.min(sourceSequence.size(), prefixSourceCoverage.cardinality() + tmList.get(0).maxLengthSource());
for (int i = 0; i < maxSourceCoverage; ++i) {
if (sym.f2e(i).isEmpty()) {
// Source deletion
CoverageSet cov = new CoverageSet(sourceSequence.size());
cov.set(i);
Sequence<TK> src = sourceSequence.subsequence(i, i+1);
Sequence<TK> tgt = Sequences.emptySequence();
int cnt_f = 1;
int cnt_e = 1;
double cnt_fe = 1e-15; // Really discourage this! Should always be a last resort since the LM will prefer deleting words
ConcreteRule<TK,FV> syntheticRule = SyntheticRules.makeSyntheticRule(src, tgt,
cov, featureNames, inferer.scorer, inferer.featurizer, cnt_fe, cnt_e, cnt_f,
inputProperties, sourceSequence, sourceInputId, MONOTONE_ALIGNMENT);
ruleGrid.addEntry(syntheticRule);
// WSGDEBUG
// System.err.printf("ExtDel: %s%n", syntheticRule);
} else {
sourceCoverage.set(i);
}
}
// Iterate over gaps in target coverage, aligning to source gaps along the diagonal
if (targetCoverage.cardinality() != prefix.size()) {
// Iterate over the target coverage
CoverageSet finalTargetCoverage = targetCoverage.clone();
for (int i = targetCoverage.nextClearBit(0); i < prefix.size();
i = targetCoverage.nextClearBit(i+1)) {
int ei = i;
int ej = targetCoverage.nextSetBit(ei+1);
if (ej < 0) ej = prefix.size();
// Must be a valid index
int mid = Math.max(0, Math.min((int) Math.round((ej + ei) / 2.0), sourceSequence.size() - 1));
int rightQuery = sourceCoverage.nextClearBit(mid);
int leftQuery = sourceCoverage.previousClearBit(mid);
int sourceAnchor = -1;
if (leftQuery >= 0 && rightQuery < sourceSequence.size()) {
sourceAnchor = ((mid - leftQuery) < (rightQuery - mid)) ? leftQuery : rightQuery;
} else if (leftQuery >= 0) {
sourceAnchor = leftQuery;
} else if (rightQuery < sourceSequence.size()) {
sourceAnchor = rightQuery;
}
if (sourceAnchor >= 0) {
int fi = Math.max(0, sourceCoverage.previousSetBit(sourceAnchor-1)+1);
int fj = sourceCoverage.nextSetBit(sourceAnchor+1);
if (fj < 0) fj = sourceSequence.size();
Sequence<TK> src = sourceSequence.subsequence(fi, fj);
Sequence<TK> tgt = prefix.subsequence(ei, ej);
CoverageSet cov = new CoverageSet(sourceSequence.size());
cov.set(fi, fj);
int cnt_f = 1, cnt_e = 1;
double cnt_fe = 1e-9;
ConcreteRule<TK,FV> syntheticRule = SyntheticRules.makeSyntheticRule(src, tgt,
cov, featureNames, inferer.scorer, inferer.featurizer,
cnt_fe, cnt_e, cnt_f, inputProperties, sourceSequence, sourceInputId, MONOTONE_ALIGNMENT);
ruleGrid.addEntry(syntheticRule);
finalTargetCoverage.set(ei, ej);
// WSGDEBUG
// System.err.printf("ExtUnk: %s%n", syntheticRule);
}
}
if (finalTargetCoverage.cardinality() != prefix.size()) {
logger.warn("input {}: Incomplete target coverage {}", sourceInputId, finalTargetCoverage);
}
}
}
public static List<RuleBound> extractRules(SymmetricalWordAlignment align, int sourcePosition,
int length, int maxTargetPhrase) {
// Find the target span
int minTarget = Integer.MAX_VALUE;
int maxTarget = -1;
final int startSource = sourcePosition;
final int endSource = startSource + length;
for(int sourcePos = startSource; sourcePos < endSource; sourcePos++) {
assert sourcePos < align.fSize() : String.format("[%d,%d) %d %d ", startSource, endSource, sourcePos, align.fSize());
if ( align.f2e(sourcePos).size() > 0) {
for(int targetPos : align.f2e(sourcePos)) {
if (targetPos < minTarget) {
minTarget = targetPos;
}
if (targetPos > maxTarget) {
maxTarget = targetPos;
}
}
}
}
if (maxTarget < 0 || maxTarget-minTarget >= maxTargetPhrase) return Collections.emptyList();
// Admissibility check
for (int i = minTarget; i <= maxTarget; ++i) {
if ( align.e2f(i).size() > 0) {
for (int sourcePos : align.e2f(i)) {
if (sourcePos < startSource || sourcePos >= endSource) {
// Failed check
return Collections.emptyList();
}
}
}
}
// "Loose" heuristic to grow the target
// Try to grow the left bound of the target
List<RuleBound> ruleList = new ArrayList<>();
for(int startTarget = minTarget; (startTarget >= 0 &&
startTarget > maxTarget-maxTargetPhrase &&
(startTarget == minTarget || align.e2f(startTarget).size() == 0)); startTarget--) {
// Try to grow the right bound of the target
for (int endTarget=maxTarget; (endTarget < align.eSize() &&
endTarget < startTarget+maxTargetPhrase &&
(endTarget==maxTarget || align.e2f(endTarget).size() == 0)); endTarget++) {
RuleBound r = new RuleBound(startSource, endSource, startTarget, endTarget + 1);
ruleList.add(r);
}
}
return ruleList;
}
private static class RuleBound {
public final int fi;
public final int fj; // exclusive
public final int ei;
public final int ej; // exclusive
public RuleBound(int fi, int fj, int ei, int ej) {
this.fi = fi;
this.fj = fj;
this.ei = ei;
this.ej = ej;
}
}
// protected static boolean addPhrasesToIndex(WordAlignment sent, int maxPhraseLenE, int maxPhraseLenF) {
//
// int fsize = sent.f().size();
// int esize = sent.e().size();
//
// // For each English phrase:
// for (int e1 = 0; e1 < esize; ++e1) {
//
// int f1 = Integer.MAX_VALUE;
// int f2 = Integer.MIN_VALUE;
// int lastE = Math.min(esize, e1 + maxPhraseLenE) - 1;
//
// for (int e2 = e1; e2 <= lastE; ++e2) {
//
// // Find range of f aligning to e1...e2:
// SortedSet<Integer> fss = sent.e2f(e2);
// if (!fss.isEmpty()) {
// int fmin = fss.first();
// int fmax = fss.last();
// if (fmin < f1)
// f1 = fmin;
// if (fmax > f2)
// f2 = fmax;
// }
//
// // Phrase too long:
// if (f2 - f1 >= maxPhraseLenF)
// continue;
//
// // No word alignment within that range, or phrase too long?
// if (f1 > f2)
// continue;
//
// // Check if range [e1-e2] [f1-f2] is admissible:
// boolean admissible = true;
// for (int fi = f1; fi <= f2; ++fi) {
// SortedSet<Integer> ess = sent.f2e(fi);
// if (!ess.isEmpty())
// if (ess.first() < e1 || ess.last() > e2) {
// admissible = false;
// break;
// }
// }
// if (!admissible)
// continue;
//
// // See how much we can expand the phrase to cover unaligned words:
// int F1 = f1, F2 = f2;
// int lastF1 = Math.max(0, f2 - maxPhraseLenF + 1);
// while (F1 > lastF1 && sent.f2e(F1 - 1).isEmpty()) {
// --F1;
// }
// int lastF2 = Math.min(fsize - 1, f1 + maxPhraseLenF - 1);
// while (F2 < lastF2 && sent.f2e(F2 + 1).isEmpty()) {
// ++F2;
// }
//
// for (int i = F1; i <= f1; ++i) {
// int lasti = Math.min(F2, i + maxPhraseLenF - 1);
// for (int j = f2; j <= lasti; ++j) {
// assert (j - i < maxPhraseLenF);
// addPhraseToIndex(sent, i, j, e1, e2, true, 1.0f);
// }
// }
// }
// }
//
// return true;
// }
private static SymmetricalWordAlignment intersect(SymmetricalWordAlignment align,
SymmetricalWordAlignment alignInverse) {
SymmetricalWordAlignment a = new SymmetricalWordAlignment(align.f(), align.e());
for (int fi = 0, sz = align.fSize(); fi < sz; ++fi) {
for (int ei : align.f2e(fi)) {
if (alignInverse.e2f(ei).contains(fi)) {
a.addAlign(fi, ei);
}
}
}
return a;
}
@SuppressWarnings("unchecked")
private static <TK,FV> SymmetricalWordAlignment align(Sequence<TK> source,
Sequence<TK> target, List<DynamicTranslationModel<FV>> tmList) {
SymmetricalWordAlignment a = new SymmetricalWordAlignment((Sequence<IString>) source,
(Sequence<IString>) target);
int[] cnt_f = new int[source.size()];
Arrays.fill(cnt_f, -1);
for (int i = 0, tSz = target.size(); i < tSz; ++i) {
double max = -10000.0;
int argmax = -1;
final IString tgtToken = (IString) target.get(i);
for (int j = 0, sz = source.size(); j < sz; ++j) {
final IString srcToken = (IString) source.get(j);
if (cnt_f[j] < 0) cnt_f[j] = tmList.stream().mapToInt(tm -> tm.getSourceLexCount(srcToken)).sum();
int cnt_ef = tmList.stream().mapToInt(tm -> tm.getJointLexCount(srcToken, tgtToken)).sum();
double tEF = Math.log(cnt_ef) - Math.log(cnt_f[j]);
if (tEF > max) {
max = tEF;
argmax = j;
}
}
if (argmax < 0) {
// Backoff to lexical similarity
// TODO(spenceg) Only works for languages with similar orthography.
String tgt = target.get(i).toString();
for (int j = 0, sz = source.size(); j < sz; ++j) {
String src = source.get(j).toString();
double q = SimilarityMeasures.jaccard(tgt, src);
if (q > max) {
max = q;
argmax = j;
}
}
}
// Populate alignment
if (argmax >= 0) {
a.addAlign(argmax, i);
}
}
return a;
}
@SuppressWarnings("unchecked")
private static <TK,FV> SymmetricalWordAlignment alignInverse(Sequence<TK> source,
Sequence<TK> target, List<DynamicTranslationModel<FV>> tmList) {
SymmetricalWordAlignment a = new SymmetricalWordAlignment((Sequence<IString>) source,
(Sequence<IString>) target);
int[] cnt_e = new int[target.size()];
Arrays.fill(cnt_e, -1);
for (int i = 0, sSz = source.size(); i < sSz; ++i) {
double max = -10000.0;
int argmax = -1;
final IString srcToken = (IString) source.get(i);
for (int j = 0, sz = target.size(); j < sz; ++j) {
final IString tgtToken = (IString) target.get(j);
if (cnt_e[j] < 0) cnt_e[j] = tmList.stream().mapToInt(tm -> tm.getTargetLexCount(tgtToken)).sum();
int cnt_ef = tmList.stream().mapToInt(tm -> tm.getJointLexCount(srcToken, tgtToken)).sum();
double tEF = Math.log(cnt_ef) - Math.log(cnt_e[j]);
if (tEF > max) {
max = tEF;
argmax = j;
}
}
if (argmax < 0) {
// Backoff to lexical similarity
// TODO(spenceg) Only works for languages with similar orthography.
String src = source.get(i).toString();
for (int j = 0, sz = target.size(); j < sz; ++j) {
String tgt = target.get(j).toString();
double q = SimilarityMeasures.jaccard(tgt, src);
if (q > max) {
max = q;
argmax = j;
}
}
}
// Populate alignment
if (argmax >= 0) {
a.addAlign(i, argmax);
}
}
return a;
}
}
|
Andy-Peng/phrasal
|
src/edu/stanford/nlp/mt/decoder/util/SyntheticRules.java
|
Java
|
gpl-3.0
| 20,195
|
#!/bin/bash
gcc -g xpause.c -o xpause -lX11 -lXmu
|
chriskmanx/qmole
|
QMOLEDEV/xpause/build_xpause.sh
|
Shell
|
gpl-3.0
| 51
|
---
layout: page
title: About
sidebar_link: true
permalink: /about/
---
I work as a red teamer and Operator at [SpecterOps](https://specterops.io/). I enjoy security-related software development in my spare time, and tend to write about topics related to offensive PowerShell, .NET, and Windows security in general.
I intend for this blog to be a platform to document and share the things I am working on or interest me. I don't claim to be an expert.
### Projects
Projects I am currently working on:
* **Covenant** - [Covenant](https://github.com/cobbr/Covenant) is a .NET command and control framework that aims to highlight the attack surface of .NET, make the use of offensive .NET tradecraft easier, and serve as a collaborative command and control platform for red teamers.
* **SharpSploit** - [SharpSploit](https://github.com/cobbr/SharpSploit) is a .NET post-exploitation library written in C# that aims to highlight the attack surface of .NET and make the use of offensive .NET easier for red teamers.
* **PSAmsi** - [PSAmsi](https://github.com/cobbr/PSAmsi) is a tool for auditing and defeating AMSI signatures.
Projects I help to maintain:
* **Invoke-Obfuscation** - I help to maintain [Invoke-Obfuscation](https://github.com/danielbohannon/Invoke-Obfuscation), a PowerShell obfuscator, written by [Daniel Bohannon](https://twitter.com/danielhbohannon).
Projects I have worked on in the past:
* **ObfuscatedEmpire** - [ObfuscatedEmpire](https://github.com/cobbr/ObfuscatedEmpire) is an integration of [Empire](https://github.com/EmpireProject/Empire) and [Invoke-Obfuscation](https://github.com/danielbohannon/Invoke-Obfuscation), for automating obfuscation within a PowerShell C2 channel. Introductory blog post and "how to" available [here]({{site.baseurl}}/ObfuscatedEmpire.html). **This has been merged upstream to [Empire](https://github.com/EmpireProject/Empire), so just use that now!**
### Presentations
Presentations I have given at conferences:
* **BSides DFW 2017** - "PSAmsi: Offensive PowerShell Interaction with the AMSI" - A deeper dive into how the Anti-Malware Scan Interface (AMSI) works, how to enumerate AMSI signatures using PSAmsi, and how to simultaneously defeat AMSI signatures and obfuscation detection by minimizing obfuscation using PSAmsi. Also introduced the concept of AbstractSyntaxTree-based PowerShell obfuscation as a stealthier form of obfuscation. Included demos of [PSAmsi](https://github.com/cobbr/PSAmsi), a tool for auditing and defeating AMSI signatures. [Slides available here](https://github.com/cobbr/slides/blob/master/BSides/DFW/PSAmsi%20-%20Offensive%20PowerShell%20Interaction%20with%20the%20AMSI.pdf)
* **DerbyCon 2017** - "PSAmsi: Offensive PowerShell Interaction with the AMSI" - A deeper dive into how the Anti-Malware Scan Interface (AMSI) works, how to enumerate AMSI signatures using PSAmsi, and how to simultaneously defeat AMSI signatures and obfuscation detection by minimizing obfuscation using PSAmsi. Also demonstrated how to use PSAmsi generated payloads within Empire. Included demos of [PSAmsi](https://github.com/cobbr/PSAmsi), a tool for auditing and defeating AMSI signatures. [Slides available here](https://github.com/cobbr/slides/blob/master/DerbyCon/PSAmsi%20-%20Offensive%20PowerShell%20Interaction%20with%20the%20AMSI.pdf), [Recording available here](https://www.youtube.com/watch?v=rEFyalXfQWk)
* **BSides Austin 2017** - "Obfuscating The Empire" - An introduction to PowerShell logging capabilities, the Anti-Malware Scan Interface (AMSI) introduced in Windows 10, and how to use obfuscation to evade AV signatures. Included demos of [ObfuscatedEmpire](https://github.com/cobbr/ObfuscatedEmpire), an integration of [Invoke-Obfuscation](https://github.com/danielbohannon/Invoke-Obfuscation) and [Empire](https://github.com/EmpireProject/Empire). [Slides available here](https://github.com/cobbr/slides/blob/master/BSides/Austin/Obfuscating%20The%20Empire.pdf).
|
cobbr/cobbr.io
|
about.md
|
Markdown
|
gpl-3.0
| 3,962
|
"""
WSGI config for antibiobank project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "antibiobank.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
dridk/antibiobank
|
antibiobank/wsgi.py
|
Python
|
gpl-3.0
| 397
|
<?php
// lancamentos
// ---------------------------------------------------------------------
$config['lancamentos_qtdmeses_listagem'] = 6;
$config['lancamentos_taxacondominial_valor'] = 350.00;
$config['lancamentos_taxacondominial_valor_descontopadrao'] = 70.00;
$config['lancamentos_taxacondominial_vencimento_dia'] = 15;
$config['lancamentos_taxacondominial_vencimento_antecedencia'] = 7;
$config['lancamentos_taxaextra_vencimento_dia'] = 15;
$config['lancamentos_multainfracao_vencimento_dia'] = 15;
$config['lancamentos_acordo_vencimento_dia'] = 15;
// pagamento
// ---------------------------------------------------------------------
$config['pagamentos_atraso_porcentagem_multa'] = 2;
$config['pagamentos_atraso_porcentagem_juros_ad'] = 0.033;
$config['pagamentos_atraso_autoabono'] = true;
$config['pagamentos_desconto_porcentagem_maxima'] = 50;
// arquivo_retorno
// ---------------------------------------------------------------------
//define('MB', 1024*1024);
$config['arquivos_retorno_tamanho_maximo'] = 4;
$config['arquivos_retorno_tamanho_maximo_mb'] = 1024*1024 * $config['arquivos_retorno_tamanho_maximo']; // não mexa
// boleto
// ---------------------------------------------------------------------
$config['boletos_arquivo_diretorioimagens'] = 'http://localhost/siac/img/boleto';
$config['boletos_arquivo_diretoriogravacao'] = 'c:'.DS.'siac-boletos';
$config['boletos_arquivo_nomearquivo'] = 'boletos-{TIPO}-{ANOMES}.pdf';
$config['boletos_arquivo_pdf_titulo'] = 'BOLETOS';
$config['boletos_arquivo_pdf_criador'] = 'SIAC - SISTEMA INTEGRADO DE AUTOMAÇÃO CONDOMINIAL';
$config['boletos_codigobarra_fatorlargura'] = 0.25;
$config['boletos_codigobarra_altura'] = 13; // não mexa
$config['boletos_dados_banco_imagemlogo'] = 'logohsbc.jpg'; // não mexa
$config['boletos_dados_banco_codigo'] = '399'; // não mexa
$config['boletos_dados_agencia_cod_cedente'] = '3432599'; // não mexa
$config['boletos_dados_cedente'] = 'SOC. RESID. ALTO DE PINHEIROS';
$config['boletos_dados_cpfcnpj_cedente'] = 'CNPJ 0333.3692/0001-88';
// gerais
// ---------------------------------------------------------------------
$config['siac_listagem_qtdregistros'] = 100;
$config['siac_listagem_status_navigator'] = 'Página %page% de %pages% (%current% registros, do %start%º ao %end%º, de um total de %count%)';
// CONSTANTES
// ---------------------------------------------------------------------
!defined('TIPO_LANCAMENTO_QUALQUER') && define('TIPO_LANCAMENTO_QUALQUER' ,-1);
!defined('TIPO_LANCAMENTO_TAXACONDOMINIAL') && define('TIPO_LANCAMENTO_TAXACONDOMINIAL' , 0);
!defined('TIPO_LANCAMENTO_TAXAEXTRA') && define('TIPO_LANCAMENTO_TAXAEXTRA' , 1);
!defined('TIPO_LANCAMENTO_MULTAINFRACAO') && define('TIPO_LANCAMENTO_MULTAINFRACAO' , 2);
!defined('TIPO_LANCAMENTO_ACORDO') && define('TIPO_LANCAMENTO_ACORDO' , 3);
!defined('STATUS_PARCELA_CORRETA') && define('STATUS_PARCELA_CORRETA' , 0);
!defined('STATUS_PARCELA_REGULARIZADA') && define('STATUS_PARCELA_REGULARIZADA' , 1);
!defined('STATUS_PARCELA_PENDENTE') && define('STATUS_PARCELA_PENDENTE' , 2);
!defined('TIPO_LIQUIDACAO_CHEQUE') && define('TIPO_LIQUIDACAO_CHEQUE' , 1);
!defined('TIPO_LIQUIDACAO_DINHEIRO') && define('TIPO_LIQUIDACAO_DINHEIRO' , 2);
!defined('TIPO_LIQUIDACAO_COMPENSACAO') && define('TIPO_LIQUIDACAO_COMPENSACAO' , 3);
!defined('OCORRENCIA_RETORNO_LIQUIDACAO') && define('OCORRENCIA_RETORNO_LIQUIDACAO' , '06');
!defined('OCORRENCIA_EMISSAO_CONFIRMADA') && define('OCORRENCIA_EMISSAO_CONFIRMADA' , '07');
!defined('OCORRENCIA_PARCELA_REJEITADA') && define('OCORRENCIA_PARCELA_REJEITADA' , '08');
!defined('MOEDA_REAL') && define('MOEDA_REAL' , 9);
!defined('MOEDA_VARIAVEL') && define('MOEDA_VARIAVEL' , 0);
|
mfandrade/siac
|
app/config/siac.config.php
|
PHP
|
gpl-3.0
| 3,810
|
// upload stuff to the keying server...
function putPng(desturl, obj) {
jQuery.ajax({
type: "PUT",
url: desturl,
contentType: "image/png",
data: obj,
error: function(jqxhr, textStatus) {
//alert("Communication error: " + textStatus);
}
});
}
function postJson(desturl, obj) {
jQuery.ajax({
type: "POST",
url: desturl,
contentType: "application/json",
data: JSON.stringify(obj),
error: function(jqxhr, textStatus) {
//alert("Communication error: " + textStatus);
}
});
}
$(document).ready(function() {
$("#pngImage").change(function() {
var file = $("#pngImage")[0].files[0];
var fr = new FileReader();
fr.onload = function(e) {
var data = e.target.result;
putPng('/key_dataurl', data);
};
fr.readAsDataURL(file);
});
$("#titleUp").click(function() {
postJson('/dissolve_in/30', {});
});
$("#titleDown").click(function() {
postJson('/dissolve_out/30', {});
});
$("#d0").click(function() {
postJson('/dirty_level/0', {});
});
$("#d1").click(function() {
postJson('/dirty_level/1', {});
});
});
|
exavideo/exacore
|
keyer/public_html/upload.js
|
JavaScript
|
gpl-3.0
| 1,276
|
# ios-overscroll
Javascript library to prevent overscroll behavior on IOS devices by using single main scroll container like 'window' object or <body> tag
# status
Currently still in early development ( September 25, 2017 )
|
bayucandra/ios-overscroll
|
README.md
|
Markdown
|
gpl-3.0
| 226
|
/**
* Simple css theme
* Jason Grimston
* 25/04/2016
**/
body {
font-family: Arial, sans-serif;
}
* {
box-sizing: border-box;
}
.main {
min-height: 100vh;
min-width: 100vw;
overflow: auto;
display: flex;
align-items: center;
flex-direction: column;
background: linear-gradient(145deg, #7143ff, #ed178e, #191c28);
background-size: 100% 100%;
/*-webkit-animation: backgroundGradient 30s linear infinite;*/
/*-moz-animation: backgroundGradient 30s linear infinite;*/
/*animation: backgroundGradient 30s linear infinite;*/
padding-top:85vh;
}
.flex {
display: flex;
}
.flex-1 {
flex: 1
}
.full-height {
min-height: 100vh
}
.full-width {
min-width: 100vw;
}
.fill-width{
width: 100%;
}
.horizontal-center {
align-items: center;
}
.vertical-center {
justify-content: center;
}
.flex-direction-col {
flex-direction: column;
}
.flex-wrap{
flex-wrap: wrap;
}
.max-width-container{
padding-left:15px;
padding-right:15px;
margin:0 auto;
width:100%;
max-width:768px;
}
/* Above the fold */
.above-the-fold-wrapper{
position: fixed;
top: 0;
left:0;
z-index: 0;
min-height:85vh;
}
.above-the-fold {
background: rgba(255,255,255,.9);
border-radius: 50%;
width:60vmin;
height:60vmin;
-webkit-box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
-moz-box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
}
@-webkit-keyframes backgroundGradient {
0% {
background-position: 18% 0%;
}
50% {
background-position: 83% 100%;
}
100% {
background-position: 18% 0%;
}
}
@-moz-keyframes backgroundGradient {
0% {
background-position: 18% 0%;
}
50% {
background-position: 83% 100%;
}
100% {
background-position: 18% 0%;
}
}
@keyframes backgroundGradient {
0% {
background-position: 18% 0%;
}
50% {
background-position: 83% 100%;
}
100% {
background-position: 18% 0%;
}
}
.logo-wrapper {
text-align: center;
padding: 25px;
}
.logo-wrapper svg {
width: 25vmin;
height: auto;
}
svg .left-eye {
}
/* Content */
.content-wrapper{
background: #FFF;
max-width: 80vw;
padding: 30px;
border-radius: 25px;
}
/* misc */
.text-wrapper {
margin: 0px 20px;
}
/* Typography */
.fredoka-one {
font-family: 'Fredoka One', cursive;
}
.lato{
font-family: 'Lato', sans-serif;
}
.text-center {
text-align: center;
}
p a{
color:#FFFFFF;
text-decoration: none;
background:#7143FF;
display:inline-block;
-webkit-transition: all 400ms ease-out;
-moz-transition: all 400ms ease-out;
-ms-transition: all 400ms ease-out;
-o-transition: all 400ms ease-out;
transition: all 400ms ease-out;
}
p a:hover{
background:#FFFFFF;
color:#000000;
transform: translateY(-2px) scale(1.01);
}
h1 {
font-size: 2rem;
font-weight: normal;
margin: 0;
padding: 0;
margin-bottom:20px
}
@media (min-width: 33.4995rem) {
h1 {
font-size: 1.5rem;
margin-bottom:30px
}
}
@media (min-width: 44.687rem) {
h1 {
font-size: 2rem;
margin-bottom:40px
}
}
.no-margin{
margin: 0;
}
/* Form overrides */
.form-wrapper {
margin: 20px 20px 45px;
background: rgba(0, 0, 0, .1);
padding: 30px 30px 45px;
overflow: hidden;
border-radius: 20px;
}
.simform ol:before {
background: #7143FF;
border-radius: 20px;
}
.simform label {
font-size: 1rem;
}
@media (min-width: 33.4995rem) {
.simform label {
font-size: 1.3rem;
}
}
@media (min-width: 44.687rem) {
.simform label {
font-size: 1.8rem;
}
}
.questions li.current > span label, .no-js .questions li > span label {
margin: 0 0 .4em;
}
.questions input {
color: #FFFFFF;
}
.error-message.show {
color: red;
}
.next {
bottom: 3.15em
}
@media (min-width: 33.4995rem) {
.next {
bottom: 2.8em
}
}
@media (min-width: 44.687rem) {
.next {
bottom: 2.65em
}
}
.next.show {
color: #FFFFFF;
transform: translate3d(0, 1.9em, 0);
}
.simform .progress {
background: #ED178E;
margin: 20px 0;
}
.simform .number {
font-size: 0.4em;
margin: 0;
}
.final-message.show {
text-align: left;
padding: 0;
}
/* Arrow */
.arrow-down-svg {
position: absolute;
margin: auto;
width:32px;
left: 0;
bottom: 0;
right: 0;
animation: pulseDown 1.5s alternate infinite cubic-bezier(0.175, 0.885, 0.320, 1.275);
}
/* Animations */
@keyframes breath {
from {
transform: translate3d(0, 0%, 0);
}
to {
transform: translate3d(0, -5%, 0);
}
}
@keyframes flyIn {
from {
transform: scale(0) translate3d(-50vw,0,0);
}
to {
transform: scale(1) translate3d(0,0,0) ;
}
}
@keyframes raise {
from {
transform: translate3d(-50vw,0,0);
}
to {
transform: translate3d(0,0,0) ;
}
}
@keyframes pulseDown{
0%{
transform: translate3d(0,-5vh,0);
opacity: 0;
}
100% {
opacity:1;
transform: translate3d(0,0,0) ;
}
}
/* the logo animations */
.wdr_skull{
animation: breath 1000ms alternate infinite;
animation-timing-function: linear;
}
/* page2 */
.page2-wrapper{
/*border:15px solid #7143FF;*/
background: rgba(25,28,40,.9);
z-index: 1;
-webkit-box-shadow: 0 0 60px 20px rgba(2, 2, 2, .2);
-moz-box-shadow: 0 0 60px 20px rgba(2, 2, 2, .2);
box-shadow: 0 0 60px 20px rgba(2, 2, 2, .2);
color:#FFF;
padding-top:20px;
padding-bottom:60px;
}
.page2-section{
margin-top: 15px;
margin-bottom: 100px;
}
/* projects */
.project-section{
margin: 15px;
}
.project-section-title{
margin-top:20px;
text-shadow: 2px 3px 3px rgba(0,0,0,.15)
}
.project-wrapper{
padding: 15px;
min-width:100%;
}
@media (min-width: 768px){
.project-wrapper {
min-width: 50%;
}
}
.project-img{
max-width:100%;
width:100%;
height:auto;
border-radius:26px;
-webkit-box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
-moz-box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
}
.project-link{
cursor: pointer;
position: relative;
display: block;
}
.project-img{
transition: all 300ms ease-in;
display: block;
}
.project-link:hover img{
/*opacity:.4;*/
}
.hover-text-wrapper {
color: #FFF;
text-decoration: none;
text-shadow: 2px 3px 3px rgba(0, 0, 0, .15);
background: rgba(0, 0, 0, 0.8);
border-radius: 26px;
position: absolute;
top: 0;
padding: 30px;
height: 100%;
width: 100%;
opacity:0;
transition:all 300ms ease-out;
}
.hover-text{
transition:all 300ms ease-out;
transform:translateY(50px);
opacity: 0;
pointer-events: none;
}
.project-link:hover .hover-text{
transform:translateY(0);
opacity:1;
}
.project-link:hover .hover-text-wrapper{
opacity:1;
}
/* Forms */
input, textarea{
background:#FFFFFF;
border:2px solid #333333;
border-radius: 20px;
line-height:2em;
outline:none;
padding: 5px 20px;
width:auto;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
resize: none;
color:#333333
}
.input-wrapper{
padding:0 7px 15px 8px;
}
.btn{
background:#7143FF;
border-radius:20px;
padding: 10px 15px;
color:#FFF;
min-width: 200px;
border:none;
outline:none;
}
.btn:hover{
background: rgba(116, 58, 255, 0.80);
-webkit-box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
-moz-box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
box-shadow: 0 0 10px 0px rgba(2, 2, 2, .2);
}
button{
cursor: pointer;
}
#form-messages{
opacity:0;
border-radius: 20px;
padding:15px;
display: none;
margin-bottom: 15px;
}
#form-messages.success{
color:#FFFFFF;
background: rgba(0, 162, 0, 0.73);
opacity:1;
display: inline-block;
}
#form-messages.error{
color:#FFFFFF;
background: rgba(166, 0, 0, 0.87);
opacity:1;
display: inline-block;
}
#ajax-contact, #form-messages{
transition: opacity 300ms ease-out;
}
|
webdevreaper/portfolio
|
assets/style/style.css
|
CSS
|
gpl-3.0
| 8,414
|
{% extends "global/Base.html" %}
{% load staticfiles otree_tags %}
{% block title %}
{% endblock %}
{% block content %}
<p>
Maintenant vous prenez une décision sur le choix de votre assurance voiture
<br>
La voiture autonome diminue grandement le risque d'accident.
</p>
{% next_button %}
{% endblock %}
|
anthropo-lab/XP
|
voiture_autonome_assurance/templates/voiture_autonome_assurance/InformationPage2.html
|
HTML
|
gpl-3.0
| 321
|
/*
* 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.
* Author : J-G
* Date : 26-08-2017
*/
package programs;
import biologic.FastaFile;
import biologic.BCFFile;
import biologic.BamBaiFile;
import biologic.VCFFile;
import biologic.BamFile;
import biologic.BedFile;
import configuration.Docker;
import biologic.Results;
import biologic.Unknown;
import configuration.Cluster;
import configuration.Util;
import java.io.File;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Map;
import java.util.Iterator;
import program.RunProgram;
import static program.RunProgram.PortInputUP;
import static program.RunProgram.df;
import static program.RunProgram.status_error;
import workflows.workflow_properties;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.ArrayUtils;
import static program.RunProgram.status_running;
/**
*
* @author J-G
* @date 26-08-2017
*
*/
public class samtools_mpileup extends RunProgram {
// CREATE VARIABLES HERE
private String allDoInputs = "";
private HashMap<String,String> sharedFolders = new HashMap<String,String>();
//INPUTS
private String input1 = "";
private String inputId1 = "";
private String inputPath1 = "";
private String input2 = "";
private String inputId2 = "";
private String inputPath2 = "";
private String input3 = "";
private String inputId3 = "";
private String inputPath3 = "";
private String[] inputsPath3= {};
private String[] inputsIDs3 = {};
private String input4 = "";
private String inputId4 = "";
private String inputPath4 = "";
//OUTPUTS
private String output1 = "";
private String outputInDo1 = "";
//PATHS
private static final String outputsPath = "."+File.separator+"results"+File.separator+"samtools"+File.separator+"mpileup"+File.separator+"";
private static final String[] Advanced_Options = {
"AO_AO__illumina1DOT3PLUS_box",
"AO_OO__BCF_box"
};
public samtools_mpileup(workflow_properties properties){
this.properties=properties;
execute();
}
@Override
public boolean init_checkRequirements(){
// In case program is started without edition
pgrmStartWithoutEdition(properties);
// TEST OUTPUT PATH
String specificId = Util.returnRandomAndDate();
if (properties.isSet("ObjectID")) {
String oId = properties.get("ObjectID");
oId = Util.replaceSpaceByUnderscore(oId);
specificId = specificId+"_"+oId;
}
String specificPath = outputsPath+specificId;
if (!Util.CreateDir(specificPath) && !Util.DirExists(specificPath)){
setStatus(status_BadRequirements,Util.BROutputsDir());
return false;
}
// TEST INPUT VARIABLES HERE
// ports are 3-PortInputUp, 2-PortInputDOWN, 4-PortInputDOWN2
Vector<Integer>BedFile1 = properties.getInputID("BedFile",PortInputDOWN2);
inputPath1 = Unknown.getVectorFilePath(BedFile1);
inputId1 = Unknown.getVectorFileId(BedFile1);
input1 = Util.getFileNameAndExt(inputPath1);
Vector<Integer>FastaFile2 = properties.getInputID("FastaFile",PortInputUP);
inputPath2 = Unknown.getVectorFilePath(FastaFile2);
inputId2 = Unknown.getVectorFileId(FastaFile2);
input2 = Util.getFileNameAndExt(inputPath2);
Vector<Integer>BamFile3 = properties.getInputID("BamFile",PortInputDOWN);
inputPath3 = Unknown.getVectorFilePath(BamFile3);
inputId3 = Unknown.getVectorFileId(BamFile3);
input3 = Util.getFileNameAndExt(inputPath3);
// Get the multiple inputs
inputsPath3 = Unknown.getAllVectorFilePath(BamFile3);
inputsIDs3 = Unknown.getVectorFileIds(BamFile3);
Vector<Integer>BamBaiFile4 = properties.getInputID("BamBaiFile",PortInputDOWN);
inputPath4 = Unknown.getVectorFilePath(BamBaiFile4);
inputId4 = Unknown.getVectorFileId(BamBaiFile4);
input4 = Util.getFileNameAndExt(inputPath4);
//INSERT YOUR INPUT TEST HERE
if (BedFile1.isEmpty()||input1.equals("Unknown")||input1.equals("")){
setStatus(status_warning,Util.BRTypeFile("BedFile"));
//return false;
}
// Please, check if it's "else if" or it's a real "if"
if (FastaFile2.isEmpty()||input2.equals("Unknown")||input2.equals("")){
setStatus(status_warning,Util.BRTypeFile("FastaFile"));
//return false;
}
// Please, check if it's "else if" or it's a real "if"
if ((BamFile3.isEmpty()||input3.equals("Unknown")||input3.equals("")) &&
(BamBaiFile4.isEmpty()||input4.equals("Unknown")||input4.equals(""))){
setStatus(status_BadRequirements,Util.BRTypeFile("BamBaiFile or BamFile"));
return false;
}
// Test docker Var presence
if (Docker.areDockerVariablesNotInProperties(properties)){
setStatus(status_BadRequirements,Util.BRDockerVariables());
return false;
}
// Extract Docker Variables
String doOutputs = properties.get("DockerOutputs");
String doInputs = properties.get("DockerInputs");
// Prepare ouputs
output1 = specificPath+File.separator+"OutputOf_"+input3+".bam";
outputInDo1 = doOutputs+"OutputOf_"+input3+".bam";
if (properties.isSet("AO_OO__VCF_box")) {
output1 = specificPath+File.separator+"OutputOf_"+input3+".vcf";
outputInDo1 = doOutputs+"OutputOf_"+input3+".vcf";
} else if (properties.isSet("AO_OO__BCF_box")) {
output1 = specificPath+File.separator+"OutputOf_"+input3+".bcf";
outputInDo1 = doOutputs+"OutputOf_"+input3+".bcf";
}
output1 = Util.onlyOneOutputOf(output1);
outputInDo1 = Util.onlyOneOutputOf(outputInDo1);
// Prepare shared folders
String[] simplePath = {inputPath1,inputPath2,inputPath3,inputPath4};
String[] allInputsPath = Util.merge2TablesWithoutDup(simplePath, inputsPath3);
String[] simpleId = {inputId1,inputId2,inputId3,inputId4};
String[] allInputsId = Util.merge2TablesWithoutDup(simpleId, inputsIDs3);
sharedFolders = Docker.createSharedFolders(allInputsPath,allInputsId,doInputs);
sharedFolders = Docker.addInSharedFolder(sharedFolders,specificPath,doOutputs);
// Prepare inputs
HashMap<String,String> allInputsPathArg = new HashMap<String,String>();
allInputsPathArg.put(inputPath1,"--positions");
allInputsPathArg.put(inputPath2,"--fasta-ref");
allInputsPathArg.put(inputPath3,"");
allInputsPathArg.put(inputPath4,"");
for (String st:inputsPath3){
if (allInputsPathArg.get(st)==null)
allInputsPathArg.put(st,"");
}
allDoInputs = Docker.createAllDockerInputs(allInputsPathArg,allInputsPath,allInputsId,doInputs);
// Prepare cluster relations
Cluster.createLinkDockerClusterInputs(properties,allInputsPath,allInputsId,doInputs);
Cluster.createLinkDockerClusterOutput(properties,output1,outputInDo1);
// DOCKER INIT
if (Docker.isDockerHere()){
long duration = Docker.prepareContainer(properties,sharedFolders);
if (!Docker.isDockerContainerIDPresentIn(properties)){
setStatus(status_BadRequirements,Util.BRDockerInit());
return false;
}
setStatus(status_running,Util.RUNDockerDuration("launch",duration));
} else {
setStatus(status_BadRequirements,Util.BRDockerNotFound());
return false;
}
return true;
}
// def functions for init_createCommandLine
// In case program is started without edition and params need to be setted
private void pgrmStartWithoutEdition (workflow_properties properties){
if (!(properties.isSet("Default_Options"))
&& !(properties.isSet("Advanced_Options"))
){
Util.getDefaultPgrmValues(properties,false);
}
}
@Override
public String[] init_createCommandLine() {
// Program and Options
String options = "";
if (properties.isSet("Advanced_Options"))
options += Util.findOptionsNew(Advanced_Options,properties);
// Pre command line
String preCli = options+" "+allDoInputs+" > "+outputInDo1;
// Docker command line
String dockerCli = properties.get("ExecutableDocker")+" "+preCli;
long duration = Docker.prepareDockerBashFile(properties,dockerCli);
setStatus(status_running, "\t<TIME> Time to prepare docker bash file is >"+duration+" s");
setStatus(status_running,"Docker CommandLine: \n$ "+dockerCli);
// Cluster
String clusterCli = properties.get("ExecutableCluster")+" "+preCli;
Cluster.createClusterRunningCLiFromDocker(properties, clusterCli);
// Command line
String[] com = {""};
return com;
}
/*
* Output Parsing
*/
@Override
public void post_parseOutput(){
long duration = Docker.removeContainer(properties);
setStatus(status_running, Util.RUNDockerDuration("stop and remove",duration));
if (output1.endsWith("vcf"))
VCFFile.saveFile(properties,output1,"samtools_mpileup","VCFFile");
if (output1.endsWith("bcf"))
BCFFile.saveFile(properties,output1,"samtools_mpileup","BCFFile");
if (output1.endsWith("bam"))
BamFile.saveFile(properties,output1,"samtools_mpileup","BamFile");
Results.saveResultsPgrmOutput(properties,this.getPgrmOutput(),"samtools_mpileup");
}
}
|
JeGoi/armadillo2
|
src/programs/samtools_mpileup.java
|
Java
|
gpl-3.0
| 10,323
|
#include "stm32f10x.h"
#include "clock_hal.h"
#include "main.h"
volatile uint32_t ms_ticks;
volatile uint32_t uwTimingDelay;
RCC_ClocksTypeDef RCC_Clocks;
/**
* @brief Decrements the TimingDelay variable.
* @param None
* @retval None
*/
void TimingDelay_Decrement(void)
{
if (uwTimingDelay != 0x00)
{
uwTimingDelay--;
}
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
ms_ticks++;
TimingDelay_Decrement();
millisecond_interval_timer();
}
void clock_init_hal(void){
RCC_GetClocksFreq(&RCC_Clocks);
SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000);
}
|
miago/graffiti
|
src/hal/clock_hal.c
|
C
|
gpl-3.0
| 717
|
<?php
/**
* WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan
*
* The PHP page that serves all page requests on WebExploitScan installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All WebExploitScan code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
$NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 821';
$TAGCLEAR='A<?phps+@?(?:system|exec|passthru|shell_exec|popen|eval|assert)(base64_decode([\'"](?:aWYgKCRfR0VUWy|aWYgKCRfUE9TVF)[^\'"]{99,3000}[\'"]))(?:?>|Z)';
$TAGBASE64='QTw/cGhwcytAPyg/OnN5c3RlbXxleGVjfHBhc3N0aHJ1fHNoZWxsX2V4ZWN8cG9wZW58ZXZhbHxhc3NlcnQpKGJhc2U2NF9kZWNvZGUoW1wnIl0oPzphV1lnS0NSZlIwVlVXeXxhV1lnS0NSZlVFOVRWRilbXlwnIl17OTksMzAwMH1bXCciXSkpKD86Pz58Wik=';
$TAGHEX='413c3f706870732b403f283f3a73797374656d7c657865637c70617373746872757c7368656c6c5f657865637c706f70656e7c6576616c7c61737365727429286261736536345f6465636f6465285b5c27225d283f3a615759674b4352665230565557797c615759674b435266554539545646295b5e5c27225d7b39392c333030307d5b5c27225d2929283f3a3f3e7c5a29';
$TAGHEXPHP='';
$TAGURI='A%3C%3Fphps%2B%40%3F%28%3F%3Asystem%7Cexec%7Cpassthru%7Cshell_exec%7Cpopen%7Ceval%7Cassert%29%28base64_decode%28%5B%5C%27%22%5D%28%3F%3AaWYgKCRfR0VUWy%7CaWYgKCRfUE9TVF%29%5B%5E%5C%27%22%5D%7B99%2C3000%7D%5B%5C%27%22%5D%29%29%28%3F%3A%3F%3E%7CZ%29';
$TAGCLEAR2='';
$TAGBASE642='';
$TAGHEX2='';
$TAGHEXPHP2='';
$TAGURI2='';
$DATEADD='10/09/2019';
$LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 821 ';
$ACTIVED='1';
$VSTATR='malware_signature';
|
libre/webexploitscan
|
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-821-malware_signature.php
|
PHP
|
gpl-3.0
| 1,638
|
```python
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n == 0:
return [0]
stack = ['0', '1']
stackout = ['0', '1']
n -= 1
for i in range(n):
stack.reverse()
for i in range(len(stackout)):
stackout[i] = stackout[i].zfill(len(stackout[-1])+1)
for op in stack:
stackout.append('1'+op)
stack = [x for x in stackout]
for i in range(len(stackout)):
stackout[i] = int(stackout[i],2)
return stackout
```
字符串补0 栈
|
boke1208/LeetCodeInPython
|
89.md
|
Markdown
|
gpl-3.0
| 694
|
/*
$License:
Copyright (C) 2011 InvenSense Corporation, All Rights Reserved.
See included License.txt for License information.
$
*/
/*******************************************************************************
*
* $Id: mlmath.c 5629 2011-06-11 03:13:08Z mcaramello $
*
*******************************************************************************/
#include <math.h>
double ml_asin (double x) {
return asin (x);
}
double ml_atan (double x) {
return atan (x);
}
double ml_atan2 (double x, double y) {
return atan2 (x, y);
}
double ml_log (double x) {
return log (x);
}
double ml_sqrt (double x) {
return sqrt (x);
}
double ml_ceil (double x) {
return ceil (x);
}
double ml_floor (double x) {
return floor (x);
}
double ml_cos (double x) {
return cos (x);
}
double ml_sin (double x) {
return sin (x);
}
double ml_acos (double x) {
return acos (x);
}
double ml_pow (double x, double y) {
return pow (x, y);
}
|
imran27/myfiles
|
motion_driver_6.12/arm/STM32F4_MD6/Projects/eMD6/core/mllite/mlmath.c
|
C
|
gpl-3.0
| 1,003
|
/*
Test the SMB_QUERY_FILE_UNIX_INFO2 Unix extension.
Copyright (C) 2007 James Peach
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 "includes.h"
#include "libcli/libcli.h"
#include "torture/util.h"
#include "torture/unix/proto.h"
#include "lib/cmdline/popt_common.h"
#include "libcli/resolve/resolve.h"
#include "param/param.h"
struct unix_info2 {
uint64_t end_of_file;
uint64_t num_bytes;
NTTIME status_change_time;
NTTIME access_time;
NTTIME change_time;
uint64_t uid;
uint64_t gid;
uint32_t file_type;
uint64_t dev_major;
uint64_t dev_minor;
uint64_t unique_id;
uint64_t permissions;
uint64_t nlink;
NTTIME create_time;
uint32_t file_flags;
uint32_t flags_mask;
};
static struct smbcli_state *connect_to_server(struct torture_context *tctx)
{
NTSTATUS status;
struct smbcli_state *cli;
const char *host = torture_setting_string(tctx, "host", NULL);
const char *share = torture_setting_string(tctx, "share", NULL);
struct smbcli_options options;
struct smbcli_session_options session_options;
lpcfg_smbcli_options(tctx->lp_ctx, &options);
lpcfg_smbcli_session_options(tctx->lp_ctx, &session_options);
status = smbcli_full_connection(tctx, &cli, host,
lpcfg_smb_ports(tctx->lp_ctx),
share, NULL, lpcfg_socket_options(tctx->lp_ctx),
popt_get_cmdline_credentials(),
lpcfg_resolve_context(tctx->lp_ctx),
tctx->ev, &options, &session_options,
lpcfg_gensec_settings(tctx, tctx->lp_ctx));
if (!NT_STATUS_IS_OK(status)) {
torture_comment(tctx, "failed to connect to //%s/%s: %s\n",
host, share, nt_errstr(status));
torture_fail(tctx, "Failed to connect to server");
return NULL;
}
return cli;
}
static bool check_unix_info2(struct torture_context *torture,
struct unix_info2 *info2)
{
printf("\tcreate_time=0x%016llu flags=0x%08x mask=0x%08x\n",
(unsigned long long)info2->create_time,
info2->file_flags, info2->flags_mask);
if (info2->file_flags == 0) {
return true;
}
/* If we have any file_flags set, they must be within the range
* defined by flags_mask.
*/
if ((info2->flags_mask & info2->file_flags) == 0) {
torture_result(torture, TORTURE_FAIL,
__location__": UNIX_INFO2 flags field 0x%08x, "
"does not match mask 0x%08x\n",
info2->file_flags, info2->flags_mask);
}
return true;
}
static NTSTATUS set_path_info2(void *mem_ctx,
struct smbcli_state *cli,
const char *fname,
struct unix_info2 *info2)
{
union smb_setfileinfo sfinfo;
ZERO_STRUCT(sfinfo.basic_info.in);
sfinfo.generic.level = RAW_SFILEINFO_UNIX_INFO2;
sfinfo.generic.in.file.path = fname;
sfinfo.unix_info2.in.end_of_file = info2->end_of_file;
sfinfo.unix_info2.in.num_bytes = info2->num_bytes;
sfinfo.unix_info2.in.status_change_time = info2->status_change_time;
sfinfo.unix_info2.in.access_time = info2->access_time;
sfinfo.unix_info2.in.change_time = info2->change_time;
sfinfo.unix_info2.in.uid = info2->uid;
sfinfo.unix_info2.in.gid = info2->gid;
sfinfo.unix_info2.in.file_type = info2->file_type;
sfinfo.unix_info2.in.dev_major = info2->dev_major;
sfinfo.unix_info2.in.dev_minor = info2->dev_minor;
sfinfo.unix_info2.in.unique_id = info2->unique_id;
sfinfo.unix_info2.in.permissions = info2->permissions;
sfinfo.unix_info2.in.nlink = info2->nlink;
sfinfo.unix_info2.in.create_time = info2->create_time;
sfinfo.unix_info2.in.file_flags = info2->file_flags;
sfinfo.unix_info2.in.flags_mask = info2->flags_mask;
return smb_raw_setpathinfo(cli->tree, &sfinfo);
}
static bool query_file_path_info2(void *mem_ctx,
struct torture_context *torture,
struct smbcli_state *cli,
int fnum,
const char *fname,
struct unix_info2 *info2)
{
NTSTATUS result;
union smb_fileinfo finfo;
finfo.generic.level = RAW_FILEINFO_UNIX_INFO2;
if (fname) {
finfo.generic.in.file.path = fname;
result = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
} else {
finfo.generic.in.file.fnum = fnum;
result = smb_raw_fileinfo(cli->tree, mem_ctx, &finfo);
}
torture_assert_ntstatus_equal(torture, result, NT_STATUS_OK,
smbcli_errstr(cli->tree));
info2->end_of_file = finfo.unix_info2.out.end_of_file;
info2->num_bytes = finfo.unix_info2.out.num_bytes;
info2->status_change_time = finfo.unix_info2.out.status_change_time;
info2->access_time = finfo.unix_info2.out.access_time;
info2->change_time = finfo.unix_info2.out.change_time;
info2->uid = finfo.unix_info2.out.uid;
info2->gid = finfo.unix_info2.out.gid;
info2->file_type = finfo.unix_info2.out.file_type;
info2->dev_major = finfo.unix_info2.out.dev_major;
info2->dev_minor = finfo.unix_info2.out.dev_minor;
info2->unique_id = finfo.unix_info2.out.unique_id;
info2->permissions = finfo.unix_info2.out.permissions;
info2->nlink = finfo.unix_info2.out.nlink;
info2->create_time = finfo.unix_info2.out.create_time;
info2->file_flags = finfo.unix_info2.out.file_flags;
info2->flags_mask = finfo.unix_info2.out.flags_mask;
if (!check_unix_info2(torture, info2)) {
return false;
}
return true;
}
static bool query_file_info2(void *mem_ctx,
struct torture_context *torture,
struct smbcli_state *cli,
int fnum,
struct unix_info2 *info2)
{
return query_file_path_info2(mem_ctx, torture, cli,
fnum, NULL, info2);
}
static bool query_path_info2(void *mem_ctx,
struct torture_context *torture,
struct smbcli_state *cli,
const char *fname,
struct unix_info2 *info2)
{
return query_file_path_info2(mem_ctx, torture, cli,
-1, fname, info2);
}
static bool search_callback(void *private_data, const union smb_search_data *fdata)
{
struct unix_info2 *info2 = (struct unix_info2 *)private_data;
info2->end_of_file = fdata->unix_info2.end_of_file;
info2->num_bytes = fdata->unix_info2.num_bytes;
info2->status_change_time = fdata->unix_info2.status_change_time;
info2->access_time = fdata->unix_info2.access_time;
info2->change_time = fdata->unix_info2.change_time;
info2->uid = fdata->unix_info2.uid;
info2->gid = fdata->unix_info2.gid;
info2->file_type = fdata->unix_info2.file_type;
info2->dev_major = fdata->unix_info2.dev_major;
info2->dev_minor = fdata->unix_info2.dev_minor;
info2->unique_id = fdata->unix_info2.unique_id;
info2->permissions = fdata->unix_info2.permissions;
info2->nlink = fdata->unix_info2.nlink;
info2->create_time = fdata->unix_info2.create_time;
info2->file_flags = fdata->unix_info2.file_flags;
info2->flags_mask = fdata->unix_info2.flags_mask;
return true;
}
static bool find_single_info2(void *mem_ctx,
struct torture_context *torture,
struct smbcli_state *cli,
const char *fname,
struct unix_info2 *info2)
{
union smb_search_first search;
NTSTATUS status;
/* Set up a new search for a single item, not using resume keys. */
ZERO_STRUCT(search);
search.t2ffirst.level = RAW_SEARCH_TRANS2;
search.t2ffirst.data_level = SMB_FIND_UNIX_INFO2;
search.t2ffirst.in.max_count = 1;
search.t2ffirst.in.flags = FLAG_TRANS2_FIND_CLOSE;
search.t2ffirst.in.pattern = fname;
status = smb_raw_search_first(cli->tree, mem_ctx,
&search, info2, search_callback);
torture_assert_ntstatus_equal(torture, status, NT_STATUS_OK,
smbcli_errstr(cli->tree));
torture_assert_int_equal(torture, search.t2ffirst.out.count, 1,
"expected exactly one result");
torture_assert_int_equal(torture, search.t2ffirst.out.end_of_search, 1,
"expected end_of_search to be true");
return check_unix_info2(torture, info2);
}
#define ASSERT_FLAGS_MATCH(info2, expected) \
if ((info2)->file_flags != (1 << i)) { \
torture_result(torture, TORTURE_FAIL, \
__location__": INFO2 flags field was 0x%08x, "\
"expected 0x%08x\n",\
(info2)->file_flags, expected); \
}
static void set_no_metadata_change(struct unix_info2 *info2)
{
info2->uid = SMB_UID_NO_CHANGE;
info2->gid = SMB_GID_NO_CHANGE;
info2->permissions = SMB_MODE_NO_CHANGE;
info2->end_of_file =
((uint64_t)SMB_SIZE_NO_CHANGE_HI << 32) | SMB_SIZE_NO_CHANGE_LO;
info2->status_change_time =
info2->access_time =
info2->change_time =
info2->create_time =
((uint64_t)SMB_SIZE_NO_CHANGE_HI << 32) | SMB_SIZE_NO_CHANGE_LO;
}
static bool verify_setinfo_flags(void *mem_ctx,
struct torture_context *torture,
struct smbcli_state *cli,
const char *fname)
{
struct unix_info2 info2;
uint32_t smb_fmask;
int i;
bool ret = true;
NTSTATUS status;
if (!query_path_info2(mem_ctx, torture, cli, fname, &info2)) {
return false;
}
smb_fmask = info2.flags_mask;
/* For each possible flag, ask to set exactly 1 flag, making sure
* that flag is in our requested mask.
*/
for (i = 0; i < 32; ++i) {
info2.file_flags = ((uint32_t)1 << i);
info2.flags_mask = smb_fmask | info2.file_flags;
set_no_metadata_change(&info2);
status = set_path_info2(mem_ctx, cli, fname, &info2);
if (info2.file_flags & smb_fmask) {
torture_assert_ntstatus_equal(torture,
status, NT_STATUS_OK,
"setting valid UNIX_INFO2 flag");
if (!query_path_info2(mem_ctx, torture, cli,
fname, &info2)) {
return false;
}
ASSERT_FLAGS_MATCH(&info2, 1 << i);
} else {
/* We tried to set a flag the server doesn't
* understand.
*/
torture_assert_ntstatus_equal(torture,
status, NT_STATUS_INVALID_PARAMETER,
"setting invalid UNIX_INFO2 flag");
}
}
/* Make sure that a zero flags field does nothing. */
set_no_metadata_change(&info2);
info2.file_flags = 0xFFFFFFFF;
info2.flags_mask = 0;
status = set_path_info2(mem_ctx, cli, fname, &info2);
torture_assert_ntstatus_equal(torture, status, NT_STATUS_OK,
"setting empty flags mask");
return ret;
}
static int create_file(struct smbcli_state *cli, const char * fname)
{
return smbcli_nt_create_full(cli->tree, fname, 0,
SEC_FILE_READ_DATA|SEC_FILE_WRITE_DATA, FILE_ATTRIBUTE_NORMAL,
NTCREATEX_SHARE_ACCESS_NONE, NTCREATEX_DISP_OPEN_IF,
0, 0);
}
static bool match_info2(struct torture_context *torture,
const struct unix_info2 *pinfo,
const struct unix_info2 *finfo)
{
printf("checking results match\n");
torture_assert_u64_equal(torture, finfo->end_of_file, 0,
"end_of_file should be 0");
torture_assert_u64_equal(torture, finfo->num_bytes, 0,
"num_bytes should be 0");
torture_assert_u64_equal(torture, finfo->end_of_file,
pinfo->end_of_file, "end_of_file mismatch");
torture_assert_u64_equal(torture, finfo->num_bytes, pinfo->num_bytes,
"num_bytes mismatch");
/* Don't match access_time. */
torture_assert_u64_equal(torture, finfo->status_change_time,
pinfo->status_change_time,
"status_change_time mismatch");
torture_assert_u64_equal(torture, finfo->change_time,
pinfo->change_time, "change_time mismatch");
torture_assert_u64_equal(torture, finfo->uid, pinfo->uid,
"UID mismatch");
torture_assert_u64_equal(torture, finfo->gid, pinfo->gid,
"GID mismatch");
torture_assert_int_equal(torture, finfo->file_type, pinfo->file_type,
"file_type mismatch");
torture_assert_u64_equal(torture, finfo->dev_major, pinfo->dev_major,
"dev_major mismatch");
torture_assert_u64_equal(torture, finfo->dev_minor, pinfo->dev_minor,
"dev_minor mismatch");
torture_assert_u64_equal(torture, finfo->unique_id, pinfo->unique_id,
"unique_id mismatch");
torture_assert_u64_equal(torture, finfo->permissions,
pinfo->permissions, "permissions mismatch");
torture_assert_u64_equal(torture, finfo->nlink, pinfo->nlink,
"nlink mismatch");
torture_assert_u64_equal(torture, finfo->create_time, pinfo->create_time,
"create_time mismatch");
return true;
}
#define FILENAME "\\smb_unix_info2.txt"
bool unix_torture_unix_info2(struct torture_context *torture)
{
void *mem_ctx;
struct smbcli_state *cli;
int fnum;
struct unix_info2 pinfo, finfo;
mem_ctx = talloc_init("smb_query_unix_info2");
torture_assert(torture, mem_ctx != NULL, "out of memory");
if (!(cli = connect_to_server(torture))) {
talloc_free(mem_ctx);
return false;
}
smbcli_unlink(cli->tree, FILENAME);
fnum = create_file(cli, FILENAME);
torture_assert(torture, fnum != -1, smbcli_errstr(cli->tree));
printf("checking SMB_QFILEINFO_UNIX_INFO2 for QueryFileInfo\n");
if (!query_file_info2(mem_ctx, torture, cli, fnum, &finfo)) {
goto fail;
}
printf("checking SMB_QFILEINFO_UNIX_INFO2 for QueryPathInfo\n");
if (!query_path_info2(mem_ctx, torture, cli, FILENAME, &pinfo)) {
goto fail;
}
if (!match_info2(torture, &pinfo, &finfo)) {
goto fail;
}
printf("checking SMB_FIND_UNIX_INFO2 for FindFirst\n");
if (!find_single_info2(mem_ctx, torture, cli, FILENAME, &pinfo)) {
goto fail;
}
if (!match_info2(torture, &pinfo, &finfo)) {
goto fail;
}
/* XXX: should repeat this test with SetFileInfo. */
printf("checking SMB_SFILEINFO_UNIX_INFO2 for SetPathInfo\n");
if (!verify_setinfo_flags(mem_ctx, torture, cli, FILENAME)) {
goto fail;
}
smbcli_close(cli->tree, fnum);
smbcli_unlink(cli->tree, FILENAME);
torture_close_connection(cli);
talloc_free(mem_ctx);
return true;
fail:
smbcli_close(cli->tree, fnum);
smbcli_unlink(cli->tree, FILENAME);
torture_close_connection(cli);
talloc_free(mem_ctx);
return false;
}
/* vim: set sts=8 sw=8 : */
|
kernevil/samba
|
source4/torture/unix/unix_info2.c
|
C
|
gpl-3.0
| 13,702
|
package eu.siacs.conversations.ui;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.axolotl.AxolotlService;
import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.services.BarcodeProvider;
import eu.siacs.conversations.services.XmppConnectionService.OnCaptchaRequested;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.XmppConnection.Features;
import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.pep.Avatar;
public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
private static final int REQUEST_DATA_SAVER = 0x37af244;
private AutoCompleteTextView mAccountJid;
private EditText mPassword;
private EditText mPasswordConfirm;
private CheckBox mRegisterNew;
private Button mCancelButton;
private Button mSaveButton;
private Button mDisableOsOptimizationsButton;
private TextView mDisableOsOptimizationsHeadline;
private TextView getmDisableOsOptimizationsBody;
private TableLayout mMoreTable;
private LinearLayout mStats;
private RelativeLayout mOsOptimizations;
private TextView mServerInfoSm;
private TextView mServerInfoRosterVersion;
private TextView mServerInfoCarbons;
private TextView mServerInfoMam;
private TextView mServerInfoCSI;
private TextView mServerInfoBlocking;
private TextView mServerInfoPep;
private TextView mServerInfoHttpUpload;
private TextView mServerInfoPush;
private TextView mSessionEst;
private TextView mOtrFingerprint;
private TextView mAxolotlFingerprint;
private TextView mOwnFingerprintDesc;
private TextView mAccountJidLabel;
private ImageView mAvatar;
private RelativeLayout mOtrFingerprintBox;
private RelativeLayout mAxolotlFingerprintBox;
private ImageButton mOtrFingerprintToClipboardButton;
private ImageButton mAxolotlFingerprintToClipboardButton;
private LinearLayout keys;
private LinearLayout keysCard;
private LinearLayout mNamePort;
private EditText mHostname;
private EditText mPort;
private AlertDialog mCaptchaDialog = null;
private Jid jidToEdit;
private boolean mInitMode = false;
private boolean mUsernameMode = Config.DOMAIN_LOCK != null;
private boolean mShowOptions = false;
private Account mAccount;
private String messageFingerprint;
private boolean mFetchingAvatar = false;
private final OnClickListener mSaveButtonClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
final String password = mPassword.getText().toString();
final String passwordConfirm = mPasswordConfirm.getText().toString();
if (!mInitMode && passwordChangedInMagicCreateMode()) {
gotoChangePassword(password);
return;
}
if (mInitMode && mAccount != null) {
mAccount.setOption(Account.OPTION_DISABLED, false);
}
if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited()) {
mAccount.setOption(Account.OPTION_DISABLED, false);
if (!xmppConnectionService.updateAccount(mAccount)) {
Toast.makeText(EditAccountActivity.this,R.string.unable_to_update_account,Toast.LENGTH_SHORT).show();
}
return;
}
final boolean registerNewAccount = mRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI;
if (mUsernameMode && mAccountJid.getText().toString().contains("@")) {
mAccountJid.setError(getString(R.string.invalid_username));
mAccountJid.requestFocus();
return;
}
final Jid jid;
try {
if (mUsernameMode) {
jid = Jid.fromParts(mAccountJid.getText().toString(), getUserModeDomain(), null);
} else {
jid = Jid.fromString(mAccountJid.getText().toString());
}
} catch (final InvalidJidException e) {
if (mUsernameMode) {
mAccountJid.setError(getString(R.string.invalid_username));
} else {
mAccountJid.setError(getString(R.string.invalid_jid));
}
mAccountJid.requestFocus();
return;
}
String hostname = null;
int numericPort = 5222;
if (mShowOptions) {
hostname = mHostname.getText().toString().replaceAll("\\s","");
final String port = mPort.getText().toString().replaceAll("\\s","");
if (hostname.contains(" ")) {
mHostname.setError(getString(R.string.not_valid_hostname));
mHostname.requestFocus();
return;
}
try {
numericPort = Integer.parseInt(port);
if (numericPort < 0 || numericPort > 65535) {
mPort.setError(getString(R.string.not_a_valid_port));
mPort.requestFocus();
return;
}
} catch (NumberFormatException e) {
mPort.setError(getString(R.string.not_a_valid_port));
mPort.requestFocus();
return;
}
}
if (jid.isDomainJid()) {
if (mUsernameMode) {
mAccountJid.setError(getString(R.string.invalid_username));
} else {
mAccountJid.setError(getString(R.string.invalid_jid));
}
mAccountJid.requestFocus();
return;
}
if (registerNewAccount) {
if (!password.equals(passwordConfirm)) {
mPasswordConfirm.setError(getString(R.string.passwords_do_not_match));
mPasswordConfirm.requestFocus();
return;
}
}
if (mAccount != null) {
if (mInitMode && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
mAccount.setOption(Account.OPTION_MAGIC_CREATE, mAccount.getPassword().contains(password));
}
mAccount.setJid(jid);
mAccount.setPort(numericPort);
mAccount.setHostname(hostname);
mAccountJid.setError(null);
mPasswordConfirm.setError(null);
mAccount.setPassword(password);
mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
if (!xmppConnectionService.updateAccount(mAccount)) {
Toast.makeText(EditAccountActivity.this,R.string.unable_to_update_account,Toast.LENGTH_SHORT).show();
return;
}
} else {
if (xmppConnectionService.findAccountByJid(jid) != null) {
mAccountJid.setError(getString(R.string.account_already_exists));
mAccountJid.requestFocus();
return;
}
mAccount = new Account(jid.toBareJid(), password);
mAccount.setPort(numericPort);
mAccount.setHostname(hostname);
mAccount.setOption(Account.OPTION_USETLS, true);
mAccount.setOption(Account.OPTION_USECOMPRESSION, true);
mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
xmppConnectionService.createAccount(mAccount);
}
mHostname.setError(null);
mPort.setError(null);
if (!mAccount.isOptionSet(Account.OPTION_DISABLED)
&& !registerNewAccount
&& !mInitMode) {
finish();
} else {
updateSaveButton();
updateAccountInformation(true);
}
}
};
private final OnClickListener mCancelButtonClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
deleteMagicCreatedAccountAndReturnIfNecessary();
finish();
}
};
private Toast mFetchingMamPrefsToast;
private TableRow mPushRow;
private String mSavedInstanceAccount;
private boolean mSavedInstanceInit = false;
private Button mClearDevicesButton;
public void refreshUiReal() {
invalidateOptionsMenu();
if (mAccount != null
&& mAccount.getStatus() != Account.State.ONLINE
&& mFetchingAvatar) {
startActivity(new Intent(getApplicationContext(),
ManageAccountActivity.class));
finish();
} else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
if (!mFetchingAvatar) {
mFetchingAvatar = true;
xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
}
}
if (mAccount != null) {
updateAccountInformation(false);
}
updateSaveButton();
}
@Override
public boolean onNavigateUp() {
deleteMagicCreatedAccountAndReturnIfNecessary();
return super.onNavigateUp();
}
@Override
public void onBackPressed() {
deleteMagicCreatedAccountAndReturnIfNecessary();
super.onBackPressed();
}
private void deleteMagicCreatedAccountAndReturnIfNecessary() {
if (Config.MAGIC_CREATE_DOMAIN != null
&& mAccount != null
&& mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
&& mAccount.isOptionSet(Account.OPTION_REGISTER)
&& xmppConnectionService.getAccounts().size() == 1) {
xmppConnectionService.deleteAccount(mAccount);
startActivity(new Intent(EditAccountActivity.this, WelcomeActivity.class));
}
}
@Override
public void onAccountUpdate() {
refreshUi();
}
private final UiCallback<Avatar> mAvatarFetchCallback = new UiCallback<Avatar>() {
@Override
public void userInputRequried(final PendingIntent pi, final Avatar avatar) {
finishInitialSetup(avatar);
}
@Override
public void success(final Avatar avatar) {
finishInitialSetup(avatar);
}
@Override
public void error(final int errorCode, final Avatar avatar) {
finishInitialSetup(avatar);
}
};
private final TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
updateSaveButton();
}
@Override
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
}
@Override
public void afterTextChanged(final Editable s) {
}
};
private final OnClickListener mAvatarClickListener = new OnClickListener() {
@Override
public void onClick(final View view) {
if (mAccount != null) {
final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString());
startActivity(intent);
}
}
};
protected void finishInitialSetup(final Avatar avatar) {
runOnUiThread(new Runnable() {
@Override
public void run() {
final Intent intent;
final XmppConnection connection = mAccount.getXmppConnection();
final boolean wasFirstAccount = xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1;
if (avatar != null || (connection != null && !connection.getFeatures().pep())) {
intent = new Intent(getApplicationContext(), StartConversationActivity.class);
if (wasFirstAccount) {
intent.putExtra("init", true);
}
} else {
intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString());
intent.putExtra("setup", true);
}
if (wasFirstAccount) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
startActivity(intent);
finish();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_BATTERY_OP || requestCode == REQUEST_DATA_SAVER) {
updateAccountInformation(mAccount == null);
}
}
@Override
protected void processFingerprintVerification(XmppUri uri) {
if (mAccount != null && mAccount.getJid().toBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
if (xmppConnectionService.verifyFingerprints(mAccount,uri.getFingerprints())) {
Toast.makeText(this,R.string.verified_fingerprints,Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this,R.string.invalid_barcode,Toast.LENGTH_SHORT).show();
}
}
protected void updateSaveButton() {
boolean accountInfoEdited = accountInfoEdited();
if (!mInitMode && passwordChangedInMagicCreateMode()) {
this.mSaveButton.setText(R.string.change_password);
this.mSaveButton.setEnabled(true);
this.mSaveButton.setTextColor(getPrimaryTextColor());
} else if (accountInfoEdited && !mInitMode) {
this.mSaveButton.setText(R.string.save);
this.mSaveButton.setEnabled(true);
this.mSaveButton.setTextColor(getPrimaryTextColor());
} else if (mAccount != null
&& (mAccount.getStatus() == Account.State.CONNECTING || mAccount.getStatus() == Account.State.REGISTRATION_SUCCESSFUL|| mFetchingAvatar)) {
this.mSaveButton.setEnabled(false);
this.mSaveButton.setTextColor(getSecondaryTextColor());
this.mSaveButton.setText(R.string.account_status_connecting);
} else if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !mInitMode) {
this.mSaveButton.setEnabled(true);
this.mSaveButton.setTextColor(getPrimaryTextColor());
this.mSaveButton.setText(R.string.enable);
} else {
this.mSaveButton.setEnabled(true);
this.mSaveButton.setTextColor(getPrimaryTextColor());
if (!mInitMode) {
if (mAccount != null && mAccount.isOnlineAndConnected()) {
this.mSaveButton.setText(R.string.save);
if (!accountInfoEdited) {
this.mSaveButton.setEnabled(false);
this.mSaveButton.setTextColor(getSecondaryTextColor());
}
} else {
this.mSaveButton.setText(R.string.connect);
}
} else {
this.mSaveButton.setText(R.string.next);
}
}
}
protected boolean accountInfoEdited() {
if (this.mAccount == null) {
return false;
}
return jidEdited() ||
!this.mAccount.getPassword().equals(this.mPassword.getText().toString()) ||
!this.mAccount.getHostname().equals(this.mHostname.getText().toString()) ||
!String.valueOf(this.mAccount.getPort()).equals(this.mPort.getText().toString());
}
protected boolean jidEdited() {
final String unmodified;
if (mUsernameMode) {
unmodified = this.mAccount.getJid().getLocalpart();
} else {
unmodified = this.mAccount.getJid().toBareJid().toString();
}
return !unmodified.equals(this.mAccountJid.getText().toString());
}
protected boolean passwordChangedInMagicCreateMode() {
return mAccount != null
&& mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
&& !this.mAccount.getPassword().equals(this.mPassword.getText().toString())
&& !this.jidEdited()
&& mAccount.isOnlineAndConnected();
}
@Override
protected String getShareableUri() {
if (mAccount != null) {
return mAccount.getShareableUri();
} else {
return "";
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
this.mSavedInstanceAccount = savedInstanceState.getString("account");
this.mSavedInstanceInit = savedInstanceState.getBoolean("initMode", false);
}
setContentView(R.layout.activity_edit_account);
this.mAccountJid = (AutoCompleteTextView) findViewById(R.id.account_jid);
this.mAccountJid.addTextChangedListener(this.mTextWatcher);
this.mAccountJidLabel = (TextView) findViewById(R.id.account_jid_label);
this.mPassword = (EditText) findViewById(R.id.account_password);
this.mPassword.addTextChangedListener(this.mTextWatcher);
this.mPasswordConfirm = (EditText) findViewById(R.id.account_password_confirm);
this.mAvatar = (ImageView) findViewById(R.id.avater);
this.mAvatar.setOnClickListener(this.mAvatarClickListener);
this.mRegisterNew = (CheckBox) findViewById(R.id.account_register_new);
this.mStats = (LinearLayout) findViewById(R.id.stats);
this.mOsOptimizations = (RelativeLayout) findViewById(R.id.os_optimization);
this.mDisableOsOptimizationsButton = (Button) findViewById(R.id.os_optimization_disable);
this.mDisableOsOptimizationsHeadline = (TextView) findViewById(R.id.os_optimization_headline);
this.getmDisableOsOptimizationsBody = (TextView) findViewById(R.id.os_optimization_body);
this.mSessionEst = (TextView) findViewById(R.id.session_est);
this.mServerInfoRosterVersion = (TextView) findViewById(R.id.server_info_roster_version);
this.mServerInfoCarbons = (TextView) findViewById(R.id.server_info_carbons);
this.mServerInfoMam = (TextView) findViewById(R.id.server_info_mam);
this.mServerInfoCSI = (TextView) findViewById(R.id.server_info_csi);
this.mServerInfoBlocking = (TextView) findViewById(R.id.server_info_blocking);
this.mServerInfoSm = (TextView) findViewById(R.id.server_info_sm);
this.mServerInfoPep = (TextView) findViewById(R.id.server_info_pep);
this.mServerInfoHttpUpload = (TextView) findViewById(R.id.server_info_http_upload);
this.mPushRow = (TableRow) findViewById(R.id.push_row);
this.mServerInfoPush = (TextView) findViewById(R.id.server_info_push);
this.mOtrFingerprint = (TextView) findViewById(R.id.otr_fingerprint);
this.mOtrFingerprintBox = (RelativeLayout) findViewById(R.id.otr_fingerprint_box);
this.mOtrFingerprintToClipboardButton = (ImageButton) findViewById(R.id.action_copy_to_clipboard);
this.mAxolotlFingerprint = (TextView) findViewById(R.id.axolotl_fingerprint);
this.mAxolotlFingerprintBox = (RelativeLayout) findViewById(R.id.axolotl_fingerprint_box);
this.mAxolotlFingerprintToClipboardButton = (ImageButton) findViewById(R.id.action_copy_axolotl_to_clipboard);
this.mOwnFingerprintDesc = (TextView) findViewById(R.id.own_fingerprint_desc);
this.keysCard = (LinearLayout) findViewById(R.id.other_device_keys_card);
this.keys = (LinearLayout) findViewById(R.id.other_device_keys);
this.mNamePort = (LinearLayout) findViewById(R.id.name_port);
this.mHostname = (EditText) findViewById(R.id.hostname);
this.mHostname.addTextChangedListener(mTextWatcher);
this.mClearDevicesButton = (Button) findViewById(R.id.clear_devices);
this.mClearDevicesButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showWipePepDialog();
}
});
this.mPort = (EditText) findViewById(R.id.port);
this.mPort.setText("5222");
this.mPort.addTextChangedListener(mTextWatcher);
this.mSaveButton = (Button) findViewById(R.id.save_button);
this.mCancelButton = (Button) findViewById(R.id.cancel_button);
this.mSaveButton.setOnClickListener(this.mSaveButtonClickListener);
this.mCancelButton.setOnClickListener(this.mCancelButtonClickListener);
this.mMoreTable = (TableLayout) findViewById(R.id.server_info_more);
if (savedInstanceState != null && savedInstanceState.getBoolean("showMoreTable")) {
changeMoreTableVisibility(true);
}
final OnCheckedChangeListener OnCheckedShowConfirmPassword = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
if (isChecked) {
mPasswordConfirm.setVisibility(View.VISIBLE);
} else {
mPasswordConfirm.setVisibility(View.GONE);
}
updateSaveButton();
}
};
this.mRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword);
if (Config.DISALLOW_REGISTRATION_IN_UI) {
this.mRegisterNew.setVisibility(View.GONE);
}
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.editaccount, menu);
final MenuItem showQrCode = menu.findItem(R.id.action_show_qr_code);
final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list);
final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server);
final MenuItem showPassword = menu.findItem(R.id.action_show_password);
final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
final MenuItem share = menu.findItem(R.id.action_share);
renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
share.setVisible(mAccount != null && !mInitMode);
if (mAccount != null && mAccount.isOnlineAndConnected()) {
if (!mAccount.getXmppConnection().getFeatures().blocking()) {
showBlocklist.setVisible(false);
} else {
showBlocklist.setEnabled(mAccount.getBlocklist().size() > 0);
}
if (!mAccount.getXmppConnection().getFeatures().register()) {
changePassword.setVisible(false);
}
mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
changePresence.setVisible(manuallyChangePresence());
} else {
showQrCode.setVisible(false);
showBlocklist.setVisible(false);
showMoreInfo.setVisible(false);
changePassword.setVisible(false);
mamPrefs.setVisible(false);
changePresence.setVisible(false);
}
if (mAccount != null) {
showPassword.setVisible(mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
&& !mAccount.isOptionSet(Account.OPTION_REGISTER));
} else {
showPassword.setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
if (showMoreInfo.isVisible()) {
showMoreInfo.setChecked(mMoreTable.getVisibility() == View.VISIBLE);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
protected void onStart() {
super.onStart();
final int theme = findTheme();
if (this.mTheme != theme) {
recreate();
} else if (getIntent() != null) {
try {
this.jidToEdit = Jid.fromString(getIntent().getStringExtra("jid"));
} catch (final InvalidJidException | NullPointerException ignored) {
this.jidToEdit = null;
}
boolean init = getIntent().getBooleanExtra("init", false);
this.mInitMode = init || this.jidToEdit == null;
this.messageFingerprint = getIntent().getStringExtra("fingerprint");
if (!mInitMode) {
this.mRegisterNew.setVisibility(View.GONE);
if (getActionBar() != null) {
getActionBar().setTitle(getString(R.string.account_details));
}
} else {
this.mAvatar.setVisibility(View.GONE);
ActionBar ab = getActionBar();
if (ab != null) {
if (init && Config.MAGIC_CREATE_DOMAIN == null) {
ab.setDisplayShowHomeEnabled(false);
ab.setDisplayHomeAsUpEnabled(false);
}
ab.setTitle(R.string.action_add_account);
}
}
}
SharedPreferences preferences = getPreferences();
boolean useTor = Config.FORCE_ORBOT || preferences.getBoolean("use_tor", false);
this.mShowOptions = useTor || preferences.getBoolean("show_connection_options", false);
mHostname.setHint(useTor ? R.string.hostname_or_onion : R.string.hostname_example);
this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
}
@Override
public void onSaveInstanceState(final Bundle savedInstanceState) {
if (mAccount != null) {
savedInstanceState.putString("account", mAccount.getJid().toBareJid().toString());
savedInstanceState.putBoolean("initMode", mInitMode);
savedInstanceState.putBoolean("showMoreTable", mMoreTable.getVisibility() == View.VISIBLE);
}
super.onSaveInstanceState(savedInstanceState);
}
protected void onBackendConnected() {
boolean init = true;
if (mSavedInstanceAccount != null) {
try {
this.mAccount = xmppConnectionService.findAccountByJid(Jid.fromString(mSavedInstanceAccount));
this.mInitMode = mSavedInstanceInit;
init = false;
} catch (InvalidJidException e) {
this.mAccount = null;
}
} else if (this.jidToEdit != null) {
this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
}
if (mAccount != null) {
this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
if (this.mAccount.getPrivateKeyAlias() != null) {
this.mPassword.setHint(R.string.authenticate_with_certificate);
if (this.mInitMode) {
this.mPassword.requestFocus();
}
}
if (mPendingFingerprintVerificationUri != null) {
processFingerprintVerification(mPendingFingerprintVerificationUri);
mPendingFingerprintVerificationUri = null;
}
updateAccountInformation(init);
}
if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
this.mCancelButton.setEnabled(false);
this.mCancelButton.setTextColor(getSecondaryTextColor());
}
if (mUsernameMode) {
this.mAccountJidLabel.setText(R.string.username);
this.mAccountJid.setHint(R.string.username_hint);
} else {
final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
R.layout.simple_list_item,
xmppConnectionService.getKnownHosts());
this.mAccountJid.setAdapter(mKnownHostsAdapter);
}
updateSaveButton();
invalidateOptionsMenu();
}
private String getUserModeDomain() {
if (mAccount != null) {
return mAccount.getJid().getDomainpart();
} else {
return Config.DOMAIN_LOCK;
}
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.action_show_block_list:
final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
startActivity(showBlocklistIntent);
break;
case R.id.action_server_info_show_more:
changeMoreTableVisibility(!item.isChecked());
break;
case R.id.action_share_barcode:
shareBarcode();
break;
case R.id.action_share_http:
shareLink(true);
break;
case R.id.action_share_uri:
shareLink(false);
break;
case R.id.action_change_password_on_server:
gotoChangePassword(null);
break;
case R.id.action_mam_prefs:
editMamPrefs();
break;
case R.id.action_renew_certificate:
renewCertificate();
break;
case R.id.action_change_presence:
changePresence();
break;
case R.id.action_show_password:
showPassword();
break;
}
return super.onOptionsItemSelected(item);
}
private void shareLink(boolean http) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String text;
if (http) {
text = mAccount.getShareableLink();
} else {
text = mAccount.getShareableUri();
}
intent.putExtra(Intent.EXTRA_TEXT,text);
startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
}
private void shareBarcode() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,BarcodeProvider.getUriForAccount(this,mAccount));
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/png");
startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
}
private void changeMoreTableVisibility(boolean visible) {
mMoreTable.setVisibility(visible ? View.VISIBLE : View.GONE);
}
private void gotoChangePassword(String newPassword) {
final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
if (newPassword != null) {
changePasswordIntent.putExtra("password", newPassword);
}
startActivity(changePasswordIntent);
}
private void renewCertificate() {
KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
}
private void changePresence() {
Intent intent = new Intent(this, SetPresenceActivity.class);
intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT,mAccount.getJid().toBareJid().toString());
startActivity(intent);
}
@Override
public void alias(String alias) {
if (alias != null) {
xmppConnectionService.updateKeyInAccount(mAccount, alias);
}
}
private void updateAccountInformation(boolean init) {
if (init) {
this.mAccountJid.getEditableText().clear();
if (mUsernameMode) {
this.mAccountJid.getEditableText().append(this.mAccount.getJid().getLocalpart());
} else {
this.mAccountJid.getEditableText().append(this.mAccount.getJid().toBareJid().toString());
}
this.mPassword.setText(this.mAccount.getPassword());
this.mHostname.setText("");
this.mHostname.getEditableText().append(this.mAccount.getHostname());
this.mPort.setText("");
this.mPort.getEditableText().append(String.valueOf(this.mAccount.getPort()));
this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
}
if (!mInitMode) {
this.mAvatar.setVisibility(View.VISIBLE);
this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, getPixel(72)));
} else {
this.mAvatar.setVisibility(View.GONE);
}
if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
this.mRegisterNew.setVisibility(View.VISIBLE);
this.mRegisterNew.setChecked(true);
this.mPasswordConfirm.setText(this.mAccount.getPassword());
} else {
this.mRegisterNew.setVisibility(View.GONE);
this.mRegisterNew.setChecked(false);
}
if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
Features features = this.mAccount.getXmppConnection().getFeatures();
this.mStats.setVisibility(View.VISIBLE);
boolean showBatteryWarning = !xmppConnectionService.getPushManagementService().availableAndUseful(mAccount) && isOptimizingBattery();
boolean showDataSaverWarning = isAffectedByDataSaver();
showOsOptimizationWarning(showBatteryWarning,showDataSaverWarning);
this.mSessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
.getLastSessionEstablished()));
if (features.rosterVersioning()) {
this.mServerInfoRosterVersion.setText(R.string.server_info_available);
} else {
this.mServerInfoRosterVersion.setText(R.string.server_info_unavailable);
}
if (features.carbons()) {
this.mServerInfoCarbons.setText(R.string.server_info_available);
} else {
this.mServerInfoCarbons
.setText(R.string.server_info_unavailable);
}
if (features.mam()) {
this.mServerInfoMam.setText(R.string.server_info_available);
} else {
this.mServerInfoMam.setText(R.string.server_info_unavailable);
}
if (features.csi()) {
this.mServerInfoCSI.setText(R.string.server_info_available);
} else {
this.mServerInfoCSI.setText(R.string.server_info_unavailable);
}
if (features.blocking()) {
this.mServerInfoBlocking.setText(R.string.server_info_available);
} else {
this.mServerInfoBlocking.setText(R.string.server_info_unavailable);
}
if (features.sm()) {
this.mServerInfoSm.setText(R.string.server_info_available);
} else {
this.mServerInfoSm.setText(R.string.server_info_unavailable);
}
if (features.pep()) {
AxolotlService axolotlService = this.mAccount.getAxolotlService();
if (axolotlService != null && axolotlService.isPepBroken()) {
this.mServerInfoPep.setText(R.string.server_info_broken);
} else {
this.mServerInfoPep.setText(R.string.server_info_available);
}
} else {
this.mServerInfoPep.setText(R.string.server_info_unavailable);
}
if (features.httpUpload(0)) {
this.mServerInfoHttpUpload.setText(R.string.server_info_available);
} else {
this.mServerInfoHttpUpload.setText(R.string.server_info_unavailable);
}
this.mPushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
if (xmppConnectionService.getPushManagementService().available(mAccount)) {
this.mServerInfoPush.setText(R.string.server_info_available);
} else {
this.mServerInfoPush.setText(R.string.server_info_unavailable);
}
final String otrFingerprint = this.mAccount.getOtrFingerprint();
if (otrFingerprint != null && Config.supportOtr()) {
this.mOtrFingerprintBox.setVisibility(View.VISIBLE);
this.mOtrFingerprint.setText(CryptoHelper.prettifyFingerprint(otrFingerprint));
this.mOtrFingerprintToClipboardButton
.setVisibility(View.VISIBLE);
this.mOtrFingerprintToClipboardButton
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (copyTextToClipboard(CryptoHelper.prettifyFingerprint(otrFingerprint), R.string.otr_fingerprint)) {
Toast.makeText(
EditAccountActivity.this,
R.string.toast_message_otr_fingerprint,
Toast.LENGTH_SHORT).show();
}
}
});
} else {
this.mOtrFingerprintBox.setVisibility(View.GONE);
}
final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
this.mAxolotlFingerprintBox.setVisibility(View.VISIBLE);
if (ownAxolotlFingerprint.equals(messageFingerprint)) {
this.mOwnFingerprintDesc.setTextColor(getResources().getColor(R.color.accent));
} else {
this.mOwnFingerprintDesc.setTextColor(getSecondaryTextColor());
}
this.mAxolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
this.mAxolotlFingerprintToClipboardButton
.setVisibility(View.VISIBLE);
this.mAxolotlFingerprintToClipboardButton
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
copyOmemoFingerprint(ownAxolotlFingerprint);
}
});
} else {
this.mAxolotlFingerprintBox.setVisibility(View.GONE);
}
boolean hasKeys = false;
keys.removeAllViews();
for(XmppAxolotlSession session : mAccount.getAxolotlService().findOwnSessions()) {
if (!session.getTrust().isCompromised()) {
boolean highlight = session.getFingerprint().equals(messageFingerprint);
addFingerprintRow(keys,session,highlight);
hasKeys = true;
}
}
if (hasKeys && Config.supportOmemo()) {
keysCard.setVisibility(View.VISIBLE);
Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
if (otherDevices == null || otherDevices.isEmpty()) {
mClearDevicesButton.setVisibility(View.GONE);
} else {
mClearDevicesButton.setVisibility(View.VISIBLE);
}
} else {
keysCard.setVisibility(View.GONE);
}
} else {
if (this.mAccount.errorStatus()) {
final EditText errorTextField;
if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED) {
errorTextField = this.mPassword;
} else if (mShowOptions
&& this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
&& this.mHostname.getText().length() > 0) {
errorTextField = this.mHostname;
} else {
errorTextField = this.mAccountJid;
}
errorTextField.setError(getString(this.mAccount.getStatus().getReadableId()));
if (init || !accountInfoEdited()) {
errorTextField.requestFocus();
}
} else {
this.mAccountJid.setError(null);
this.mPassword.setError(null);
this.mHostname.setError(null);
}
this.mStats.setVisibility(View.GONE);
}
}
private void showOsOptimizationWarning(boolean showBatteryWarning, boolean showDataSaverWarning) {
this.mOsOptimizations.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
if (showDataSaverWarning) {
this.mDisableOsOptimizationsHeadline.setText(R.string.data_saver_enabled);
this.getmDisableOsOptimizationsBody.setText(R.string.data_saver_enabled_explained);
this.mDisableOsOptimizationsButton.setText(R.string.allow);
this.mDisableOsOptimizationsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
Uri uri = Uri.parse("package:"+getPackageName());
intent.setData(uri);
try {
startActivityForResult(intent, REQUEST_DATA_SAVER);
} catch (ActivityNotFoundException e) {
Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_data_saver, Toast.LENGTH_SHORT).show();
}
}
});
} else if (showBatteryWarning) {
this.mDisableOsOptimizationsButton.setText(R.string.disable);
this.mDisableOsOptimizationsHeadline.setText(R.string.battery_optimizations_enabled);
this.getmDisableOsOptimizationsBody.setText(R.string.battery_optimizations_enabled_explained);
this.mDisableOsOptimizationsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
Uri uri = Uri.parse("package:"+getPackageName());
intent.setData(uri);
try {
startActivityForResult(intent, REQUEST_BATTERY_OP);
} catch (ActivityNotFoundException e) {
Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void showWipePepDialog() {
Builder builder = new Builder(this);
builder.setTitle(getString(R.string.clear_other_devices));
builder.setIconAttribute(android.R.attr.alertDialogIcon);
builder.setMessage(getString(R.string.clear_other_devices_desc));
builder.setNegativeButton(getString(R.string.cancel), null);
builder.setPositiveButton(getString(R.string.accept),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mAccount.getAxolotlService().wipeOtherPepDevices();
}
});
builder.create().show();
}
private void editMamPrefs() {
this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
this.mFetchingMamPrefsToast.show();
xmppConnectionService.fetchMamPreferences(mAccount, this);
}
private void showPassword() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.dialog_show_password, null);
TextView password = (TextView) view.findViewById(R.id.password);
password.setText(mAccount.getPassword());
builder.setTitle(R.string.password);
builder.setView(view);
builder.setPositiveButton(R.string.cancel, null);
builder.create().show();
}
@Override
public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
refreshUi();
}
@Override
public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if ((mCaptchaDialog != null) && mCaptchaDialog.isShowing()) {
mCaptchaDialog.dismiss();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(EditAccountActivity.this);
final View view = getLayoutInflater().inflate(R.layout.captcha, null);
final ImageView imageView = (ImageView) view.findViewById(R.id.captcha);
final EditText input = (EditText) view.findViewById(R.id.input);
imageView.setImageBitmap(captcha);
builder.setTitle(getString(R.string.captcha_required));
builder.setView(view);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String rc = input.getText().toString();
data.put("username", account.getUsername());
data.put("password", account.getPassword());
data.put("ocr", rc);
data.submit();
if (xmppConnectionServiceBound) {
xmppConnectionService.sendCreateAccountWithCaptchaPacket(
account, id, data);
}
}
});
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (xmppConnectionService != null) {
xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
}
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (xmppConnectionService != null) {
xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
}
}
});
mCaptchaDialog = builder.create();
mCaptchaDialog.show();
}
});
}
public void onShowErrorToast(final int resId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onPreferencesFetched(final Element prefs) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mFetchingMamPrefsToast != null) {
mFetchingMamPrefsToast.cancel();
}
AlertDialog.Builder builder = new Builder(EditAccountActivity.this);
builder.setTitle(R.string.server_side_mam_prefs);
String defaultAttr = prefs.getAttribute("default");
final List<String> defaults = Arrays.asList("never", "roster", "always");
final AtomicInteger choice = new AtomicInteger(Math.max(0,defaults.indexOf(defaultAttr)));
builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
choice.set(which);
}
});
builder.setNegativeButton(R.string.cancel, null);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
prefs.setAttribute("default",defaults.get(choice.get()));
xmppConnectionService.pushMamPreferences(mAccount, prefs);
}
});
builder.create().show();
}
});
}
@Override
public void onPreferencesFetchFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mFetchingMamPrefsToast != null) {
mFetchingMamPrefsToast.cancel();
}
Toast.makeText(EditAccountActivity.this,R.string.unable_to_fetch_mam_prefs,Toast.LENGTH_LONG).show();
}
});
}
@Override
public void OnUpdateBlocklist(Status status) {
refreshUi();
}
}
|
Fenisu/Conversations
|
src/main/java/eu/siacs/conversations/ui/EditAccountActivity.java
|
Java
|
gpl-3.0
| 43,491
|
/*
* Copyright (c) 1997, 2002 by Michael J. Roberts. All Rights Reserved.
*
* Please see the accompanying license file, LICENSE.TXT, for information
* on using and copying this software.
*/
/*
Name
htmlmng.h - MNG (animated) image object
Function
Notes
Modified
05/03/02 MJRoberts - creation
*/
#ifndef HTMLMNG_H
#define HTMLMNG_H
/* include MNG library header */
#include <libmng_types.h>
#ifndef TADSHTML_H
#include "tadshtml.h"
#endif
/* ------------------------------------------------------------------------ */
/*
* Options flags
*/
/*
* Always discard alpha information. If this is set, if an image has an
* alpha channel, we'll explicitly create a default background for the
* image and blend the image into the default background.
*/
#define HTMLMNG_OPT_NO_ALPHA 0x0001
/* ------------------------------------------------------------------------ */
/*
* Playback states.
*/
enum htmlmng_state_t
{
/*
* Initializing. In this state, we haven't yet finished reading the
* image header.
*/
HTMLMNG_STATE_INIT,
/*
* Playing, waiting to draw first frame. In this state, we've loaded
* the image, and we have a timer wait pending, but we have yet to
* display the first frame of the animation. At this point, the
* playback clock is frozen until we draw the first frame. We don't
* start the clock on playback until we've displayed the first image,
* in case we're doing a lot of loading work all at once (loading other
* images, for example) and thus might be too busy for the start of the
* animation to be displayed smoothly. We assume that once we get
* around to showing the first frame, we're done with any batch of work
* that might have been underway and are ready to start servicing
* display updates for the animation.
*/
HTMLMNG_STATE_WAIT_FIRST,
/*
* Playing. In this state, we're attempting to show frames from the
* MNG in the time sequence specified in the file.
*/
HTMLMNG_STATE_PLAYING,
/*
* Done. In this state, we have either reached the end of the
* animation, or we've permanently frozen playback. No further timed
* events will be processed.
*/
HTMLMNG_STATE_DONE,
};
/* ------------------------------------------------------------------------ */
/*
* MNG helper client interface. This is an interface that must be
* implemented by the client code using the MNG helper. In most cases,
* this can be implemented by the system-specific MNG display object.
*/
class CHtmlMngClient
{
public:
/*
* Select the canvas format and allocate the canvas. The canvas is the
* memory into which the MNG decoder writes the pixels. We let the
* client code handle the allocation of the canvas so that the client
* can display directly from the canvas rather than having to go
* through an intermediate copy.
*
* The client code should call mng_set_canvasstyle() on the MNG handle,
* and should set the background color if an alpha channel isn't
* desired and the image source has alpha information.
*
* Returns zero on success, non-zero on error.
*/
virtual int init_mng_canvas(mng_handle handle,
int width, int height) = 0;
/* get a pointer to a row of pixels from the canvas */
virtual char *get_mng_canvas_row(int rownum) = 0;
/*
* Receive notification of a change in the image. If the client is
* double-buffering the image, the client must copy from the canvas to
* its other buffer. If this client displays directly from the canvas,
* the client need do nothing here, because the MNG helper will have
* updated the canvas directly.
*/
virtual void notify_mng_update(int x, int y, int wid, int ht) = 0;
/*
* Set a timer. The client must call our notify_timer() method after
* the given number of milliseconds elapse.
*/
virtual void set_mng_timer(long msecs) = 0;
/* cancel the timer previously set with set_mng_timer() */
virtual void cancel_mng_timer() = 0;
};
/* ------------------------------------------------------------------------ */
/*
* MNG helper object. This object is meant to encapsulate the MNG library,
* so that minimal platform-specific code is necessary. This class is
* designed to be instantiated as a helper object by the platform-specific
* implementation (of CHtmlSysImageMng_xxx).
*/
class CHtmlMng
{
public:
CHtmlMng(class CHtmlMngClient *client);
~CHtmlMng();
/* load an image from a file */
int start_mng_read(const textchar_t *filename,
unsigned long seekpos, unsigned long filesize);
/* halt playback */
void halt_playback()
{
/*
* set our state to 'done' - we'll ignore any further timer events
* once we're in this state
*/
state_ = HTMLMNG_STATE_DONE;
/* note that we have timer event pending */
event_is_pending_ = FALSE;
}
/* pause playback */
void pause_playback();
/* resume from pause */
void resume_playback();
/* get the dimensions */
unsigned long get_height() const { return height_; }
unsigned long get_width() const { return width_; }
/*
* Notify that we've just drawn. The system-specific client should
* call this whenever it draws the image, so that we can take care of
* any timer-related processing when drawing occurs.
*/
void notify_draw();
/*
* Notify of a timer event. The system-specific client should simply
* pass along a notify_timer() call from the display site to us here.
*/
void notify_timer();
/*
* Get the timer event status. This indicates if we have a timer event
* pending, and if so, the system time (as given by
* os_get_sys_clock_ms()) at which the timer is scheduled to expire.
*/
int is_timer_pending() const { return event_is_pending_; }
long get_timer_time() const { return pending_event_time_; }
private:
/* allocate memory for the image */
void allocate_rows(unsigned long height, unsigned long width,
int bits_per_pixel);
/* MNG callback: allocate memory, cleared to all zeroes */
static mng_ptr alloc_cb(mng_size_t len);
/* MNG callback: free memory allocated with alloc_cb() */
static void free_cb(mng_ptr ptr, mng_size_t);
/* MNG callback: open stream */
static mng_bool open_cb(mng_handle handle)
{ return get_this(handle)->open_cbm(); }
mng_bool open_cbm();
/* MNG callback: close stream */
static mng_bool close_cb(mng_handle handle)
{ return get_this(handle)->close_cbm(); }
mng_bool close_cbm();
/* MNG callback: read from stream */
static mng_bool read_cb(mng_handle handle, mng_ptr buf,
mng_uint32 len, mng_uint32p actualp)
{ return get_this(handle)->read_cbm(buf, len, actualp); }
mng_bool read_cbm(mng_ptr buf, mng_uint32 len, mng_uint32p actualp);
/* MNG callback: process header */
static mng_bool process_header_cb(mng_handle handle,
mng_uint32 wid, mng_uint32 ht)
{ return get_this(handle)->process_header_cbm(wid, ht); }
mng_bool process_header_cbm(mng_uint32 wid, mng_uint32 ht);
/* MNG callback: get a canvas line */
static mng_ptr getcanvasline_cb(mng_handle handle,
mng_uint32 rownum)
{ return get_this(handle)->getcanvasline_cbm(rownum); }
mng_ptr getcanvasline_cbm(mng_uint32 rownum);
/* MNG callback: refresh the display */
static mng_bool refresh_cb(mng_handle handle,
mng_uint32 x, mng_uint32 y,
mng_uint32 wid, mng_uint32 ht)
{ return get_this(handle)->refresh_cbm(x, y, wid, ht); }
mng_bool refresh_cbm(mng_uint32 x, mng_uint32 y,
mng_uint32 wid, mng_uint32 ht);
/* MNG callback: get tick count; simply use osifc */
static mng_uint32 gettickcount_cb(mng_handle handle)
{ return os_get_sys_clock_ms(); }
/* MNG callback: set a timer */
static mng_bool settimer_cb(mng_handle handle, mng_uint32 msecs)
{ return get_this(handle)->settimer_cbm(msecs); }
mng_bool settimer_cbm(mng_uint32 msecs);
/*
* callback service routine: given an MNG handle, get 'this'; we
* stored our 'this' pointer in the user data in the MNG handle on
* creation, so simply get the user data from the MNG handle and cast
* it appropriately
*/
static CHtmlMng *get_this(mng_handle handle);
/* client interface */
class CHtmlMngClient *client_;
/* our client system image resource object */
class CHtmlSysImageAnimated *sys_image_;
/* input file name, starting seek position, and stream size */
const textchar_t *file_name_;
unsigned long file_seek_start_;
unsigned long file_size_;
/* amount of data left to read from the input stream */
unsigned long file_rem_;
/* file handle */
osfildef *fp_;
/* our MNG handle */
mng_handle handle_;
/* number of rows allocated */
unsigned long height_;
/* width of each row */
unsigned long width_;
/*
* Resume timer.
*
* When we're in the 'initializing' state, this indicates the delay in
* milliseconds until the next event after the first frame. When we
* draw the first frame, we'll officially start playback.
*
* When we're in the 'playing' state, this indicates the actual system
* time (as given by os_get_sys_clock_ms()) of the next resume event.
*/
long resume_time_;
/*
* Next event time. This keeps track of the next timer event we
* expect. When our display site changes, and we have a pending event,
* we'll use this information to reset our event timer with the new
* site. This time is an actual system time as given by
* os_get_sys_clock_ms().
*/
long pending_event_time_;
int event_is_pending_;
/* current playback state */
htmlmng_state_t state_;
/* flag: playback is paused */
int paused_;
/* status to restore when we resume from a pause */
int pause_event_is_pending_;
long pause_event_delta_;
};
#endif /* HTMLMNG_H */
|
juandesant/spatterlight
|
terps/tads/htmltads/htmlmng.h
|
C
|
gpl-3.0
| 10,967
|
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Command\Redis;
/**
* @group commands
* @group realm-hash
*/
class HLEN_Test extends PredisCommandTestCase
{
/**
* {@inheritdoc}
*/
protected function getExpectedCommand()
{
return 'Predis\Command\Redis\HLEN';
}
/**
* {@inheritdoc}
*/
protected function getExpectedId()
{
return 'HLEN';
}
/**
* @group disconnected
*/
public function testFilterArguments()
{
$arguments = array('key');
$expected = array('key');
$command = $this->getCommand();
$command->setArguments($arguments);
$this->assertSame($expected, $command->getArguments());
}
/**
* @group disconnected
*/
public function testParseResponse()
{
$this->assertSame(1, $this->getCommand()->parseResponse(1));
}
/**
* @group connected
* @requiresRedisVersion >= 2.0.0
*/
public function testReturnsLengthOfHash()
{
$redis = $this->getClient();
$redis->hmset('metavars', 'foo', 'bar', 'hoge', 'piyo', 'lol', 'wut');
$this->assertSame(3, $redis->hlen('metavars'));
$this->assertSame(0, $redis->hlen('unknown'));
}
/**
* @group connected
* @requiresRedisVersion >= 2.0.0
* @expectedException \Predis\Response\ServerException
* @expectedExceptionMessage Operation against a key holding the wrong kind of value
*/
public function testThrowsExceptionOnWrongType()
{
$redis = $this->getClient();
$redis->set('foo', 'bar');
$redis->hlen('foo');
}
}
|
wuceyang/smartcms
|
vendor/predis/predis/tests/Predis/Command/Redis/HLEN_Test.php
|
PHP
|
gpl-3.0
| 1,863
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Tue Dec 13 18:06:07 CET 2016 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.commons.logging.impl.SimpleLog (SLF4J 1.7.22 API)</title>
<meta name="date" content="2016-12-13">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.commons.logging.impl.SimpleLog (SLF4J 1.7.22 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/commons/logging/impl/SimpleLog.html" title="class in org.apache.commons.logging.impl">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/commons/logging/impl/class-use/SimpleLog.html" target="_top">Frames</a></li>
<li><a href="SimpleLog.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.commons.logging.impl.SimpleLog" class="title">Uses of Class<br>org.apache.commons.logging.impl.SimpleLog</h2>
</div>
<div class="classUseContainer">No usage of org.apache.commons.logging.impl.SimpleLog</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/commons/logging/impl/SimpleLog.html" title="class in org.apache.commons.logging.impl">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/commons/logging/impl/class-use/SimpleLog.html" target="_top">Frames</a></li>
<li><a href="SimpleLog.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2005–2016 <a href="http://www.qos.ch">QOS.ch</a>. All rights reserved.</small></p>
</body>
</html>
|
sigma-phi-delta-beta-nu/liars-dice-ai
|
lib/slf4j-1.7.22/site/apidocs/org/apache/commons/logging/impl/class-use/SimpleLog.html
|
HTML
|
gpl-3.0
| 4,580
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.